W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
現(xiàn)在的網(wǎng)站包含大量的動態(tài)內(nèi)容以提高用戶體驗,比過去要復(fù)雜得多。所謂動態(tài)內(nèi)容,就是根據(jù)用戶環(huán)境和需要,Web應(yīng)用程序能夠輸出相應(yīng)的內(nèi)容。動態(tài)站點(diǎn)會受到一種名為“跨站腳本攻擊”(Cross Site Scripting, 安全專家們通常將其縮寫成 XSS)的威脅,而靜態(tài)站點(diǎn)則完全不受其影響。
攻擊者通常會在有漏洞的程序中插入JavaScript、VBScript、 ActiveX或Flash以欺騙用戶。一旦得手,他們可以盜取用戶帳戶信息,修改用戶設(shè)置,盜取/污染cookie和植入惡意廣告等。
對XSS最佳的防護(hù)應(yīng)該結(jié)合以下兩種方法:一是驗證所有輸入數(shù)據(jù),有效檢測攻擊(這個我們前面小節(jié)已經(jīng)有過介紹);另一個是對所有輸出數(shù)據(jù)進(jìn)行適當(dāng)?shù)奶幚恚苑乐谷魏我殉晒ψ⑷氲哪_本在瀏覽器端運(yùn)行。
那么Go里面是怎么做這個有效防護(hù)的呢?Go的html/template里面帶有下面幾個函數(shù)可以幫你轉(zhuǎn)義
我們看4.1小節(jié)的例子
fmt.Println("username:", template.HTMLEscapeString(r.Form.Get("username"))) //輸出到服務(wù)器端
fmt.Println("password:", template.HTMLEscapeString(r.Form.Get("password")))
template.HTMLEscape(w, []byte(r.Form.Get("username"))) //輸出到客戶端
如果我們輸入的username是<script>alert()</script>
,那么我們可以在瀏覽器上面看到輸出如下所示:
Go的html/template包默認(rèn)幫你過濾了html標(biāo)簽,但是有時候你只想要輸出這個<script>alert()</script>
看起來正常的信息,該怎么處理?請使用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>!
轉(zhuǎn)換成?template.HTML
?后,變量的內(nèi)容也不會被轉(zhuǎn)義
轉(zhuǎn)義的例子:
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>")
轉(zhuǎn)義之后的輸出:
Hello, <script>alert('you have been pwned')</script>!
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: