4.3小节
This commit is contained in:
51
4.3.md
Normal file
51
4.3.md
Normal file
@@ -0,0 +1,51 @@
|
||||
#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小节的例子
|
||||
|
||||
fmt.Println("username:", HTMLEscapeString(r.Form["username"])) //输出到服务器端
|
||||
fmt.Println("password:", HTMLEscapeString(r.Form["password"]))
|
||||
HTMLEscape(w,r.Form["username"]) //输出到客户端
|
||||
|
||||
那么我们在输出我们的模板的时候怎么处理的呢?Go的html/template包现在默认就帮你过滤了html元素,但是有时候你又想输出这样的信息,text/template也支持。请看下面的例子所示
|
||||
|
||||
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>!
|
||||
|
||||
转义的例子:
|
||||
|
||||
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, <script>alert('you have been pwned')</script>!
|
||||
|
||||
|
||||
|
||||
## links
|
||||
* [目录](<preface.md>)
|
||||
* 上一节: [验证的输入](<4.2.md>)
|
||||
* 下一节: [防止多次递交表单](<4.4.md>)
|
||||
|
||||
## LastModified
|
||||
* $Id$
|
||||
Reference in New Issue
Block a user