提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 一.xss漏洞的定义
-
-
-
- [跨站脚本攻击(xss):指攻击者通过篡改网页,嵌入恶意脚本程序,在用户浏览网页时,控制用户浏览器进行恶意操作的一种攻击方式。](#跨站脚本攻击(xss):指攻击者通过篡改网页,嵌入恶意脚本程序,在用户浏览网页时,控制用户浏览器进行恶意操作的一种攻击方式。)
-
- [1.1 xss的介绍](#1.1 xss的介绍)
- [1.2 XSS类 型](#1.2 XSS类 型)
- 1.3XSS分类详解
- [1.4 xss攻击原理](#1.4 xss攻击原理)
- [1.5 常见XSS攻击方式](#1.5 常见XSS攻击方式)
-
- 二、xss的危害
- 三:xss的防御手段
一.xss漏洞的定义
- 什么是跨站脚本攻击
跨站脚本攻击(xss):指攻击者通过篡改网页,嵌入恶意脚本程序,在用户浏览网页时,控制用户浏览器进行恶意操作的一种攻击方式。
1.1 xss的介绍
- 跨站脚本攻击(Cross Site Scripting),为了不和层叠样式表(Cascading Style Sheets )的缩写混淆,故将跨站脚本攻击缩写为XSS。恶意攻击者往web页面里插入恶意script代码,当用户浏览该页时,嵌入其中web里面的script代码会被执行,从而达到恶意攻击用户的目的
1.2 XSS类 型
反射型:
- 反射型也称为非持久型,这种类型的脚本是最常见的,也是使用最为广泛的一种,主要用于将恶意的脚本附加到URL地址的参数中。
存储型:
- 攻击者将已经构造完成的恶意页面发送给用户,用户访问看似正常的页面后收到攻击,这类XSS通常无法直接在URL中看到恶意代码,具有较强的持久性和隐蔽性。
DOM
- DOM型XSS无需和后端交互,而是基于JavaScript上,JS解析URL中恶意参数导致执行JS代码
1.3XSS分类详解
(1)存储型XSS
- 存储型XSS:持久性,代码是存储在web服务器中的,比如在个人信息或发表文章等地方插入代码,如果没有过滤或者过滤不严,那么这些代码将存储在服务器中,用户访问该页面的时候触发代码执行。这种XSS比较危险,容易造成蠕虫、盗窃cookie。每一个访问特定页面的用户,都会受到攻击。
- 特点:XSS攻击代码存储于web server 上;攻击者一般是通过网站的留言、评论、博客、日志等功能(所有能够向web
server输入内容的地方),将攻击代码存储到web server上的

(2)反射型XSS
- 反射型跨站脚本也称作非持久型、参数型跨站脚本、这类型的脚本是最常见的 ,也是使用最为广泛的一种,主要用于将恶意的脚本附加到URL地址的参数中。
html
http://www.test.com/search.php?key="><script>alert("xss")</script>

1.4 xss攻击原理
- XSS是指攻击者在网页中嵌入客户端脚本,通常是JavaScript 编写的恶意代码,也有使用其他客户端脚本语言编写的。当用户使用浏览器浏览被嵌入恶意代码的网页时,恶意代码将会在用户的浏览器上执行。
- Javascript 可以用来获取用户的 Cookie、改变网页内容、URL 跳转,攻击者可以在 script 标签中输入Javascript 代码,如 alert(/xss/),实现一些"特殊效果"。
1.5 常见XSS攻击方式
下面我列举的标签大部分是可以自动触发js代码的,无需用户去交互,大部分情况下我们也是希望是自动触发而不是等用户去触发。







二、xss的危害



三:xss的防御手段
案例
- HtmlFilter
java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* HTML过滤器,用于去除XSS漏洞隐患。
* * @author ruoyi
*/
public final class HtmlFilter {
/**
* regex flag union representing /si modifiers in php
*/
private static final int REGEX_FLAGS_SI = Pattern.CASE_INSENSITIVE | Pattern.DOTALL;
/**
* The constant P_COMMENTS.
*/
private static final Pattern P_COMMENTS = Pattern.compile("<!--(.*?)-->", Pattern.DOTALL);
/**
* The constant P_COMMENT.
*/
private static final Pattern P_COMMENT = Pattern.compile("^!--(.*)--$", REGEX_FLAGS_SI);
/**
* The constant P_TAGS.
*/
private static final Pattern P_TAGS = Pattern.compile("<(.*?)>", Pattern.DOTALL);
/**
* The constant P_END_TAG.
*/
private static final Pattern P_END_TAG = Pattern.compile("^/([a-z0-9]+)", REGEX_FLAGS_SI);
/**
* The constant P_START_TAG.
*/
private static final Pattern P_START_TAG = Pattern.compile("^([a-z0-9]+)(.*?)(/?)$", REGEX_FLAGS_SI);
/**
* The constant P_QUOTED_ATTRIBUTES.
*/
private static final Pattern P_QUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)=([\"'])(.*?)\\2", REGEX_FLAGS_SI);
/**
* The constant P_UNQUOTED_ATTRIBUTES.
*/
private static final Pattern P_UNQUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)(=)([^\"\\s']+)", REGEX_FLAGS_SI);
/**
* The constant P_PROTOCOL.
*/
private static final Pattern P_PROTOCOL = Pattern.compile("^([^:]+):", REGEX_FLAGS_SI);
/**
* The constant P_ENTITY.
*/
private static final Pattern P_ENTITY = Pattern.compile("&#(\\d+);?");
/**
* The constant P_ENTITY_UNICODE.
*/
private static final Pattern P_ENTITY_UNICODE = Pattern.compile("&#x([0-9a-f]+);?");
/**
* The constant P_ENCODE.
*/
private static final Pattern P_ENCODE = Pattern.compile("%([0-9a-f]{2});?");
/**
* The constant P_VALID_ENTITIES.
*/
private static final Pattern P_VALID_ENTITIES = Pattern.compile("&([^&;]*)(?=(;|&|$))");
/**
* The constant P_VALID_QUOTES.
*/
private static final Pattern P_VALID_QUOTES = Pattern.compile("(>|^)([^<]+?)(<|$)", Pattern.DOTALL);
/**
* The constant P_END_ARROW.
*/
private static final Pattern P_END_ARROW = Pattern.compile("^>");
/**
* The constant P_BODY_TO_END.
*/
private static final Pattern P_BODY_TO_END = Pattern.compile("<([^>]*?)(?=<|$)");
/**
* The constant P_XML_CONTENT.
*/
private static final Pattern P_XML_CONTENT = Pattern.compile("(^|>)([^<]*?)(?=>)");
/**
* The constant P_STRAY_LEFT_ARROW.
*/
private static final Pattern P_STRAY_LEFT_ARROW = Pattern.compile("<([^>]*?)(?=<|$)");
/**
* The constant P_STRAY_RIGHT_ARROW.
*/
private static final Pattern P_STRAY_RIGHT_ARROW = Pattern.compile("(^|>)([^<]*?)(?=>)");
/**
* The constant P_AMP.
*/
private static final Pattern P_AMP = Pattern.compile("&");
/**
* The constant P_QUOTE.
*/
private static final Pattern P_QUOTE = Pattern.compile("\"");
/**
* The constant P_LEFT_ARROW.
*/
private static final Pattern P_LEFT_ARROW = Pattern.compile("<");
/**
* The constant P_RIGHT_ARROW.
*/
private static final Pattern P_RIGHT_ARROW = Pattern.compile(">");
/**
* The constant P_BOTH_ARROWS.
*/
private static final Pattern P_BOTH_ARROWS = Pattern.compile("<>");
/**
* The constant P_REMOVE_PAIR_BLANKS.
*/
private static final ConcurrentMap<String, Pattern> P_REMOVE_PAIR_BLANKS = new ConcurrentHashMap<>();
/**
* The constant P_REMOVE_SELF_BLANKS.
*/
private static final ConcurrentMap<String, Pattern> P_REMOVE_SELF_BLANKS = new ConcurrentHashMap<>();
public static final String PREFIX = "#//";
/**
* set of allowed html elements, along with allowed attributes for each element
*/
private final Map<String, List<String>> vAllowed;
/**
* counts of open tags for each (allowable) html element
*/
private final Map<String, Integer> vTagCounts = new HashMap<>();
/**
* html elements which must always be self-closing (e.g. "<img />")
*/
private final String[] vSelfClosingTags;
/**
* html elements which must always have separate opening and closing tags (e.g. "<b></b>")
*/
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. "<b></b>" or "<b />")
*/
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;
/**
* The Encode quotes.
*/
private final boolean encodeQuotes;
/**
* flag determining whether to try to make tags when presented with "unbalanced" angle brackets (e.g. "<b text </b>"
* becomes "<b> text </b>"). If set to false, unbalanced angle brackets will be html escaped.
*/
private final boolean alwaysMakeTags;
/**
* Default constructor.
*/
public HtmlFilter() {
vAllowed = new HashMap<>();
final ArrayList<String> atts = new ArrayList<>();
atts.add("href");
atts.add("target");
vAllowed.put("a", atts);
final ArrayList<String> imgAtts = new ArrayList<>();
imgAtts.add("src");
imgAtts.add("width");
imgAtts.add("height");
imgAtts.add("alt");
vAllowed.put("img", imgAtts);
final ArrayList<String> noAtts = new ArrayList<>();
vAllowed.put("b", noAtts);
vAllowed.put("strong", noAtts);
vAllowed.put("i", noAtts);
vAllowed.put("em", noAtts);
vSelfClosingTags = new String[]{"img"};
vNeedClosingTags = new String[]{"a", "b", "strong", "i", "em"};
vDisallowed = new String[]{};
vAllowedProtocols = new String[]{"http", "mailto", "https"};
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 = false;
}
/**
* Map-parameter configurable constructor.
*
* @param conf map containing configuration. keys match field names.
*/
@SuppressWarnings("unchecked")
public HtmlFilter(final Map<String, Object> 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<String, List<String>>) 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;
}
/**
* Reset.
*/
private void reset() {
vTagCounts.clear();
}
/**
* Chr string.
*
* @param decimal the decimal
* @return the string
*/
public static String chr(final int decimal) {
return String.valueOf((char) decimal);
}
/**
* Html special chars string.
*
* @param s the s
* @return the string
*/
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;
s = escapeComments(s);
s = balanceHtml(s);
s = checkTags(s);
s = processRemoveBlanks(s);
return s;
}
/**
* Is always make tags boolean.
*
* @return the boolean
*/
public boolean isAlwaysMakeTags() {
return alwaysMakeTags;
}
/**
* Is strip comments boolean.
*
* @return the boolean
*/
public boolean isStripComments() {
return stripComment;
}
/**
* Escape comments string.
*
* @param s the s
* @return the string
*/
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("<!--" + htmlSpecialChars(match) + "-->"));
}
m.appendTail(buf);
return buf.toString();
}
/**
* Balance html string.
*
* @param s the s
* @return the string
*/
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;
}
/**
* Check tags string.
*
* @param s the s
* @return the string
*/
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);
// these get tallied in processTag
// (remember to reset before subsequent calls to filter method)
final StringBuilder sBuilder = new StringBuilder(buf.toString());
for (String key : vTagCounts.keySet()) {
for (int ii = 0; ii < vTagCounts.get(key); ii++) {
sBuilder.append("</").append(key).append(">");
}
}
s = sBuilder.toString();
return s;
}
/**
* Process remove blanks string.
*
* @param s the s
* @return the string
*/
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[^>]*)?></" + tag + ">"));
}
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;
}
/**
* Regex replace string.
*
* @param regex_pattern the regex pattern
* @param replacement the replacement
* @param s the s
* @return the string
*/
private static String regexReplace(final Pattern regexPattern, final String replacement, final String s) {
Matcher m = regexPattern.matcher(s);
return m.replaceAll(replacement);
}
/**
* Process tag string.
*
* @param s the s
* @return the string
*/
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 (false == inArray(name, vSelfClosingTags)) {
if (vTagCounts.containsKey(name)) {
vTagCounts.put(name, vTagCounts.get(name) - 1);
return "</" + name + ">";
}
}
}
}
// 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)) {
final StringBuilder params = new StringBuilder();
final Matcher m2 = P_QUOTED_ATTRIBUTES.matcher(body);
final Matcher m3 = P_UNQUOTED_ATTRIBUTES.matcher(body);
final List<String> paramNames = new ArrayList<>();
final List<String> paramValues = new ArrayList<>();
while (m2.find()) {
paramNames.add(m2.group(1));
paramValues.add(m2.group(3));
}
while (m3.find()) {
paramNames.add(m3.group(1));
paramValues.add(m3.group(3));
}
String paramName, paramValue;
for (int ii = 0; ii < paramNames.size(); ii++) {
paramName = paramNames.get(ii).toLowerCase();
paramValue = paramValues.get(ii);
if (allowedAttribute(name, paramName)) {
if (inArray(paramName, vProtocolAtts)) {
paramValue = processParamProtocol(paramValue);
}
params.append(' ').append(paramName).append("=\"").append(paramValue).append("\"");
}
}
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 "";
}
/**
* Process param protocol string.
*
* @param s the s
* @return the string
*/
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);
if (s.startsWith(PREFIX)) {
s = "#" + s.substring(3);
}
}
}
return s;
}
/**
* Decode entities string.
*
* @param s the s
* @return the string
*/
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;
}
/**
* Validate entities string.
*
* @param s the s
* @return the string
*/
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());
}
/**
* Encode quotes string.
*
* @param s the s
* @return the string
*/
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);
// 不替换双引号为",防止json格式无效 regexReplace(P_QUOTE, """, two)
m.appendReplacement(buf, Matcher.quoteReplacement(one + two + three));
}
m.appendTail(buf);
return buf.toString();
} else {
return s;
}
}
/**
* Check entity string.
*
* @param preamble the preamble
* @param term the term
* @return the string
*/
private String checkEntity(final String preamble, final String term) {
return ";".equals(term) && isValidEntity(preamble) ? '&' + preamble : "&" + preamble;
}
/**
* Is valid entity boolean.
*
* @param entity the entity
* @return the boolean
*/
private boolean isValidEntity(final String entity) {
return inArray(entity, vAllowedEntities);
}
/**
* In array boolean.
*
* @param s the s
* @param array the array
* @return the boolean
*/
private static boolean inArray(final String s, final String[] array) {
for (String item : array) {
if (item != null && item.equals(s)) {
return true;
}
}
return false;
}
/**
* Allowed boolean.
*
* @param name the name
* @return the boolean
*/
private boolean allowed(final String name) {
return (vAllowed.isEmpty() || vAllowed.containsKey(name)) && !inArray(name, vDisallowed);
}
/**
* Allowed attribute boolean.
*
* @param name the name
* @param paramName the param name
* @return the boolean
*/
private boolean allowedAttribute(final String name, final String paramName) {
return allowed(name) && (vAllowed.isEmpty() || vAllowed.get(name).contains(paramName));
}
}
- 测试
java
public static void main(String[] args) {
// 1. 创建过滤实例(使用默认规则)
HtmlFilter htmlFilter = new HtmlFilter();
// 2. 待过滤的恶意输入
String maliciousInput = "<script>alert('XSS')</script><a href='javascript:alert(1)'>危险链接</a><img src=x onerror='alert(2)' />";
if (StringUtils.isNotEmpty(maliciousInput)) {
// 3. 执行过滤
String safeInput = htmlFilter.filter(maliciousInput);
// 4. 输出结果(已过滤危险内容)
System.out.println("=====================================");
System.out.println(maliciousInput);
System.out.println(safeInput);
}
}

- 应用
