forked from ostrovok-tech/pgdump-obfuscator
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
257 lines (230 loc) · 5.61 KB
/
main.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
package main
import (
"bufio"
"bytes"
"errors"
"flag"
"io"
"log"
"os"
"os/signal"
"runtime/pprof"
"strings"
"syscall"
"time"
"fmt"
)
type configFlags []string
func (self *configFlags) String() string {
return strings.Join(*self, ", ")
}
func (self *configFlags) Set(value string) error {
*self = append(*self, value)
return nil
}
func (self *configFlags) ToConfiguration() (*Configuration, error) {
configuration := &Configuration{}
for _, v := range *self {
splittedValues := strings.Split(v, ":")
if len(splittedValues) == 3 {
table, column, name := splittedValues[0], splittedValues[1], splittedValues[2]
scrambler, err := GetScrambleByName(name)
if err != nil {
return configuration, err
}
configuration.Obfuscations = append(
configuration.Obfuscations,
TargetedObfuscation{
Target{Table: table, Column: column},
scrambler,
},
)
} else {
return nil, errors.New(fmt.Sprintf("Inccorrect data in configuration flags!\n"))
}
}
return configuration, nil
}
type Target struct {
Database string
Schema string
Table string
Column string
}
type TargetedObfuscation struct {
T Target
O func(s []byte) []byte
}
func find(elements []string, one string) int {
for i, s := range elements {
if s == one {
return i
}
}
return -1
}
var fieldSeparator = []byte("\t")
func processDataLine(config *Configuration, target *Target, columns []string, line *[]byte) error {
fields := bytes.Split(*line, fieldSeparator)
if len(fields) != len(columns) {
return errors.New("Number of columns does not match number of data fields")
}
var value []byte
for _, to := range config.Obfuscations {
if to.T.Table != target.Table {
continue
}
// TODO: try map
columnIndex := find(columns, to.T.Column)
if columnIndex == -1 {
return errors.New("Target column not found in earlier header. Wrong table?")
}
value = fields[columnIndex]
if len(value) == 0 {
continue
} else if len(value) == 2 && value[0] == '\\' && value[1] == 'N' {
continue
} else {
fields[columnIndex] = to.O(value)
}
}
*line = bytes.Join(fields, fieldSeparator)
return nil
}
const (
parseStateInvalid = iota
parseStateOther
parseStateCopy
)
var bytesCopyBegin = []byte("COPY ")
var bytesCopyEnd = []byte("\\.\n")
var bytesNewline = []byte("\n")
const copySyntaxDelimiters = " \n'\"(),;"
func process(config *Configuration, input *bufio.Reader, output io.Writer) error {
target := Target{}
state := parseStateOther
var columns []string
// TODO: try map
configuredTables := make([]string, 1)
for _, to := range config.Obfuscations {
if find(configuredTables, to.T.Table) == -1 {
configuredTables = append(configuredTables, to.T.Table)
}
}
var currentLineNumber uint64
var line []byte
defer func() {
if r := recover(); r != nil {
log.Fatalln("Line", currentLineNumber, "error:", r)
}
}()
var err, readErr error
for currentLineNumber = 0; ; currentLineNumber++ {
line, readErr = input.ReadBytes('\n')
if readErr != nil && readErr != io.EOF {
panic("At ReadBytes")
}
if len(line) == 0 {
goto next
}
switch state {
case parseStateOther:
if bytes.HasPrefix(line, bytesCopyBegin) {
state = parseStateCopy
lineString := string(line)
tokens := strings.FieldsFunc(lineString, func(r rune) bool {
return strings.ContainsRune(copySyntaxDelimiters, r)
})
if len(tokens) < 4 {
return errors.New("process: parse error: too few tokens in COPY statement: " + string(line))
}
target.Table = tokens[1]
columns = tokens[2 : len(tokens)-2]
}
case parseStateCopy:
if bytes.Equal(line, bytesCopyEnd) {
state = parseStateOther
columns = nil
target = Target{}
} else if find(configuredTables, target.Table) != -1 {
// Data rows
hasNewlineSuffix := bytes.HasSuffix(line, bytesNewline)
if hasNewlineSuffix {
line = line[:len(line)-1]
}
err = processDataLine(config, &target, columns, &line)
if err != nil {
log.Println("process: line", currentLineNumber, "error:", err)
} else if hasNewlineSuffix {
line = append(line, '\n')
}
}
}
output.Write(line)
next:
if readErr == io.EOF {
return nil
}
}
return nil
}
func main() {
var configs configFlags
inputPath := flag.String("input", "-", "Input filename, '-' for stdin")
cpuprofile := flag.String("cpuprofile", "", "Write CPU profile to file")
memprofile := flag.String("memprofile", "", "Write memory profile to file")
flag.Var(&configs, "c", "Configs, example: auth_user:email:email, auth_user:password:bytes")
flag.Parse()
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Println(err.Error())
os.Exit(1)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
defer f.Close()
}
if *memprofile != "" {
f, err := os.Create(*memprofile)
if err != nil {
log.Println(err.Error())
os.Exit(1)
}
go func() {
for {
time.Sleep(5 * time.Second)
pprof.WriteHeapProfile(f)
}
}()
defer pprof.WriteHeapProfile(f)
defer f.Close()
}
sigIntChan := make(chan os.Signal, 1)
signal.Notify(sigIntChan, syscall.SIGINT)
go func() {
<-sigIntChan
os.Exit(1)
}()
// Initialize input reading
log.Println("Reading from", *inputPath)
var inputFile *os.File = os.Stdin
if *inputPath != "-" {
var err error
inputFile, err = os.Open(*inputPath)
if err != nil {
log.Println(err.Error())
os.Exit(1)
}
defer inputFile.Close()
}
input := bufio.NewReader(inputFile)
// TODO
output := os.Stdout
configuration, err := configs.ToConfiguration()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
process(configuration, input, output)
}