SQL注入是常见的系统安全问题之一,用户通过特定方式向系统发送SQL脚本,可直接自定义操作系统数据库,如果系统没有对SQL注入进行拦截,那么用户甚至可以直接对数据库进行增删改查等操作。
XSS全称为CrossSiteScript跨站点脚本攻击,和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注入*@authorGitEgg*/@Log4j2@AllArgsConstructorpublicclassSqlInjectionFilterimplementsGlobalFilter,Ordered{......//当返回参数为true时,解析请求参数和返回参数if(shouldSqlInjection(exchange)){MultiValueMap<String,String>queryParams=request.getQueryParams();booleanchkRetGetParams=SqlInjectionRuleUtils.mapRequestSqlKeyWordsCheck(queryParams);booleanchkRetJson=false;booleanchkRetFormData=false;HttpHeadersheaders=request.getHeaders();MediaTypecontentType=headers.getContentType();longlength=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){returnWebfluxResponseUtils.responseWrite(exchange,"参数中不允许存在sql关键字");}returnchain.filter(exchange);}else{returnchain.filter(exchange);}}......}/***防xss注入*@authorGitEgg*/@Log4j2@AllArgsConstructorpublicclassXssInjectionFilterimplementsGlobalFilter,Ordered{......//当返回参数为true时,记录请求参数和返回参数if(shouldXssInjection(exchange)){MultiValueMap<String,String>queryParams=request.getQueryParams();booleanchkRetGetParams=XssInjectionRuleUtils.mapRequestSqlKeyWordsCheck(queryParams);booleanchkRetJson=false;booleanchkRetFormData=false;HttpHeadersheaders=request.getHeaders();MediaTypecontentType=headers.getContentType();longlength=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){returnWebfluxResponseUtils.responseWrite(exchange,"参数中不允许存在XSS注入关键字");}returnchain.filter(exchange);}else{returnchain.filter(exchange);}}......}2、新增SqlInjectionRuleUtils工具类和XssInjectionRuleUtils工具类,通过正则表达式,用于判断参数是否属于SQL注入/XSS攻击脚本。
- 通过正则表达式对参数进行是否有SQL注入风险的判断
/***防sql注入工具类*@authorGitEgg*/@Slf4jpublicclassSqlInjectionRuleUtils{/***SQL的正则表达式*/privatestaticStringbadStrReg="\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.?SELECT|UPDATE.?SET|INSERT\\sINTO.?VALUES|(SELECT|DELETE).?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s(TABLE|DATABASE)";/***SQL的正则表达式*/privatestaticPatternsqlPattern=Pattern.compile(badStrReg,Pattern.CASE_INSENSITIVE);/***sql注入校验map**@parammap*@return*/publicstaticbooleanmapRequestSqlKeyWordsCheck(MultiValueMap<String,String>map){//对post请求参数值进行sql注入检验returnmap.entrySet().stream().parallel().anyMatch(entry->{//这里需要将参数转换为小写来处理StringlowerValue=Optional.ofNullable(entry.getValue()).map(Object::toString).map(String::toLowerCase).orElse("");if(sqlPattern.matcher(lowerValue).find()){log.error("参数[{}]中包含不允许sql的关键词",lowerValue);returntrue;}returnfalse;});}/***sql注入校验json**@paramvalue*@return*/publicstaticbooleanjsonRequestSqlKeyWordsCheck(Stringvalue){if(JSONUtil.isJsonObj(value)){JSONObjectjson=JSONUtil.parseObj(value);Map<String,Object>map=json;//对post请求参数值进行sql注入检验returnmap.entrySet().stream().parallel().anyMatch(entry->{//这里需要将参数转换为小写来处理StringlowerValue=Optional.ofNullable(entry.getValue()).map(Object::toString).map(String::toLowerCase).orElse("");if(sqlPattern.matcher(lowerValue).find()){log.error("参数[{}]中包含不允许sql的关键词",lowerValue);returntrue;}returnfalse;});}else{JSONArrayjson=JSONUtil.parseArray(value);List<Object>list=json;//对post请求参数值进行sql注入检验returnlist.stream().parallel().anyMatch(obj->{//这里需要将参数转换为小写来处理StringlowerValue=Optional.ofNullable(obj).map(Object::toString).map(String::toLowerCase).orElse("");if(sqlPattern.matcher(lowerValue).find()){log.error("参数[{}]中包含不允许sql的关键词",lowerValue);returntrue;}returnfalse;});}}}- 通过正则表达式对参数进行是否有XSS攻击风险的判断
/***XSS注入过滤工具类*@authorGitEgg*/publicclassXssInjectionRuleUtils{privatestaticfinalPattern[]PATTERNS={//Avoidanythingina<script>typeofexpressionPattern.compile("<script>(.*?)</script>",Pattern.CASE_INSENSITIVE),//Avoidanythinginasrc='...'typeofexpressionPattern.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),//Removeanylonesome</script>tagPattern.compile("</script>",Pattern.CASE_INSENSITIVE),//Avoidanythingina<iframe>typeofexpressionPattern.compile("<iframe>(.*?)</iframe>",Pattern.CASE_INSENSITIVE),//Removeanylonesome<script...>tagPattern.compile("<script(.*?)>",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL),//Removeanylonesome<img...>tagPattern.compile("<img(.*?)>",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL),//Avoideval(...)expressionsPattern.compile("eval\\((.*?)\\)",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL),//Avoidexpression(...)expressionsPattern.compile("expression\\((.*?)\\)",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL),//Avoidjavascript:...expressionsPattern.compile("javascript:",Pattern.CASE_INSENSITIVE),//Avoidvbscript:...expressionsPattern.compile("vbscript:",Pattern.CASE_INSENSITIVE),//Avoidonload=expressionsPattern.compile("on(load|error|mouSEO((SearchEngineOptimization))ver|submit|reset|focus|click)(.*?)=",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL)};publicstaticStringstripXSS(Stringvalue){if(StringUtils.isEmpty(value)){returnvalue;}for(PatternscriptPattern:PATTERNS){value=scriptPattern.matcher(value).replaceAll("");}returnvalue;}publicstaticbooleanhasStripXSS(Stringvalue){if(!StringUtils.isEmpty(value)){for(PatternscriptPattern:PATTERNS){if(scriptPattern.matcher(value).find()==true){returntrue;}}}returnfalse;}/***xss注入校验map**@parammap*@return*/publicstaticbooleanmapRequestSqlKeyWordsCheck(MultiValueMap<String,String>map){//对post请求参数值进行sql注入检验returnmap.entrySet().stream().parallel().anyMatch(entry->{//这里需要将参数转换为小写来处理StringlowerValue=Optional.ofNullable(entry.getValue()).map(Object::toString).map(String::toLowerCase).orElse("");if(hasStripXSS(lowerValue)){returntrue;}returnfalse;});}/***xss注入校验json**@paramvalue*@return*/publicstaticbooleanjsonRequestSqlKeyWordsCheck(Stringvalue){if(JSONUtil.isJsonObj(value)){JSONObjectjson=JSONUtil.parseObj(value);Map<String,Object>map=json;//对post请求参数值进行sql注入检验returnmap.entrySet().stream().parallel().anyMatch(entry->{//这里需要将参数转换为小写来处理StringlowerValue=Optional.ofNullable(entry.getValue()).map(Object::toString).map(String::toLowerCase).orElse("");if(hasStripXSS(lowerValue)){returntrue;}returnfalse;});}else{JSONArrayjson=JSONUtil.parseArray(value);List<Object>list=json;//对post请求参数值进行sql注入检验returnlist.stream().parallel().anyMatch(obj->{//这里需要将参数转换为小写来处理StringlowerValue=Optional.ofNullable(obj).map(Object::toString).map(String::toLowerCase).orElse("");if(hasStripXSS(lowerValue)){returntrue;}returnfalse;});}}}3、在GatewayRequestContextFilter中新增判断那些请求需要解析参数。因为出于性能等方面的考虑,网关并不是对所有的参数都进行解析,只有在需要记录日志、防止SQL注入/XSS攻击时才会进行解析。
/***checkshouldreadrequestdatawhetherornot*@returnboolean*/privatebooleanshouldReadRequestData(ServerWebExchangeexchange){if(gatewayPluginProperties.getLogRequest().getRequestLog()&&GatewayLogTypeEnum.ALL.getType().equals(gatewayPluginProperties.getLogRequest().getLogType())){log.debug("[GatewayContext]PropertiesSetReadAllRequestData");returntrue;}booleanserviceFlag=false;booleanpathFlag=false;booleanlbFlag=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()))){StringrequestPath=exchange.getRequest().getPath().pathWithinApplication().value();for(Stringpath:readRequestDataPathList){if(ANT_PATH_MATCHER.match(path,requestPath)){log.debug("[GatewayContext]PropertiesSetReadSpecificRequestDataWithRequestPath:{},MathPattern:{}",requestPath,path);pathFlag=true;break;}}}Routeroute=exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);URIrouteUri=route.getUri();if(!"lb".equalsIgnoreCase(routeUri.getScheme())){lbFlag=true;}StringrouteServiceId=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]PropertiesSetReadSpecificRequestDataWithServiceId:{}",routeServiceId);serviceFlag=true;}}if(GatewayLogTypeEnum.CONFIGURE.getType().equals(gatewayPluginProperties.getLogRequest().getLogType())&&serviceFlag&&pathFlag&&!lbFlag){returntrue;}elseif(GatewayLogTypeEnum.SERVICE.getType().equals(gatewayPluginProperties.getLogRequest().getLogType())&&serviceFlag&&!lbFlag){returntrue;}elseif(GatewayLogTypeEnum.PATH.getType().equals(gatewayPluginProperties.getLogRequest().getLogType())&&pathFlag){returntrue;}returnfalse;}4、在GatewayPluginProperties中新增配置,用于读取Gateway过滤器的系统配置,判断开启新增的防止SQL注入/XSS攻击插件。
@Slf4j@Getter@Setter@ToStringpublicclassGatewayPluginPropertiesimplementsInitializingBean{publicstaticfinalStringGATEWAY_PLUGIN_PROPERTIES_PREFIX="spring.cloud.gateway.plugin.config";publicstaticfinalStringGATEWAY_PLUGIN_PROPERTIES_PREFIX_LOG_REQUEST=GATEWAY_PLUGIN_PROPERTIES_PREFIX".logRequest";publicstaticfinalStringGATEWAY_PLUGIN_PROPERTIES_PREFIX_SQL_INJECTION=GATEWAY_PLUGIN_PROPERTIES_PREFIX".sqlInjection";publicstaticfinalStringGATEWAY_PLUGIN_PROPERTIES_PREFIX_XSS_INJECTION=GATEWAY_PLUGIN_PROPERTIES_PREFIX".xssInjection";/***EnableOrDisable*/privateBooleanenable=false;/***LogProperties*/privateLogPropertieslogRequest;/***SqlInjectionProperties*/privateSqlInjectionPropertiessqlInjection;/***XssInjectionProperties*/privateXssInjectionPropertiesxssInjection;@OverridepublicvoidafterPropertiesSet(){log.info("GatewaypluginlogRequestenable:",logRequest.enable);log.info("GatewaypluginsqlInjectionenable:",sqlInjection.enable);log.info("GatewaypluginxssInjectionenable:",xssInjection.enable);}/***日志记录相关配置*/@Getter@Setter@ToStringpublicstaticclassLogPropertiesimplementsInitializingBean{/***EnableOrDisableLogRequestDetail*/privateBooleanenable=false;/***EnableOrDisableReadRequestData*/privateBooleanrequestLog=false;/***EnableOrDisableReadResponseData*/privateBooleanresponseLog=false;/***logType*all:所有日志*configure:serviceId和pathList交集*serviceId:只记录serviceId配置列表*pathList:只记录pathList配置列表*/privateStringlogType="all";/***EnableReadRequestDataWhenusediscoverroutebyserviceId*/privateList<String>serviceIdList=Collections.emptyList();/***EnableReadRequestDatabyspecificpath*/privateList<String>pathList=Collections.emptyList();@OverridepublicvoidafterPropertiesSet()throwsException{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@ToStringpublicstaticclassSqlInjectionPropertiesimplementsInitializingBean{/***EnableOrDisable*/privateBooleanenable=false;/***EnableReadRequestDataWhenusediscoverroutebyserviceId*/privateList<String>serviceIdList=Collections.emptyList();/***EnableReadRequestDatabyspecificpath*/privateList<String>pathList=Collections.emptyList();@OverridepublicvoidafterPropertiesSet(){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@ToStringpublicstaticclassXssInjectionPropertiesimplementsInitializingBean{/***EnableOrDisable*/privateBooleanenable=false;/***EnableReadRequestDataWhenusediscoverroutebyserviceId*/privateList<String>serviceIdList=Collections.emptyList();/***EnableReadRequestDatabyspecificpath*/privateList<String>pathList=Collections.emptyList();@OverridepublicvoidafterPropertiesSet(){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")publicclassGatewayPluginConfig{/***Gateway插件是否生效*@return*/@Bean@ConditionalOnMissingBean(GatewayPluginProperties.class)@ConfigurationProperties(GatewayPluginProperties.GATEWAY_PLUGIN_PROPERTIES_PREFIX)publicGatewayPluginPropertiesgatewayPluginProperties(){returnnewGatewayPluginProperties();}....../***sql注入拦截插件*@return*/@Bean@ConditionalOnMissingBean(SqlInjectionFilter.class)@ConditionalOnProperty(prefix=GatewayPluginProperties.GATEWAY_PLUGIN_PROPERTIES_PREFIX,value={"sqlInjection.enable"},havingValue="true")publicSqlInjectionFiltersqlInjectionFilter(@AutowiredGatewayPluginPropertiesgatewayPluginProperties){SqlInjectionFiltersqlInjectionFilter=newSqlInjectionFilter(gatewayPluginProperties);log.debug("LoadSQLInjectionFilterConfigBean");returnsqlInjectionFilter;}/***xss注入拦截插件*@return*/@Bean@ConditionalOnMissingBean(XssInjectionFilter.class)@ConditionalOnProperty(prefix=GatewayPluginProperties.GATEWAY_PLUGIN_PROPERTIES_PREFIX,value={"xssInjection.enable"},havingValue="true")publicXssInjectionFilterxssInjectionFilter(@AutowiredGatewayPluginPropertiesgatewayPluginProperties){XssInjectionFilterxssInjectionFilter=newXssInjectionFilter(gatewayPluginProperties);log.debug("LoadXSSInjectionFilterConfigBean");returnxssInjectionFilter;}......} 在日常开发过程中很多业务需求都不会从前端传入SQL脚本和XSS脚本,所以很多的开发框架都不去识别前端参数是否有安全风险,然后直接禁止掉所有前端传入的的脚本,这样就强制规避了SQL注入和XSS攻击的风险。但是在某些特殊业务情况下,尤其是传统行业系统,需要通过前端配置执行脚本,然后由业务系统去执行这些配置的脚本,这个时候就需要通过配置来进行识别和判断,然后对容易引起安全性风险的脚本进转换和配置,在保证业务正常运行的情况下完成脚本配置。