달력

52024  이전 다음

  • 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
  • 31

JSP XSS Filter

Develope/JSP 2014. 4. 2. 15:50
반응형

출처 : http://shonm.tistory.com/m/post/425



웹 페이지 입력 란에

 

<script> alert('1111'); </script>

 

이런 식으로 입력을 하면 입력 정보를 불러 올 때 alert 가 뜨게 될 수 있는데...

 

이게 악성 스크립트를 전송 하여 클릭 시 PC 의 인증 정보를 수집하여

 

공격하는 Cross Site Scripting 이 가능 하다고 본다고 한다.

 

그래서 < , > 등을 입력 받지 못하도록 막아야 한다고 대형 사이트의 보안 권고

 

사항이 나온다.

 

JSP 개발 상황이라면 class 2개 를 만들고 web.xml 에 간단한 filter 추가로

 

해결 할 수 있다.

 

일단 servlet-api.jar 파일을 lib 폴더에 넣는다. (tomcat 등에 있다.)

 

그 다음 class 2 개를 추가 한다.

 

추가 해야 할 class 1

 

package com.incross.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;


public class RequestWrapper extends HttpServletRequestWrapper {

public RequestWrapper(HttpServletRequest servletRequest) {         

super(servletRequest);     

}     

 

public String[] getParameterValues(String parameter) {       

 String[] values = super.getParameterValues(parameter);       

 

 if (values==null)  {                  

  return null;          

 

 }      

 

 int count = values.length;      

 

 String[] encodedValues = new String[count];      

 

 for (int i = 0; i < count; i++) {                

  encodedValues[i] = stripXSS(values[i]); //cleanXSS(values[i]);        

 }       

 

 return encodedValues;    

}     

 

public String getParameter(String parameter) {           

 

 String value = super.getParameter(parameter);           

 

 if (value == null) {                  

  

  return null;                   

  

 }           

 

 //return cleanXSS(value);

 return stripXSS(value);

 

}     

 

public String getHeader(String name) {         

 

 String value = super.getHeader(name);         

 

 if (value == null){             

  return null;         

 }

  

 //return cleanXSS(value);

 return stripXSS(value);

}     

 

private String cleanXSS(String value) {      

 //You'll need to remove the spaces from the html entities below         

 

 value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");         

 

 value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");         

 

 value = value.replaceAll("'", "& #39;");        

 

 value = value.replaceAll("eval\\((.*)\\)", "");         

 

 value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");         

 

 value = value.replaceAll("script", "");        

 

 // HTML transformation characters

 value = org.springframework.web.util.HtmlUtils.htmlEscape(value);


 // SQL injection characters

 value = StringEscapeUtils.escapeSql(value);

 

 return value;     

 

 

public static String stripXSS(String value) {


        if (value != null) {

            // NOTE: It's highly recommended to use the ESAPI library and uncomment the following line to

            // avoid encoded attacks.

            // value = ESAPI.encoder().canonicalize(value);

            // Avoid null characters

            value = value.replaceAll("", "");

            // Avoid anything between script tags

            Pattern scriptPattern = Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE);

            value = scriptPattern.matcher(value).replaceAll("");

            // Avoid anything in a src='...' type of expression

            scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);

            value = scriptPattern.matcher(value).replaceAll("");

 

            scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);

            value = scriptPattern.matcher(value).replaceAll("");


            // Remove any lonesome </script> tag

            scriptPattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE);

            value = scriptPattern.matcher(value).replaceAll("");

 

            // Remove any lonesome <script ...> tag

            scriptPattern = Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);

            value = scriptPattern.matcher(value).replaceAll("");

 

            // Avoid eval(...) expressions

            scriptPattern = Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);

            value = scriptPattern.matcher(value).replaceAll("");

 

            // Avoid expression(...) expressions

            scriptPattern = Pattern.compile("expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);

            value = scriptPattern.matcher(value).replaceAll("");


            // Avoid javascript:... expressions

            scriptPattern = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE);

            value = scriptPattern.matcher(value).replaceAll("");

 

            // Avoid vbscript:... expressions

            scriptPattern = Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE);

            value = scriptPattern.matcher(value).replaceAll("");

 

            // Avoid onload= expressions

            scriptPattern = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);

            value = scriptPattern.matcher(value).replaceAll("");


    // HTML transformation characters

    value = org.springframework.web.util.HtmlUtils.htmlEscape(value);

    // SQL injection characters

    value = StringEscapeUtils.escapeSql(value);

        }

        return value;

    }


 

}


>>>>>>>>>> 내가 좀 손본거임...ㅎㅎ cleanXSS=>stripXSS

 

 

===============================================================

추가 해야 할 class 2

 

package com.incross.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class CrossScriptingFilter implements Filter {

 public FilterConfig filterConfig;
 
 public void init(FilterConfig filterConfig) throws ServletException { 
        this.filterConfig = filterConfig;    
 }    

 public void destroy() {
         this.filterConfig = null;     
 }    

 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {        

  chain.doFilter(new RequestWrapper((HttpServletRequest) request), response);     
 } 
 
}

 

================================================================

web.xml 에 추가 해야 할 사항

 

<filter>     
 <filter-name>XSS</filter-name>     
 <filter-class>com.incross.util.CrossScriptingFilter</filter-class> 
</filter>

