云服务器网:购买云服务器和VPS必上的网站!

怎么防止:ssh怎么防止sql注入

ssh怎样避免sql注入ssh避免sql注入的方法:1.在对应的web文件中添加以下代码:httpHeaderSecurity<!–filter2com.wis

SSH怎样避免SQL注入

ssh避免sql注入的方法:

1.在对应的web文件中添加以下代码:

<filter>

<filter-name>httpHeaderSecurity</filter-name>

<!--filter2<filter-class>com.wisdombud.cqupt.edu.web.filter.HttpHeaderSecurityFilter</filter-class>-->

<filter-class>com.wisdombud.cqupt.edu.web.vpn.filter.HttpHeaderSecurityFilter</filter-class>

<async-supported>true</async-supported>

</filter>

<filter-mapping>

<filter-name>httpHeaderSecurity</filter-name>

<url-pattern>*</url-pattern>

</filter-mapping>

2.过滤类,代码:

/*

*LicensedtotheApacheSoftwareFoundation(ASF)underoneormore

*contributorlicenseagreements.SeetheNOTICEfiledistributedwith

*thisworkforadditionalinformationregardingcopyrightownership.

*TheASFlicensesthisfiletoYouundertheApacheLicense,Version2.0

*(the"License");youmaynotusethisfileexceptincompliancewith

*theLicense.YoumayobtainacopyoftheLicenseat

*

*http://www.apache.org/licenses/LICENSE⑵.0

*

*Unlessrequiredbyapplicablelaworagreedtoinwriting,software

*distributedundertheLicenseisdistributedonan"ASIS"BASIS,

*WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.

*SeetheLicenseforthespecificlanguagegoverningpermissionsand

*limitationsundertheLicense.

*/

packagecom.wisdombud.cqupt.edu.web.vpn.filter;

importjava.io.IOException;

importjava.util.Iterator;

importjava.util.Map;

importjava.util.Map.Entry;

importjava.util.regex.Matcher;

importjava.util.regex.Pattern;

importjavax.servlet.FilterChain;

importjavax.servlet.RequestDispatcher;

importjavax.servlet.ServletException;

importjavax.servlet.ServletRequest;

importjavax.servlet.ServletResponse;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importorg.apache.commons.lang3.StringUtils;

importorg.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter;

importorg.slf4j.LoggerFactory;

importcom.wisdombud.cqupt.edu.web.filter.MutableHttpServletRequest;

importcom.wisdombud.cqupt.edu.web.filter.XssHttpServletRequestWrapperNew;

/**

*Providesasingleconfigurationpointforsecuritymeasuresthatrequiredthe

*additionofoneormoreHTTPheaderstotheresponse.

*/

publicclassHttpHeaderSecurityFilterextendsStrutsPrepareAndExecuteFilter{

privatestaticfinalorg.slf4j.LoggerLOGGER=LoggerFactory.getLogger(HttpHeaderSecurityFilter.class);

@Override

publicvoiddoFilter(finalServletRequestreq,finalServletResponseres,finalFilterChainchain)

throwsIOException,ServletException{

finalHttpServletRequestrequest=(HttpServletRequest)req;

finalHttpServletResponseresponse=(HttpServletResponse)res;

finalMutableHttpServletRequestmutableHttpServletRequest=newMutableHttpServletRequest(request);

mutableHttpServletRequest.putHeader("X-Frame-Options","SAMEORIGIN");

response.setHeader("X-Frame-Options","SAMEORIGIN");

response.setHeader("X-Content-Type-Options","nosniff");

finalbooleanisTrue=sqlInjection(request);

if(isTrue){

finalRequestDispatcherdispatcher=request.getRequestDispatcher("/400.jsp");

dispatcher.forward(request,response);

return;

}

super.doFilter(newXssHttpServletRequestWrapperNew(request),response,chain);

}

privateBooleansqlInjection(finalHttpServletRequesthttpRequest){

booleanisIngect=false;

//获得上下文的要求参数

finalMapvalueTreeMap=httpRequest.getParameterMap();

//取得要求参数集合的迭代器

finalIteratoriterator=valueTreeMap.entrySet().iterator();

//遍历组装要求参数

while(iterator.hasNext()){

//取得迭代的键值对

finalEntryentry=(Entry)iterator.next();

//取得键值对中的键值

finalStringkey=(String)entry.getKey();

if("title".equals(key)){

System.err.println(key);

}

//原要求参数,由于有可能一键对多值所以这里用的String[]

String[]oldValues=null;

//对参数值转换成String类型的

if(entry.getValue()instanceofString){

oldValues=newString[]{entry.getValue().toString()};

}else{

oldValues=(String[])entry.getValue();

}

for(inti=0;i<oldValues.length;i++){

if(StringUtils.isNotBlank(oldValues[i])){

if(HasInjectionData(oldValues[i])){

isIngect=true;

break;

}

}

}

if(isIngect){

returnisIngect;

}

}

returnisIngect;

}

///<summary>

///验证是否是存在注入代码(条件语句)

///</summary>

///<paramname="inputData"></param>

publicbooleanHasInjectionData(finalStringinputData){

//里面定义歹意字符集合

//验证inputData是否是包括歹意集合

if(StringUtils.isBlank(inputData)){

returnfalse;

}

finalPatternpattern=Pattern.compile(GetRegexString());

finalMatchermatcher=pattern.matcher(inputData.trim().toLowerCase());

finalbooleanb=matcher.matches();

if(b){

LOGGER.info(String.format("检测出SQL注入的歹意数据,{0}",inputData));

returntrue;

}else{

returnfalse;

}

}

///<summary>

///获得正则表达式

///</summary>

///<returns></returns>

privateStringGetRegexString(){

//构造SQL的注入关键字符

finalString[]strBadChar=

{"select\\s","from\\s","or\\s","insert\\s","delete\\s","update\\s","drop\\s","truncate\\s",

"exec\\s","count\\(","declare\\s","asc\\(","mid\\(","char\\(","netuser","xp_cmdshell","/add\\s",

"execmaster.dbo.xp_cmdshell","netlocalgroupadministrators","and\\s","=\\s","where\\s","<",">"};

//构造正则表达式

Stringstr_Regex=".*(";

for(inti=0;i<strBadChar.length-1;i++){

str_Regex+=strBadChar[i]+"|";

}

str_Regex+=strBadChar[strBadChar.length-1]+").*";

returnstr_Regex;

}

}

3.调用类,代码:

packagecom.wisdombud.cqupt.edu.web.filter;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletRequestWrapper;

importjava.util.Collections;

importjava.util.Enumeration;

importjava.util.HashMap;

importjava.util.HashSet;

importjava.util.Map;

importjava.util.Set;

publicfinalclassMutableHttpServletRequestextendsHttpServletRequestWrapper{

//holdscustomheaderandvaluemapping

privatefinalMap<String,String>customHeaders;

publicMutableHttpServletRequest(HttpServletRequestrequest){

super(request);

this.customHeaders=newHashMap<String,String>();

}

publicvoidputHeader(Stringname,Stringvalue){

this.customHeaders.put(name,value);

}

publicStringgetHeader(Stringname){

//checkthecustomheadersfirst

StringheaderValue=customHeaders.get(name);

if(headerValue!=null){

returnheaderValue;

}

//elsereturnfromintotheoriginalwrappedobject

return((HttpServletRequest)getRequest()).getHeader(name);

}

publicEnumeration<String>getHeaderNames(){

//createasetofthecustomheadernames

Set<String>set=newHashSet<String>(customHeaders.keySet());

//nowaddtheheadersfromthewrappedrequestobject

@SuppressWarnings("unchecked")

Enumeration<String>e=((HttpServletRequest)getRequest()).getHeaderNames();

while(e.hasMoreElements()){

//addthenamesoftherequestheadersintothelist

Stringn=e.nextElement();

set.add(n);

}

//createanenumerationfromthesetandreturn

returnCollections.enumeration(set);

}

}

本文来源:https://www.yuntue.com/post/61268.html | 云服务器网,转载请注明出处!

关于作者: yuntue

云服务器(www.yuntue.com)是一家专门做阿里云服务器代金券、腾讯云服务器优惠券的网站,这里你可以找到阿里云服务器腾讯云服务器等国内主流云服务器优惠价格,以及海外云服务器、vps主机等优惠信息,我们会为你提供性价比最高的云服务器和域名、数据库、CDN、免费邮箱等企业常用互联网资源。

为您推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注