-
Notifications
You must be signed in to change notification settings - Fork 0
/
obfuscator.go
76 lines (68 loc) · 2.01 KB
/
obfuscator.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
package sqllexer
import (
"regexp"
"strings"
)
type SQLObfuscatorConfig struct {
ReplaceDigits bool
DollarQuotedFunc bool
}
type SQLObfuscator struct {
config *SQLObfuscatorConfig
}
func NewSQLObfuscator(config *SQLObfuscatorConfig) *SQLObfuscator {
return &SQLObfuscator{config: config}
}
const (
StringPlaceholder = "?"
NumberPlaceholder = "?"
)
// Obfuscate takes an input SQL string and returns an obfuscated SQL string.
// The obfuscator replaces all literal values with a single placeholder
func (o *SQLObfuscator) Obfuscate(input string) string {
var obfuscatedSQL string
lexer := NewSQLLexer(input)
for token := range lexer.ScanAllTokens() {
switch token.Type {
case NUMBER:
obfuscatedSQL += NumberPlaceholder
case STRING:
obfuscatedSQL += StringPlaceholder
case INCOMPLETE_STRING:
obfuscatedSQL += StringPlaceholder
case IDENT:
if o.config.ReplaceDigits {
// regex to replace digits in identifier
// we try to avoid using regex as much as possible,
// as regex isn't the most performant,
// but it's the easiest to implement and maintain
digits_regex := regexp.MustCompile(`\d+`)
obfuscatedSQL += digits_regex.ReplaceAllString(token.Value, "?")
} else {
obfuscatedSQL += token.Value
}
case COMMENT:
obfuscatedSQL += token.Value
case MULTILINE_COMMENT:
obfuscatedSQL += token.Value
case DOLLAR_QUOTED_STRING:
obfuscatedSQL += "?"
case DOLLAR_QUOTED_FUNCTION:
if o.config.DollarQuotedFunc {
// obfuscate the content of dollar quoted function
quotedFunc := strings.TrimPrefix(token.Value, "$func$")
quotedFunc = strings.TrimSuffix(quotedFunc, "$func$")
obfuscatedSQL += "$func$" + o.Obfuscate(quotedFunc) + "$func$"
} else {
// treat dollar quoted function as dollar quoted string
obfuscatedSQL += "?"
}
case ERROR | UNKNOWN:
// if we encounter an error or unknown token, we just append the value
obfuscatedSQL += token.Value
default:
obfuscatedSQL += token.Value
}
}
return strings.TrimSpace(obfuscatedSQL)
}