Files
build-web-application-with-…/zh/04.3.md
2017-06-10 11:49:09 +08:00

73 lines
3.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 4.3 预防跨站脚本
现在的网站包含大量的动态内容以提高用户体验比过去要复杂得多。所谓动态内容就是根据用户环境和需要Web应用程序能够输出相应的内容。动态站点会受到一种名为“跨站脚本攻击”Cross Site Scripting, 安全专家们通常将其缩写成 XSS的威胁而静态站点则完全不受其影响。
攻击者通常会在有漏洞的程序中插入JavaScript、VBScript、 ActiveX或Flash以欺骗用户。一旦得手他们可以盗取用户帐户信息修改用户设置盗取/污染cookie和植入恶意广告等。
对XSS最佳的防护应该结合以下两种方法一是验证所有输入数据有效检测攻击(这个我们前面小节已经有过介绍);另一个是对所有输出数据进行适当的处理,以防止任何已成功注入的脚本在浏览器端运行。
那么Go里面是怎么做这个有效防护的呢Go的html/template里面带有下面几个函数可以帮你转义
- func HTMLEscape(w io.Writer, b []byte) //把b进行转义之后写到w
- func HTMLEscapeString(s string) string //转义s之后返回结果字符串
- func HTMLEscaper(args ...interface{}) string //支持多个参数一起转义,返回结果字符串
我们看4.1小节的例子
```Go
fmt.Println("username:", template.HTMLEscapeString(r.Form.Get("username"))) //输出到服务器端
fmt.Println("password:", template.HTMLEscapeString(r.Form.Get("password")))
template.HTMLEscape(w, []byte(r.Form.Get("username"))) //输出到客户端
```
如果我们输入的username是`<script>alert()</script>`,那么我们可以在浏览器上面看到输出如下所示:
![](images/4.3.escape.png?raw=true)
图4.3 Javascript过滤之后的输出
Go的html/template包默认帮你过滤了html标签但是有时候你只想要输出这个`<script>alert()</script>`看起来正常的信息该怎么处理请使用text/template。请看下面的例子
```Go
import "text/template"
...
t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned')</script>")
```
输出
Hello, <script>alert('you have been pwned')</script>!
或者使用template.HTML类型
```Go
import "html/template"
...
t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
err = t.ExecuteTemplate(out, "T", template.HTML("<script>alert('you have been pwned')</script>"))
```
输出
Hello, <script>alert('you have been pwned')</script>!
转换成`template.HTML`后,变量的内容也不会被转义
转义的例子:
```Go
import "html/template"
...
t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned')</script>")
```
转义之后的输出:
Hello, &lt;script&gt;alert(&#39;you have been pwned&#39;)&lt;/script&gt;!
## links
* [目录](<preface.md>)
* 上一节: [验证的输入](<04.2.md>)
* 下一节: [防止多次递交表单](<04.4.md>)