posted by 방랑군 2012. 1. 7. 20:50


출처 : 
http://blog.naver.com/PostView.nhn?blogId=inidu2&logNo=110122998191&parentCategoryNo=33&viewDate=&currentPage=1&listtype=0&from=postList&userTopListOpen=true&userTopListCount=10&userTopListManageOpen=false&userTopListCurrentPage=1 

테스트를
 여러  하긴 했으나 예상치 못한 예외 상황이 있을수도 있습니다.


고려사항 : 에디터 사용유무 판단, ajax 통신을 위한 json 형태 결과 반환

인코딩 처리는 서버쪽에서만 처리.  폼으로 넘길  하지 않고 디비 저장전에 인코딩 처리.



Sql injection 방어 코딩 – 모든 입력폼값이 적용 

1.     입력

기본적으로 ‘ => '  ,  “ => " 문자만 모두 치환해도 sql 조작이 불가능해짐.

쿼리 실행 전에 특수문자와 html 태그 변환  에디터 사용 여부에 따라 구분해서 인코딩

DB 클래스 내부에서 인코딩되므로 폼값에 별도 처리 없이 그대로 넘김

 

2.     출력 – ajax 통신으로 결과를 json으로 받아서 처리하는 것을 기준.

페이지에 뿌려줄때

-       muse.htmlEncode(data.LIST[i].title) html 인코딩 처리를 해서 html 태그로 페이지가 깨지는 것을 방지

 

폼에 뿌려줄 

-       html 디코딩 처리 $("[name='title']").val(muse.htmlDecode(data.title));

 

에디터에 뿌려줄 때

-      받은 json 을 그대로 입력 $('#contents').val(data.contents);



 

 

 

js

 쿼리 결과를 json으로 받아서 보여줄  사용

 

 

    /**

     * html encode

     */

    htmlEncode: function (str) {

        return str.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/ /g, "&nbsp;").replace(/\n/g, "<br />").replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;");

    },

   

    /**

     * html decode

     */

    htmlDdecode: function (str) {

        return str.replace(/&lt;/g, "<").replace(/&gt;/g, ">");

    }

 

 

 

 

 DB.cs

 디비에 입력, 수정할  필드값 EncodeString하고 가져올   필드 DecodeString, 조건절에 Filtering으로 특수 문자 삭제

 

 

/// <summary>

    /// SQL 인젝션 필터 - Select 에서 조건절 필터링

    /// </summary>

    private static string Filtering(string inputSQL)

    {

        return inputSQL.Replace(":", "").Replace("+", "").Replace(";", "").Replace("--", "").Replace("\"", "");

    }

 

 

    /// <summary>

    /// 데이타베이스 인젝션 방어 문자열 반환

    /// </summary>

    /// <param name="source">원문</param>

    /// <returns></returns>

    public static string EncodeString(string source)

    {

        if (source.IndexOf("&lt;") == -1) // 인코딩 안된 경우

        {

            source = System.Web.HttpUtility.HtmlEncode(source); // ', " 제외

        }

        source = source.Replace("\"", "&quot;").Replace("'", "&#39;");

 

        return source;

    }

 

    public static string DecodeString(string source)

    {

        source = source.Replace("&#39;", "'").Replace("&quot;", "\"").Replace("/", "\\/").Replace("\n", "\\n").Replace("\t", "\\t").Replace("\r", "\\r").Replace("\x08", "\\b").Replace("\x0c", "\\f").Replace("\"", "\\\"");

        if (source.IndexOf("<") == -1) // 에디터에 넘길 경우

        {

            source = System.Web.HttpUtility.HtmlDecode(source);

        }

 

        return source;

    }