說到注入攻擊(xss攻擊),我看到baidu和google 上的實現方式,主要是分爲以下幾種:
第一種:通過Filter 過濾器轉義請求參數攜帶的特殊字符(注意POST 和GET請求參數方法不一樣)
第二種:通過配置SpringMVC 的MessageConverter<T>過濾請求參數攜帶的特殊字符
第三種:通過Mybatis 攔截器,攔截所有的insert和update 操作(請求參數特殊字符的轉義),攔截所有的select 操作(查詢 結果的反轉)
重點講解第三種實現方式:
核心功能代碼:
import java.lang.reflect.Field;
import java.util.Properties;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.HtmlUtils;
/**
* 加碼特殊字符轉義(html)
*
*/
@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }) })
public class EncodeInterceptor implements Interceptor {
// 日誌記錄
public static final Logger log = LoggerFactory.getLogger(EncodeInterceptor.class);
// 編碼HTML(默認不開啓)
private boolean escapeHTML = false;
// set 和 get 方法
public boolean isEscapeHTML() {
return escapeHTML;
}
public void setEscapeHTML(boolean escapeHTML) {
this.escapeHTML = escapeHTML;
}
// 構造函數
public EncodeInterceptor() {
super();
}
public EncodeInterceptor(boolean escapeHTML) {
super();
this.escapeHTML = escapeHTML;
}
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
// 獲取 SQL
SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
// 獲取參數
Object parameter = invocation.getArgs()[1];
if(this.escapeHTML){
// 獲取私有成員變量
Field[] declaredFields = parameter.getClass().getDeclaredFields();
for (Field field : declaredFields) {
// 判斷MySQL數據庫操作:insert 或者 update
if (SqlCommandType.INSERT.equals(sqlCommandType) || SqlCommandType.UPDATE.equals(sqlCommandType)) {
// 判斷是否開啓--HTML轉義(String 類型轉義)
if(field.getType() == String.class ){
// 無視private/protected修飾符, 不經過setter函數.
field.setAccessible(true);
try {
String value = (String)field.get(parameter);
field.set(parameter, HtmlUtils.htmlEscape(value));
} catch (IllegalAccessException e) {
log.error(e.getMessage());
}
}
}
}
}
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
// TODO Auto-generated method stub
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
// TODO Auto-generated method stub
}
}
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.HtmlUtils;
import com.digipower.ucas.domain.BusForm;
import com.digipower.ucas.vo.BusFormWrapper;
/**
* 轉義字符->特殊字符
*
*/
@Intercepts({
@Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,RowBounds.class, ResultHandler.class }),
@Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class })
})
public class DecodeInterceptor implements Interceptor {
// 日誌記錄
public static final Logger log = LoggerFactory.getLogger(EncodeInterceptor.class);
// 編碼HTML(默認不開啓)
private boolean escapeHTML = false;
// 攔截指定Mapper
private List<String> mappers;
// set 和 get 方法
public boolean isEscapeHTML() {
return escapeHTML;
}
public void setEscapeHTML(boolean escapeHTML) {
this.escapeHTML = escapeHTML;
}
public List<String> getMappers() {
return mappers;
}
public void setMappers(List<String> mappers) {
this.mappers = mappers;
}
// 構造函數
public DecodeInterceptor() {
super();
}
public DecodeInterceptor(boolean escapeHTML) {
super();
this.escapeHTML = escapeHTML;
}
public DecodeInterceptor(boolean escapeHTML, List<String> mappers) {
super();
this.escapeHTML = escapeHTML;
this.mappers = mappers;
}
@Override
public Object intercept(Invocation invocation) throws Throwable {
// 攔截特定的查詢mapper
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
String mapper = mappedStatement.getId();
// 獲取 SQL
SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
if (SqlCommandType.SELECT.equals(sqlCommandType)) {
Object result = invocation.proceed();
// 判斷返回集合是否爲array
String name = result.getClass().getName();
if(!StringUtils.isEmpty(name) && "java.util.ArrayList".equalsIgnoreCase(name)){
ArrayList<Object> list = (ArrayList<Object>)result;
if(list != null && list.size() > 0){
for(Object obj : list){
// 獲取私有成員變量
Class<?> clazz = obj.getClass();
for (; clazz != Object.class; clazz = clazz.getSuperclass()) {//向上循環 遍歷父類
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
// 判斷是否開啓--HTML反轉(String 類型轉義)
if (field.getType() == String.class) {
// 無視private/protected修飾符, 不經過setter函數.
field.setAccessible(true);
try {
String value = (String) field.get(obj);
field.set(obj, HtmlUtils.htmlUnescape(value));
} catch (IllegalAccessException e) {
log.error(e.getMessage());
}
}
}
}
}
}
return list;
} else {
// 獲取私有成員變量
Class<?> clazz = result.getClass();
for (; clazz != Object.class; clazz = clazz.getSuperclass()) {//向上循環 遍歷父類
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
// 判斷是否開啓--HTML反轉(String 類型轉義)
if (field.getType() == String.class) {
// 無視private/protected修飾符, 不經過setter函數.
field.setAccessible(true);
try {
String value = (String) field.get(result);
field.set(result, HtmlUtils.htmlUnescape(value));
} catch (IllegalAccessException e) {
log.error(e.getMessage());
}
}
}
}
return result;
}
}
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
// TODO Auto-generated method stub
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
// TODO Auto-generated method stub
}
}
SpringBoot 涉及MyBatis 配置文件:
@Configuration
public class MyBatisConfig {
/**
* mybatis 自定義攔截器
* @return
*/
@Bean
public DecodeInterceptor getDecodeInterceptor(@Value("${escapeHTML}") boolean escapeHTML, @Value("${unescapeHTML}") String unescapeHTML){
DecodeInterceptor interceptor = null;
if(StringUtils.isEmpty(unescapeHTML)){
interceptor = new DecodeInterceptor(escapeHTML);
}else {
List<String> mappers = null;
if(unescapeHTML.contains(",")){
mappers = Arrays.asList(unescapeHTML.split(","));
} else {
mappers = Arrays.asList(new String[]{unescapeHTML});
}
interceptor = new DecodeInterceptor(escapeHTML, mappers);
}
return interceptor;
}
/**
* mybatis 自定義攔截器
* @return
*/
@Bean
public EncodeInterceptor getEncodeInterceptor(@Value("${escapeHTML}") boolean escapeHTML){
EncodeInterceptor interceptor = new EncodeInterceptor(escapeHTML);
return interceptor;
}
}