/
acra-rollback.go
398 lines (350 loc) · 11.9 KB
/
acra-rollback.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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/*
Copyright 2016, Cossack Labs Limited
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 main is entry point for AcraRollback utility. AcraRollback allows users to decrypt data from database:
// it generates a clean SQL dump from an existing protected one. To decrypt the protected data, the utility makes
// a request to users database using SELECT query, then decrypts data, then generates the SQL dump which it can execute,
// or write to file.
//
// https://github.com/cossacklabs/acra/wiki/AcraRollback
package main
import (
"bufio"
"container/list"
"crypto/tls"
"database/sql"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/go-sql-driver/mysql"
pgx "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/stdlib"
log "github.com/sirupsen/logrus"
"github.com/cossacklabs/acra/acrastruct"
"github.com/cossacklabs/acra/cmd"
"github.com/cossacklabs/acra/keystore"
"github.com/cossacklabs/acra/keystore/filesystem"
"github.com/cossacklabs/acra/keystore/keyloader"
keystoreV2 "github.com/cossacklabs/acra/keystore/v2/keystore"
filesystemV2 "github.com/cossacklabs/acra/keystore/v2/keystore/filesystem"
"github.com/cossacklabs/acra/logging"
"github.com/cossacklabs/acra/network"
"github.com/cossacklabs/acra/utils"
"github.com/cossacklabs/acra/utils/args"
)
// Constants used by AcraRollback
var (
// defaultConfigPath relative path to config which will be parsed as default
defaultConfigPath = utils.GetConfigPathByName("acra-rollback")
serviceName = "acra-rollback"
)
// ErrorExit prints error and exits.
func ErrorExit(msg string, err error) {
log.WithError(err).Errorln(msg)
os.Exit(1)
}
// Executor interface for any executor.
type Executor interface {
Execute([]byte)
Close()
}
// InsertExecutor will run Insert statement
type InsertExecutor struct {
insertStatement *sql.Stmt
}
// NewInsertExecutor creates new executor for Insert statements
func NewInsertExecutor(sql string, db *sql.DB) *InsertExecutor {
stmt, err := db.Prepare(sql)
if err != nil {
ErrorExit("can't prepare sql statement", err)
}
return &InsertExecutor{insertStatement: stmt}
}
// Execute inserts
func (ex *InsertExecutor) Execute(data []byte) {
_, err := ex.insertStatement.Exec(&data)
if err != nil {
ErrorExit("can't bind args to prepared statement", err)
}
}
// Close executor
func (ex *InsertExecutor) Close() {
ex.insertStatement.Close()
}
// WriteToFileExecutor writes to file
type WriteToFileExecutor struct {
encoder utils.BinaryEncoder
file *os.File
sql string
writer *bufio.Writer
}
// NewWriteToFileExecutor creates new object ready to write encoded sql to filePath
func NewWriteToFileExecutor(filePath string, sql string, encoder utils.BinaryEncoder) *WriteToFileExecutor {
absPath, err := filepath.Abs(filePath)
if err != nil {
ErrorExit("can't get absolute path for output file", err)
}
file, err := os.Create(absPath)
if err != nil {
ErrorExit("can't create output file", err)
}
writer := bufio.NewWriter(file)
return &WriteToFileExecutor{sql: sql, file: file, writer: writer, encoder: encoder}
}
// PLACEHOLDER char
var PLACEHOLDER = "$1"
// NEWLINE char
var NEWLINE = []byte{'\n'}
// Execute write to file
func (ex *WriteToFileExecutor) Execute(data []byte) {
encoded := ex.encoder.EncodeToString(data)
outputSQL := strings.Replace(ex.sql, PLACEHOLDER, encoded, 1)
n, err := ex.writer.Write([]byte(outputSQL))
if err != nil {
ErrorExit("Can't write to output file", err)
}
if n != len(outputSQL) {
fmt.Println("Incorrect write count")
os.Exit(1)
}
n, err = ex.writer.Write(NEWLINE)
if err != nil {
ErrorExit("Can't write newline char to output file", err)
}
if n != 1 {
fmt.Println("Incorrect write count")
os.Exit(1)
}
}
// Close file
func (ex *WriteToFileExecutor) Close() {
if err := ex.writer.Flush(); err != nil {
log.WithError(err).Errorln("Can't flush data in writer")
}
if err := ex.file.Sync(); err != nil {
log.WithError(err).Errorln("Can't sync file")
}
if err := ex.file.Close(); err != nil {
log.WithError(err).Errorln("Can't close file")
}
}
func registerFlags(flagSet *flag.FlagSet) {
flagSet.String("keys_dir", keystore.DefaultKeyDirShort, "Folder from which the keys will be loaded")
flagSet.String("client_id", "", "Client ID should be name of file with private key")
flagSet.String("connection_string", "", "Connection string for DB PostgreSQL(postgresql://{user}:{password}@{host}:{port}/{dbname}?sslmode={sslmode}), MySQL ({user}:{password}@tcp({host}:{port})/{dbname})")
flagSet.String("select", "", "Query to fetch data for decryption")
flagSet.String("insert", "", "Query for insert decrypted data with placeholders (pg: $n, mysql: ?)")
flagSet.String("output_file", "decrypted.sql", "File for store inserts queries")
flagSet.Bool("execute", false, "Execute inserts")
flagSet.Bool("escape", false, "Escape bytea format")
flagSet.Bool("mysql_enable", false, "Handle MySQL connections")
flagSet.Bool("postgresql_enable", false, "Handle Postgresql connections")
flagSet.Bool("tls_database_enabled", false, "Enable TLS for DB")
network.RegisterTLSArgsForService(flagSet, true, "", network.DatabaseNameConstructorFunc())
network.RegisterTLSBaseArgs(flagSet)
keyloader.RegisterKeyStoreStrategyParameters()
}
func main() {
logging.SetLogLevel(logging.LogVerbose)
registerFlags(flag.CommandLine)
if err := cmd.ParseFlags(flag.CommandLine, os.Args[1:]); err != nil {
if err == cmd.ErrDumpRequested {
cmd.DumpConfig(defaultConfigPath, serviceName, true)
os.Exit(0)
}
log.WithError(err).WithField(logging.FieldKeyEventCode, logging.EventCodeErrorCantReadServiceConfig).
Errorln("Can't parse args")
os.Exit(1)
}
serviceConfig, err := cmd.ParseConfig(defaultConfigPath, serviceName)
if err != nil {
log.WithError(err).WithField(logging.FieldKeyEventCode, logging.EventCodeErrorCantReadServiceConfig).
Errorln("Can't parse config")
os.Exit(1)
}
paramsExtractor := args.NewServiceExtractor(flag.CommandLine, serviceConfig)
keysDir := paramsExtractor.GetString("keys_dir", "")
clientID := paramsExtractor.GetString("client_id", "")
connectionString := paramsExtractor.GetString("connection_string", "")
sqlSelect := paramsExtractor.GetString("select", "")
sqlInsert := paramsExtractor.GetString("insert", "")
outputFile := paramsExtractor.GetString("output_file", "")
execute := paramsExtractor.GetBool("execute", "")
escapeFormat := paramsExtractor.GetBool("escape", "")
useMysql := paramsExtractor.GetBool("mysql_enable", "")
usePostgresql := paramsExtractor.GetBool("postgresql_enable", "")
dbTLSEnabled := paramsExtractor.GetBool("tls_database_enabled", "")
twoDrivers := useMysql && usePostgresql
noDrivers := !(useMysql || usePostgresql)
if twoDrivers || noDrivers {
log.Errorln("You must pass only --mysql_enable or --postgresql_enable (one required)")
os.Exit(1)
}
if useMysql {
PLACEHOLDER = "?"
}
if !strings.Contains(sqlInsert, PLACEHOLDER) {
log.Errorln("SQL INSERT statement doesn't contain any placeholders")
os.Exit(1)
}
if connectionString == "" {
log.Errorln("Connection_string arg is missing")
os.Exit(1)
}
cmd.ValidateClientID(clientID)
if sqlSelect == "" {
log.Errorln("Sql_select arg is missing")
os.Exit(1)
}
if sqlInsert == "" {
log.Errorln("Sql_insert arg is missing")
os.Exit(1)
}
if outputFile == "" && !execute {
log.Errorln("Output_file missing or execute flag")
os.Exit(1)
}
var keystorage keystore.DecryptionKeyStore
if filesystemV2.IsKeyDirectory(keysDir, paramsExtractor) {
keystorage = openKeyStoreV2(keysDir, paramsExtractor)
} else {
keystorage = openKeyStoreV1(keysDir, paramsExtractor)
}
var dbTLSConfig *tls.Config
if dbTLSEnabled {
host, err := network.GetDriverConnectionStringHost(connectionString, useMysql)
if err != nil {
log.WithError(err).Errorln("Failed to get DB host from connection URL")
os.Exit(1)
}
dbTLSConfig, err = network.NewTLSConfigByName(paramsExtractor, "", host, network.DatabaseNameConstructorFunc())
if err != nil {
log.WithError(err).WithField(logging.FieldKeyEventCode, logging.EventCodeErrorTransportConfiguration).
Errorln("Configuration error: can't create database TLS config")
os.Exit(1)
}
}
var db *sql.DB
if useMysql {
config, err := mysql.ParseDSN(connectionString)
if err != nil {
log.WithError(err).Errorln("Can't parse connection string for MySQL driver")
os.Exit(1)
}
if dbTLSConfig != nil {
tlsConfigName := "custom"
if err := mysql.RegisterTLSConfig(tlsConfigName, dbTLSConfig); err != nil {
log.WithError(err).Errorln("Failed to register TLS config")
os.Exit(1)
}
config.TLSConfig = tlsConfigName
}
connector, err := mysql.NewConnector(config)
if err != nil {
log.WithError(err).Errorln("Can't initialize MySQL connector")
os.Exit(1)
}
db = sql.OpenDB(connector)
} else {
config, err := pgx.ParseConfig(connectionString)
if err != nil {
log.WithError(err).Errorln("Can't parse config ")
os.Exit(1)
}
if dbTLSConfig != nil {
config.TLSConfig = dbTLSConfig
}
db = stdlib.OpenDB(*config)
}
defer db.Close()
err = db.Ping()
if err != nil {
log.WithError(err).Errorln("Can't connect to db")
os.Exit(1)
}
rows, err := db.Query(sqlSelect)
if err != nil {
log.WithError(err).Errorf("Error with select query '%v'", sqlSelect)
os.Exit(1)
}
defer rows.Close()
executors := list.New()
if outputFile != "" {
if useMysql {
executors.PushFront(NewWriteToFileExecutor(outputFile, sqlInsert, &utils.MysqlEncoder{}))
} else {
if escapeFormat {
executors.PushFront(NewWriteToFileExecutor(outputFile, sqlInsert, &utils.EscapeEncoder{}))
} else {
executors.PushFront(NewWriteToFileExecutor(outputFile, sqlInsert, &utils.HexEncoder{}))
}
}
}
if execute {
executors.PushFront(NewInsertExecutor(sqlInsert, db))
}
for e := executors.Front(); e != nil; e = e.Next() {
executor := e.Value.(Executor)
defer executor.Close()
}
for i := 0; rows.Next(); i++ {
var data []byte
err = rows.Scan(&data)
if err != nil {
ErrorExit("Can't read data from row", err)
}
privateKeys, err := keystorage.GetServerDecryptionPrivateKeys([]byte(clientID))
if err != nil {
log.WithError(err).Errorf("Can't get private key for row with number %v", i)
continue
}
decrypted, err := acrastruct.DecryptRotatedAcrastruct(data, privateKeys, nil)
utils.ZeroizePrivateKeys(privateKeys)
if err != nil {
log.WithError(err).Errorf("Can't decrypt acrastruct in row with number %v", i)
continue
}
for e := executors.Front(); e != nil; e = e.Next() {
executor := e.Value.(Executor)
executor.Execute(decrypted)
}
}
}
func openKeyStoreV1(keysDir string, extractor *args.ServiceExtractor) keystore.DecryptionKeyStore {
var keyStoreEncryptor keystore.KeyEncryptor
keyStoreEncryptor, err := keyloader.CreateKeyEncryptor(extractor, "")
if err != nil {
log.WithError(err).Errorln("Can't init keystore KeyEncryptor")
os.Exit(1)
}
keystorage, err := filesystem.NewFilesystemKeyStore(keysDir, keyStoreEncryptor)
if err != nil {
log.WithError(err).Errorln("Can't initialize keystore")
os.Exit(1)
}
return keystorage
}
func openKeyStoreV2(keyDirPath string, extractor *args.ServiceExtractor) keystore.DecryptionKeyStore {
keyStoreSuite, err := keyloader.CreateKeyEncryptorSuite(extractor, "")
if err != nil {
log.WithError(err).Errorln("Can't init keystore keyStoreSuite")
os.Exit(1)
}
keyDir, err := filesystemV2.OpenDirectoryRW(keyDirPath, keyStoreSuite)
if err != nil {
log.WithError(err).WithField("path", keyDirPath).Error("cannot open key directory")
os.Exit(1)
}
return keystoreV2.NewServerKeyStore(keyDir)
}