java Filter Special Character Operation of xss Attack Solution

  • 2021-10-13 07:24:55
  • OfStack

XSS, full name: cross-site scripting (cross-site scripting), is one of the most dangerous and common vulnerabilities in current web applications. Attackers try to inject malicious script code (often js script) into trusted websites to perform malicious operations. When users browse pages containing malicious scripts with browsers, they will execute this malicious script, which will further affect users (such as endless websites, stealing cookie information of users and pretending to be users to operate), etc.

It is similar to SQL injection, which is also attacked by injecting malicious instructions. However, SQL injection is performed on the server side, while XSS attack is performed on the client side, which is the essential difference between them.

In fact, I feel that it is not necessary to distinguish whether xss attack is reflective XSS, storage XSS or DOM Based XSS, but only need to know how to protect it. The most effective measure of protection is filtering, which filters the content submitted by the front page to the background. The details are as follows:

1. Solution 1

Intercept all request parameters, and contain special characters in request parameters. < 'Or' > 'Filter.


package com.haier.openplatform.srm.base.filter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;
public class StringFilter extends OncePerRequestFilter{
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
chain.doFilter(new StringFilterRequest((HttpServletRequest)request), response);
}
}
class StringFilterRequest extends HttpServletRequestWrapper {
public StringFilterRequest(HttpServletRequest request) {
super(request);
}
@Override
public String getParameter(String name) {
//  Before the return value   Filter first 
return filterDangerString(super.getParameter(name));
}
@Override
public String[] getParameterValues(String name) {
//  Before the return value   Filter first 
String[] values = super.getParameterValues(name);
if(values==null){
return null;
}
for (int i = 0; i < values.length; i++) {
values[i] = filterDangerString(values[i]);
}
return values;
}
@Override
public Map getParameterMap() {
Map keys = super.getParameterMap();
Set set = keys.entrySet();
Iterator iters = set.iterator();
while (iters.hasNext()) {
Object key = iters.next();
Object value = keys.get(key);
keys.put(key, filterDangerString((String[]) value));
}
return keys;
}
/*@Override
public Object getAttribute(String name) {
// TODO Auto-generated method stub
Object object = super.getAttribute(name);
if (object instanceof String) {
return filterDangerString((String) super.getAttribute(name));
} else
return object;
}*/
public String filterDangerString(String value) {
if (value == null) {
return null;
}
//        value = value.replaceAll("\\{", " { ");
value = value.replaceAll("<", "&lt;");
value = value.replaceAll(">", "&gt;");
//        value = value.replaceAll("\t", "    ");
//        value = value.replaceAll("\r\n", "\n");
//        value = value.replaceAll("\n", "<br/>");
//        value = value.replaceAll("'", "&#39;");
//        value = value.replaceAll("\\\\", "&#92;");
//        value = value.replaceAll("\"", "&quot;");
//        value = value.replaceAll("\\}", " In fact, in fact, the ").trim();
return value;
}
public String[] filterDangerString(String[] value) {
if (value == null) {
return null;
}
for (int i = 0; i < value.length; i++) {
String val = filterDangerString(value[i]);
value[i] = val;
}
return value;
}
}

Filter configuration in web. xm:


 <filter>
  <filter-name>StringFilter</filter-name>
  <filter-class>com.xxx.base.filter.StringFilter</filter-class>
 </filter>
 
 <filter-mapping>
  <filter-name>StringFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

2. Solution 2 (turned, not verified)

2.1 Front End Filtering

2.1. 1 javascript native method


// Escape    Element's innerHTML The content is the escaped character   
function htmlEncode ( str ) {  
  var ele = document.createElement('span');  
  ele.appendChild( document.createTextNode( str ) );  
  return ele.innerHTML;  
}  
// Analyse    
function htmlDecode ( str ) {  
  var ele = document.createElement('span');  
  ele.innerHTML = str;  
  return ele.textContent;  
} 

2.1. 2 JQuery method


function htmlEncodeJQ ( str ) {  
    return $('<span/>').text( str ).html();  
}  
function htmlDecodeJQ ( str ) {  
    return $('<span/>').html( str ).text();  
} 

2.1. 3 Invoking a method


var msg1= htmlEncodeJQ('<script>alert('test');</script>');
var msg1= htmlEncode('<script>alert('test');</script>');
// The result becomes: &lt;script&gt;alert('test');&lt;/script&gt;

2.2 Back-end filtering

2.2. 1 java 1 Framework automated tool classes,

For example: org. springframework. web. util. HtmlUtils


public static void main(String[] args) {
    String content = "<script>alert('test');</script>";
    System.out.println("content="+content);
    content = HtmlUtils.htmlEscape(content);
    System.out.println("content="+content);
    content = HtmlUtils.htmlUnescape(content);
    System.out.println("content="+content);
}

But there is a problem, that is, all its html tags are not resolved.

Maybe this is not what you want. What you want is 1 part parsing and 1 part unparsing. Look down there.

2.2. 2 Complete your requirements with regularity yourself


package top.lrshuai.blog.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * 
 * @author lrshuai
 * @since 2017-10-13
 * @version 0.0.1
 */
public class HTMLUtils {
/**
 *  Filter all HTML  Label 
 * @param htmlStr
 * @return
 */
public static String filterHTMLTag(String htmlStr) {
    // Definition HTML Regular expression of tag  
    String reg_html="<[^>]+>"; 
    Pattern pattern=Pattern.compile(reg_html,Pattern.CASE_INSENSITIVE); 
    Matcher matcher=pattern.matcher(htmlStr); 
    htmlStr=matcher.replaceAll(""); // Filter html Label  
    return htmlStr;
}
/**
 *  Filter labels by label name 
 * @param htmlStr
 * @param tagName
 * @return
 */
public static String filterTagByName(String htmlStr,String tagName) {
    String reg_html="<"+tagName+"[^>]*?>[\\s\\S]*?<\\/"+tagName+">";
    Pattern pattern=Pattern.compile(reg_html,Pattern.CASE_INSENSITIVE); 
    Matcher matcher=pattern.matcher(htmlStr); 
    htmlStr=matcher.replaceAll(""); // Filter html Label  
    return htmlStr;
}
/**
 *  Filter on the label  style  Style 
 * @param htmlStr
 * @return
 */
public static String filterHTMLTagInStyle(String htmlStr) {
    String reg_html="style=('|\")(.*?)('|\")";
    Pattern pattern=Pattern.compile(reg_html,Pattern.CASE_INSENSITIVE); 
    Matcher matcher=pattern.matcher(htmlStr); 
    htmlStr=matcher.replaceAll(""); // Filter html Label  
    return htmlStr;
}
/**
 *  Replace expression 
 * @param htmlStr
 * @param tagName
 * @return
 */
public static String replayFace(String htmlStr) {
    String reg_html="\\[em_\\d{1,}\\]";
    Pattern pattern =Pattern.compile(reg_html,Pattern.CASE_INSENSITIVE); 
    Matcher matcher=pattern.matcher(htmlStr);
    if(matcher.find()) {
        matcher.reset();
        while(matcher.find()) {
            String num = matcher.group(0);
            String number=num.substring(num.lastIndexOf('_')+1, num.length()-1);
            htmlStr = htmlStr.replace(num, "<img src='/face/arclist/"+number+".gif' border='0' />");
        }
    }
    return htmlStr;
}
    public static void main(String[] args) {
        String html = "<script>alert('test');</script><img src='/face/arclist/5.gif' border='0' /><div style='position:fixs;s'></div><style>body{color:#fff;}</style><Style>body{color:#fff;}</Style><STYLE>body{color:#fff;}</STYLE>";
        System.out.println("html="+html);
        html = HTMLUtils.filterTagByName(html, "style");
        System.out.println("html="+html);
        html = HTMLUtils.filterTagByName(html, "script");
        System.out.println("html="+html);
        html = HTMLUtils.filterHTMLTagInStyle(html);
        System.out.println("html="+html);
    }
}

java Filter Special String Upgrade

In addition to 32, there is a special space in ASCII, which is 160. The space in db is uninterrupted space- > On the page & Spaces generated by nbsp;


 /**
     *  Filter special characters 
     * @param str
     * @return
     *
     * \u00A0  Special spaces 
     */
    public static String stringFilter (String str){
        String regEx="[\\u00A0\\s\"`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~ ! @# $ % ... &* ()- +|{} "" ';: "" ' . ,,? ]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

Related articles: