我有一个结构,其中注入(inject)了 XSS。为了删除它,我对其进行 json.Marshal,然后运行 json.HTMLEscape。然后我将它 json.Unmarshal 成一个新的结构。
问题是新结构仍然注入(inject)了 XSS。
我根本不知道如何从结构中删除 XSS。我可以编写一个函数来在现场执行此操作,但考虑到有 json.HTMLEscape 并且我们可以将其解码回来它应该可以正常工作,但事实并非如此。
type Person struct {
Name string `json:"name"`
}
func main() {
var p, p2 Person
// p.Name has XSS
p.Name = "<script>alert(1)</script>"
var tBytes bytes.Buffer
// I marshal it so I can use json.HTMLEscape
marshalledJson, _ := json.Marshal(p)
json.HTMLEscape(&tBytes, marshalledJson)
// here I insert it into a new struct, sadly the p2 struct has the XSS still
err := json.Unmarshal(tBytes.Bytes(), &p2)
if err != nil {
fmt.Printf(err.Error())
}
fmt.Print(p2)
}
预期结果是 p2.Name 像 <script>alert(1)</script>
一样被清理
最佳答案
首先, json.HTMLEscape
不做你想做的事:
HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029 characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029 so that the JSON will be safe to embed inside HTML <script> tags.
但你想要的是:
p2.Name to be sanitized like
<script>alert(1)</script>
您可以通过调用 html.EscapeString
获得,但不任何 json 编码器例程。1
其次,如果您检查 json.Marshal
的结果你会看到它已经替换了 <
与 \u003c
等等——它已经完成了 json.HTMLEscape
, 所以 json.HTMLEscape
没有任何字符可以替换!参见 https://play.golang.org/p/Zergs3bwElY举个例子。
正如 Ahmed Hashem 指出的那样,如果您真的想做这类事情,您可以使用反射来查找字符串字段(如 Implement XSS protection in Golang 中所示)——但一般来说,在输入点执行此操作可能更明智。请注意,那里的答案不会递归到可能包含字符串的内部对象。
1JSON 不是 HTML,也不是 XML 等。在您的头脑和代码中将它们分开。
另见 https://medium.com/@oazzat19/what-is-the-difference-between-html-vs-xml-vs-json-254864972bbb ,一个关于我们如何到达这里的简短摘要,据我所知没有错误,这对于随机网络文章来说非常好。 :-) 使用 JSON 时,我们得到非常简单的类型化数据:对象、字符串、数字、列表/数组、 bool 值和空值;见https://www.w3schools.com/js/js_json_syntax.asp , https://www.w3schools.com/js/js_json_objects.asp , 和 https://cswr.github.io/JsonSchema/spec/basic_types/例如。
关于json - Golang 结构解码 xss,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57733277/