现在的网站包含大量的动态内容以提高用户体验,比过去要复杂得多。攻击者通常会在有漏洞的程序中插入JavaScript以欺骗用户。一旦得手,他们可以盗取用户帐户信息,修改用户设置,盗取/污染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 //支持多个参数一起转义,返回结果字符串
GO代码
package main
import (
"fmt"
"html/template"
"log"
"net/http"
)
func saygo(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
t, _ := template.ParseFiles("form.html")
t.Execute(w, nil)
} else {
w.Header().Set("Content-Type", "text/html;charset=utf-8")
r.ParseForm()
//username := r.Form.Get("username")
username := template.HTMLEscapeString(r.Form.Get("username"))
fmt.Fprintf(w, username)
fmt.Fprintf(w, "<br/>")
t, _ := template.ParseFiles("form.html")
t.Execute(w, nil)
}
}
func main() {
http.HandleFunc("/", saygo)
err := http.ListenAndServe(":9090", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
模板文件:
<html>
<head>
<title>预防跨站脚本</title>
</head>
<body>
<form action="" method="post">
输入:<input type="text" value="<script>alert('攻击')</script>" name="username"><br/>
<input type="submit" value="提交">
</form>
</body>
</html>
通过示例,你就可以明白GO是怎么处理转义安全的.
I have some cellulite and no shortage of scars
gay porn Natalie Getz Looks Hot in ICE
monster box collection 1
miranda lambert weight lossEntertainer tops herself again at Grammy Awards Show photo Show
miranda lambert weight lossEntertainer tops herself again at Grammy Awards Show photo Show
