了解网络安全知识,能够在编写代码时预防常见的跨站脚本攻击、跨站请求伪造、框架钓鱼、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