一、开场先科普下XSS
跨站脚本攻击
(Cross Site Scripting),为不和
层叠样式表
(Cascading Style Sheets,
CSS
)的缩写混淆,故将跨站脚本攻击缩写为XSS。恶意攻击者往Web页面里插入恶意Script代码,当用户浏览该页之时,嵌入其中Web里面的Script代码会被执行,从而达到恶意攻击用户的目的。
二、直接上代码实例
在线演示
:
https://wall-wxk.github.io/blogDemo/2017/01/19/noEncode.html
<!DOCTYPE HTML>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>encode防止xss攻击</title>
</head>
<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>
如果这段字符串是保存在数据库里。那么下次用户刷新这个页面,alert方法将会被执行,也就是会弹出 wall 这个信息。
因为能插入js代码,那这个想象空间就很大了,几乎很多事都能干。
最简单的就是用js获取访问当前网站的用户的document.cookie,然后ajax发送到信息收集网站,那么用户就等于在裸泳了。
三、解决方式-对字符串进行转义后再输出
1.在存储进数据库的时候,对字符串进行encode
这种方式可以解决一部分问题,但是不够灵活。因为字符串有可能输出在html,也有可能输出在JavaScript代码中。
2.在使用字符串的时候进行encode
这种方式是根据使用场景,在前端输出时,按需求进行encode,灵活应对。
四、直接上encode方法
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>
,得到的结果如下:
perfect!直接把xss漏洞给堵上了!
五、科普下转义字符
更多内容,可以查看HTML转义字符表
在线演示:https://wall-wxk.github.io/blogDemo/2017/01/19/xss.html
最后,附上完整的测试代码
<!DOCTYPE HTML>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>encode防止xss攻击</title>
</head>
<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>
原文入口:http://www.jianshu.com/p/6fa7622767c5