您好,登錄后才能下訂單哦!
本篇內容介紹了“如何使用springMVC通過Filter實現防止xss注入”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
跨站腳本工具(cross 斯特scripting),為不和層疊樣式表(cascading style sheets,CSS)的縮寫混淆,故將跨站腳本攻擊縮寫為XSS。
惡意攻擊者往web頁面里插入惡意scriptScript代碼,當用戶瀏覽該頁之時,嵌入其中Web里面的Script代碼會被執行,從而達到惡意攻擊用戶的目的。
防止XSS攻擊簡單的預防就是對Request請求中的一些參數去掉一些比較敏感的腳本命令。
原本是打算通過springMVC的HandlerInterceptor機制來實現的,通過獲取request然后對request中的參數進行修改,結果雖然值修改了,但在Controller中獲取的數值還是沒有修改的。沒辦法就是要Filter來完成。
簡單來說就是創建一個新的httpRequest類XsslHttpServletRequestWrapper,然后重寫一些get方法(獲取參數時對參數進行XSS判斷預防)。
@WebFilter(filterName="xssMyfilter",urlPatterns="/*") public class MyXssFilter implements Filter{ @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { XsslHttpServletRequestWrapper xssRequest = new XsslHttpServletRequestWrapper((HttpServletRequest)request); chain.doFilter(xssRequest , response); } @Override public void destroy() { } }
XSS代碼的過濾是在XsslHttpServletRequestWrapper中實現的,主要是覆蓋實現了getParameter,getParameterValues,getHeader這幾個方法,然后對獲取的value值進行XSS處理。
public class XsslHttpServletRequestWrapper extends HttpServletRequestWrapper { HttpServletRequest xssRequest = null; public XsslHttpServletRequestWrapper(HttpServletRequest request) { super(request); xssRequest = request; } @Override public String getParameter(String name) { String value = super.getParameter(replaceXSS(name)); if (value != null) { value = replaceXSS(value); } return value; } @Override public String[] getParameterValues(String name) { String[] values = super.getParameterValues(replaceXSS(name)); if(values != null && values.length > 0){ for(int i =0; i< values.length ;i++){ values[i] = replaceXSS(values[i]); } } return values; } @Override public String getHeader(String name) { String value = super.getHeader(replaceXSS(name)); if (value != null) { value = replaceXSS(value); } return value; } /** * 去除待帶script、src的語句,轉義替換后的value值 */ public static String replaceXSS(String value) { if (value != null) { try{ value = value.replace("+","%2B"); //'+' replace to '%2B' value = URLDecoder.decode(value, "utf-8"); }catch(UnsupportedEncodingException e){ }catch(IllegalArgumentException e){ } // Avoid null characters value = value.replaceAll("\0", ""); // Avoid anything between script tags Pattern scriptPattern = Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); // Avoid anything in a src='...' type of e­xpression scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Remove any lonesome </script> tag scriptPattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); // Remove any lonesome <script ...> tag scriptPattern = Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Avoid eval(...) e­xpressions scriptPattern = Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Avoid e­xpression(...) e­xpressions scriptPattern = Pattern.compile("e­xpression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); // Avoid javascript:... e­xpressions scriptPattern = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); // Avoid alert:... e­xpressions scriptPattern = Pattern.compile("alert", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); // Avoid οnlοad= e­xpressions scriptPattern = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); value = scriptPattern.matcher(value).replaceAll(""); scriptPattern = Pattern.compile("vbscript[\r\n| | ]*:[\r\n| | ]*", Pattern.CASE_INSENSITIVE); value = scriptPattern.matcher(value).replaceAll(""); } return filter(value); } /** * 過濾特殊字符 */ public static String filter(String value) { if (value == null) { return null; } StringBuffer result = new StringBuffer(value.length()); for (int i=0; i<value.length(); ++i) { switch (value.charAt(i)) { case '<': result.append("<"); break; case '>': result.append(">"); break; case '"': result.append("""); break; case '\'': result.append("'"); break; case '%': result.append("%"); break; case ';': result.append(";"); break; case '(': result.append("("); break; case ')': result.append(")"); break; case '&': result.append("&"); break; case '+': result.append("+"); break; default: result.append(value.charAt(i)); break; } } return result.toString(); } }
xss過濾請求的參數:Content-Type為 json(application/json)
SpringMVC 對于application/json 轉換處理說明:
spring mvc默認使用MappingJackson2HttpMessageConverter轉換器,
而它是使用jackson來序列化對象的,如果我們能 將jackson的序列化和反序列化過程修改,加入過濾xss代碼,并將其注冊到MappingJackson2HttpMessageConverter中
import java.io.IOException; import org.apache.commons.text.StringEscapeUtils; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; /** * 反序列化 * */ public class XssDefaultJsonDeserializer extends StdDeserializer<String> { public XssDefaultJsonDeserializer(){ this(null); } public XssDefaultJsonDeserializer(Class<String> vc) { super(vc); } @Override public String deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException { // TODO Auto-generated method stub //return StringEscapeUtils.escapeEcmaScript(jsonParser.getText()); return StringEscapeUtils.unescapeHtml4(jsonParser.getText()); } }
@Configuration @EnableWebMvc public class SpingMVCConfig extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { super.configureMessageConverters(converters); // TODO Auto-generated method stub SimpleModule module = new SimpleModule(); // 反序列化 module.addDeserializer(String.class, new XssDefaultJsonDeserializer()); // 序列化 module.addSerializer(String.class, new XssDefaultJsonSerializer()); ObjectMapper mapper = Jackson2ObjectMapperBuilder.json().build(); // 注冊自定義的序列化和反序列化器 mapper.registerModule(module); MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(mapper); converters.add(converter); } }
“如何使用springMVC通過Filter實現防止xss注入”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。