All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.kaizen4j.common.util.XSSUtils Maven / Gradle / Ivy

package org.kaizen4j.common.util;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;

import java.util.regex.Pattern;

import static org.kaizen4j.common.base.Symbols.EMPTY;

public final class XSSUtils {

    private static final Pattern[] patterns = new Pattern[] {
            // Script fragments
            Pattern.compile("", Pattern.CASE_INSENSITIVE),

            // src='...'
            Pattern.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),
            Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"",
                    Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),

            // lonely script tags
            Pattern.compile("", Pattern.CASE_INSENSITIVE),
            Pattern.compile("",
                    Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),

            // eval(...)
            Pattern.compile("eval\\((.*?)\\)",
                    Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),

            // expression(...)
            Pattern.compile("expression\\((.*?)\\)",
                    Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),

            // javascript:...
            Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE),

            // vbscript:...
            Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE),

            // onload=...
            Pattern.compile("onload(.*?)=",
                    Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL)};

    private static final String AVOID = "\0";

    /**
     * 过滤 XSS 脚本
     *
     * @param scriptPatterns 过滤模式
     * @param content 过滤字符串
     * @return String 过滤后的字符串
     */
    public static String filter(Pattern[] scriptPatterns, String content) {
        if (StringUtils.isEmpty(content)) {
            return content;
        }

        // Avoid null characters
        content = content.replaceAll(AVOID, EMPTY);
        for (Pattern scriptPattern : scriptPatterns) {
            content = scriptPattern.matcher(content).replaceAll(EMPTY);
        }
        content = Jsoup.clean(content, Whitelist.basic());
        return content;
    }

    /**
     * 过滤 XSS 脚本
     *
     * @param content 过滤字符串
     * @return String 过滤后的字符串
     */
    public static String filter(String content) {
        return filter(patterns, content);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy