springboot经验之sql注入、xss注入拦截(POST)
简介
sql注入、xss注入、cors攻击的简介以及解决方案,可以参考下面链接:
https://blog.csdn.net/yhhyhhyhhyhh/article/details/84504487
这里我就不做的的介绍了,解决sql注入根本方案在于使用预编译而不是拼接sql,
而通常拦截参数都只有针对GET方法,下面介绍下POST方法
POST防注入方案
1、增加httprequest包装类
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.regex.Pattern;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.StreamUtils;
@Slf4j
public class XssAndSqlHttpServletRequestWrapper extends HttpServletRequestWrapper {
private static String key = "and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|;|or|-|+";
private static Set<string> notAllowedKeyWords = new HashSet<string>(0);
static {
String keyStr[] = key.split("\\|");
for (String str : keyStr) {
notAllowedKeyWords.add(str);
}
}
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 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 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;
}
flag=checkSqlKeyWords(value);
}
return flag;
}
public boolean checkSqlKeyWords(String value){
String paramValue = value;
for (String keyword : notAllowedKeyWords) {
if (paramValue.length() > keyword.length() + 4
&& (paramValue.contains(" "+keyword)||paramValue.contains(keyword+" ")||paramValue.contains(" "+keyword+" "))) {
log.error(this.getRequestURI()+ "参数中包含不允许sql的关键词(" + keyword
+ ")");
return true;
}
}
return false;
}
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
}
};
}
}
2、增加过滤器
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;
import javax.servlet.DispatcherType;
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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.code.base.BaseResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@WebFilter(
filterName = "xssFilter",
urlPatterns = "/*",
dispatcherTypes = DispatcherType.REQUEST
)
public class XssFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) {
// no init operation
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
XssAndSqlHttpServletRequestWrapper xssRequest=new XssAndSqlHttpServletRequestWrapper(
request);
String method = ((HttpServletRequest) request).getMethod();
String param = "";
if ("POST".equalsIgnoreCase(method)) {
param = this.getBodyString(xssRequest.getReader());
if(StringUtils.isNotBlank(param)){
if(xssRequest.checkXSSAndSql(param)){
servletResponse.setCharacterEncoding("UTF-8");
servletResponse.setContentType("application/json;charset=UTF-8");
PrintWriter out = servletResponse.getWriter();
out.write(JSON.toJSONString(BaseResponse.error(AppErrorCode.PARAMS_ERROR)));
return;
}
}
}
if (xssRequest.checkParameter()) {
servletResponse.setCharacterEncoding("UTF-8");
servletResponse.setContentType("application/json;charset=UTF-8");
PrintWriter out = servletResponse.getWriter();
out.write(JSON.toJSONString(BaseResponse.error(AppErrorCode.PARAMS_ERROR)));
return;
}
filterChain.doFilter(xssRequest, servletResponse);
}
// 获取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;
}
@Override
public void destroy() {
// no destroy operation
}
}
springboot经验之sql注入、xss注入拦截(POST)的更多相关文章
- SpringCloud微服务实战——搭建企业级开发框架(五十一):微服务安全加固—自定义Gateway拦截器实现防止SQL注入/XSS攻击
SQL注入是常见的系统安全问题之一,用户通过特定方式向系统发送SQL脚本,可直接自定义操作系统数据库,如果系统没有对SQL注入进行拦截,那么用户甚至可以直接对数据库进行增删改查等操作. XSS ...
- StringEscapeUtils的常用使用,防止SQL注入及XSS注入
StringEscapeUtils的常用使用,防止SQL注入及XSS注入 2017年10月20日 11:29:44 小狮王 阅读数:8974 版权声明:本文为博主原创文章,转载请注明出处. htt ...
- web安全之XSS注入
之前在做项目的时候有遇到一些安全问题,XSS注入就是其中之一 那么,什么是XSS注入呢? XSS又叫CSS (Cross Site Script) ,跨站脚本攻击.它指的是恶意攻击者往Web页面里插入 ...
- XSS 注入检查点
如果你有个论坛,一般你会很注意用户发帖的注入问题,往往这个地方不会被注入,因为开发特别照顾.原则上XSS都是用户输入的,但是许多边角还是容易忽略.枚举一些检查点. 分页 分页通用组件获取url,修改p ...
- (非原)SQL注入专题--整理帖 && like 语句拼sql 如何防止注入攻击。
原地址:blog.csdn.net/lvjin110/article/details/28697695 like 语句拼sql 如何防止注入攻击?http://bbs.csdn.net/topics/ ...
- 简单的xss注入和防御
什么是xss注入: xss通常就是通过巧妙的方法注入指令到指定页面,使用户加载执行的恶意的js(或者其他类型)的代码,攻击者会获取用户的一系列信息,如cookie等,从而进行其他用户信息的盗取 为什么 ...
- SpringBoot中的application.properties外部注入覆盖
由想要忽略properties中的某些属性,引发的对SpringBoot中的application.properties外部注入覆盖,以及properties文件使用的思考. SpringBoot 配 ...
- 富文本编辑器防止xss注入javascript版
富文本编辑器:ueditor 其实富文本编辑器已经有防止xss注入功能,但是你服务端程序在接收的时候在做一次转义,否则有可能然后前端验证直接提交数据导致被xss攻击. 为了节省后端程序开销则在前端 显 ...
- sql server手工注入
sql server手工注入 测试网站testasp.vulnweb.com 1. http://testasp.vulnweb.com/showforum.asp?id=0 http://testa ...
- 基于DOM的XSS注入漏洞简单解析
基于DOM的XSS注入漏洞简单解析http://automationqa.com/forum.php?mod=viewthread&tid=2956&fromuid=21
随机推荐
- 19-Docker数据持久化
什么是Docker数据持久化 容器在运行时会在镜像层上加上一层:可写层. 当删除容器时,可写层就会一起被删除,数据丢失. 数据持久化就是就是将数据持久化保存,删除容器之后,数据仍然存在. 方法1-挂载 ...
- Linux 驱动需要考虑的同步问题
--- title: Linux 驱动需要考虑的同步问题 date: 2020-06-22 07:21:32 categories: tags: - ipc - linux - kernel - dr ...
- NB-IoT,LoRA,WIFI,蓝牙,Zigbee,MQTT,CoAP之间的关系
--- title: file_name date: 2020-06-22 07:26:20 categories: tags: - iot - wifi - Bluetooth - MQTT - c ...
- 化腐朽为神奇!揭开ISP图像处理的神秘面纱,基于瑞芯微RK3568J工业平台!
ISP图像处理前后图像对比 化腐朽为神奇!经过ISP图像处理的图片前后对比是如此惊人!从下图中可以观察到,未经处理的原始图像偏绿且暗淡,而经ISP图像处理的图像能够清晰地还原现场真实的颜色细节! 图1 ...
- Sqlalchemy 连接SQL Server 登录失败
实验系统环境 Windows平台 Sqlalchemy 2.0.23 Python 3.10 SQL Server 2012 aioodbc 0.5.0 问题详情 sqlalchemy.exc.Int ...
- NewStarCTF 2023 week1
NewStarCTF 2023 WEEK1|CRYPTO brainfuck http://bf.doleczek.pl/ flag{Oiiaioooooiai#b7c0b1866fe58e12} C ...
- CentOS中增加网络连接数的方法
CentOS默认对外访问,发起的TCP链接总数小于28232个. 可以通过以下命令的结果计算出来 $ cat /proc/sys/net/ipv4/ip_local_port_range 我这里得到的 ...
- 效率工具RunFlow完全手册之进阶篇
欢迎来到RunFlow手册的进阶篇,如果您还不了解RunFlow,建议先阅读我们的基础篇. (Solo 社区投稿) 搜索文件 按文件大小过滤,添加 len 参数,比如:len:1kb-2kb,len: ...
- 使用libzip压缩文件和文件夹
简单说说自己遇到的坑: 分清楚三个组件:zlib.minizip和libzip.zlib是底层和最基础的C库,用于使用Deflate算法压缩和解压缩文件流或者单个文件,但是如果要压缩文件夹就很麻烦,主 ...
- CPU的保护模式
保护模式是为了克服实模式低劣的内存管理方式,物理内存地址不能直接被程序访问,程序内部的地址需要被转化为物理地址后再去访问.实模式CPU运行环境16位,保护模式32位. 寄存器扩展: 由于CPU发展到3 ...