/
sql_sanitizer.go
382 lines (334 loc) · 9.58 KB
/
sql_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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
// © 2023 SolarWinds Worldwide, LLC. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package reporter
import (
"github.com/solarwinds/apm-go/internal/config"
"strings"
"unicode"
"unicode/utf8"
)
// The SQL sanitization mode
const (
// Disabled - disable SQL sanitizing (the default).
Disabled = iota
// EnabledAuto - enable SQL sanitizing and attempt to automatically determine
// which quoting form to use.
EnabledAuto
// EnabledDropDoubleQuoted - enable SQL sanitizing and force dropping double-
// quoted runes.
EnabledDropDoubleQuoted
// EnabledKeepDoubleQuoted enable SQL sanitizing and force retaining double-
// quoted runes.
EnabledKeepDoubleQuoted
)
// The database types
const (
PostgreSQL = "postgresql"
Oracle = "oracle"
MySQL = "mysql"
Sybase = "sybase"
SQLServer = "sqlserver"
DefaultDB = "default"
)
// FSMState defines the states of a FSM
type FSMState int
// The states for the SQL sanitization FSM
const (
FSMUninitialized FSMState = iota
FSMCopy
FSMCopyEscape
FSMStringStart
FSMStringBody
FSMStringEscape
FSMStringEnd
FSMNumber
FSMNumericExtension
FSMIdentifier
FSMQuotedIdentifier
FSMQuotedIdentifierEscape
)
const (
// ReplacementRune is the rune to replace the removed literals
ReplacementRune = '?'
// EscapeRune is the SQL escape rune
EscapeRune = '\\'
// MaxSQLLen defines the maximum number of runes after truncation.
MaxSQLLen = 2048
// Ellipsis is appended to the truncated SQL statement
Ellipsis = '…'
)
// SQLOperatorRunes defines the list of SQL operators
var SQLOperatorRunes = map[rune]bool{
'.': true,
';': true,
'(': true,
')': true,
',': true,
'+': true,
'-': true,
'*': true,
'/': true,
'|': true,
'=': true,
'!': true,
'^': true,
'>': true,
'<': true,
'[': true,
']': true,
}
// SQLSanitizer sanitizes the SQL statement by removing literals from it.
type SQLSanitizer struct {
// database types
dbType string
// the quotes surrounding literals
literalQuotes map[rune]rune
// the quotes surrounding identifiers, e.g., column names
identifierQuotes map[rune]rune
}
// the sanitizers for various database types, which is initialized in the init
// function.
var sanitizers map[string]*SQLSanitizer
func init() {
sanitizers = initSanitizersMap()
}
func initSanitizersMap() map[string]*SQLSanitizer {
sanitizeFlag := config.GetSQLSanitize()
if sanitizeFlag == Disabled {
return nil
}
ss := make(map[string]*SQLSanitizer)
for _, t := range []string{PostgreSQL, Oracle, MySQL, Sybase, SQLServer, DefaultDB} {
ss[t] = NewSQLSanitizer(t, sanitizeFlag)
}
return ss
}
// NewSQLSanitizer returns the pointer of a new SQLSanitizer.
func NewSQLSanitizer(dbType string, sanitizeFlag int) *SQLSanitizer {
sanitizer := SQLSanitizer{
dbType: strings.ToLower(dbType),
literalQuotes: make(map[rune]rune),
identifierQuotes: make(map[rune]rune),
}
sanitizer.literalQuotes['\''] = '\''
if sanitizeFlag == EnabledDropDoubleQuoted {
sanitizer.literalQuotes['"'] = '"'
} else if sanitizeFlag == EnabledKeepDoubleQuoted {
sanitizer.identifierQuotes['"'] = '"'
} else {
if dbType == PostgreSQL || dbType == Oracle {
sanitizer.identifierQuotes['"'] = '"'
} else {
sanitizer.literalQuotes['"'] = '"'
}
}
if dbType == MySQL {
sanitizer.identifierQuotes['`'] = '`'
} else if dbType == Sybase || dbType == SQLServer {
sanitizer.identifierQuotes['['] = ']'
}
// For double-dollar quoted literals: $tag$literal$tag$
if dbType == PostgreSQL {
sanitizer.literalQuotes['$'] = '$'
}
return &sanitizer
}
// Sanitize does the SQL sanitization by removing literals from the statement, it
// also truncates the statement after sanitization if it's longer than MaxSQLLen.
func (s *SQLSanitizer) Sanitize(sql string) string {
currState := FSMCopy
prevState := FSMUninitialized
var closingQuote rune
// A very simple stack implementation solely for the sanitizer. It doesn't
// enforce enough boundary checks and is not concurrent-safe.
buffer := make([]rune, utf8.RuneCountInString(sql))
runeCnt := 0 // should not exceed MaxSQLLen-1
maxRuneCnt := MaxSQLLen - 1 // len("…")
StackPush := func(r rune) {
if runeCnt < len(buffer) {
buffer[runeCnt] = r
runeCnt++
}
}
StackPop := func() {
if runeCnt > 0 {
runeCnt--
}
}
// depth = 1 means to peek the top element
StackPeek := func(depth int) rune {
if runeCnt < depth {
// too deep
return 0
}
return buffer[runeCnt-depth]
}
StackCopy := func() []rune {
return buffer[:runeCnt]
}
StackSize := func() int {
return runeCnt
}
// For PostgreSQL's dollar-quoted literal only.
// see https://www.postgresql.org/docs/9.0/sql-syntax-lexical.html
tag := []rune{'$'}
for i, currRune := range sql {
if StackSize() >= maxRuneCnt {
StackPush(Ellipsis)
break
}
if currState != prevState {
prevState = currState
}
switch currState {
case FSMStringStart:
// Handle PostgreSQL's double-dollar quoted literal
if s.dbType == PostgreSQL && closingQuote == '$' {
if currRune == '$' {
currState = FSMStringBody
StackPush(ReplacementRune)
}
// Record the tag: '$tag$'. It will be used to compare with the
// literal when a '$' is seen to identify the end of string.
tag = append(tag, currRune)
break // break out of switch
}
StackPush(ReplacementRune)
if currRune == closingQuote {
currState = FSMStringEnd
} else if currRune == EscapeRune {
currState = FSMStringEscape
} else {
currState = FSMStringBody
}
case FSMStringBody:
if currRune == closingQuote {
if s.dbType == PostgreSQL &&
closingQuote == '$' &&
i+len(tag) <= utf8.RuneCountInString(sql) && // slice bounds check
strings.Compare(string(tag), string([]rune(sql)[i:i+len(tag)])) != 0 {
// Do nothing - It's only a '$' inside a string, rather than
// the literal end. The nested dollar-quoted string is not handled
// specially as they are all replaced with the placeholder.
} else {
currState = FSMStringEnd
if s.dbType == PostgreSQL && closingQuote == '$' {
tag = []rune{'$'} // reset the tag
}
}
} else if currRune == EscapeRune && closingQuote != '$' {
// The escape rune, e.g., a '\', should not be escaped inside a
// dollar-quoted string of PostgreSQL. However, it doesn't have
// to be handle specially either as the entire string body will
// be removed (replaced with the placeholder) anyways.
currState = FSMStringEscape
}
case FSMStringEscape:
currState = FSMStringBody
case FSMStringEnd:
// Handle PostgreSQL's double-dollar quoted literal
if s.dbType == PostgreSQL && closingQuote == '$' {
if currRune == '$' {
// The real end of closing quote
currState = FSMCopy
}
break // break out of switch
}
if currRune == closingQuote {
currState = FSMStringBody
} else {
StackPush(currRune)
currState = FSMCopy
}
case FSMCopyEscape:
StackPush(currRune)
currState = FSMCopy
case FSMNumber:
if !unicode.IsDigit(currRune) {
if currRune == '.' || currRune == 'E' {
currState = FSMNumericExtension
} else {
StackPush(currRune)
currState = FSMCopy
}
}
case FSMNumericExtension:
currState = FSMNumber
case FSMIdentifier:
if c, ok := s.literalQuotes[currRune]; ok {
// PostgreSQL has literals like X'FEFF' or U&'\0441'
top1 := unicode.ToUpper(StackPeek(1))
top2 := unicode.ToUpper(StackPeek(2))
if top1 == 'X' || top1 == 'B' || top1 == 'U' || top1 == 'N' {
StackPop()
} else if top1 == '&' && top2 == 'U' {
StackPop()
StackPop()
}
closingQuote = c
currState = FSMStringStart
} else {
StackPush(currRune)
if unicode.IsSpace(currRune) || SQLOperatorRunes[currRune] {
currState = FSMCopy
}
}
case FSMQuotedIdentifier:
StackPush(currRune)
if currRune == closingQuote {
currState = FSMCopy
} else if currRune == EscapeRune {
currState = FSMQuotedIdentifierEscape
}
case FSMQuotedIdentifierEscape:
StackPush(currRune)
currState = FSMQuotedIdentifier
default:
if lq, ok := s.literalQuotes[currRune]; ok {
closingQuote = lq
currState = FSMStringStart
} else if iq, has := s.identifierQuotes[currRune]; has {
StackPush(currRune)
closingQuote = iq
currState = FSMQuotedIdentifier
} else if currRune == EscapeRune {
StackPush(currRune)
currState = FSMCopyEscape
} else if unicode.IsLetter(currRune) || currRune == '_' {
StackPush(currRune)
currState = FSMIdentifier
} else if unicode.IsDigit(currRune) {
StackPush(ReplacementRune)
currState = FSMNumber
} else {
StackPush(currRune)
}
}
}
return string(StackCopy())
}
// SQLSanitize checks the sanitizer of the database type and does the sanitization
// accordingly. It uses the default sanitizer if the type is not found.
func SQLSanitize(dbType string, sql string) string {
return sqlSanitize(sanitizers, dbType, sql)
}
func sqlSanitize(ss map[string]*SQLSanitizer, dbType string, sql string) string {
if ss == nil {
return sql
}
if s, ok := ss[dbType]; ok {
return s.Sanitize(sql)
}
return ss[DefaultDB].Sanitize(sql)
}