php富文本中防止xss,允许用户做富文本编辑的站点要怎么防 XSS 呢

  • Post author:
  • Post category:php


4

2019-03-12 10:26:10 +08:00

参考下

“`java

// 预编译 XSS 过滤正则表达式

private static List xssPatterns = ListUtils.newArrayList(

Pattern.compile(“(|))|(\\s*(script|link|style|iframe)\\s*>)”, Pattern.CASE_INSENSITIVE),

Pattern.compile(“\\s*(href|src)\\s*=\\s*(\”\\s*(javascript|vbscript):[^\”]+\”|’\\s*(javascript|vbscript):[^’]+’|(javascript|vbscript):[^\\s]+)\\s*(?=>)”, Pattern.CASE_INSENSITIVE),

Pattern.compile(“\\s*on[a-z]+\\s*=\\s*(\”[^\”]+\”|'[^’]+’|[^\\s]+)\\s*(?=>)”, Pattern.CASE_INSENSITIVE),

Pattern.compile(“(eval\\((.*?)\\)|xpression\\((.*?)\\))”, Pattern.CASE_INSENSITIVE)

);

/**

* XSS 非法字符过滤,内容以开头的用以下规则(保留标签)

* @author ThinkGem

*/

public static String xssFilter(String text) {

String oriValue = StringUtils.trim(text);

if (text != null){

String value = oriValue;

for (Pattern pattern : xssPatterns) {

Matcher matcher = pattern.matcher(value);

if (matcher.find()) {

value = matcher.replaceAll(StringUtils.EMPTY);

}

}

// 如果开始不是 HTML,XML,JOSN 格式,则再进行 HTML 的 “、 转码。

if (!StringUtils.startsWithIgnoreCase(value, “”) // HTML

&& !StringUtils.startsWithIgnoreCase(value, “<?xml “) // XML

&& !StringUtils.contains(value, “id=\”FormHtml\””) // JFlow

&& !(StringUtils.startsWith(value, “{“) && StringUtils.endsWith(value, “}”)) // JSON Object

&& !(StringUtils.startsWith(value, “[“) && StringUtils.endsWith(value, “]”)) // JSON Array

){

StringBuilder sb = new StringBuilder();

for (int i = 0; i < value.length(); i++) {

char c = value.charAt(i);

switch (c) {

case ‘>’:

sb.append(“>”);

break;

case ‘

sb.append(“<”);

break;

case ‘\”:

sb.append(“'”);

break;

case ‘\”‘:

sb.append(“"”);

break;

// case ‘&’:

// sb.append(“&”);

// break;

// case ‘#’:

// sb.append(“#”);

// break;

default:

sb.append(c);

break;

}

}

value = sb.toString();

}

if (logger.isInfoEnabled() && !value.equals(oriValue)){

logger.info(“xssFilter: {} <=<=<= {}”, value, text);

}

return value;

}

return null;

}

// 预编译 SQL 过滤正则表达式

private static Pattern sqlPattern = Pattern.compile(“(?:’)|(?:–)|(/\\*(?:.|[\\n\\r])*?\\*/)|(\\b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)\\b)”, Pattern.CASE_INSENSITIVE);

/**

* SQL 过滤,防止注入,传入参数输入有 select 相关代码,替换空。

* @author ThinkGem

*/

public static String sqlFilter(String text){

if (text != null){

String value = text;

Matcher matcher = sqlPattern.matcher(text);

if (matcher.find()) {

value = matcher.replaceAll(StringUtils.EMPTY);

}

if (logger.isWarnEnabled() && !value.equals(text)){

logger.info(“sqlFilter: {} <=<=<= {}”, value, text);

return StringUtils.EMPTY;

}

return value;

}

return null;

}

“`