-
-
Notifications
You must be signed in to change notification settings - Fork 122
/
sanitizer.go
308 lines (277 loc) · 7.28 KB
/
sanitizer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
// Lute - 一款结构化的 Markdown 引擎,支持 Go 和 JavaScript
// Copyright (c) 2019-present, b3log.org
//
// Lute is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
// http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.
package render
import (
"bytes"
"io"
"strings"
"github.com/88250/lute/html"
"github.com/88250/lute/util"
)
// 没有实现可扩展的策略,仅过滤不安全的标签和属性。
// 鸣谢 https://github.com/microcosm-cc/bluemonday
var setOfElementsToSkipContent = map[string]interface{}{
"frame": nil,
"frameset": nil,
//"iframe": nil,
"noembed": nil,
"noframes": nil,
"noscript": nil,
"nostyle": nil,
"object": nil,
"script": nil,
"style": nil,
"title": nil,
}
func Sanitize(str string) string {
return string(sanitize([]byte(str)))
}
func sanitize(tokens []byte) []byte {
var (
buff bytes.Buffer
skipElementContent bool
skippingElementsCount int64
mostRecentlyStartedToken string
)
caretLeftSpace := bytes.Contains(tokens, []byte(" "+util.Caret))
tokens = bytes.ReplaceAll(tokens, util.CaretTokens, []byte(util.CaretReplacement))
tokenizer := html.NewTokenizer(bytes.NewReader(tokens))
for {
if tokenizer.Next() == html.ErrorToken {
err := tokenizer.Err()
if err == io.EOF {
ret := buff.Bytes()
if caretLeftSpace {
ret = bytes.ReplaceAll(ret, []byte("\""+util.CaretReplacement), []byte("\" "+util.CaretReplacement))
} else {
ret = bytes.ReplaceAll(ret, []byte("\" "+util.CaretReplacement), []byte("\""+util.CaretReplacement))
}
ret = bytes.ReplaceAll(ret, []byte(util.CaretReplacement), util.CaretTokens)
return ret
}
return util.StrToBytes(err.Error())
}
token := tokenizer.Token()
switch token.Type {
case html.DoctypeToken:
case html.CommentToken:
case html.StartTagToken:
mostRecentlyStartedToken = token.Data
if _, ok := setOfElementsToSkipContent[token.Data]; ok {
skipElementContent = true
skippingElementsCount++
buff.WriteString(" ")
break
}
if len(token.Attr) != 0 {
token.Attr = sanitizeAttrs(token.Attr)
}
if !skipElementContent {
// do not escape multiple query parameters
if linkable(token.Data) {
writeLinkableBuf(&buff, &token)
} else {
buff.WriteString(token.String())
}
}
case html.EndTagToken:
if mostRecentlyStartedToken == token.Data {
mostRecentlyStartedToken = ""
}
if _, ok := setOfElementsToSkipContent[token.Data]; ok {
skippingElementsCount--
if skippingElementsCount == 0 {
skipElementContent = false
}
buff.WriteString(" ")
break
}
if !skipElementContent {
buff.WriteString(token.String())
}
case html.SelfClosingTagToken:
if len(token.Attr) != 0 {
token.Attr = sanitizeAttrs(token.Attr)
}
if !skipElementContent {
// do not escape multiple query parameters
if linkable(token.Data) {
writeLinkableBuf(&buff, &token)
} else {
buff.WriteString(token.String())
}
}
case html.TextToken:
if !skipElementContent {
switch mostRecentlyStartedToken {
case "script":
// not encouraged, but if a policy allows JavaScript we
// should not HTML escape it as that would break the output
buff.WriteString(token.Data)
case "style":
// not encouraged, but if a policy allows CSS styles we
// should not HTML escape it as that would break the output
buff.WriteString(token.Data)
default:
// HTML escape the text
buff.WriteString(token.String())
}
}
}
}
}
func linkable(elementName string) bool {
switch elementName {
case "a", "area", "blockquote", "img", "link", "script":
return true
default:
return false
}
}
func writeLinkableBuf(buff *bytes.Buffer, token *html.Token) {
// do not escape multiple query parameters
tokenBuff := bytes.NewBufferString("")
tokenBuff.WriteString("<")
tokenBuff.WriteString(token.Data)
for _, attr := range token.Attr {
if attr.Key == util.CaretReplacement {
tokenBuff.WriteString(" " + util.CaretReplacement)
continue
}
tokenBuff.WriteByte(' ')
tokenBuff.WriteString(attr.Key)
tokenBuff.WriteString(`="`)
switch attr.Key {
case "href", "src":
tokenBuff.WriteString(html.EscapeString(attr.Val))
default:
// re-apply
tokenBuff.WriteString(html.EscapeString(attr.Val))
}
tokenBuff.WriteByte('"')
}
if token.Type == html.SelfClosingTagToken {
tokenBuff.WriteString(" /")
}
tokenBuff.WriteString(">")
buff.WriteString(tokenBuff.String())
}
func sanitizeAttrs(attrs []*html.Attribute) (ret []*html.Attribute) {
for _, attr := range attrs {
if !allowAttr(attr.Key) {
continue
}
if "src" == attr.Key {
val := strings.TrimSpace(attr.Val)
if strings.HasPrefix(val, "data:image/svg+xml") || strings.HasPrefix(val, "data:text/html") || strings.HasPrefix(val, "javascript") {
continue
}
}
ret = append(ret, attr)
}
return
}
func allowAttr(attrName string) bool {
for name := range eventAttrs {
if attrName == name {
return false
}
}
return true
}
// HTML 事件属性。https://www.w3schools.com/tags/ref_eventattributes.asp
var eventAttrs = map[string]interface{}{
// Window
"onafterprint": nil,
"onbeforeprint": nil,
"onbeforeunload": nil,
"onerror": nil,
"onhashchange": nil,
"onload": nil,
"onmessage": nil,
"onoffline": nil,
"ononline": nil,
"onpagehide": nil,
"onpageshow": nil,
"onpopstate": nil,
"onresize": nil,
"onstorage": nil,
"onunload": nil,
// Form
"onblur": nil,
"onchange": nil,
"oncontextmenu": nil,
"onfocus": nil,
"oninput": nil,
"oninvalid": nil,
"onreset": nil,
"onsearch": nil,
"onselect": nil,
"onsubmit": nil,
// Keyboard
"onkeydown": nil,
"onkeypress": nil,
"onkeyup": nil,
// Mouse
"onclick": nil,
"ondblclick": nil,
"onmousedown": nil,
"onmousemove": nil,
"onmouseout": nil,
"onmouseover": nil,
"onmouseleave": nil,
"onmouseenter": nil,
"onmouseup": nil,
"onmousewheel": nil,
"onwheel": nil,
// Drag
"ondrag": nil,
"ondragend": nil,
"ondragenter": nil,
"ondragleave": nil,
"ondragover": nil,
"ondragstart": nil,
"ondrop": nil,
"onscroll": nil,
// Clipboard
"oncopy": nil,
"oncut": nil,
"onpaste": nil,
// Media
"onabort": nil,
"oncanplay": nil,
"oncanplaythrough": nil,
"oncuechange": nil,
"ondurationchange": nil,
"onemptied": nil,
"onended": nil,
//"onerror": nil,
"onloadeddata": nil,
"onloadedmetadata": nil,
"onloadstart": nil,
"onpause": nil,
"onplay": nil,
"onplaying": nil,
"onprogress": nil,
"onratechange": nil,
"onseeked": nil,
"onseeking": nil,
"onstalled": nil,
"onsuspend": nil,
"ontimeupdate": nil,
"onvolumechange": nil,
"onwaiting": nil,
// Misc
"ontoggle": nil,
// SVG
"onbegin": nil,
"onend": nil,
"onrepeat": nil,
}