目錄
3.XssAndSqlHttpServletRequestWrapper包裝器 包裝類
7.反黑客小介紹(黑客大哥們好小弟這沒啥大用O(∩_∩)O~,但是對待小白黑客還好)
1.springboot 啓動類 引入 過濾器配置
package com.superman;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.BasicConfigurator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import com.superman.conf.filter.XssAndSqlFilter;
import com.superman.tonifi.InitInfo;
/**
* 項目啓動類
*
* @author yushen
*
*/
@SpringBootApplication
public class Provider_App {
/**
* 項目啓動入口
*
* @param args
*/
public static void main(String[] args) {
SpringApplication.run(Provider_App.class, args);
InitInfo.Info(); //初始化內容
// 自動快速地使用缺省Log4j環境。
BasicConfigurator.configure();
}
/**
* 防止xss 和 sql 注入
*
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@Bean
public FilterRegistrationBean xssFilterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new XssAndSqlFilter());
filterRegistrationBean.setOrder(1);
filterRegistrationBean.setEnabled(true);
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.setName("XssAndSqlFilter");
Map<String, String> initParameters = new HashMap();
initParameters.put("excludes", "/favicon.ico,/img/*,/js/*,/css/*");
initParameters.put("isIncludeRichText", "true");
filterRegistrationBean.setInitParameters(initParameters);
return filterRegistrationBean;
}
}
- 這個可以註冊到的的地方除了springbootappliaction 以外別的 配置也可以註冊更具自己選擇,最好方springbootappliaction 中 方便省事
2.過濾器
package com.superman.conf.filter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
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;
import org.apache.commons.lang3.StringUtils;
/**
* 防止
* xss 和 sql 注入漏洞
* @author yushen
* 20200611
*
*/
public class XssAndSqlFilter implements Filter {
/**
* TODO 這個可以註冊到的的地方除了springbootappliaction 以外別的 配置也可以註冊更具自己選擇,最好方springbootappliaction 中 方便省事
*
* @Bean
public FilterRegistrationBean xssFilterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new XssAndSqlFilter());
filterRegistrationBean.setOrder(1);
filterRegistrationBean.setEnabled(true);
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.setName("XssAndSqlFilter");
Map<String, String> initParameters = new HashMap();
initParameters.put("excludes", "/favicon.ico,/img/*,/js/*,/css/*");
initParameters.put("isIncludeRichText", "true");
filterRegistrationBean.setInitParameters(initParameters);
return filterRegistrationBean;
}
*/
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
String method = "GET";
String param = "";
XssAndSqlHttpServletRequestWrapper xssRequest = null;
if (request instanceof HttpServletRequest) {
method = ((HttpServletRequest) request).getMethod();
xssRequest = new XssAndSqlHttpServletRequestWrapper((HttpServletRequest) request);
}
if ("POST".equalsIgnoreCase(method)) {
param = this.getBodyString(xssRequest.getReader());
if(StringUtils.isNotBlank(param)){
if(xssRequest.checkXSSAndSql(param)){
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
// out.write(JSONResponseUtil.getWrappedERRString("您所訪問的頁面請求中有違反安全規則元素存在,拒絕訪問!"));
out.write("您所訪問的頁面請求中有違反安全規則元素存在,拒絕訪問!");
return;
}
}
}
if (xssRequest.checkParameter()) {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
// out.write(JSONResponseUtil.getWrappedERRString("您所訪問的頁面請求中有違反安全規則元素存在,拒絕訪問!"));
out.write("您所訪問的頁面請求中有違反安全規則元素存在,拒絕訪問!");
return;
}
chain.doFilter(xssRequest, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
// 獲取request請求body中參數
public static String getBodyString(BufferedReader br) {
String inputLine;
String str = "";
try {
while ((inputLine = br.readLine()) != null) {
str += inputLine;
}
br.close();
} catch (IOException e) {
System.out.println("IOException: " + e);
}
return str;
}
}
3.XssAndSqlHttpServletRequestWrapper包裝器 包裝類
package com.superman.conf.filter;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.regex.Pattern;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.springframework.util.StreamUtils;
/**
* 過濾器相關
* @author yushen
* 20200611
* 創建XssAndSqlHttpServletRequestWrapper包裝器,這是實現XSS過濾的關鍵,
* 在其內重寫了getParameter,getParameterValues,getHeader等方法,對http請求內的參數進行了過濾
*
*/
public class XssAndSqlHttpServletRequestWrapper extends HttpServletRequestWrapper {
HttpServletRequest orgRequest = null;
private Map<String, String[]> parameterMap;
private final byte[] body; //用於保存讀取body中數據
public XssAndSqlHttpServletRequestWrapper(HttpServletRequest request) throws IOException{
super(request);
orgRequest = request;
parameterMap = request.getParameterMap();
body = StreamUtils.copyToByteArray(request.getInputStream());
}
// 重寫幾個HttpServletRequestWrapper中的方法
/**
* 獲取所有參數名
*
* @return 返回所有參數名
*/
@Override
public Enumeration<String> getParameterNames() {
Vector<String> vector = new Vector<String>(parameterMap.keySet());
return vector.elements();
}
/**
* 覆蓋getParameter方法,將參數名和參數值都做xss & sql過濾。<br/>
* 如果需要獲得原始的值,則通過super.getParameterValues(name)來獲取<br/>
* getParameterNames,getParameterValues和getParameterMap也可能需要覆蓋
*/
@Override
public String getParameter(String name) {
String[] results = parameterMap.get(name);
if (results == null || results.length <= 0)
return null;
else {
String value = results[0];
if (value != null) {
value = xssEncode(value);
}
return value;
}
}
/**
* 獲取指定參數名的所有值的數組,如:checkbox的所有數據 接收數組變量 ,如checkobx類型
*/
@Override
public String[] getParameterValues(String name) {
String[] results = parameterMap.get(name);
if (results == null || results.length <= 0)
return null;
else {
int length = results.length;
for (int i = 0; i < length; i++) {
results[i] = xssEncode(results[i]);
}
return results;
}
}
/**
* 覆蓋getHeader方法,將參數名和參數值都做xss & sql過濾。<br/>
* 如果需要獲得原始的值,則通過super.getHeaders(name)來獲取<br/>
* getHeaderNames 也可能需要覆蓋
*/
@Override
public String getHeader(String name) {
String value = super.getHeader(xssEncode(name));
if (value != null) {
value = xssEncode(value);
}
return value;
}
/**
* 將容易引起xss & sql漏洞的半角字符直接替換成全角字符
*
* @param s
* @return
*/
private static String xssEncode(String s) {
if (s == null || s.isEmpty()) {
return s;
} else {
s = stripXSSAndSql(s);
}
StringBuilder sb = new StringBuilder(s.length() + 16);
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '>':
sb.append(">");// 轉義大於號
break;
case '<':
sb.append("<");// 轉義小於號
break;
// case '\'':
// sb.append("'");// 轉義單引號
// break;
// case '\"':
// sb.append(""");// 轉義雙引號
// break;
case '&':
sb.append("&");// 轉義&
break;
case '#':
sb.append("#");// 轉義#
break;
default:
sb.append(c);
break;
}
}
return sb.toString();
}
/**
* 獲取最原始的request
*
* @return
*/
public HttpServletRequest getOrgRequest() {
return orgRequest;
}
/**
* 獲取最原始的request的靜態方法
*
* @return
*/
public static HttpServletRequest getOrgRequest(HttpServletRequest req) {
if (req instanceof XssAndSqlHttpServletRequestWrapper) {
return ((XssAndSqlHttpServletRequestWrapper) req).getOrgRequest();
}
return req;
}
/**
*
* 防止xss跨腳本攻擊(替換,根據實際情況調整)
*/
public static String stripXSSAndSql(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(
"<[\r\n| | ]*script[\r\n| | ]*>(.*?)</[\r\n| | ]*script[\r\n| | ]*>", Pattern.CASE_INSENSITIVE);
value = scriptPattern.matcher(value).replaceAll("");
// Avoid anything in a
// src="http://www.yihaomen.com/article/java/..." type of
// e-xpression
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("</[\r\n| | ]*script[\r\n| | ]*>", Pattern.CASE_INSENSITIVE);
value = scriptPattern.matcher(value).replaceAll("");
// Remove any lonesome <script ...> tag
scriptPattern = Pattern.compile("<[\r\n| | ]*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 e-xpression(...) expressions
scriptPattern = Pattern.compile("e-xpression\\((.*?)\\)",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
value = scriptPattern.matcher(value).replaceAll("");
// Avoid javascript:... expressions
scriptPattern = Pattern.compile("javascript[\r\n| | ]*:[\r\n| | ]*", Pattern.CASE_INSENSITIVE);
value = scriptPattern.matcher(value).replaceAll("");
// Avoid vbscript:... expressions
scriptPattern = Pattern.compile("vbscript[\r\n| | ]*:[\r\n| | ]*", 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("");
}
return value;
}
public static boolean checkXSSAndSql(String value) {
boolean flag = false;
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(
"<[\r\n| | ]*script[\r\n| | ]*>(.*?)</[\r\n| | ]*script[\r\n| | ]*>", Pattern.CASE_INSENSITIVE);
flag = scriptPattern.matcher(value).find();
if (flag) {
return flag;
}
// Avoid anything in a
// src="http://www.yihaomen.com/article/java/..." type of
// e-xpression
scriptPattern = Pattern.compile("src[\r\n| | ]*=[\r\n| | ]*[\\\"|\\\'](.*?)[\\\"|\\\']",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
flag = scriptPattern.matcher(value).find();
if (flag) {
return flag;
}
// Remove any lonesome </script> tag
scriptPattern = Pattern.compile("</[\r\n| | ]*script[\r\n| | ]*>", Pattern.CASE_INSENSITIVE);
flag = scriptPattern.matcher(value).find();
if (flag) {
return flag;
}
// Remove any lonesome <script ...> tag
scriptPattern = Pattern.compile("<[\r\n| | ]*script(.*?)>",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
flag = scriptPattern.matcher(value).find();
if (flag) {
return flag;
}
// Avoid eval(...) expressions
scriptPattern = Pattern.compile("eval\\((.*?)\\)",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
flag = scriptPattern.matcher(value).find();
if (flag) {
return flag;
}
// Avoid e-xpression(...) expressions
scriptPattern = Pattern.compile("e-xpression\\((.*?)\\)",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
flag = scriptPattern.matcher(value).find();
if (flag) {
return flag;
}
// Avoid javascript:... expressions
scriptPattern = Pattern.compile("javascript[\r\n| | ]*:[\r\n| | ]*", Pattern.CASE_INSENSITIVE);
flag = scriptPattern.matcher(value).find();
if (flag) {
return flag;
}
// Avoid vbscript:... expressions
scriptPattern = Pattern.compile("vbscript[\r\n| | ]*:[\r\n| | ]*", Pattern.CASE_INSENSITIVE);
flag = scriptPattern.matcher(value).find();
if (flag) {
return flag;
}
// Avoid onload= expressions
scriptPattern = Pattern.compile("onload(.*?)=",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
flag = scriptPattern.matcher(value).find();
if (flag) {
return flag;
}
}
return flag;
}
public final boolean checkParameter() {
Map<String, String[]> submitParams = new HashMap(parameterMap);
Set<String> submitNames = submitParams.keySet();
for (String submitName : submitNames) {
Object submitValues = submitParams.get(submitName);
if ((submitValues instanceof String)) {
if (checkXSSAndSql((String) submitValues)) {
return true;
}
} else if ((submitValues instanceof String[])) {
for (String submitValue : (String[])submitValues){
if (checkXSSAndSql(submitValue)) {
return true;
}
}
}
}
return false;
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public int read() throws IOException {
return bais.read();
}
@Override
public boolean isFinished() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isReady() {
// TODO Auto-generated method stub
return false;
}
@Override
public void setReadListener(ReadListener arg0) {
// TODO Auto-generated method stub
}
};
}
}
4.修改驗證登錄代碼 這裏只寫了基礎的 瞭解意思即可
//2.校驗手機號和token號
String sql = "select * from userlogin where phonenum='"+phonenum+"' and token='"+tokennum+"' ";
//3.不準確退回從新輸入登錄
try {
int resttokenjy = aed.queryApiInfo(sql).size();
if(resttokenjy != 1){
return new AsyncResult<>("驗證碼不正確!");
}
} catch (Exception e) {
log.error(e.toString());
return new AsyncResult<>("驗證碼不正確!");
}
- 重點是加上try 如果發生異常 也好吧信息異步返回 回去
- 更具業務需求,返回自己特殊更多的內容,有需要進行其他安全設施的也可以像安全記錄中進行記錄數據
- 如發現危險用戶 惡意攻擊系統等
5.測試內容
6.測試結果
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
2020-06-12 10:02:22.045 INFO com.alibaba.druid.pool.DruidDataSource - {dataSource-1} inited
2020-06-12 10:02:22.192 ERROR com.superman.global.service.usercheck.UserLoginCheckService - org.springframework.jdbc.BadSqlGrammarException:
### Error querying database. Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '#'' at line 1
### The error may exist in file [D:\eclipseworks_2020\superporject\super_portal\target\classes\mybatis\mapper\ds1\ApiOneDao.xml]
### The error may involve com.superman.globaldao.ds1.ApiOneDao.queryApiInfo-Inline
### The error occurred while setting parameters
### SQL: select id from userlogin where phonenum='15600000000' and token='' or 1=1 #'
### Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '#'' at line 1
; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '#'' at line 1
7.反黑客小介紹(黑客大哥們好小弟這沒啥大用O(∩_∩)O~,但是對待小白黑客還好)
- ok 我們這裏可以看到 原本 半角代碼 # 已經變成全角代碼# 如此以來就可以完全防止sql 和xss 注入了,當然,還有有高手
- 攻擊破解系統,這時候就是繼續再加點過濾器和系統安全防護策略,還有安全校驗來實現,
- 總體來講
- 要向防止系統被攻破
- 就要自己多方几堵牆 阻擋破解的牆越多,黑客發現這麼多阻擋,由於利益的權衡後發現,破解你的系統有些虧,大部分就
- 去破解別的系統去了^_^ , 這說法僅當參考哈,還是你們想和黑客戰鬥的大哥們去戰鬥比試比試吧,
- pk 下誰更牛 棒棒噠 O(∩_∩)O
ok