SQL注入是常見的系統安全問題之一,使用者通過特定方式向系統發送SQL腳本,可直接自定義作業系統資料庫,如果系統沒有對SQL注入進行攔截,那麼使用者甚至可以直接對資料庫進行增删改查等操作。
XSS全稱為Cross Site Script跨站點腳本攻擊,和SQL注入類似,都是通過特定方式向系統發送攻擊腳本,對系統進行控制和侵害。SQL注入主要以攻擊資料庫來達到攻擊系統的目的,而XSS則是以惡意執行前端腳本來攻擊系統。
項目架構中使用mybatis/mybatis-plus資料持久層架構,在使用過程中,已有規避SQL注入的規則和使用方法。但是在實際開發過程中,由于各種原因,開發人員對持久層架構的掌握水準不同,有些特殊業務情況必須從前台傳入SQL腳本。這時就需要對系統進行加強,防止特殊情況下引起的系統風險。
在微服務架構下,我們考慮如何實作SQL注入/XSS攻擊攔截時,肯定不會在每個微服務都實作一遍SQL注入/XSS攻擊攔截。根據我們微服務系統的設計,所有的請求都會經過Gateway網關,是以在實作時就可以參照前面的日志攔截器來實作。在接收到一個請求時,通過攔截器解析請求參數,判斷是否有SQL注入/XSS攻擊參數,如果有,那麼傳回異常即可。
我們前面在對微服務Gateway進行自定義擴充時,增加了Gateway插件功能。我們會根據系統需求開發各種Gateway功能擴充插件,并且可以根據系統配置檔案來啟用/禁用這些插件。下面我們就将防止SQL注入/XSS攻擊攔截器作為一個Gateway插件來開發和配置。
1、新增SqlInjectionFilter 過濾器和XssInjectionFilter過濾器,分别用于解析請求參數并對參數進行判斷是否存在SQL注入/XSS攻腳本。此處有公共判斷方法,通過配置檔案來讀取請求的過濾配置,因為不是多有的請求都會引發SQL注入和XSS攻擊,如果無差别的全部攔截和請求,那麼勢必影響到系統的性能。
- 判斷SQL注入的攔截器
/**
* 防sql注入
* @author GitEgg
*/
@Log4j2
@AllArgsConstructor
public class SqlInjectionFilter implements GlobalFilter, Ordered {
......
// 當傳回參數為true時,解析請求參數和傳回參數
if (shouldSqlInjection(exchange))
{
MultiValueMap<String, String> queryParams = request.getQueryParams();
boolean chkRetGetParams = SqlInjectionRuleUtils.mapRequestSqlKeyWordsCheck(queryParams);
boolean chkRetJson = false;
boolean chkRetFormData = false;
HttpHeaders headers = request.getHeaders();
MediaType contentType = headers.getContentType();
long length = headers.getContentLength();
if(length > 0 && null != contentType && (contentType.includes(MediaType.APPLICATION_JSON)
||contentType.includes(MediaType.APPLICATION_JSON_UTF8))){
chkRetJson = SqlInjectionRuleUtils.jsonRequestSqlKeyWordsCheck(gatewayContext.getRequestBody());
}
if(length > 0 && null != contentType && contentType.includes(MediaType.APPLICATION_FORM_URLENCODED)){
log.debug("[RequestLogFilter](Request)FormData:{}",gatewayContext.getFormData());
chkRetFormData = SqlInjectionRuleUtils.mapRequestSqlKeyWordsCheck(gatewayContext.getFormData());
}
if (chkRetGetParams || chkRetJson || chkRetFormData)
{
return WebfluxResponseUtils.responseWrite(exchange, "參數中不允許存在sql關鍵字");
}
return chain.filter(exchange);
}
else {
return chain.filter(exchange);
}
}
......
}
- 判斷XSS攻擊的攔截器
/**
* 防xss注入
* @author GitEgg
*/
@Log4j2
@AllArgsConstructor
public class XssInjectionFilter implements GlobalFilter, Ordered {
......
// 當傳回參數為true時,記錄請求參數和傳回參數
if (shouldXssInjection(exchange))
{
MultiValueMap<String, String> queryParams = request.getQueryParams();
boolean chkRetGetParams = XssInjectionRuleUtils.mapRequestSqlKeyWordsCheck(queryParams);
boolean chkRetJson = false;
boolean chkRetFormData = false;
HttpHeaders headers = request.getHeaders();
MediaType contentType = headers.getContentType();
long length = headers.getContentLength();
if(length > 0 && null != contentType && (contentType.includes(MediaType.APPLICATION_JSON)
||contentType.includes(MediaType.APPLICATION_JSON_UTF8))){
chkRetJson = XssInjectionRuleUtils.jsonRequestSqlKeyWordsCheck(gatewayContext.getRequestBody());
}
if(length > 0 && null != contentType && contentType.includes(MediaType.APPLICATION_FORM_URLENCODED)){
log.debug("[RequestLogFilter](Request)FormData:{}",gatewayContext.getFormData());
chkRetFormData = XssInjectionRuleUtils.mapRequestSqlKeyWordsCheck(gatewayContext.getFormData());
}
if (chkRetGetParams || chkRetJson || chkRetFormData)
{
return WebfluxResponseUtils.responseWrite(exchange, "參數中不允許存在XSS注入關鍵字");
}
return chain.filter(exchange);
}
else {
return chain.filter(exchange);
}
}
......
}
2、新增SqlInjectionRuleUtils工具類和XssInjectionRuleUtils工具類,通過正規表達式,用于判斷參數是否屬于SQL注入/XSS攻擊腳本。
- 通過正規表達式對參數進行是否有SQL注入風險的判斷
/**
* 防sql注入工具類
* @author GitEgg
*/
@Slf4j
public class SqlInjectionRuleUtils {
/**
* SQL的正規表達式
*/
private static String badStrReg = "\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
/**
* SQL的正規表達式
*/
private static Pattern sqlPattern = Pattern.compile(badStrReg, Pattern.CASE_INSENSITIVE);
/**
* sql注入校驗 map
*
* @param map
* @return
*/
public static boolean mapRequestSqlKeyWordsCheck(MultiValueMap<String, String> map) {
//對post請求參數值進行sql注入檢驗
return map.entrySet().stream().parallel().anyMatch(entry -> {
//這裡需要将參數轉換為小寫來處理
String lowerValue = Optional.ofNullable(entry.getValue())
.map(Object::toString)
.map(String::toLowerCase)
.orElse("");
if (sqlPattern.matcher(lowerValue).find()) {
log.error("參數[{}]中包含不允許sql的關鍵詞", lowerValue);
return true;
}
return false;
});
}
/**
* sql注入校驗 json
*
* @param value
* @return
*/
public static boolean jsonRequestSqlKeyWordsCheck(String value) {
if (JSONUtil.isJsonObj(value)) {
JSONObject json = JSONUtil.parseObj(value);
Map<String, Object> map = json;
//對post請求參數值進行sql注入檢驗
return map.entrySet().stream().parallel().anyMatch(entry -> {
//這裡需要将參數轉換為小寫來處理
String lowerValue = Optional.ofNullable(entry.getValue())
.map(Object::toString)
.map(String::toLowerCase)
.orElse("");
if (sqlPattern.matcher(lowerValue).find()) {
log.error("參數[{}]中包含不允許sql的關鍵詞", lowerValue);
return true;
}
return false;
});
} else {
JSONArray json = JSONUtil.parseArray(value);
List<Object> list = json;
//對post請求參數值進行sql注入檢驗
return list.stream().parallel().anyMatch(obj -> {
//這裡需要将參數轉換為小寫來處理
String lowerValue = Optional.ofNullable(obj)
.map(Object::toString)
.map(String::toLowerCase)
.orElse("");
if (sqlPattern.matcher(lowerValue).find()) {
log.error("參數[{}]中包含不允許sql的關鍵詞", lowerValue);
return true;
}
return false;
});
}
}
}
- 通過正規表達式對參數進行是否有XSS攻擊風險的判斷
/**
* XSS注入過濾工具類
* @author GitEgg
*/
public class XssInjectionRuleUtils {
private static final Pattern[] PATTERNS = {
// Avoid anything in a <script> type of expression
Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE),
// Avoid anything in a src='...' type of expression
Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
// Remove any lonesome </script> tag
Pattern.compile("</script>", Pattern.CASE_INSENSITIVE),
// Avoid anything in a <iframe> type of expression
Pattern.compile("<iframe>(.*?)</iframe>", Pattern.CASE_INSENSITIVE),
// Remove any lonesome <script ...> tag
Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
// Remove any lonesome <img ...> tag
Pattern.compile("<img(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
// Avoid eval(...) expressions
Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
// Avoid expression(...) expressions
Pattern.compile("expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
// Avoid javascript:... expressions
Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE),
// Avoid vbscript:... expressions
Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE),
// Avoid onload= expressions
Pattern.compile("on(load|error|mouseover|submit|reset|focus|click)(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL)
};
public static String stripXSS(String value) {
if (StringUtils.isEmpty(value)) {
return value;
}
for (Pattern scriptPattern : PATTERNS) {
value = scriptPattern.matcher(value).replaceAll("");
}
return value;
}
public static boolean hasStripXSS(String value) {
if (!StringUtils.isEmpty(value)) {
for (Pattern scriptPattern : PATTERNS) {
if (scriptPattern.matcher(value).find() == true)
{
return true;
}
}
}
return false;
}
/**
* xss注入校驗 map
*
* @param map
* @return
*/
public static boolean mapRequestSqlKeyWordsCheck(MultiValueMap<String, String> map) {
//對post請求參數值進行sql注入檢驗
return map.entrySet().stream().parallel().anyMatch(entry -> {
//這裡需要将參數轉換為小寫來處理
String lowerValue = Optional.ofNullable(entry.getValue())
.map(Object::toString)
.map(String::toLowerCase)
.orElse("");
if (hasStripXSS(lowerValue)) {
return true;
}
return false;
});
}
/**
* xss注入校驗 json
*
* @param value
* @return
*/
public static boolean jsonRequestSqlKeyWordsCheck(String value) {
if (JSONUtil.isJsonObj(value)) {
JSONObject json = JSONUtil.parseObj(value);
Map<String, Object> map = json;
//對post請求參數值進行sql注入檢驗
return map.entrySet().stream().parallel().anyMatch(entry -> {
//這裡需要将參數轉換為小寫來處理
String lowerValue = Optional.ofNullable(entry.getValue())
.map(Object::toString)
.map(String::toLowerCase)
.orElse("");
if (hasStripXSS(lowerValue)) {
return true;
}
return false;
});
} else {
JSONArray json = JSONUtil.parseArray(value);
List<Object> list = json;
//對post請求參數值進行sql注入檢驗
return list.stream().parallel().anyMatch(obj -> {
//這裡需要将參數轉換為小寫來處理
String lowerValue = Optional.ofNullable(obj)
.map(Object::toString)
.map(String::toLowerCase)
.orElse("");
if (hasStripXSS(lowerValue)) {
return true;
}
return false;
});
}
}
}
3、在GatewayRequestContextFilter 中新增判斷那些請求需要解析參數。因為出于性能等方面的考慮,網關并不是對所有的參數都進行解析,隻有在需要記錄日志、防止SQL注入/XSS攻擊時才會進行解析。
/**
* check should read request data whether or not
* @return boolean
*/
private boolean shouldReadRequestData(ServerWebExchange exchange){
if(gatewayPluginProperties.getLogRequest().getRequestLog()
&& GatewayLogTypeEnum.ALL.getType().equals(gatewayPluginProperties.getLogRequest().getLogType())){
log.debug("[GatewayContext]Properties Set Read All Request Data");
return true;
}
boolean serviceFlag = false;
boolean pathFlag = false;
boolean lbFlag = false;
List<String> readRequestDataServiceIdList = gatewayPluginProperties.getLogRequest().getServiceIdList();
List<String> readRequestDataPathList = gatewayPluginProperties.getLogRequest().getPathList();
if(!CollectionUtils.isEmpty(readRequestDataPathList)
&& (GatewayLogTypeEnum.PATH.getType().equals(gatewayPluginProperties.getLogRequest().getLogType())
|| GatewayLogTypeEnum.CONFIGURE.getType().equals(gatewayPluginProperties.getLogRequest().getLogType()))){
String requestPath = exchange.getRequest().getPath().pathWithinApplication().value();
for(String path : readRequestDataPathList){
if(ANT_PATH_MATCHER.match(path,requestPath)){
log.debug("[GatewayContext]Properties Set Read Specific Request Data With Request Path:{},Math Pattern:{}", requestPath, path);
pathFlag = true;
break;
}
}
}
Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
URI routeUri = route.getUri();
if(!"lb".equalsIgnoreCase(routeUri.getScheme())){
lbFlag = true;
}
String routeServiceId = routeUri.getHost().toLowerCase();
if(!CollectionUtils.isEmpty(readRequestDataServiceIdList)
&& (GatewayLogTypeEnum.SERVICE.getType().equals(gatewayPluginProperties.getLogRequest().getLogType())
|| GatewayLogTypeEnum.CONFIGURE.getType().equals(gatewayPluginProperties.getLogRequest().getLogType()))){
if(readRequestDataServiceIdList.contains(routeServiceId)){
log.debug("[GatewayContext]Properties Set Read Specific Request Data With ServiceId:{}",routeServiceId);
serviceFlag = true;
}
}
if (GatewayLogTypeEnum.CONFIGURE.getType().equals(gatewayPluginProperties.getLogRequest().getLogType())
&& serviceFlag && pathFlag && !lbFlag)
{
return true;
}
else if (GatewayLogTypeEnum.SERVICE.getType().equals(gatewayPluginProperties.getLogRequest().getLogType())
&& serviceFlag && !lbFlag)
{
return true;
}
else if (GatewayLogTypeEnum.PATH.getType().equals(gatewayPluginProperties.getLogRequest().getLogType())
&& pathFlag)
{
return true;
}
return false;
}
4、在GatewayPluginProperties中新增配置,用于讀取Gateway過濾器的系統配置,判斷開啟新增的防止SQL注入/XSS攻擊插件。
@Slf4j
@Getter
@Setter
@ToString
public class GatewayPluginProperties implements InitializingBean {
public static final String GATEWAY_PLUGIN_PROPERTIES_PREFIX = "spring.cloud.gateway.plugin.config";
public static final String GATEWAY_PLUGIN_PROPERTIES_PREFIX_LOG_REQUEST = GATEWAY_PLUGIN_PROPERTIES_PREFIX + ".logRequest";
public static final String GATEWAY_PLUGIN_PROPERTIES_PREFIX_SQL_INJECTION = GATEWAY_PLUGIN_PROPERTIES_PREFIX + ".sqlInjection";
public static final String GATEWAY_PLUGIN_PROPERTIES_PREFIX_XSS_INJECTION = GATEWAY_PLUGIN_PROPERTIES_PREFIX + ".xssInjection";
/**
* Enable Or Disable
*/
private Boolean enable = false;
/**
* LogProperties
*/
private LogProperties logRequest;
/**
* SqlInjectionProperties
*/
private SqlInjectionProperties sqlInjection;
/**
* XssInjectionProperties
*/
private XssInjectionProperties xssInjection;
@Override
public void afterPropertiesSet() {
log.info("Gateway plugin logRequest enable:", logRequest.enable);
log.info("Gateway plugin sqlInjection enable:", sqlInjection.enable);
log.info("Gateway plugin xssInjection enable:", xssInjection.enable);
}
/**
* 日志記錄相關配置
*/
@Getter
@Setter
@ToString
public static class LogProperties implements InitializingBean{
/**
* Enable Or Disable Log Request Detail
*/
private Boolean enable = false;
/**
* Enable Or Disable Read Request Data
*/
private Boolean requestLog = false;
/**
* Enable Or Disable Read Response Data
*/
private Boolean responseLog = false;
/**
* logType
* all: 所有日志
* configure:serviceId和pathList交集
* serviceId: 隻記錄serviceId配置清單
* pathList:隻記錄pathList配置清單
*/
private String logType = "all";
/**
* Enable Read Request Data When use discover route by serviceId
*/
private List<String> serviceIdList = Collections.emptyList();
/**
* Enable Read Request Data by specific path
*/
private List<String> pathList = Collections.emptyList();
@Override
public void afterPropertiesSet() throws Exception {
if(!CollectionUtils.isEmpty(serviceIdList)){
serviceIdList = serviceIdList.stream().map(String::toLowerCase).collect(Collectors.toList());
}
if(!CollectionUtils.isEmpty(pathList)){
pathList = pathList.stream().map(String::toLowerCase).collect(Collectors.toList());
}
}
}
/**
* sql注入攔截相關配置
*/
@Getter
@Setter
@ToString
public static class SqlInjectionProperties implements InitializingBean{
/**
* Enable Or Disable
*/
private Boolean enable = false;
/**
* Enable Read Request Data When use discover route by serviceId
*/
private List<String> serviceIdList = Collections.emptyList();
/**
* Enable Read Request Data by specific path
*/
private List<String> pathList = Collections.emptyList();
@Override
public void afterPropertiesSet() {
if(!CollectionUtils.isEmpty(serviceIdList)){
serviceIdList = serviceIdList.stream().map(String::toLowerCase).collect(Collectors.toList());
}
if(!CollectionUtils.isEmpty(pathList)){
pathList = pathList.stream().map(String::toLowerCase).collect(Collectors.toList());
}
}
}
/**
* xss注入攔截相關配置
*/
@Getter
@Setter
@ToString
public static class XssInjectionProperties implements InitializingBean{
/**
* Enable Or Disable
*/
private Boolean enable = false;
/**
* Enable Read Request Data When use discover route by serviceId
*/
private List<String> serviceIdList = Collections.emptyList();
/**
* Enable Read Request Data by specific path
*/
private List<String> pathList = Collections.emptyList();
@Override
public void afterPropertiesSet() {
if(!CollectionUtils.isEmpty(serviceIdList)){
serviceIdList = serviceIdList.stream().map(String::toLowerCase).collect(Collectors.toList());
}
if(!CollectionUtils.isEmpty(pathList)){
pathList = pathList.stream().map(String::toLowerCase).collect(Collectors.toList());
}
}
}
}
5、GatewayPluginConfig 配置過濾器在啟動時動态判斷是否啟用某些Gateway插件。在這裡我們将新增的SQL注入攔截插件和XSS攻擊攔截插件配置進來,可以根據配置檔案動态判斷是否啟用SQL注入攔截插件和XSS攻擊攔截插件。
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = GatewayPluginProperties.GATEWAY_PLUGIN_PROPERTIES_PREFIX, value = { "enable"}, havingValue = "true")
public class GatewayPluginConfig {
/**
* Gateway插件是否生效
* @return
*/
@Bean
@ConditionalOnMissingBean(GatewayPluginProperties.class)
@ConfigurationProperties(GatewayPluginProperties.GATEWAY_PLUGIN_PROPERTIES_PREFIX)
public GatewayPluginProperties gatewayPluginProperties(){
return new GatewayPluginProperties();
}
......
/**
* sql注入攔截插件
* @return
*/
@Bean
@ConditionalOnMissingBean(SqlInjectionFilter.class)
@ConditionalOnProperty(prefix = GatewayPluginProperties.GATEWAY_PLUGIN_PROPERTIES_PREFIX, value = { "sqlInjection.enable" },havingValue = "true")
public SqlInjectionFilter sqlInjectionFilter(@Autowired GatewayPluginProperties gatewayPluginProperties){
SqlInjectionFilter sqlInjectionFilter = new SqlInjectionFilter(gatewayPluginProperties);
log.debug("Load SQL Injection Filter Config Bean");
return sqlInjectionFilter;
}
/**
* xss注入攔截插件
* @return
*/
@Bean
@ConditionalOnMissingBean(XssInjectionFilter.class)
@ConditionalOnProperty(prefix = GatewayPluginProperties.GATEWAY_PLUGIN_PROPERTIES_PREFIX, value = { "xssInjection.enable" },havingValue = "true")
public XssInjectionFilter xssInjectionFilter(@Autowired GatewayPluginProperties gatewayPluginProperties){
XssInjectionFilter xssInjectionFilter = new XssInjectionFilter(gatewayPluginProperties);
log.debug("Load XSS Injection Filter Config Bean");
return xssInjectionFilter;
}
......
}
在日常開發過程中很多業務需求都不會從前端傳入SQL腳本和XSS腳本,是以很多的開發架構都不去識别前端參數是否有安全風險,然後直接禁止掉所有前端傳入的的腳本,這樣就強制規避了SQL注入和XSS攻擊的風險。但是在某些特殊業務情況下,尤其是傳統行業系統,需要通過前端配置執行腳本,然後由業務系統去執行這些配置的腳本,這個時候就需要通過配置來進行識别和判斷,然後對容易引起安全性風險的腳本進轉換和配置,在保證業務正常運作的情況下完成腳本配置。
源碼位址:
Gitee:
https://gitee.com/wmz1930/GitEgg
GitHub:
https://github.com/wmz1930/GitEgg