<filter-mapping>     
 <filter-name>XSS</filter-name>     
 <url-pattern>/*</url-pattern> 
</filter-mapping>















================================================================


출처 : http://www.javablog.fr/java-security-cross-site-scripting-xss-and-sql-injection.html

A simple post concerning the Cross Site Scripting (XSS) and SQL injection which are types of security vulnerability used in Web applications. In SQL-Injection the vulnerability is exploited by injecting SQL Queries as user inputs. In XSS, Javascript code is injected (basically client side scripting) to the remote server (persistente or non-persistent). For more information, Wikipedia is a good source http://en.wikipedia.org/wiki/Cross-site_scripting andhttp://en.wikipedia.org/wiki/SQL_injection.



Cross Site Scripting (XSS)
XSS injects executable code via the GET or POST parameters in HTTP requests. So, here, I would present an example of special characters (<, >, ‘, …) transformation into their HTML code in order to not be executed by the browser.

An example of XSS attack could be filling javascript code in in form’s field:

1"/><script>alert(xss attack);</script>



SQL injection
SQL injection is a code injection technique, used to attack data driven applications, in which malicious SQL statements are inserted into an entry field for execution.
A best-pratice is no use the concatenation of SQL queries and variables like:

1"SELECT id, name FROM TABLE_PERSON WHERE id="+myIdVariable;"

…instead, use the parametrized queries via the PreparedStatement.

An example of SQL injection could be:

1.../mycontext/myservice.do?name=12&id=123' AND '1'=='1'--



Solution and implementation
First, we create HTTP filter RequestWrappingFilter in order to intercept the HTTP request configured in the web.xml file:

1<filter>
2<filter-name>RequestWrappingFilter</filter-name>
3<filter-class>com.huo.filter.RequestWrappingFilter</filter-class>
4</filter>
5 
6<filter-mapping>
7<filter-name>RequestWrappingFilter</filter-name>
8<url-pattern>/*</url-pattern>
9</filter-mapping>

… the goal of this filter is to wrapper the request into an own-coded wrapperMyHttpRequestWrapper which transforms:

01package com.huo.filter;
02 
03import java.io.IOException;
04 
05import javax.servlet.Filter;
06import javax.servlet.FilterChain;
07import javax.servlet.FilterConfig;
08import javax.servlet.ServletException;
09import javax.servlet.ServletRequest;
10import javax.servlet.ServletReponse;
11import javax.servlet.http.HttpServletRequest;
12 
13public class RequestWrappingFilter implements Filter{
14 
15    public void doFilter(ServletRequest req, ServletReponse res, FilterChain chain)throws IOException, ServletException{
16        chain.doFilter(new MyHttpRequestWrapper(req), res);
17    }
18 
19    public void init(FilterConfig config) throws ServletException{
20    }
21 
22    public void destroy() throws ServletException{
23    }
24}
01package com.huo.filter;
02 
03import java.util.HashMap;
04import java.util.Map;
05 
06import javax.servlet.ServletException;
07import javax.servlet.http.HttpServletRequest;
08import javax.servlet.http.HttpServletRequestWrapper;
09 
10import org.apache.commons.lang.StringEscapeUtils;
11 
12public class MyHttpRequestWrapper implements HttpServletRequestWrapper{
13    private Map<String, String[]> escapedParametersValuesMap = new HashMap<String, String[]>();
14 
15    public MyHttpRequestWrapper(HttpServletRequest req){
16        super(req);
17    }
18 
19    @Override
20    public String getParameter(String name){
21        String[] escapedParameterValues = escapedParametersValuesMap.get(name);
22        String escapedParameterValue = null;
23        if(escapedParameterValues!=null){
24            escapedParameterValue = escapedParameterValues[0];
25        }else{
26            String parameterValue = super.getParameter(name);
27 
28            // HTML transformation characters
29            escapedParameterValue = org.springframework.web.util.HtmlUtils.htmlEscape(parameterValue);
30             
31            // SQL injection characters
32            escapedParameterValue = StringEscapeUtils.escapeSql(escapedParameterValue);
33             
34            escapedParametersValuesMap.put(name, new String[]{escapedParameterValue});
35        }//end-else
36         
37        return escapedParameterValue;
38    }
39 
40    @Override
41    public String[] getParameterValues(String name){
42        String[] escapedParameterValues = escapedParametersValuesMap.get(name);
43        if(escapedParameterValues==null){
44            String[] parametersValues = super.getParameterValues(name);
45            escapedParameterValue = new String[parametersValues.length];
46 
47            //
48            for(int i=0; i<parametersValues.length; i++){
49                String parameterValue = parametersValues[i];
50                String escapedParameterValue = parameterValue;
51                 
52                // HTML transformation characters
53                escapedParameterValue = org.springframework.web.util.HtmlUtils.htmlEscape(parameterValue);
54             
55                // SQL injection characters
56                escapedParameterValue = StringEscapeUtils.escapeSql(escapedParameterValue);
57             
58                escapedParameterValues[i] = escapedParameterValue;
59            }//end-for
60             
61            escapedParametersValuesMap.put(name, escapedParameterValues);
62        }//end-else
63         
64        return escapedParameterValues;
65    }
66}


반응형
Posted by 친절한 웬디양~ㅎㅎ
|
반응형

 출처 : http://blog.naver.com/musasin84?Redirect=Log&logNo=60195725004

JSP에서 객체를 초기화하고, DB접속을 하며 수 많은 상단에 선언되었던 내용들이 사라지고, 서블릿에서 request.setAttribute(key, value)에 담았던 값을 getAttribute(key)로 얻어오는 것 이외에는 전혀 달라질 게 없다. 참! *.jsp로 되었던 URL이 *Servlet 으로 바뀐 점!

 

변경된 boardList.jsp 

크게 설명할게 없을 정도로 간결해졌다. 서블릿에서 설정한 값들을 빼와 변수에 담았을 뿐!

약 250line던 소스가 약 110line으로 줄었다.

 

  <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

  <%@ page import="model.board.BoardModel, java.util.List" %>

  <%

      List<BoardModel> boardList = (List<BoardModel>)request.getAttribute("boardList");

      BoardModel boardModel = (BoardModel)request.getAttribute("boardModel");

      int totalCount = (Integer)request.getAttribute("totalCount");

      String searchText = boardModel.getSearchText();

      String searchType = boardModel.getSearchType();

      String searchTextUTF8 = new String(searchText.getBytes("ISO-8859-1"), "UTF-8");

      int pageNum = Integer.parseInt(boardModel.getPageNum());

      int listCount = boardModel.getListCount();

      int pagePerBlock = boardModel.getPagePerBlock();

      String pageNavigator = (String)request.getAttribute("pageNavigator");

  %>

 

 

그외 등록, 보기, 수정도 다 이런식이다. 이렇게 간결해지면서 HTML/CSS/SCRIPT에 더 집중할 수 있게 해주고, 뭐랄까? 개발자로서 작성된 소스들이 이뻐보인달까~ 

 

JSTL/EL 활용

JSTL (JSP Standard Tag Library)와 EL (Expression Language)는 위의 boardList.jsp 소스를 더 간결하게 해주는 아주 유용한 것들이다. 서블릿에서 설정했던 값들을 getAttribute()를 통해 일일이 얻어와 사용했던 방법을 짧은 표현식으로 쉽게 얻게 해준다. 이 JSTL과 EL은 지금 시점에도 많이 사용되기 때문에 알아두면 좋다.

 

JSTL (JSP Standard Tag Library)

JSTL를 사용하기위해서는 라이브러리(*.jar)파일이 필요하다. (사이트

사이트에 들어가보면 Servlet/JSP 버젼에 맞게 사용할 수 있다.

 

 

다운을 받는 *.jar 파일을 /WEB-INF/lib 안에 넣어 사용해야 한다. 

 

(board : JSTL이 적용된 파일, board_nouse_jstl : JSTL이 적용되기 전 파일)

 

그리고 최상단에 사용할 태그라이브러리를 선언하자.

 

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

    <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

 

 

Core 태그라이브러리와 Function 태그라이브러리를 선언했다. 올바르게 선언되었다면 JSP에서 "<c:"를 치는 순간 자동완성기능이 표시되는 모습을 볼 수 있다.

 

 

태그라이브러리를 사용하기 위해서는 사용법을 익힐 필요가 있는 데 잘 정리되어 있는 사이트가 있어 이 곳을 참고하자.

  - EL (http://cafe.naver.com/buldon/1057)

  - EL, Function (http://wiki.gurubee.net/pages/viewpage.action?pageId=983139&)

  - Core (http://wiki.gurubee.net/display/DEVSTUDY/2.+Core+Tag)

(일반적으로 사용했던 제어문, 비교문, 반복문 등 문법이 바뀐다는 걸 알아둬야 한다.)

 

JSTL/EL 사용 전

JSTL/EL 사용 후 

  if ('TEST'.equals('TEST')) { }

  <c:if test="'TEST' eq 'TEST'"><c:if> 

  String str = request.getAttribute('key');

  <c:out value="${key}" /> or ${key}

  for (int i=0; i<boardList.size(); i++) {

    BoardModel board = boardList.get(i);

    board.getSubject()

  }

  <c:forEach var="board" items="${boardList}"

           varStatus="status">

       <c:out value="${board.subject}" />

  </c:forEach>

  request.getContextPath()/board/

  <c:url value="/board/" />

 if (true) { } else { }

  <c:choose>

     <c:when test="${true}">

     </c:when>

     <c:otherwise>

     </c:otherwise>

  </c:choose>

 

이 외에도 많다. 다른 문법이기때문에 사용법을 필히 익힐 필요가 있다. 

 

왜 써야하는 지 잘 모를 수 있으니 얼마나 간결해지는 지 한번 더 보자.

 JSTL/EL 사용 전

 

  <%

        BoardModel boardModel = (BoardModel)request.getAttribute("boardModel");

        int totalCount = (Integer)request.getAttribute("totalCount");

        String searchText = boardModel.getSearchText();

   %>

   <p><%=boardModel.getSubject()%></p>

   <p><%=boardModel.getContents()%></p>

   <p><%=totalCount %></p>

   <p><%=searchText %></p>

 

 

 JSTL/EL 사용 후

 

   <p><c:out value="${boardModel.subject}" /></p>

   <p>${boardModel.contents}</p>

   <p>${totalCount}</p>

   <p>${boardModel.searchText}</p>

 

 

확연히 차이가 날 수밖에 없다. 서블릿에서 설정된 속성값들을 바로 쓸 수 있는 큰 장점이 있다. 그리고 이클립스에서 태그라이브러리는 HTML태그와 글자색이 동일해 뭔가 모르게 깔끔한 느낌을 준다. ㅋ 

 

마무리

이번에 작성한 내용은 JSTL/EL의 사용법을 설명하기보다는 사용함으로써의 이점을 설명하는 데 주력했다. (사용법은 위 URL에서 확인)

 

 

 

 

반응형
Posted by 친절한 웬디양~ㅎㅎ
|
반응형
출처 : http://mediakorea.net/sirboard/board_view.php?sm_id=JSPstudy&sb_id=311&search_category=&search_select=&search_text=&search_op=&page=16&next_num=

1. JSP와 서블릿 상호호출

서JSP는 디자인 중심, 서블릿은 기능 중심의 페이지에 적당합니다. 사이트를 만든다고 하면 기능 중심의 사이트는 서블릿이 좋을 것이고, 디자인 중심의 사이트는 JSP가좋습니다. 간혹 서블릿 중심 디자인의 핵심 기술인 서블릿에서 JSP페이지를 호출하는 방법이 있습니다.

(1) 서블릿에서 JSP호출

서블릿에서 JSP를 호출하려면 다음과 같은 코드를 서블릿에 작성해야 합니다.

RequestDispatcher rd;

rd = getServletContext().getRequestDispatcher(" JSP파일 경로");

rd.forward(request,response);


서블릿에서 JSP를 호출하면서 데이터를 넘기고자 한다면, 다음과 같은 코드가 와야합니다.

request.setAttribute(name,value);


다. value자리에는 모든 종류의 오브젝트가 올 수 있습니다. Vector 클래스를 이용한다면 복수 개의 데이터로 한번에 넘길 수 있습니다. JSP에서 이용하고자 한다면 JSP페이지에 다음과 같이 작성하면 됩니다.

request.getAttribute(name);


(2) JSP에서 서블릿 호출하기

JSP페이지에서 서블릿을 호출하는 방법은 JSP페이지에서 <jsp:forward>액션을 다음과 같이 하면 됩니다.

<jsp:forward page="서블릿 클래스 경로"/>


jsp페이지에서 추가적인 데이터를 서블릿으로 보내고자 한다면 <jsp:param>액션을 이용하면 됩니다.

jsp:forward page="서블릿 클래스 경로"

        <jsp : param name = "name" value="value"/>

        ( <jsp: param> 필요한 만큼 반복)

</jsp:forward>


이외 참고...... http://www.voiceportal.co.kr/731

반응형
Posted by 친절한 웬디양~ㅎㅎ
|
반응형
SimpleDateFormat 을 이용한 현재 시간 구하기


java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyyMMdd HH:mm:ss", java.util.Locale.KOREA);
Long reg_date = Long.parseLong(formatter.format(new java.util.Date()));



"yyyyMMddHHmmss = 년월일시분초" 이 부분 응용해서 적용하면 됨..

년월일을 얻고 싶을 경우에는 아래와 같이 하면 된다.
= new java.text.SimpleDateFormat("yyyyMMdd", java.util.Locale.KOREA);

위 예제에서는 Long 타입으로 변수 대입을 했는데
int형이나 String형으로 상황에 맞게 대입시키면 된다.


반응형
Posted by 친절한 웬디양~ㅎㅎ
|