C# - 공유기 관리 웹 페이지 인증
이 글은 아래의 질문에 대한 답변으로 정리한 것입니다.
공유기 관리 페이지에 접근시 윈도우 인증창이 뜹니다.
; https://www.sysnet.pe.kr/3/0/1118
질문의 요지는, 예를 들어 IPTime 같은 무선 Access Point 공유기 제품의 관리 페이지를 접근하면 다음과 같은 식으로 Internet Explorer의 경우 인증 정보를 요구하는 창이 뜬다는 것입니다.
[그림 1: IE 인증창]
사실, 공유기의 내부 운영체제는 윈도우가 아닐 가능성이 큽니다. 대부분 비용상의 문제로 무료 리눅스를 사용하고 있을 것이기 때문에 웹 페이지 로그인이 위와 같이 요구될 때는 NTLM이나 윈도우 통합 인증일 가능성은 거의 없습니다. 그렇다면 남은 것은 ^^ Basic 인증! 바로 그것입니다.
Fiddler를 이용해 한번 패킷을 가로채 볼까요?
맨 처음 관리 페이지를 요구하면 다음과 같은 요청/응답이 발생합니다.
===== 요청 =====
GET http://192.168.1.2/cgi-bin/timepro.cgi?tmenu=main_frame&smenu=main_frame HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Accept-Language: ko,en-US;q=0.7,en;q=0.3
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)
Accept-Encoding: gzip, deflate
Host: 192.168.1.2
DNT: 1
Connection: Keep-Alive
===== 응답 =====
HTTP/1.0 401 Unauthorized
Date: Wed, 30 Jan 2013 19:16:06 GMT
Server: Httpd/1.0
Connection: close
WWW-Authenticate: Basic realm=""
Content-Type: text/html; charset=ISO-8859-1
<HTML><HEAD><TITLE>401 Unauthorized</TITLE></HEAD>
<BODY><H1>401 Unauthorized</H1>
Your client does not have permission to get URL /cgi-bin/timepro.cgi from this server.
</BODY></HTML>
HTTP 응답 헤더에 WWW-Authenticate: Basic realm=""를 보면 인증이 필요하다는 것을 웹 서버가 알리면서 그 방식은 Basic이 되는 것입니다.
IE 웹 브라우저는 위와 같은 헤더가 HTTP 응답에 끼어 있으면 [그림 1]과 같은 창을 띄워 사용자로부터 계정 정보를 입력 받습니다.
근데, Basic 인증은 암호화가 되지 않는 계정 정보를 전달하는 프로토콜입니다. 그래서 사용자가 계정 정보를 입력하고 엔터를 치면 IE 웹 브라우저는 해당 계정 정보를 Base64 인코딩을 해서 전송합니다. 아래는 사용자 정보를 입력받은 IE가 웹 서버에 전송하는 요청을 Fiddler로 본 것입니다.
GET http://192.168.1.2/cgi-bin/timepro.cgi?tmenu=main_frame&smenu=main_frame HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Accept-Language: ko,en-US;q=0.7,en;q=0.3
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)
Accept-Encoding: gzip, deflate
Host: 192.168.1.2
Authorization: Basic a2V2aW46cHd0ZXN0
Connection: Keep-Alive
DNT: 1
Base64 인코딩 된 형태는 간단합니다. 예를 들어, ID == kevin, Password == pwtest라면 kevin:pwtest라고 ":" 문자를 이용하여 합친 후 그것을 Base64 인코딩 시키면 됩니다.
즉 위의 "Basic a2V2aW46cHd0ZXN0"을 풀어보면 "Basic kevin:pwtest" 값입니다.
자... 이제 답이 나왔군요. ^^ 따라서 공유기의 관리자 페이지에 요구하는 모든 HTTP 요청에 Authorization 헤더를 함께 설정해 두면, 응답이 정상적으로 나옵니다.
^^ 실제로 위와 같은 이론을 바탕으로 코드를 만들면 다음과 같은데요.
byte[] contents = Encoding.ASCII.GetBytes("[...ID...]:[...PASSWORD...]");
string authText = Convert.ToBase64String(contents);
string authHeader = "Basic " + authText;
WebClient wc = new WebClient();
wc.Headers.Add("Authorization", authHeader);
string respText = wc.DownloadString("http://...공유기IP.../cgi-bin/timepro.cgi?tmenu=main_frame&smenu=main_frame");
Console.WriteLine(respText);
그런데, 이런 인증 부분을 WebClient의 경우 자동으로 처리해 주는 Credentials 속성을 가지고 있습니다. 따라서 좀 더 간단하게는 다음과 같이 코딩하는 것이 가능합니다.
static void Main(string[] args)
{
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("kevin", "pwtest");
string respText = wc.DownloadString("http://192.168.1.2/cgi-bin/timepro.cgi?tmenu=main_frame&smenu=main_frame");
Console.WriteLine(respText);
}
닷넷의 경우에 일부 공유기와의 통신에 다음과 같은 식으로 오류가 발생할 수 있습니다.
Unhandled Exception: System.Net.WebException: The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF
at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
at System.Net.WebClient.DownloadString(Uri address)
at ConsoleApplication1.Program.Main(String[] args) in d:\ConsoleApplication1\Program.cs:line 20
검색해 보니 답이 나오는군요. ^^
C#: Handling WebClient “protocol violation”
; http://stackoverflow.com/questions/3142403/c-handling-webclient-protocol-violation
따라서 app.config에 아래의 설정을 추가하면 해결됩니다.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing = "true"/>
</settings>
</system.net>
</configuration>
첨부된 파일은 위의 모든 사항이 반영된 예제입니다.
[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]