/
crypto.go
504 lines (445 loc) · 11.2 KB
/
crypto.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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
package plural
import (
"bytes"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/AlecAivazis/survey/v2"
"github.com/mitchellh/go-homedir"
"github.com/urfave/cli"
"github.com/pluralsh/plural-cli/pkg/api"
"github.com/pluralsh/plural-cli/pkg/crypto"
"github.com/pluralsh/plural-cli/pkg/scm"
"github.com/pluralsh/plural-cli/pkg/utils"
"github.com/pluralsh/plural-cli/pkg/utils/git"
)
var prefix = []byte("CHARTMART-ENCRYPTED")
const (
GitAttributesFile = ".gitattributes"
GitIgnoreFile = ".gitignore"
)
const Gitattributes = `/**/helm/**/values.yaml filter=plural-crypt diff=plural-crypt
/**/helm/**/values.yaml* filter=plural-crypt diff=plural-crypt
/**/helm/**/README.md* filter=plural-crypt diff=plural-crypt
/**/helm/**/default-values.yaml* filter=plural-crypt diff=plural-crypt
/**/terraform/**/main.tf filter=plural-crypt diff=plural-crypt
/**/terraform/**/main.tf* filter=plural-crypt diff=plural-crypt
/**/manifest.yaml filter=plural-crypt diff=plural-crypt
/**/output.yaml filter=plural-crypt diff=plural-crypt
/diffs/**/* filter=plural-crypt diff=plural-crypt
context.yaml filter=plural-crypt diff=plural-crypt
workspace.yaml filter=plural-crypt diff=plural-crypt
context.yaml* filter=plural-crypt diff=plural-crypt
workspace.yaml* filter=plural-crypt diff=plural-crypt
helm-values/*.yaml filter=plural-crypt diff=plural-crypt
.env filter=plural-crypt diff=plural-crypt
.gitattributes !filter !diff
`
const Gitignore = `/**/.terraform
/**/.terraform*
/**/terraform.tfstate*
/bin
*~
.idea
*.swp
*.swo
.DS_STORE
.vscode
`
// IMPORTANT
// Repo cryptography relies on git smudge and clean filters, which pipe a file into stdin and respond with a new version
// of the file from stdout. If we write anything besides the crypto text, it will no longer be decryptable naturally.
func (p *Plural) cryptoCommands() []cli.Command {
return []cli.Command{
{
Name: "encrypt",
Usage: "encrypts stdin and writes to stdout",
Action: handleEncrypt,
},
{
Name: "decrypt",
Usage: "decrypts stdin and writes to stdout",
Action: handleDecrypt,
},
{
Name: "init",
Usage: "initializes git filters for you",
Action: cryptoInit,
},
{
Name: "unlock",
Usage: "auto-decrypts all affected files in the repo",
Action: handleUnlock,
},
{
Name: "import",
Usage: "imports an aes key for plural to use",
Action: importKey,
},
{
Name: "recover",
Usage: "recovers repo encryption keys from a working k8s cluster",
Action: initKubeconfig(p.handleRecover),
},
{
Name: "random",
Usage: "generates a random string",
Action: randString,
Flags: []cli.Flag{
cli.IntFlag{
Name: "len",
Usage: "the length of the string to generate",
Value: 32,
},
},
},
{
Name: "ssh-keygen",
Usage: "generate an ed5519 keypair for use in git ssh",
Action: affirmed(handleKeygen, "This command will autogenerate an ed5519 keypair, without passphrase. Sound good?", "PLURAL_CRYPTO_SSH_KEYGEN"),
},
{
Name: "export",
Usage: "dumps the current aes key to stdout",
Action: exportKey,
},
{
Name: "share",
Usage: "allows a list of plural users to decrypt this repository",
ArgsUsage: "",
Flags: []cli.Flag{
cli.StringSliceFlag{
Name: "email",
Usage: "a email to share with (multiple allowed)",
Required: true,
},
},
Action: p.handleCryptoShare,
},
{
Name: "setup-keys",
Usage: "creates an age keypair, and uploads the public key to plural for use in plural crypto share",
Flags: []cli.Flag{
cli.StringFlag{
Name: "name",
Usage: "a name for the key",
Required: true,
},
},
Action: p.handleSetupKeys,
},
{
Name: "backups",
Usage: "manages backups of your encryption keys",
Subcommands: p.backupCommands(),
},
{
Name: "fingerprint",
Usage: "generates a file with the key fingerprint",
Action: keyFingerprint,
},
}
}
func (p *Plural) backupCommands() []cli.Command {
return []cli.Command{
{
Name: "list",
Usage: "lists your current key backups",
Action: p.listBackups,
},
{
Name: "create",
Usage: "creates a backup for your current key",
Action: affirmed(p.createBackup, backupMsg, "PLURAL_BACKUPS_CREATE"),
},
{
Name: "restore",
Usage: "restores a key backup as your current encryption key",
ArgsUsage: "NAME",
Action: requireArgs(p.restoreBackup, []string{"NAME"}),
},
}
}
func handleEncrypt(c *cli.Context) error {
data, err := io.ReadAll(os.Stdin)
if bytes.HasPrefix(data, prefix) {
_, err := os.Stdout.Write(data)
if err != nil {
return err
}
return nil
}
if err != nil {
return err
}
cryptoProv, err := crypto.Build()
if err != nil {
return err
}
result, err := crypto.Encrypt(cryptoProv, data)
if err != nil {
return err
}
_, err = os.Stdout.Write(prefix)
if err != nil {
return err
}
_, err = os.Stdout.Write(result)
if err != nil {
return err
}
return nil
}
func handleDecrypt(c *cli.Context) error {
var file io.Reader
if c.Args().Present() {
p, _ := filepath.Abs(c.Args().First())
f, err := os.Open(p)
defer func(f *os.File) {
_ = f.Close()
}(f)
if err != nil {
return err
}
file = f
} else {
file = os.Stdin
}
data, err := io.ReadAll(file)
if err != nil {
return err
}
if !bytes.HasPrefix(data, prefix) {
_, err := os.Stdout.Write(data)
if err != nil {
return err
}
return nil
}
prov, err := crypto.Build()
if err != nil {
return err
}
result, err := crypto.Decrypt(prov, data[len(prefix):])
if err != nil {
return err
}
_, err = os.Stdout.Write(result)
if err != nil {
return err
}
return nil
}
// CheckGitCrypt method checks if the .gitattributes and .gitignore files exist and have desired content.
// Some old repos can have fewer files to encrypt and must be updated.
func CheckGitCrypt(c *cli.Context) error {
if !utils.Exists(GitAttributesFile) || !utils.Exists(GitIgnoreFile) {
return cryptoInit(c)
}
toCompare := map[string]string{GitAttributesFile: Gitattributes, GitIgnoreFile: Gitignore}
for file, content := range toCompare {
equal, err := utils.CompareFileContent(file, content)
if err != nil {
return err
}
if !equal {
return cryptoInit(c)
}
}
return nil
}
func cryptoInit(c *cli.Context) error {
encryptConfig := [][]string{
{"filter.plural-crypt.smudge", "plural crypto decrypt"},
{"filter.plural-crypt.clean", "plural crypto encrypt"},
{"filter.plural-crypt.required", "true"},
{"diff.plural-crypt.textconv", "plural crypto decrypt"},
}
utils.Highlight("Creating git encryption filters\n")
for _, conf := range encryptConfig {
if err := gitConfig(conf[0], conf[1]); err != nil {
return err
}
}
if err := utils.WriteFile(GitAttributesFile, []byte(Gitattributes)); err != nil {
return err
}
if err := utils.WriteFile(GitIgnoreFile, []byte(Gitignore)); err != nil {
return err
}
_, err := crypto.Build()
return err
}
func (p *Plural) handleCryptoShare(c *cli.Context) error {
p.InitPluralClient()
emails := c.StringSlice("email")
if err := crypto.SetupAge(p.Client, emails); err != nil {
return err
}
prov, err := crypto.BuildAgeProvider()
if err != nil {
return err
}
return crypto.Flush(prov)
}
func (p *Plural) handleSetupKeys(c *cli.Context) error {
p.InitPluralClient()
name := c.String("name")
if err := crypto.SetupIdentity(p.Client, name); err != nil {
return err
}
utils.Success("Public key uploaded successfully\n")
return nil
}
func handleUnlock(c *cli.Context) error {
_, err := crypto.Build()
if err != nil {
return err
}
repoRoot, err := git.Root()
if err != nil {
return err
}
// fixes Invalid cross-device link when using os.Rename
gitIndexDir, err := filepath.Abs(filepath.Join(repoRoot, ".git"))
if err != nil {
return err
}
gitIndex := filepath.Join(gitIndexDir, "index")
dump, err := os.CreateTemp(gitIndexDir, "index.bak")
if err != nil {
return err
}
if err := os.Rename(gitIndex, dump.Name()); err != nil {
return err
}
if err := gitCommand("checkout", "HEAD", "--", repoRoot).Run(); err != nil {
_ = os.Rename(dump.Name(), gitIndex)
return errUnlock
}
os.Remove(dump.Name())
return nil
}
func exportKey(c *cli.Context) error {
key, err := crypto.Materialize()
if err != nil {
return err
}
marshal, err := key.Marshal()
if err != nil {
return err
}
_, err = os.Stdout.Write(marshal)
if err != nil {
return err
}
return nil
}
func importKey(c *cli.Context) error {
data, err := io.ReadAll(os.Stdin)
if err != nil {
return err
}
key, err := crypto.Import(data)
if err != nil {
return err
}
return key.Flush()
}
func randString(c *cli.Context) error {
var err error
intVar := c.Int("len")
len := c.Args().Get(0)
if len != "" {
intVar, err = strconv.Atoi(len)
if err != nil {
return err
}
}
str, err := crypto.RandStr(intVar)
if err != nil {
return err
}
fmt.Println(str)
return nil
}
func handleKeygen(c *cli.Context) error {
path, err := homedir.Expand("~/.ssh")
if err != nil {
return err
}
pub, priv, err := scm.GenerateKeys(false)
if err != nil {
return err
}
filename, ok := utils.GetEnvStringValue("PLURAL_CRYPTO_KEYPAIR_NAME")
if !ok {
input := &survey.Input{Message: "What do you want to name your keypair?", Default: "id_plrl"}
err = survey.AskOne(input, &filename, survey.WithValidator(func(val interface{}) error {
name, _ := val.(string)
if utils.Exists(filepath.Join(path, name)) {
return fmt.Errorf("File ~/.ssh/%s already exists", name)
}
return nil
}))
if err != nil {
return err
}
}
if err := os.WriteFile(filepath.Join(path, filename), []byte(priv), 0600); err != nil {
return err
}
if err := os.WriteFile(filepath.Join(path, filename+".pub"), []byte(pub), 0644); err != nil {
return err
}
return nil
}
func (p *Plural) handleRecover(c *cli.Context) error {
if err := p.InitKube(); err != nil {
return err
}
secret, err := p.Secret("console", "console-conf")
if err != nil {
return err
}
key, ok := secret.Data["key"]
if !ok {
return fmt.Errorf("could not find `key` in console-conf secret")
}
aesKey, err := crypto.Import(key)
if err != nil {
return err
}
if err := crypto.Setup(aesKey.Key); err != nil {
return err
}
utils.Success("Key successfully synced locally!\n")
fmt.Println("you might need to run `plural crypto init` and `plural crypto setup-keys` to decrypt any repos with your new key")
return nil
}
func (p *Plural) listBackups(c *cli.Context) error {
p.InitPluralClient()
backups, err := p.Client.ListKeyBackups()
if err != nil {
return api.GetErrorResponse(err, "ListKeyBackups")
}
headers := []string{"Name", "Repositories", "Digest", "Created On"}
return utils.PrintTable(backups, headers, func(back *api.KeyBackup) ([]string, error) {
return []string{back.Name, strings.Join(back.Repositories, ", "), back.Digest, back.InsertedAt}, nil
})
}
func (p *Plural) createBackup(c *cli.Context) error {
p.InitPluralClient()
return crypto.BackupKey(p.Client)
}
func (p *Plural) restoreBackup(c *cli.Context) error {
p.InitPluralClient()
name := c.Args().First()
return crypto.DownloadBackup(p.Client, name)
}
func keyFingerprint(_ *cli.Context) error {
return crypto.CreateKeyFingerprintFile()
}