現在的網站包含大量的動態內容以提高用戶體驗,比過去要復雜得多,所謂動態內容,就是根據用戶環境和需要,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:", template.HTMLEscapeString(r.Form.Get("username"))) //輸出到服務器端
fmt.Println("password:", template.HTMLEscapeString(r.Form.Get("password")))
template.HTMLEscape(w, []byte(r.Form.Get("username"))) //輸出到客戶端
Go的html/template包默認幫你過濾了html標簽,但是有時候你只想要輸出這個alert()看起來正常的資訊,該怎么處理?請使用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>!
或者使用template.HTML型別
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后,變數的內容也不會被轉義
轉義的例子:
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>!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/258141.html
標籤:其他
