티스토리 뷰


출처 : mungchung.com


<%
    '////////////////////////////////////////////////////////////////////
    '//가.  명령어 삽입(Command Injection) 가능성
    '////////////////////////////////////////////////////////////////////
    Dim title, str
    title = "What's Up!!! <what happen> Oh my god!!!! & goodness"
    str = ""
    //변환을 수행할 함수
    Sub ReplaceStr(content, byref str)
        content = replace(content, "'", """)
        content = replace(content, "&", "&")
        content = replace(content, "<", "<")
        content = replace(content, ">", ">")
       
        str = content
    End Sub

    ReplaceStr title, str
    response.write str
%>

'////////////////////////////////////////////////////////////////////
'//나.  크로스 사이트 스크립팅 (XSS) 가능성
'////////////////////////////////////////////////////////////////////
/include/config.inc.asp
<%
    atag = "p,br"       'XSS 허용할 태그 리스트
    UploadedPath = "/Uploaded_Files/"   '업로드 기본 경로
    fileext = "jpg,gif,png,pcx"     '허용할 확장자 리스트
%>


/include/secure.inc.asp
<%
    '공격 위험성이 존재하는 문자들을 필터링
    '문자열 입력값을 검증
    '숫자형은 데이터 타입을 별도로 체크하도록 한다.
    Function sqlFilter(search)
        Dim strSearch(5), strReplace(5), cnt, data
       
        'SQL Injection 특수문자 필터링
        '필수 필터링 문자 리스트
        strSearch(0)="'"
        strSearch(1)=""""
        strSearch(2)="\"
        strSearch(3)=null
        strSearch(4)="#"
        strSearch(5)="--"
        strSearch(6)=";"

        '변환될 필터 문자  
        strReplace(0)="''"
        strReplace(1)=""""""
        strReplace(2)="\\"
        strReplace(3)="\"&null
        strReplace(4)="\#"
        strReplace(5)="\--"
        strReplace(6)="\;"
       
        data = search
        For cnt = 0 to 6 '필터링 인덱스를 배열 크기와 맞춰준다.
            data = replace(data, LCASE(strSearch(cnt)), strReplace(cnt))
        Next

        sqlFilter = data
    End Function

    'XSS 출력 필터 함수
    'XSS 필터 함수
    '$str - 필터링할 출력값
    '$avatag - 허용할 태그 리스트 예)  $avatag = "p,br"
    Function clearXSS(strString, avatag)
        'XSS 필터링
        strString = replace(strString, "<", "<")
        strString = replace(strString, "\0", "")
       
        '허용할 태그 변환
        avatag = replace(avatag, " ", "")       '공백 제거
        If (avatag <> "") Then
            taglist = split(avatag, ",")
       
            for each p in taglist
                strString = replace(strString, "<"&p&" ", "<"&p&" ", 1, -1, 1)
                strString = replace(strString, "<"&p&">", "<"&p&">", 1, -1, 1)
                strString = replace(strString, "</"&p&" ", "</"&p&" ", 1, -1, 1)
            next
        End If
       
        clearXSS = strString
    End Function

    '확장자 검사
    '$filename: 파일명
    '$avaext: 허용할 확장자 예) $avaext = "jpg,gif,pdf"
    '리턴값: true-"ok", false-"error"
    Function Check_Ext(filename,avaext)
        Dim bad_file, FileStartName, FileEndName
       
        If instr(filename, "\0") Then
            Response.Write "허용하지 않는 입력값"
            Response.End
        End If
       
        '업로드 금지 확장자 체크
        bad_file = "asp,html,htm,asa,hta"
       
        filename = Replace(filename, " ", "")
        filename = Replace(filename, "%", "")

        FileStartName = Left(filename,InstrRev(filename,".")-1)
        FileEndName = Mid(filename, InstrRev(filename, ".")+1)
           
        bad_file = split(bad_file, ",")

        for each p in bad_file
            if instr(FileEndName, p)>0 then
                Check_Ext = "error"
                Exit Function
            end if
        next
       
        '허용할 확장자 체크
        if avaext <> "" Then
            ok_file = split(avaext, ",")
       
            for each p in ok_file
                if instr(FileEndName, p)>0 then
                    Check_Ext = "ok"
                    Exit Function
                End If
            next
        End If
       
        Check_Ext = "error"
    End Function

    '다운로드 경로 체크 함수
    '$dn_dir - 다운로드 디렉토리 경로(path)
    '$fname - 다운로드 파일명
    '리턴 - true:파운로드 파일 경로, false: "error"
    Function Check_Path(dn_dir, fname)
        '디렉토리 구분자를 하나로 통일
        dn_dir = Replace(dn_dir, "/", "\")
        fname = Replace(fname, "/", "\")
       
        strFile = Server.MapPath(dn_dir) & "\" & fname '서버 절대경로
       
        strFname = Mid(fname,InstrRev(fname,"\")+1) '파일 이름 추출, ..\ 등의 하위 경로 탐색은 제거 됨
        Response.Write strFname
       
        strFPath = Server.MapPath(dn_dir) & "\" & strFname '웹서버의 파일 다운로드 절대 경로

        If strFPath = strFile Then
            Check_Path = strFile '정상일 경우 파일 경로 리턴
        Else
            Check_Path = "error"
        End If
    End Function

    'IP 체크 함수
    Function Check_IP(IP_Addr)
        If Request.Servervariables("REMOTE_ADDR") = IP_Addr Then
            Check_IP = "TRUE"
        Else
            Check_IP = "FALSE"
        End If
    End Function
%>



/head.asp
<%
    '페이지에서 에러가 발생하여도 페이지 오류를 외부로 출력하지 않기위해 사용
    On Error Resume Next
    'On Error GoTo 0도 가능하나 2003에서는 실행되지 않음
    if err.number <> 0 then
        'Response.Write err.description & "<BR>" & err.source & "<BR>"
        err.clear
    End if
%>


/content.asp
<!--#include virtual="/include/connection.inc.asp"-->   <% 'DB연결 헤더 %>
<!--#include virtual="/include/secure.inc.asp"-->   <% '보안관련라이브러리 %>
<!--#include virtual="/include/config.inc.asp"-->   <% '전역변수리스트 %>
<!--#include virtual="/head.asp"-->             <% '초기 설정 페이지(에러 메세지 미출력) %>
<%
    Dim strSQL
    Dim intSeq, strName, strEmail, strSubject, strContent, intCount, dtmReg_Date, intExist
    Dim blnTag, strUserIP
    Dim atag

    '입력값이 숫자형인 경우 IsNumeric 함수를 사용한다.
    If IsNumeric(seq) Then
        intSeq = Request.QueryString("seq")
    Else
        Response.Write "허용하지 않는 입력값입니다."
        Reponse.End
    End If

    '문자(열)인 경우 sqlfilter 사용
    'intSeq = sqlFilter(Request.QueryString("seq")) 'SQL Injection 필터링

    '읽은 횟수 검색
    strSQL = "SELECT count(*) FROM board WHERE intSeq='" & intSeq & "'"

    objRs.Open strSQL, objDBConn

    intExist = objRs(0)
    objRs.Close

    If intExist <> 1 Then
        Response.Write "해당글이 없습니다."
    Else
        '읽은 횟수 증가
        strSQL = "UPDATE board SET intCount=intCount+1 WHERE intSeq='" & intSeq & "'"
        objRs.Open strSQL, objDBConn

        '게시물 SELECTZ
        strSQL = "SELECT strName,strEmail,strSubject,strContent,intCount,strUserIP,blnTag,dtmReg_Date FROM board WHERE intSeq='" & intSeq & "'"
        objRs.Open strSQL, objDBConn

        strName = objRs(0)
        strEmail = objRs(1)
        strSubject = objRs(2)
        strContent = objRs(3)
        intCount = objRs(4)
        strUserIP = objRs(5)
        blnTag = objRs(6)
        dtmReg_Date = objRs(7)

        objRs.Close
        Set objRs = Nothing

        objDBConn.Close
        Set objDBConn = Nothing

        '게시물 출력값에 XSS 필터링
        '사용자가 입력하는 출력되는 값은 strName, strEmail, strSubject, strContent으로 이 부분은 XSS 공격이 가능한 부분들이다.
        '일반적으로 본문만 선택적으로 HTML 태그 사용을 허용하며 나머지 부분들은 사용할 수 없도록 하는것이 바람직하다.
        strName = clearXSS(strName, atag)
        strEmail = clearXSS(strEmail, atag)
        strSubject = clearXSS(strSubject, atag)
        strContent = clearXSS(strContent, atag)
       
        '줄넘김 처리
        strContent = replace(strContent, vbLf, vbLf & "<br>")
%>

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=ks_c_5601-1987">
<title>내용보기</title>
</head>

<body>
<div align=center>
<table border=1>
<tr>
    <td>이름</td>
    <td><%=strName%></td>
    <td>등록일</td>
    <td><%=dtmReg_Date%></td>
</tr>
<tr>
    <td>이메일</td>
    <td><%=strEmail%></td>
    <td>조회</td>
    <td><%=intCount%></td>
</tr>
<tr>
    <td>제목</td>
    <td colspan=3><%=strSubject%></td>
</tr>
<tr>
    <td>내용</td>
    <td colspan=3><%=strContent%></td>
</tr>
<tr>
    <td colspan=4>
    <a href="list.asp">목록으로</a> <a href="edit.asp?seq=<%=intSeq%>">수정하기</a> <a href="delete.asp?seq=<%=intSeq%>">삭제하기</a>
    </td>
</tr>
</table>

</div> 
</body>
</html>

<%
    End If
%>



'////////////////////////////////////////////////////////////////////
'//다.  SQL 구문 삽입 가능성
'////////////////////////////////////////////////////////////////////
SQL Injection은 쿼리문의 잘못 해석함에서 발생하는 문제이다. 이를 해결하기 위해서는 쿼리문을 생성시에 입력된 값에 대한 유효성 검사를 수행하면 된다. ‘, “ 문자를 \’, \”로 변경해 주거나 아예 공백으로 처리하는 방법이다.

삭제해야 할 프로시저
xp_cmdshell
xp_stratmail
xp_sendmail
xp_grantlogin
xp_makewebtask


'////////////////////////////////////////////////////////////////////
'//사.  다운로드 취약성
'////////////////////////////////////////////////////////////////////
<!--#include virtual="/include/connection.inc.asp"-->   <% 'DB연결 헤더 %>
<!--#include virtual="/include/secure.inc.asp"-->       <% '보안관련라이브러리 %>
<!--#include virtual="/include/config.inc.asp"-->       <% '전역변수리스트 %>
<!--#include virtual="/head.asp"-->         <% '초기 설정 페이지(에러 메세지 미출력) %>
<%
    Dim dn_dir, fname, val_ok
    Dim UploadedPath

    dn_dir = Request("dir")
    fname = Request("fname")    '파일 이름

    ' IE 5.01에서는 이 방식을 사용할때 메모리 관련 문제가 발생할 수 있다.
    strUA = Request.ServerVariables("HTTP_USER_AGENT")
    If Instr(strUA, "MSIE") Then
        intVersion = CDbl(mid(strUA, Instr(strUA, "MSIE")+5, 3))

        If intVersion < 5.01 Then
            Response.Write "error"
        End If
    End If

    if fname = "" Then
        Response.Write "<script language=javascript>"
        Response.Write "alert(""파일명을 입력해 주세요"");"
        Response.Write "history.back();"
        Response.Write "</script>"
    End If

    dn_dir = UploadedPath & dn_dir
    val_ok = Check_Path(dn_dir, fname)

    If  val_ok <> "error" Then  '사용자가 다운 받는 파일과 웹서버의 파일 다운로드 경로가 맞는지 비교
        Set objStream = Server.CreateObject("ADODB.Stream") 'Stream 이용

        Response.ContentType = "application/unknown"    'ContentType 선언
        Response.AddHeader "Content-Disposition","attachment; filename=" & fname
       
        objStream.Open
        objStream.Type = 1
        objStream.LoadFromFile val_ok

        download = objStream.Read
        Response.BinaryWrite download
    End If

    Set objstream = nothing '객체 초기화
%>
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함