跨站點腳本編制和重定向問題
了解網絡安全知識,能夠在編寫代碼時預防常見的跨站腳本攻擊、跨站請求偽造、框架釣魚、SQL註入、直接對象引用等攻擊;
一:解決sql盲註
if (!StringUtil.isAllNullOrEmpty(bt)) {
// 對過閘須知標題進行格式化
String btName = WebUtil.encodeSqlLike(bt.trim(), "/");
// 增加根據過閘須知標題查詢(模糊查詢)
// add by zhangcf 20160622 start
sqlBuildHql.append(" and gzxz.bt like ? escape ‘/‘ ");
//param.add("\‘%" + bt + "%\‘");
param.add("%" + btName + "%");
// add by zhangcf 20160622 end
}
二:跨站點腳本編制和重定向問題
1.創建過濾器類,使其實現Filter
package com.strongit.nj.action.gzfw.servlet;
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;
/**
* @author zhangcf
* @date 20160622
*/
public class XSSFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
request = new XSSServletRequest(request);
filterChain.doFilter(request, res);
}
public void destroy() {
}
}
2.創建XSSServletRequest.Java類,將request請求進行過濾。
package com.strongit.nj.action.gzfw.servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* @author zhangcf
* @date 20160622
*/
public class XSSServletRequest extends HttpServletRequestWrapper {
public XSSServletRequest(HttpServletRequest request) {
super(request);
}
@Override
public String getParameter(String name) {
String string = super.getParameter(name);
// 返回值之前 先進行過濾
return XssFilterUtil.stripXss(string);
}
@Override
public String[] getParameterValues(String name) {
// 返回值之前 先進行過濾
String[] values = super
.getParameterValues(name);
if (values != null) {
for (int i = 0; i < values.length; i++) {
values[i] = XssFilterUtil.stripXss(values[i]);
}
}
return values;
}
}
3.創建過濾器工具類XssFilterUtil.java,
package com.strongit.nj.action.gzfw.servlet;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
/**
* @author zhangcf
* @date 20160622
*/
public class XssFilterUtil {
private static List<Pattern> patterns = null;
private static List<Object[]> getXssPatternList() {
List<Object[]> ret = new ArrayList<Object[]>();
ret.add(new Object[] { "<(no)?script[^>]*>.*?</(no)?script>",
Pattern.CASE_INSENSITIVE });
ret.add(new Object[] { "eval\\((.*?)\\)",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL });
ret.add(new Object[] { "expression\\((.*?)\\)",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL });
ret.add(new Object[] { "(javascript:|vbscript:|view-source:)*",
Pattern.CASE_INSENSITIVE });
ret.add(new Object[] { "<(\"[^\"]*\"|\‘[^\‘]*\‘|[^\‘\">])*>",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL });
ret.add(new Object[] {
"(window\\.location|window\\.|\\.location|document\\.cookie|document\\.|alert\\(.*?\\)|window\\.open\\()*",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL });
ret.add(new Object[] {
"<+\\s*\\w*\\s*(oncontrolselect|oncopy|oncut|ondataavailable|ondatasetchanged|ondatasetcomplete|ondblclick|ondeactivate|ondrag|ondragend|ondragenter|ondragleave|ondragover|ondragstart|ondrop|onerror=|onerroupdate|onfilterchange|onfinish|onfocus|onfocusin|onfocusout|onhelp|onkeydown|onkeypress|onkeyup|onlayoutcomplete|onload|onlosecapture|onmousedown|onmouseenter|onmouseleave|onmousemove|onmousout|onmouseover|onmouseup|onmousewheel|onmove|onmoveend|onmovestart|onabort|onactivate|onafterprint|onafterupdate|onbefore|onbeforeactivate|onbeforecopy|onbeforecut|onbeforedeactivate|onbeforeeditocus|onbeforepaste|onbeforeprint|onbeforeunload|onbeforeupdate|onblur|onbounce|oncellchange|onchange|onclick|oncontextmenu|onpaste|onpropertychange|onreadystatechange|onreset|onresize|onresizend|onresizestart|onrowenter|onrowexit|onrowsdelete|onrowsinserted|onscroll|onselect|onselectionchange|onselectstart|onstart|onstop|onsubmit|onunload)+\\s*=+",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL });
return ret;
}
private static List<Pattern> getPatterns() {
if (patterns == null) {
List<Pattern> list = new ArrayList<Pattern>();
String regex = null;
Integer flag = null;
int arrLength = 0;
for (Object[] arr : getXssPatternList()) {
arrLength = arr.length;
for (int i = 0; i < arrLength; i++) {
regex = (String) arr[0];
flag = (Integer) arr[1];
list.add(Pattern.compile(regex, flag));
}
}
patterns = list;
}
return patterns;
}
public static String stripXss(String value) {
if (null == value) {
return value;
}
if (StringUtils.isNotBlank(value)) {
Matcher matcher = null;
for (Pattern pattern : getPatterns()) {
matcher = pattern.matcher(value);
// 匹配
if (matcher.find()) {
// 刪除相關字符串
value = matcher.replaceAll("");
}
}
value = StringFilter.StringFilter(value);
}
// 預防SQL盲註
String[] pattern = { "%", "select", "insert", "delete", "from",
"count\\(", "drop table", "update", "truncate", "asc\\(",
"mid\\(", "char\\(", "xp_cmdshell", "exec", "master",
"netlocalgroup administrators", "net user", "or", "and" };
for (int i = 0; i < pattern.length; i++) {
value = value.replace(pattern[i].toString(), "");
}
return value;
}
public static void main(String[] args) {
String value = null;
value = XssFilterUtil
.stripXss("<br>select ***//||&;/*-+ <>$###@%$#@$%^#$^%$&^(&*)*\\‘‘count or %% ..... ,,,, ");
System.out.println("type-1: ‘" + value + "‘");
value = XssFilterUtil
.stripXss("<script src=‘‘ onerror=‘alert(document.cookie)‘></script>");
System.out.println("type-2: ‘" + value + "‘");
value = XssFilterUtil.stripXss("</script>");
System.out.println("type-3: ‘" + value + "‘");
value = XssFilterUtil.stripXss(" eval(abc);");
System.out.println("type-4: ‘" + value + "‘");
value = XssFilterUtil.stripXss(" expression(abc);");
System.out.println("type-5: ‘" + value + "‘");
value = XssFilterUtil
.stripXss("<img src=‘‘ onerror=‘alert(document.cookie);‘></img>");
System.out.println("type-6: ‘" + value + "‘");
value = XssFilterUtil
.stripXss("<img src=‘‘ onerror=‘alert(document.cookie);‘/>");
System.out.println("type-7: ‘" + value + "‘");
value = XssFilterUtil
.stripXss("<img src=‘‘ onerror=‘alert(document.cookie);‘>");
System.out.println("type-8: ‘" + value + "‘");
value = XssFilterUtil
.stripXss("<script language=text/javascript>alert(document.cookie);");
System.out.println("type-9: ‘" + value + "‘");
value = XssFilterUtil.stripXss("<script>window.location=‘url‘");
System.out.println("type-10: ‘" + value + "‘");
value = XssFilterUtil.stripXss(" onload=‘alert(\"abc\");");
System.out.println("type-11: ‘" + value + "‘");
value = XssFilterUtil.stripXss("<img src=x<!--‘<\"-->>");
System.out.println("type-12: ‘" + value + "‘");
value = XssFilterUtil.stripXss("<=img onstop=");
System.out.println("type-13: ‘" + value + "‘");
}
}
4. 過濾特殊字符建立StringFilter.java
package com.strongit.nj.action.gzfw.servlet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author zhangcf
* @date 20160622
*/
public class StringFilter {
// 過濾特殊字符
public static String StringFilter(String str) {
// 只允許字母和數字
// String regEx = "[^a-zA-Z0-9]";
// 清除掉所有特殊字符
String regEx = "[`~!@#$%^&*+()\‘+=|{}‘:;‘\\[\\]<>?~!@#¥%……&/()——+|{}【】‘;:"
+ ‘"‘ + "”“’]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return m.replaceAll("").trim();
}
// 過濾特殊字符
public static String StringFilterEasy(String str) {
// 清除掉所有特殊字符
String regEx = "[`@$^&()+=|{}‘:;‘.\\[\\]<>?~!@%]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return m.replaceAll("").trim();
}
// 過濾特殊字符
public static String StringFilterByNum(String str) {
// 只允許字母和數字
String regEx = "[^0-9]";
// 清除掉所有特殊字符
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return m.replaceAll("").trim();
}
public static String StringIsNumAndZiMu(String str) {
// 只允許字母和數字
String regEx = "[^a-zA-Z0-9]";
// 清除掉所有特殊字符
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return m.replaceAll("").trim();
}
/**
* 判斷字符串是不是Integer格式
*
* @author you.xu
* @date 2016年3月4日上午9:27:46
* @param str
* @return
*/
public static boolean StringIsNum(String str) {
boolean isNum = false;
try {
Integer.parseInt(str);
isNum = true;
} catch (NumberFormatException e) {
isNum = false;
}
return isNum;
}
}
5.配置web.xml
<filter> <filter-name>XSSFilter</filter-name> <filter-class>com.data.interceptor.XSSFilter</filter-class> </filter> <filter-mapping> <filter-name>XSSFilter</filter-n
跨站點腳本編制和重定向問題