close

Trust Me!! Trust You!!


  • Blog
  • Local Log
  • Tag Cloud
  • Key Log
  • Guestbook
  • RSS Feed
  • Write a Post
  • Admin

혹시 블로그 스킨이 깨져 보이시나요? 최신버전의 Internet Explorer(Windows용), Opera, Firefox를 사용해보세요.

Found 1 article(s) for '보안'.

  1. 2013/04/06 Simple Cross Site Scripting (XSS) Servlet Filter

Simple Cross Site Scripting (XSS) Servlet Filter

웹 프로그래밍
2013/04/06 00:03
 

Simple Cross Site Scripting (XSS) Servlet Filter

Ran into some issues on some of our Java sites today and needed a quick fix to protect the sites from malicious Cross Site Scripting (XSS) attempts. If you're not aware of what XSS is and have websites that have sensitive user data, you may want to read up, you're probably vulnerable, which means your users are vulnerable. I'm not claiming this is a perfect solution, but it was easy to implement and corrected the vulnerabilities with form and url injection. We basically have a Servlet Filter that's going to intercept every request sent to the web application and then we use an HttpServletRequestWrapper to wrap and override the getParameter methods and clean any potential script injection.


Here's the Filter:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.greatwebguy.filter;
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 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);
    }
}

Here's the wrapper:

?
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
32
33
34
35
36
37
38
39
40
41
42
43
package com.greatwebguy.filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public final 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] = cleanXSS(values[i]);
       }
      return encodedValues;
    }
    public String getParameter(String parameter) {
          String value = super.getParameter(parameter);
          if (value == null) {
                 return null;
                  }
          return cleanXSS(value);
    }
    public String getHeader(String name) {
        String value = super.getHeader(name);
        if (value == null)
            return null;
        return cleanXSS(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", "");
        return value;
    }
}

Add this to the top of your web.xml:

?
1
2
3
4
5
6
7
8
9
10
<filter>
    <filter-name>XSS</filter-name>
    <display-name>XSS</display-name>
    <description></description>
    <filter-class>com.greatwebguy.filter.CrossScriptingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>XSS</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

I'm sure the cleanXSS replacements aren't the most efficient way of doing this, you could replace it StringEscapeUtils.escapeHtml from commons lang to simplify it a little, it's up to you, it all depends on what your site is doing and whether it's going to be a pain having all the html escaped, you could also adjust the url-pattern of the filter to be more specific to your application urls, so that everything under your app isn't running through the filter.

Some things to be aware of with this approach, you'll need to account for what you've encoded or in some cases you'll end up with weird characters in your database and possibly in validation of your input boxes. Some would recommend a more positive validation rather than negative validation and only allow a certain range of characters, it's up to you, but it is something to think about.



value = value.replaceAll(“(?i)script”, “”); instead of
value = value.replaceAll(“(?i)script”, “”); for a case insensitive replacement.



NHN 공개 XSS Filter
http://local.dev.naver.com/projects/lucy-xss/download


이올린에 북마크하기
TAG Filter, javascript, JSP, Servlet, XSS, 보안
Trackback 3 / No comment.

Trackback Address :: http://viper150.cafe24.com/trackback/209

You can also say.

Prev 1 Next
블로그 이미지
이것저것 불펌금지도 퍼다가 담습니다. 외부에 비공개된 페이지 입니다. By. 어른왕자

카테고리

  • 전체 (298)
    • 사는 이야기 (115)
    • 웹 프로그래밍 (102)
    • App 프로그래밍 (22)
    • IT 뉴스&기타 (22)
    • 박한별 (4)
    • 역사&기타지식 (9)

태그목록

  • substr
  • 갤럽
  • 김용환
  • 아이폰
  • 너클볼
  • 계산
  • 락산
  • 바코드
  • 기린
  • Image Buttron
  • plugin
  • 1.6
  • 간편운동
  • 톰캣
  • 과음
  • 부부관계
  • jstl
  • 정부
  • DB2 procedure
  • 보안
  • Pop
  • pom.xml
  • FilePathCheckerModuleExample.dll
  • 저장프로시저
  • 唐田
  • 몰카
  • 양제
  • DataMatrix
  • 팬캠
  • PC일체형의자

최근에 올라온 글

  • 보험사의 조정신청 대응방법.
  • 어느 천재의 앞선 시선.
  • [병맛더빙] 누구게..... (1)
  • 韓경제 `회색 코뿔소` 상황...
  • SVN Connector 설치 URL.
  • 군대를 가지 않는 서울대생.
  • “운은 하늘의 귀여움 받는...
  • 목장에서 알바하다가 캐스...
  • [펌]믿고 거르는 관상.
  • 하루에 1세트씩 하면 좋다...

최근에 달린 댓글

  • <p align="center"><a href="h... 라임애드 02/14
  • <div style="OVERFLOW: hidden... 고사니 02/12
  • <p align="center"><a href="h... 라임정보 02/07
  • <p><img src="https://i.imgur... 브레드 01/22
  • <p><img src="https://i.imgur... 브레드 01/22

최근에 받은 트랙백

  • read this post from Bookie 7. read this post from Bookie 7 02/28
  • công ty may đồng phục. công ty may đồng phục 01/08
  • Israelnightclub`s recent blo... Israelnightclub`s recent blo.. 01/06
  • Suggested Browsing. Suggested Browsing 01/06
  • similar site. similar site 01/06

글 보관함

  • 2019/03 (1)
  • 2018/12 (1)
  • 2018/09 (1)
  • 2018/08 (1)
  • 2018/02 (1)

달력

«   2021/03   »
일 월 화 수 목 금 토
  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      

링크

  • Total : 263653
  • Today : 16
  • Yesterday : 41
Tattertools
Eolin
rss

어른왕자's blog is powered byTattertools1.1.2.2 : Animato