跨站腳本攻擊(Cross Site Scripting),爲不和層疊樣式表(Cascading Style Sheets, CSS)的縮寫混淆,故將跨站腳本攻擊縮寫爲XSS。惡意攻擊者往Web頁面裏插入惡意Script代碼,當用戶瀏覽該頁之時,嵌入其中Web裏面的Script代碼會被執行,從而達到惡意攻擊用戶的目的。javascript
在線演示:https://wall-wxk.github.io/blogDemo/2017/01/19/noEncode.html
html
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <title>encode防止xss攻擊</title> </head> <body> <input type="text" id="myInput" /> <button onclick="toSubmit();">提交</button> <p id="myText" class="demo">hello world!</p> <script type="text/javascript"> function toSubmit(){ var myText = document.getElementById("myText"), myInput = document.getElementById("myInput"), inputValue = myInput.value; myText.innerHTML = inputValue; } </script> </body> </html>
實例解釋:這是網站生產環境抽離出來的簡化代碼。在公司的產品中,有不少輸入框提供給用戶輸入一些自定義字符串。方便用戶的同時,也會招惹一些黑客過來搗亂。最簡單的就是xss注入攻擊。前端
好比上面的實例,我在輸入框直接輸入內容 <h1>wall</h1>
,獲得的結果以下:java
這種結果,確定不是產品所想要的。git
進一步鼓搗,輸入內容 <script>alert('wall');</script>
github
若是這段字符串是保存在數據庫裏。那麼下次用戶刷新這個頁面,alert方法將會被執行,也就是會彈出 wall 這個信息。
由於能插入js代碼,那這個想象空間就很大了,幾乎不少事都能幹。
最簡單的就是用js獲取訪問當前網站的用戶的document.cookie,而後ajax發送到信息收集網站,那麼用戶就等於在裸泳了。ajax
function encodeHtml(html){ return html && html.replace ? ( html.replace(/&/g, "&") //轉換&符號 .replace(/ /g, " ") // 轉換空格 .replace(/\b +/g, " ") // 轉換多個空格爲單個空格 .replace(/</g, "<") // 轉換小於符號 .replace(/>/g, ">") // 轉換大於符號 .replace(/\\/g, "\") // 轉換斜槓符號 .replace(/\'/g, "'") // 轉換單引號 .replace(/\"/g, """) // 轉換雙引號 .replace(/\n/g, "<br/>") // 轉換換行符號 .replace(/\r/g, "") //轉換回車符號 ) : html; }
代碼的做用是把對應的特殊符號,轉換爲轉義字符,而不是直接插入html中。
這樣,無論用戶輸入什麼內容,均可以直接轉換成字符串輸出在html中。數據庫
好比再次輸入內容 <script>alert('wall');</script>
,獲得的結果以下:cookie
perfect!直接把xss漏洞給堵上了!xss
更多內容,能夠查看HTML轉義字符表
在線演示:https://wall-wxk.github.io/blogDemo/2017/01/19/xss.html
最後,附上完整的測試代碼
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <title>encode防止xss攻擊</title> </head> <body> <input type="text" id="myInput" /> <button onclick="toSubmit();">提交</button> <p id="myText" class="demo">hello world!</p> <script type="text/javascript"> function toSubmit(){ var myText = document.getElementById("myText"), myInput = document.getElementById("myInput"), inputValue = myInput.value; myText.innerHTML = encodeHtml(inputValue); } function encodeHtml(html){ return html && html.replace ? ( html.replace(/&/g, "&") //轉換&符號 .replace(/ /g, " ") // 轉換空格 .replace(/\b +/g, " ") // 轉換多個空格爲單個空格 .replace(/</g, "<") // 轉換小於符號 .replace(/>/g, ">") // 轉換大於符號 .replace(/\\/g, "\") // 轉換斜槓符號 .replace(/\'/g, "'") // 轉換單引號 .replace(/\"/g, """) // 轉換雙引號 .replace(/\n/g, "<br/>") // 轉換換行符號 .replace(/\r/g, "") //轉換回車符號 ) : html; } </script> </body> </html>