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.過濾類,代碼:
/** Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wisdombud.cqupt.edu.web.vpn.filter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.FilterChain;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter;
import org.slf4j.LoggerFactory;
import com.wisdombud.cqupt.edu.web.filter.MutableHttpServletRequest;
import com.wisdombud.cqupt.edu.web.filter.XssHttpServletRequestWrapperNew;
/**
* Provides a single configuration point for security measures that required the
* addition of one or more HTTP headers to the response.
*/
public class HttpHeaderSecurityFilter extends StrutsPrepareAndExecuteFilter {
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(HttpHeaderSecurityFilter.class);
@Override
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) req;
final HttpServletResponse response = (HttpServletResponse) res;
final MutableHttpServletRequest mutableHttpServletRequest = new MutableHttpServletRequest(request);
mutableHttpServletRequest.putHeader("X-Frame-Options", "SAMEORIGIN");
response.setHeader("X-Frame-Options", "SAMEORIGIN");
response.setHeader("X-Content-Type-Options", "nosniff");
final boolean isTrue = sqlInjection(request);
if (isTrue) {
final RequestDispatcher dispatcher = request.getRequestDispatcher("/400.jsp");
dispatcher.forward(request, response);
return;
}
super.doFilter(new XssHttpServletRequestWrapperNew(request), response, chain);
}
private Boolean sqlInjection(final HttpServletRequest httpRequest) {
boolean isIngect = false;
// 獲取上下文的請求參數
final Map valueTreeMap = httpRequest.getParameterMap();
// 獲得請求參數集合的迭代器
final Iterator iterator = valueTreeMap.entrySet().iterator();
// 遍歷組裝請求參數
while (iterator.hasNext()) {
// 獲得迭代的鍵值對
final Entry entry = (Entry) iterator.next();
// 獲得鍵值對中的鍵值
final String key = (String) entry.getKey();
if("title".equals(key)){
System.err.println(key);
}
// 原請求參數,因為有可能一鍵對多值所以這里用的String[]
String[] oldValues = null;
// 對參數值轉換成String類型的
if (entry.getValue() instanceof String) {
oldValues = new String[] {entry.getValue().toString()};
} else {
oldValues = (String[]) entry.getValue();
}
for (int i = 0; i < oldValues.length; i++) {
if (StringUtils.isNotBlank(oldValues[i])) {
if (HasInjectionData(oldValues[i])) {
isIngect = true;
break;
}
}
}
if (isIngect) {
return isIngect;
}
}
return isIngect;
}
/// <summary>
/// 驗證是否存在注入代碼(條件語句)
/// </summary>
/// <param name="inputData"></param>
public boolean HasInjectionData(final String inputData) {
// 里面定義惡意字符集合
// 驗證inputData是否包含惡意集合
if(StringUtils.isBlank(inputData)){
return false;
}
final Pattern pattern = Pattern.compile(GetRegexString());
final Matcher matcher = pattern.matcher(inputData.trim().toLowerCase());
final boolean b = matcher.matches();
if (b) {
LOGGER.info(String.format("檢測出SQL注入的惡意數據, {0}", inputData));
return true;
} else {
return false;
}
}
/// <summary>
/// 獲取正則表達式
/// </summary>
/// <returns></returns>
private String GetRegexString() {
// 構造SQL的注入關鍵字符
final String[] 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\\(", "net user", "xp_cmdshell", "/add\\s",
"exec master.dbo.xp_cmdshell", "net localgroup administrators","and\\s","=\\s" ,"where\\s","<",">"};
// 構造正則表達式
String str_Regex = ".*(";
for (int i = 0; i < strBadChar.length - 1; i++) {
str_Regex += strBadChar[i] + "|";
}
str_Regex += strBadChar[strBadChar.length - 1] + ").*";
return str_Regex;
}
}
3.調用類,代碼:
package com.wisdombud.cqupt.edu.web.filter;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public final class MutableHttpServletRequest extends HttpServletRequestWrapper {
// holds custom header and value mapping
private final Map<String, String> customHeaders;
public MutableHttpServletRequest(HttpServletRequest request) {
super(request);
this.customHeaders = new HashMap<String, String>();
}
public void putHeader(String name, String value) {
this.customHeaders.put(name, value);
}
public String getHeader(String name) {
// check the custom headers first
String headerValue = customHeaders.get(name);
if (headerValue != null) {
return headerValue;
}
// else return from into the original wrapped object
return ((HttpServletRequest) getRequest()).getHeader(name);
}
public Enumeration<String> getHeaderNames() {
// create a set of the custom header names
Set<String> set = new HashSet<String>(customHeaders.keySet());
// now add the headers from the wrapped request object
@SuppressWarnings("unchecked")
Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaderNames();
while (e.hasMoreElements()) {
// add the names of the request headers into the list
String n = e.nextElement();
set.add(n);
}
// create an enumeration from the set and return
return Collections.enumeration(set);
}
}