-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathtransform.go
More file actions
296 lines (269 loc) · 8.71 KB
/
transform.go
File metadata and controls
296 lines (269 loc) · 8.71 KB
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
// Copyright 2015, Yahoo Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package webseclab
import (
"log"
"regexp"
"strconv"
"strings"
)
// This file has two parts - one related to the map of
// filter fields to the replacers (for more standard replacements).
// The second part are the functions that do transformations
// beyond simple string substitution (regexp etc.)
// Transformer transforms a string by escaping, filtering or other modification.
type Transformer interface {
Transform(s string) string
}
// StringsReplacer implements Transformer using embedded strings.Replacer.
type StringsReplacer struct {
*strings.Replacer
}
// NewStringsReplacer creates a new StringsReplacer
// using the list of old/new strings (as in strings.NewReplacer).
func NewStringsReplacer(oldnew ...string) *StringsReplacer {
r := strings.NewReplacer(oldnew...)
return &StringsReplacer{r}
}
// Transform implements the Transformer interface by calling
// string replacement function.
func (r *StringsReplacer) Transform(s string) string {
return r.Replace(s)
}
// RegexpMatchEraser implements Tranformer using the given regexp(s).
type RegexpMatchEraser struct {
// slice to allow multiple regexps for removing strings
re []*regexp.Regexp
}
// NewRegexpMatchEraser accepts a regexp string parameter
// returns a Transformer that removes the matching strings.
func NewRegexpMatchEraser(re ...string) *RegexpMatchEraser {
var r []*regexp.Regexp
for _, pattern := range re {
compiled := regexp.MustCompile(pattern)
r = append(r, compiled)
}
return &RegexpMatchEraser{r}
}
// Transform erases matching strings based on embedded regexp(s).
func (r *RegexpMatchEraser) Transform(s string) string {
for _, p := range r.re {
s = p.ReplaceAllLiteralString(s, "")
}
return s
}
// ReplaceFunction is the type alias for the Transformer interface.
type ReplaceFunction func(string) string
// Transform satisfies the Transformer interface by
// applying the functor on the string parameter.
func (f ReplaceFunction) Transform(s string) string {
return f(s)
}
// identity function
func id(s string) string {
return s
}
type transformerMap map[filter]Transformer
var trMap transformerMap
// initialize the main replacing functions
func init() {
trMap = transformerMap(make(map[filter]Transformer))
trMap[BackslashEscape] = NewStringsReplacer(`\`, `\\`)
trMap[DoubleQuotesBackslashEscape] = NewStringsReplacer(`"`, `\"`)
trMap[BackslashEscapeDoubleQuotesAndBackslash] = ReplaceFunction(backslashDoublequotes)
trMap[DoubleQuotesCook] = NewStringsReplacer(`"`, `"`)
trMap[DoubleQuotesOff] = NewStringsReplacer(`"`, "")
trMap[GreaterThanCook] = NewStringsReplacer(`>`, `>`)
trMap[GreaterThanOff] = NewStringsReplacer(`>`, "")
trMap[LessThanCook] = NewStringsReplacer(`<`, `<`)
trMap[LessThanOff] = NewStringsReplacer(`<`, "")
trMap[NoOp] = ReplaceFunction(id)
trMap[ParensOff] = NewStringsReplacer(`(`, "", `)`, "")
trMap[QuotesCook] = NewStringsReplacer(`"`, `"`, `'`, `'`)
trMap[QuotesOff] = NewStringsReplacer(`"`, "", `'`, "")
trMap[ScriptOff] = NewRegexpMatchEraser(`(?i)<script[^>]*>`, `</script>`)
trMap[SingleQuotesCook] = NewStringsReplacer(`'`, `'`)
trMap[SingleQuotesOff] = NewStringsReplacer(`'`, "")
trMap[SpacesCook] = NewStringsReplacer(` `, "")
trMap[SpacesOff] = NewStringsReplacer(` `, "")
trMap[TagsCook] = NewStringsReplacer(`<`, `<`, `>`, `>`)
trMap[TagCharsOff] = NewStringsReplacer(`<`, "", `>`, "")
trMap[TagsOff] = ReplaceFunction(RemoveTags)
trMap[TagsOffExceptTextareaClose] = ReplaceFunction(RemoveTagsExceptTextareaClose)
trMap[TagsOffUntilTextareaClose] = ReplaceFunction(RemoveTagsUntilTextareaClose)
trMap[TextareaCloseOff] = ReplaceFunction(removeTextareaClose)
trMap[TextareaSafe] = ReplaceFunction(ReplaceTextareaSafe)
}
// Transform tranforms the string based on the given filter options (one or several)
func Transform(s string, f ...filter) string {
if len(f) == 0 {
log.Printf("ERROR in Tranform(%s) - empty filter slice passed!\n", s)
}
for _, opt := range f {
if tr, ok := trMap[opt]; !ok {
log.Printf("ERROR in Transform(%s, %v) - option %v is not in the trMap! Skipping.\n", s, f, opt)
continue
} else {
s = tr.Transform(s)
}
}
return s
}
// UnescapeUnicode takes a string with Unicode escape sequences \u22
// and converts all of them to the unescaped characters:
// \u0022 => '"', \u3e => '>'
func UnescapeUnicode(s string) string {
if len(s) < 4 {
return s
}
re := regexp.MustCompile(`(\\u(00)?[0-9a-fA-F][0-9a-fA-F])`)
esc := re.ReplaceAllStringFunc(s, unescapeUnicodeHelper)
return esc
}
// same as above but for a single escape sequence
func unescapeUnicodeHelper(s string) string {
if len(s) < 4 {
log.Printf("ERROR in unescapeUnicode - %s is too short (< 4 chars)\n", s)
return s
}
i, err := strconv.ParseInt(s[len(s)-2:], 16, 8)
if err != nil {
log.Printf("ERROR in unescapeUnicode(%s) - unable to ParseInt: %s\n", s, err)
return s
}
if i >= 128 {
log.Printf("ERROR in unescapeUnicode(%s) - parsed value >= 128 %d\n", s, i)
return s
}
return string(rune(i))
}
func percentToSlash(s string) string {
return strings.Replace(s, `%5C`, `/`, -1)
}
// unescapeToHex converts backslash-encoded chars \x5c, \x27 and \x22
// to strings x5c, x27, and x22
func unescapeToHex(s string) (ret string) {
ret = ""
for i := 0; i < len(s); i++ {
if s[i] == 0x5c || s[i] == 0x27 || s[i] == 0x22 {
ret += "/x"
sOut := strconv.FormatInt(int64(s[i]), 16)
ret += sOut
} else {
ret += string(s[i])
}
}
return
}
// RemoveTags removes the tags: foo<xss x=1>bar => foobar
func RemoveTags(src string) string {
re := regexp.MustCompile(`(?i)(<([^>]+)>)`)
// be paranoid and do replacement recursevly, just in case
for {
copy := src
src = re.ReplaceAllString(src, " ")
if src == copy {
break
}
}
return re.ReplaceAllString(src, " ")
}
// RemoveTagsExceptTextareaClose removes all the tags except the closing textarea one
func RemoveTagsExceptTextareaClose(src string) (out string) {
re := regexp.MustCompile(`(?i)(<([^>]+)>)`)
m := re.FindAllStringIndex(src, -1)
last := 0
// revisit once https://github.com/golang/go/issues/5690 is resolved
for i := 0; i < len(m); i++ {
// copy the substring from "last" until the current match
// - otherwise, skip the tag and add a space
out += src[last:m[i][0]]
if strings.HasPrefix(strings.ToLower(src[m[i][0]:m[i][1]]), "</textarea>") {
out += src[m[i][0]:m[i][1]]
} else {
out += " "
}
last = m[i][1]
// leave for debugging
// fmt.Printf("%d %s\n", i, src[m[i][0]:m[i][1]])
}
if last < len(src) {
out += src[last:]
}
// leave for debugging
// fmt.Printf("RemoveTagsUntilTextareaClose Out: %s\n", out)
return out
}
// RemoveTagsUntilTextareaClose removes all the tags before the closing textarea one
func RemoveTagsUntilTextareaClose(src string) (out string) {
re := regexp.MustCompile(`(?i)(<([^>]+)>)`)
m := re.FindAllStringIndex(src, -1)
last := 0
// revisit once https://github.com/golang/go/issues/5690 is resolved
for i := 0; i < len(m); i++ {
// copy the substring from "last" until the current match
out += src[last:m[i][0]]
if strings.HasPrefix(strings.ToLower(src[m[i][0]:m[i][1]]), "</textarea>") {
out += src[m[i][0]:]
return out
}
// otherwise, skip the tag
last = m[i][1]
// leave for debugging
// fmt.Printf("%d %s\n", i, src[m[i][0]:m[i][1]])
}
if last < len(src) {
out += src[last:]
}
// leave for debugging
// fmt.Printf("RemoveTagsUntilTextareaClose Out: %s\n", out)
return out
}
// ReplaceTextareaSafe removes all the tags after the closing textarea one
func ReplaceTextareaSafe(src string) (out string) {
re := regexp.MustCompile(`(?i)(<([^>]+)>)`)
m := re.FindAllStringIndex(src, -1)
last := 0
// revisit once https://github.com/golang/go/issues/5690 is resolved
for i := 0; i < len(m); i++ {
// copy the string until the current match
out += src[last:m[i][0]]
if strings.HasPrefix(strings.ToLower(src[m[i][0]:m[i][1]]), "</textarea>") {
out += src[m[i][0]:m[i][1]]
out += Transform(src[m[i][1]:], TagsOff)
last = len(src)
break
} else {
// copy verbatim before </textarea>
out += src[m[i][0]:m[i][1]]
last = m[i][1]
}
// leave for debugging
// fmt.Printf("%d %s\n", i, src[m[i][0]:m[i][1]])
}
if last < len(src) {
out += src[last:]
}
// leave for debugging
// fmt.Printf("TextareaSafe Out: %s\n", out)
return out
}
func removeTextareaClose(in string) (out string) {
re := regexp.MustCompile(`(?i)(</textarea\s*>)`)
out = re.ReplaceAllLiteralString(in, "")
return
}
func backslashDoublequotes(in string) (out string) {
for _, r := range in {
switch r {
case '"':
out += `\"`
case '\\':
out += `\\`
default:
out += string(r)
}
}
return
}