博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
xss+sql 注入拦截form表单和json数据非法字符
阅读量:4028 次
发布时间:2019-05-24

本文共 22690 字,大约阅读时间需要 75 分钟。

是时候上硬货了。网上有些进行校验注入。只是针对form表单的操作。我这个是form表单+json。

用的是基于springmvc的拦截器,没用filter过滤器。原因就是我认为不到后台controller的请求。基本上没多大威胁。

这里有三个文件XssIntercepter(拦截器),XssHttpServletRequestWrapper,HTMLFilter

还有就是在HTMLFilter.filterParams()调这个方法的时候,有异常抛出。最好加个个异常解析。这样不至于没有提示。体验感不好

代码如下。一看就懂。代码一拷就能用。又是一个搬运工

@ControllerAdvice@Controllerpublic class BaseControllerAdvice{    @ExceptionHandler(XssException.class)    public void exceptionRevlose(XssException ex, HttpServletRequest request,HttpServletResponse response){        if(isAjaxRequest(request)){            responseBody(response,ex.getMessage());            return;        }        responseForm(response,ex.getMessage());        return;    }    public static boolean isAjaxRequest(HttpServletRequest request) {        String requestedWith = request.getHeader("x-requested-with");        if (requestedWith != null && requestedWith.equalsIgnoreCase("XMLHttpRequest")) {            return true;        } else {            return false;        }    }    public void responseForm(HttpServletResponse response,String message){        //重置response        response.reset();        //设置编码格式        response.setCharacterEncoding("UTF-8");        response.setContentType("text/html;charset=UTF-8");        try(PrintWriter pw = response.getWriter();){            pw.write("");            pw.flush();        }catch (Exception e){        }    }    public void responseBody(HttpServletResponse response,String message){        //重置response        response.reset();        //设置编码格式        response.setCharacterEncoding("UTF-8");        response.setContentType("application/json;charset=UTF-8");        try(PrintWriter pw = response.getWriter();){            JSONObject jsonObject = new JSONObject();            jsonObject.put("success",false);            jsonObject.put("msg",message);            pw.write(jsonObject.toJSONString());            pw.flush();        }catch (Exception e){        }    }}
/** * @author wwz  * @email:1512180909@qq.com */public class XssIntercepter extends HandlerInterceptorAdapter {    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {        Enumeration names = request.getParameterNames();//获取所有的表单参数        while (!names.hasMoreElements()){           return true;        }        XssHttpServletRequestWrapper xssHttpServletRequestWrapper =  new XssHttpServletRequestWrapper(request);        String value = xssHttpServletRequestWrapper.getJson();        value = HTMLFilter.htmlSpecialChars(value).replace("&","").replace(""","").replace("<","").replace(">","").replace("alert","").replace("javascript","").replace("jscript","").replace("vbscript","");        //判断是否包含非法字符        HTMLFilter.filterParams(value);        xssHttpServletRequestWrapper.setBytes(value.getBytes("utf-8"));        return true;    }}当然拦截器肯定要放到springmvc配置中,这里不详解

XssHttpServletRequestWrapper :

/** * Created by wwz on 2018-10-19. */public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {    protected volatile byte[] bytes = new byte[]{};    private HttpServletRequest request;    private String json;    public XssHttpServletRequestWrapper(HttpServletRequest request)throws Exception{        super(request);        this.request = request;        String body =  getBody();        HTMLFilter.filterParams(body);        String json =  getBodyString(request);        this.json = json;        bytes = json.getBytes("UTF-8");    }    private String getBody(){        StringBuilder builder = new StringBuilder();        Enumeration names = request.getParameterNames();        while(names.hasMoreElements()){            String paramName = (String) names.nextElement();            String[] paramValues = request.getParameterValues(paramName);            if(paramValues!=null && paramValues.length>0){                for(String s:paramValues){                    builder.append(s);                }            }        }        return builder.toString();    }    @Override    public BufferedReader getReader() throws IOException {        return new BufferedReader(new InputStreamReader(getInputStream()));    }     @Override    public String getHeader(String name) {        return HtmlUtils.htmlEscape(super.getHeader(name));    }    @Override    public String getQueryString() {        return  HtmlUtils.htmlEscape(super.getQueryString());    }    @Override    public String getParameter(String name) {        return HtmlUtils.htmlEscape(super.getParameter(name));    }    @Override    public String[] getParameterValues(String name) {        String[] values = super.getParameterValues(name);        if(values != null) {            int length = values.length;            String[] escapseValues = new String[length];            for(int i = 0; i < length; i++){                escapseValues[i] =   HTMLFilter.filterParams( HTMLFilter.htmlSpecialChars(values[i]).replace("&","").replace(""","").replace("<","").replace(">","").replace("alert",""));            }            return escapseValues;        }        return super.getParameterValues(name);    }    @Override    public ServletInputStream getInputStream() throws IOException {        final ByteArrayInputStream bais = new ByteArrayInputStream(bytes);        return new ServletInputStream() {            @Override            public int read() throws IOException {                return bais.read();            }        };    }    private String getValues(HttpServletRequest request)throws IOException{        ServletInputStream inputStream = request.getInputStream();        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));        StringBuilder builder = new StringBuilder();        String value = null;        while((value = reader.readLine())!=null){            builder.append(value);        }        reader.close();        inputStream.close();        return builder.toString();    }    /**     * 获取请求Body     *     * @param request     * @return     */    public static String getBodyString(ServletRequest request) {        StringBuilder sb = new StringBuilder();        InputStream inputStream = null;        BufferedReader reader = null;        try {            inputStream = request.getInputStream();            reader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));            String line = "";            while ((line = reader.readLine()) != null) {                sb.append(line);            }        } catch (IOException e) {            e.printStackTrace();        } finally {            if (reader != null) {                try {                    reader.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            if (inputStream != null) {                try {                    inputStream.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }        return sb.toString();    }    public byte[] getBytes() {        return bytes;    }    public void setBytes(byte[] bytes) {        this.bytes = bytes;    }    public String getJson() {        return json;    }    public void setJson(String json) {        this.json = json;    }}

 

public final class HTMLFilter {    private final  static  String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alter", "drop","alert","javascript","jscript","vbscript"};    /** regex flag union representing /si modifiers in php **/    private static final int REGEX_FLAGS_SI = Pattern.CASE_INSENSITIVE | Pattern.DOTALL;    private static final Pattern P_COMMENTS = Pattern.compile("
", Pattern.DOTALL); private static final Pattern P_COMMENT = Pattern.compile("^!--(.*)--$", REGEX_FLAGS_SI); private static final Pattern P_TAGS = Pattern.compile("<(.*?)>", Pattern.DOTALL); private static final Pattern P_END_TAG = Pattern.compile("^/([a-z0-9]+)", REGEX_FLAGS_SI); private static final Pattern P_START_TAG = Pattern.compile("^([a-z0-9]+)(.*?)(/?)$", REGEX_FLAGS_SI); private static final Pattern P_QUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)=([\"'])(.*?)\\2", REGEX_FLAGS_SI); private static final Pattern P_UNQUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)(=)([^\"\\s']+)", REGEX_FLAGS_SI); private static final Pattern P_PROTOCOL = Pattern.compile("^([^:]+):", REGEX_FLAGS_SI); private static final Pattern P_ENTITY = Pattern.compile("&#(\\d+);?"); private static final Pattern P_ENTITY_UNICODE = Pattern.compile("&#x([0-9a-f]+);?"); private static final Pattern P_ENCODE = Pattern.compile("%([0-9a-f]{2});?"); private static final Pattern P_VALID_ENTITIES = Pattern.compile("&([^&;]*)(?=(;|&|$))"); private static final Pattern P_VALID_QUOTES = Pattern.compile("(>|^)([^<]+?)(<|$)", Pattern.DOTALL); private static final Pattern P_END_ARROW = Pattern.compile("^>"); private static final Pattern P_BODY_TO_END = Pattern.compile("<([^>]*?)(?=<|$)"); private static final Pattern P_XML_CONTENT = Pattern.compile("(^|>)([^<]*?)(?=>)"); private static final Pattern P_STRAY_LEFT_ARROW = Pattern.compile("<([^>]*?)(?=<|$)"); private static final Pattern P_STRAY_RIGHT_ARROW = Pattern.compile("(^|>)([^<]*?)(?=>)"); private static final Pattern P_AMP = Pattern.compile("&"); private static final Pattern P_QUOTE = Pattern.compile("<"); private static final Pattern P_LEFT_ARROW = Pattern.compile("<"); private static final Pattern P_RIGHT_ARROW = Pattern.compile(">"); private static final Pattern P_BOTH_ARROWS = Pattern.compile("<>"); // @xxx could grow large... maybe use sesat's ReferenceMap private static final ConcurrentMap
P_REMOVE_PAIR_BLANKS = new ConcurrentHashMap
(); private static final ConcurrentMap
P_REMOVE_SELF_BLANKS = new ConcurrentHashMap
(); /** set of allowed html elements, along with allowed attributes for each element **/ private final Map
> vAllowed; /** counts of open tags for each (allowable) html element **/ private final Map
vTagCounts = new HashMap
(); /** html elements which must always be self-closing (e.g. "
") **/ private final String[] vSelfClosingTags; /** html elements which must always have separate opening and closing tags (e.g. "
") **/ private final String[] vNeedClosingTags; /** set of disallowed html elements **/ private final String[] vDisallowed; /** attributes which should be checked for valid protocols **/ private final String[] vProtocolAtts; /** allowed protocols **/ private final String[] vAllowedProtocols; /** tags which should be removed if they contain no content (e.g. "
" or "
") **/ private final String[] vRemoveBlanks; /** entities allowed within html markup **/ private final String[] vAllowedEntities; /** flag determining whether comments are allowed in input String. */ private final boolean stripComment; private final boolean encodeQuotes; private boolean vDebug = false; /** * flag determining whether to try to make tags when presented with "unbalanced" * angle brackets (e.g. "
" becomes " text "). If set to false, * unbalanced angle brackets will be html escaped. */ private final boolean alwaysMakeTags; /** Default constructor. * */ public HTMLFilter() { vAllowed = new HashMap<>(); final ArrayList
a_atts = new ArrayList
(); a_atts.add("href"); a_atts.add("target"); vAllowed.put("a", a_atts); final ArrayList
img_atts = new ArrayList
(); img_atts.add("src"); img_atts.add("width"); img_atts.add("height"); img_atts.add("alt"); vAllowed.put("img", img_atts); final ArrayList
no_atts = new ArrayList
(); vAllowed.put("b", no_atts); vAllowed.put("strong", no_atts); vAllowed.put("i", no_atts); vAllowed.put("em", no_atts); vSelfClosingTags = new String[]{"img"}; vNeedClosingTags = new String[]{"a", "b", "strong", "i", "em"}; vDisallowed = new String[]{}; vAllowedProtocols = new String[]{"http", "mailto", "https"}; // no ftp. vProtocolAtts = new String[]{"src", "href"}; vRemoveBlanks = new String[]{"a", "b", "strong", "i", "em"}; vAllowedEntities = new String[]{"amp", "gt", "lt", "quot"}; stripComment = true; encodeQuotes = true; alwaysMakeTags = true; } /** Set debug flag to true. Otherwise use default settings. See the default constructor. * * @param debug turn debug on with a true argument */ public HTMLFilter(final boolean debug) { this(); vDebug = debug; } /** Map-parameter configurable constructor. * * @param conf map containing configuration. keys match field names. */ public HTMLFilter(final Map
conf) { assert conf.containsKey("vAllowed") : "configuration requires vAllowed"; assert conf.containsKey("vSelfClosingTags") : "configuration requires vSelfClosingTags"; assert conf.containsKey("vNeedClosingTags") : "configuration requires vNeedClosingTags"; assert conf.containsKey("vDisallowed") : "configuration requires vDisallowed"; assert conf.containsKey("vAllowedProtocols") : "configuration requires vAllowedProtocols"; assert conf.containsKey("vProtocolAtts") : "configuration requires vProtocolAtts"; assert conf.containsKey("vRemoveBlanks") : "configuration requires vRemoveBlanks"; assert conf.containsKey("vAllowedEntities") : "configuration requires vAllowedEntities"; vAllowed = Collections.unmodifiableMap((HashMap
>) conf.get("vAllowed")); vSelfClosingTags = (String[]) conf.get("vSelfClosingTags"); vNeedClosingTags = (String[]) conf.get("vNeedClosingTags"); vDisallowed = (String[]) conf.get("vDisallowed"); vAllowedProtocols = (String[]) conf.get("vAllowedProtocols"); vProtocolAtts = (String[]) conf.get("vProtocolAtts"); vRemoveBlanks = (String[]) conf.get("vRemoveBlanks"); vAllowedEntities = (String[]) conf.get("vAllowedEntities"); stripComment = conf.containsKey("stripComment") ? (Boolean) conf.get("stripComment") : true; encodeQuotes = conf.containsKey("encodeQuotes") ? (Boolean) conf.get("encodeQuotes") : true; alwaysMakeTags = conf.containsKey("alwaysMakeTags") ? (Boolean) conf.get("alwaysMakeTags") : true; } private void reset() { vTagCounts.clear(); } private void debug(final String msg) { if (vDebug) { Logger.getAnonymousLogger().info(msg); } } //--------------------------------------------------------------- // my versions of some PHP library functions public static String chr(final int decimal) { return String.valueOf((char) decimal); } public static String htmlSpecialChars(final String s) { String result = s; result = regexReplace(P_AMP, "&", result); result = regexReplace(P_QUOTE, """, result); result = regexReplace(P_LEFT_ARROW, "<", result); result = regexReplace(P_RIGHT_ARROW, ">", result); return result; } //--------------------------------------------------------------- /** * given a user submitted input String, filter out any invalid or restricted * html. * * @param input text (i.e. submitted by a user) than may contain html * @return "clean" version of input, with only valid, whitelisted html elements allowed */ public String filter(final String input) { reset(); String s = input; debug("************************************************"); debug(" INPUT: " + input); s = escapeComments(s); debug(" escapeComments: " + s); s = balanceHTML(s); debug(" balanceHTML: " + s); s = checkTags(s); debug(" checkTags: " + s); s = processRemoveBlanks(s); debug("processRemoveBlanks: " + s); s = validateEntities(s); debug(" validateEntites: " + s); debug("************************************************\n\n"); return s; } public boolean isAlwaysMakeTags(){ return alwaysMakeTags; } public boolean isStripComments(){ return stripComment; } private String escapeComments(final String s) { final Matcher m = P_COMMENTS.matcher(s); final StringBuffer buf = new StringBuffer(); if (m.find()) { final String match = m.group(1); //(.*?) m.appendReplacement(buf, Matcher.quoteReplacement("
")); } m.appendTail(buf); return buf.toString(); } private String balanceHTML(String s) { if (alwaysMakeTags) { // // try and form html // s = regexReplace(P_END_ARROW, "", s); s = regexReplace(P_BODY_TO_END, "<$1>", s); s = regexReplace(P_XML_CONTENT, "$1<$2", s); } else { // // escape stray brackets // s = regexReplace(P_STRAY_LEFT_ARROW, "<$1", s); s = regexReplace(P_STRAY_RIGHT_ARROW, "$1$2><", s); // // the last regexp causes '<>' entities to appear // (we need to do a lookahead assertion so that the last bracket can // be used in the next pass of the regexp) // s = regexReplace(P_BOTH_ARROWS, "", s); } return s; } private String checkTags(String s) { Matcher m = P_TAGS.matcher(s); final StringBuffer buf = new StringBuffer(); while (m.find()) { String replaceStr = m.group(1); replaceStr = processTag(replaceStr); m.appendReplacement(buf, Matcher.quoteReplacement(replaceStr)); } m.appendTail(buf); s = buf.toString(); // these get tallied in processTag // (remember to reset before subsequent calls to filter method) for (String key : vTagCounts.keySet()) { for (int ii = 0; ii < vTagCounts.get(key); ii++) { s += "
"; } } return s; } private String processRemoveBlanks(final String s) { String result = s; for (String tag : vRemoveBlanks) { if(!P_REMOVE_PAIR_BLANKS.containsKey(tag)){ P_REMOVE_PAIR_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?>
")); } result = regexReplace(P_REMOVE_PAIR_BLANKS.get(tag), "", result); if(!P_REMOVE_SELF_BLANKS.containsKey(tag)){ P_REMOVE_SELF_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?/>")); } result = regexReplace(P_REMOVE_SELF_BLANKS.get(tag), "", result); } return result; } private static String regexReplace(final Pattern regex_pattern, final String replacement, final String s) { Matcher m = regex_pattern.matcher(s); return m.replaceAll(replacement); } private String processTag(final String s) { // ending tags Matcher m = P_END_TAG.matcher(s); if (m.find()) { final String name = m.group(1).toLowerCase(); if (allowed(name)) { if (!inArray(name, vSelfClosingTags)) { if (vTagCounts.containsKey(name)) { vTagCounts.put(name, vTagCounts.get(name) - 1); return "
"; } } } } // starting tags m = P_START_TAG.matcher(s); if (m.find()) { final String name = m.group(1).toLowerCase(); final String body = m.group(2); String ending = m.group(3); //debug( "in a starting tag, name='" + name + "'; body='" + body + "'; ending='" + ending + "'" ); if (allowed(name)) { String params = ""; final Matcher m2 = P_QUOTED_ATTRIBUTES.matcher(body); final Matcher m3 = P_UNQUOTED_ATTRIBUTES.matcher(body); final List
paramNames = new ArrayList
(); final List
paramValues = new ArrayList
(); while (m2.find()) { paramNames.add(m2.group(1)); //([a-z0-9]+) paramValues.add(m2.group(3)); //(.*?) } while (m3.find()) { paramNames.add(m3.group(1)); //([a-z0-9]+) paramValues.add(m3.group(3)); //([^\"\\s']+) } String paramName, paramValue; for (int ii = 0; ii < paramNames.size(); ii++) { paramName = paramNames.get(ii).toLowerCase(); paramValue = paramValues.get(ii);// debug( "paramName='" + paramName + "'" );// debug( "paramValue='" + paramValue + "'" );// debug( "allowed? " + vAllowed.get( name ).contains( paramName ) ); if (allowedAttribute(name, paramName)) { if (inArray(paramName, vProtocolAtts)) { paramValue = processParamProtocol(paramValue); } params += " " + paramName + "=\"" + paramValue + "\""; } } if (inArray(name, vSelfClosingTags)) { ending = " /"; } if (inArray(name, vNeedClosingTags)) { ending = ""; } if (ending == null || ending.length() < 1) { if (vTagCounts.containsKey(name)) { vTagCounts.put(name, vTagCounts.get(name) + 1); } else { vTagCounts.put(name, 1); } } else { ending = " /"; } return "<" + name + params + ending + ">"; } else { return ""; } } // comments m = P_COMMENT.matcher(s); if (!stripComment && m.find()) { return "<" + m.group() + ">"; } return ""; } private String processParamProtocol(String s) { s = decodeEntities(s); final Matcher m = P_PROTOCOL.matcher(s); if (m.find()) { final String protocol = m.group(1); if (!inArray(protocol, vAllowedProtocols)) { // bad protocol, turn into local anchor link instead s = "#" + s.substring(protocol.length() + 1, s.length()); if (s.startsWith("#//")) { s = "#" + s.substring(3, s.length()); } } } return s; } private String decodeEntities(String s) { StringBuffer buf = new StringBuffer(); Matcher m = P_ENTITY.matcher(s); while (m.find()) { final String match = m.group(1); final int decimal = Integer.decode(match).intValue(); m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); } m.appendTail(buf); s = buf.toString(); buf = new StringBuffer(); m = P_ENTITY_UNICODE.matcher(s); while (m.find()) { final String match = m.group(1); final int decimal = Integer.valueOf(match, 16).intValue(); m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); } m.appendTail(buf); s = buf.toString(); buf = new StringBuffer(); m = P_ENCODE.matcher(s); while (m.find()) { final String match = m.group(1); final int decimal = Integer.valueOf(match, 16).intValue(); m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); } m.appendTail(buf); s = buf.toString(); s = validateEntities(s); return s; } private String validateEntities(final String s) { StringBuffer buf = new StringBuffer(); // validate entities throughout the string Matcher m = P_VALID_ENTITIES.matcher(s); while (m.find()) { final String one = m.group(1); //([^&;]*) final String two = m.group(2); //(?=(;|&|$)) m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two))); } m.appendTail(buf); return encodeQuotes(buf.toString()); } private String encodeQuotes(final String s){ if(encodeQuotes){ StringBuffer buf = new StringBuffer(); Matcher m = P_VALID_QUOTES.matcher(s); while (m.find()) { final String one = m.group(1); //(>|^) final String two = m.group(2); //([^<]+?) final String three = m.group(3); //(<|$) m.appendReplacement(buf, Matcher.quoteReplacement(one + regexReplace(P_QUOTE, """, two) + three)); } m.appendTail(buf); return buf.toString(); }else{ return s; } } private String checkEntity(final String preamble, final String term) { return ";".equals(term) && isValidEntity(preamble) ? '&' + preamble : "&" + preamble; } private boolean isValidEntity(final String entity) { return inArray(entity, vAllowedEntities); } private static boolean inArray(final String s, final String[] array) { for (String item : array) { if (item != null && item.equals(s)) { return true; } } return false; } private boolean allowed(final String name) { return (vAllowed.isEmpty() || vAllowed.containsKey(name)) && !inArray(name, vDisallowed); } private boolean allowedAttribute(final String name, final String paramName) { return allowed(name) && (vAllowed.isEmpty() || vAllowed.get(name).contains(paramName)); } public static String filterParams(String value){ for(String keyword : keywords){ if(value.contains(keyword) ){ throw new XssException("包含非法的字符"); } } return value; }}

转载地址:http://qmvbi.baihongyu.com/

你可能感兴趣的文章
[Mac]Mac 操作系统 常见技巧
查看>>
苹果Swift编程语言入门教程【中文版】
查看>>
捕鱼忍者(ninja fishing)之游戏指南+游戏攻略+游戏体验
查看>>
iphone开发基础之objective-c学习
查看>>
iphone开发之SDK研究(待续)
查看>>
计算机网络复习要点
查看>>
Variable property attributes or Modifiers in iOS
查看>>
NSNotificationCenter 用法总结
查看>>
C primer plus 基础总结(一)
查看>>
剑指offer算法题分析与整理(一)
查看>>
剑指offer算法题分析与整理(三)
查看>>
部分笔试算法题整理
查看>>
Ubuntu 13.10使用fcitx输入法
查看>>
pidgin-lwqq 安装
查看>>
mint/ubuntu安装搜狗输入法
查看>>
C++动态申请数组和参数传递问题
查看>>
opencv学习——在MFC中读取和显示图像
查看>>
retext出现Could not parse file contents, check if you have the necessary module installed解决方案
查看>>
pyQt不同窗体间的值传递(一)——对话框关闭时返回值给主窗口
查看>>
linux mint下使用外部SMTP(如网易yeah.net)发邮件
查看>>