-
Notifications
You must be signed in to change notification settings - Fork 344
/
reencrypt.go
362 lines (301 loc) · 10.4 KB
/
reencrypt.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
/*
Name
reencrypt
Synopsis
reencrypt [--previous-key value] [--new-key value] [--cfg value]
Description
The reencrypt app is used to re-encrypt all data in the Postgres Traffic Vault
using a new base64-encoded AES key.
Options
--previous-key
The file path for the previous base64-encoded AES key.
--new-key
The file path for the new base64-encoded AES key.
--cfg
The path for the configuration file. Default is `./reencrypt.conf`.
*/
package main
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
import (
"bytes"
"database/sql"
"encoding/base64"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"os"
"github.com/apache/trafficcontrol/lib/go-util"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
)
const PROPERTIES_FILE = "./reencrypt.conf"
func main() {
previousKeyLocation := flag.String("previous-key", "/opt/traffic_ops/app/conf/aes.key", "(Optional) The file path for the previous base64 encoded AES key. Default is /opt/traffic_ops/app/conf/aes.key.")
newKeyLocation := flag.String("new-key", "/opt/traffic_ops/app/conf/new.key", "(Optional) The file path for the new base64 encoded AES key. Default is /opt/traffic_ops/app/conf/new.key.")
cfg := flag.String("cfg", PROPERTIES_FILE, "(Optional) The path for the configuration file. Default is "+PROPERTIES_FILE+".")
help := flag.Bool("help", false, "(Optional) Print usage information and exit.")
flag.Parse()
if *help {
flag.Usage()
os.Exit(0)
}
newKey, err := readKey(*newKeyLocation)
if err != nil {
die("reading new-key: " + err.Error())
}
previousKey, err := readKey(*previousKeyLocation)
if err != nil {
die("reading previous-key: " + err.Error())
}
dbConfBytes, err := ioutil.ReadFile(*cfg)
if err != nil {
die("reading db conf '" + *cfg + "': " + err.Error())
}
pgCfg := Config{}
err = json.Unmarshal(dbConfBytes, &pgCfg)
if err != nil {
die("unmarshalling '" + *cfg + "': " + err.Error())
}
sslStr := "require"
if !pgCfg.SSL {
sslStr = "disable"
}
db, err := sqlx.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=%s&fallback_application_name=trafficvault", pgCfg.User, pgCfg.Password, pgCfg.Hostname, pgCfg.Port, pgCfg.DBName, sslStr))
if err != nil {
die("opening database: " + err.Error())
}
tx, err := db.Begin()
if err != nil {
die(fmt.Sprintf("transaction begin failed %v %v ", err, tx))
}
defer tx.Commit()
if err = reEncryptSslKeys(tx, previousKey, newKey); err != nil {
tx.Rollback()
die("re-encrypting SSL Keys: " + err.Error())
}
if err = reEncryptUrlSigKeys(tx, previousKey, newKey); err != nil {
tx.Rollback()
die("re-encrypting URL Sig Keys: " + err.Error())
}
if err = reEncryptUriSigningKeys(tx, previousKey, newKey); err != nil {
tx.Rollback()
die("re-encrypting URI Signing Keys: " + err.Error())
}
if err = reEncryptDNSSECKeys(tx, previousKey, newKey); err != nil {
tx.Rollback()
die("re-encrypting DNSSEC Keys: " + err.Error())
}
fmt.Println("Successfully re-encrypted keys for SSL Keys, URL Sig Keys, URI Signing Keys, and DNSSEC Keys.")
}
type Config struct {
DBName string `json:"dbname"`
Hostname string `json:"hostname"`
User string `json:"user"`
Password string `json:"password"`
Port int `json:"port"`
SSL bool `json:"ssl"`
}
func readKey(keyLocation string) ([]byte, error) {
var keyBase64 string
keyBase64Bytes, err := ioutil.ReadFile(keyLocation)
if err != nil {
return []byte{}, errors.New("reading file '" + keyLocation + "':" + err.Error())
}
keyBase64 = string(keyBase64Bytes)
key, err := base64.StdEncoding.DecodeString(keyBase64)
if err != nil {
return []byte{}, fmt.Errorf("AES key cannot be decoded from base64: %w", err)
}
// verify the key works
if err = util.ValidateAESKey(key); err != nil {
return []byte{}, err
}
return key, nil
}
func reEncryptSslKeys(tx *sql.Tx, previousKey []byte, newKey []byte) error {
rows, err := tx.Query("SELECT deliveryservice, data FROM sslkey")
if err != nil {
return fmt.Errorf("querying: %w", err)
}
defer rows.Close()
sslKeyMap := map[string][]byte{}
for rows.Next() {
xmlid := ""
var encryptedSslKeys []byte
if err = rows.Scan(&xmlid, &encryptedSslKeys); err != nil {
return fmt.Errorf("getting SSL Keys: %w", err)
}
jsonKeys, err := util.AESDecrypt(encryptedSslKeys, previousKey)
if err != nil {
return fmt.Errorf("reading SSL Keys: %w", err)
}
if !bytes.HasPrefix(jsonKeys, []byte("{")) {
return fmt.Errorf("decrypted SSL Key did not have prefix '{' for xmlid %s", xmlid)
}
reencryptedKeys, err := util.AESEncrypt(jsonKeys, newKey)
if err != nil {
return fmt.Errorf("encrypting SSL Keys with new key: %w", err)
}
sslKeyMap[xmlid] = reencryptedKeys
}
for xmlid, reencryptedKeys := range sslKeyMap {
res, err := tx.Exec(`UPDATE sslkey SET data = $1 WHERE deliveryservice = $2`, reencryptedKeys, xmlid)
if err != nil {
return fmt.Errorf("updating SSL Keys for xmlid %s: %w", xmlid, err)
}
rowsAffected, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("determining rows affected for reencrypting SSL Keys with xmlid %s: %w", xmlid, err)
}
if rowsAffected == 0 {
return fmt.Errorf("no rows updated for reencrypting SSL Keys for xmlid %s", xmlid)
}
}
return nil
}
func reEncryptUrlSigKeys(tx *sql.Tx, previousKey []byte, newKey []byte) error {
rows, err := tx.Query("SELECT deliveryservice, data FROM url_sig_key")
if err != nil {
return fmt.Errorf("querying: %w", err)
}
defer rows.Close()
urlSigKeysMap := map[string][]byte{}
for rows.Next() {
ds := ""
var encryptedSslKeys []byte
if err = rows.Scan(&ds, &encryptedSslKeys); err != nil {
return fmt.Errorf("getting URL Sig Keys: %w", err)
}
jsonKeys, err := util.AESDecrypt(encryptedSslKeys, previousKey)
if err != nil {
return fmt.Errorf("reading URL Sig Keys: %w", err)
}
if !bytes.HasPrefix(jsonKeys, []byte("{")) {
return fmt.Errorf("decrypted URL Sig Key did not have prefix '{' for ds: %s", ds)
}
reencryptedKeys, err := util.AESEncrypt(jsonKeys, newKey)
if err != nil {
return fmt.Errorf("encrypting URL Sig Keys with new key: %w", err)
}
urlSigKeysMap[ds] = reencryptedKeys
}
for ds, reencryptedKeys := range urlSigKeysMap {
res, err := tx.Exec(`UPDATE url_sig_key SET data = $1 WHERE deliveryservice = $2`, reencryptedKeys, ds)
if err != nil {
return fmt.Errorf("updating URL Sig Keys for deliveryservice %s: %w", ds, err)
}
rowsAffected, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("determining rows affected for reencrypting URL Sig Keys with deliveryservice %s: %w", ds, err)
}
if rowsAffected == 0 {
return fmt.Errorf("no rows updated for reencrypting URL Sig Keys for deliveryservice %s", ds)
}
}
return nil
}
func reEncryptUriSigningKeys(tx *sql.Tx, previousKey []byte, newKey []byte) error {
rows, err := tx.Query("SELECT deliveryservice, data FROM uri_signing_key")
if err != nil {
return fmt.Errorf("querying: %w", err)
}
defer rows.Close()
uriSigningKeyMap := map[string][]byte{}
for rows.Next() {
ds := ""
var encryptedSslKeys []byte
if err = rows.Scan(&ds, &encryptedSslKeys); err != nil {
return fmt.Errorf("getting URI Signing Keys: %w", err)
}
jsonKeys, err := util.AESDecrypt(encryptedSslKeys, previousKey)
if err != nil {
return fmt.Errorf("reading URI Signing Keys: %w", err)
}
if !bytes.HasPrefix(jsonKeys, []byte("{")) {
return fmt.Errorf("decrypted URI Signing Key did not have prefix '{' for ds: %s", ds)
}
reencryptedKeys, err := util.AESEncrypt(jsonKeys, newKey)
if err != nil {
return fmt.Errorf("encrypting URI Signing Keys with new key: %w", err)
}
uriSigningKeyMap[ds] = reencryptedKeys
}
for ds, reencryptedKeys := range uriSigningKeyMap {
res, err := tx.Exec(`UPDATE uri_signing_key SET data = $1 WHERE deliveryservice = $2`, reencryptedKeys, ds)
if err != nil {
return fmt.Errorf("updating URI Signing Keys for deliveryservice %s: %w", ds, err)
}
rowsAffected, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("determining rows affected for reencrypting URI Signing Keys with deliveryservice %s: %w", ds, err)
}
if rowsAffected == 0 {
return fmt.Errorf("no rows updated for reencrypting URI Signing Keys for deliveryservice %s", ds)
}
}
return nil
}
func reEncryptDNSSECKeys(tx *sql.Tx, previousKey []byte, newKey []byte) error {
rows, err := tx.Query("SELECT cdn, data FROM dnssec")
if err != nil {
return fmt.Errorf("querying: %w", err)
}
defer rows.Close()
dnssecKeyMap := map[string][]byte{}
for rows.Next() {
cdn := ""
var encryptedSslKeys []byte
if err = rows.Scan(&cdn, &encryptedSslKeys); err != nil {
return fmt.Errorf("getting DNSSEC Keys: %w", err)
}
jsonKeys, err := util.AESDecrypt(encryptedSslKeys, previousKey)
if err != nil {
return fmt.Errorf("reading DNSSEC Keys: %w", err)
}
if !bytes.HasPrefix(jsonKeys, []byte("{")) {
return fmt.Errorf("decrypted DNSSEC Key did not have prefix '{' for cdn: %s", cdn)
}
reencryptedKeys, err := util.AESEncrypt(jsonKeys, newKey)
if err != nil {
return fmt.Errorf("encrypting DNSSEC Keys with new key: %w", err)
}
dnssecKeyMap[cdn] = reencryptedKeys
}
for cdn, reencryptedKeys := range dnssecKeyMap {
res, err := tx.Exec(`UPDATE dnssec SET data = $1 WHERE cdn = $2`, reencryptedKeys, cdn)
if err != nil {
return fmt.Errorf("updating DNSSEC Keys for cdn %s: %w", cdn, err)
}
rowsAffected, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("determining rows affected for reencrypting DNSSEC Keys with cdn %s: %w", cdn, err)
}
if rowsAffected == 0 {
return fmt.Errorf("no rows updated for reencrypting DNSSEC Keys for cdn %s", cdn)
}
}
return nil
}
func die(message string) {
fmt.Fprintln(os.Stderr, message)
os.Exit(1)
}