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攻擊的風險。但是在某些特殊業務情況下,尤其是傳統行業系統,需要透過前端配置執行指令碼,然後由業務系統去執行這些配置的指令碼,這個時候就需要透過配置來進行識別和判斷,然後對容易引起安全性風險的指令碼進轉換和配置,在保證業務正常執行的情況下完成指令碼配置。