forked from getsops/sops
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
2620 lines (2504 loc) · 87.2 KB
/
main.go
File metadata and controls
2620 lines (2504 loc) · 87.2 KB
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main // import "github.com/getsops/sops/v3/cmd/sops"
import (
"context"
encodingjson "encoding/json"
"fmt"
"io"
"net"
"net/url"
"os"
osExec "os/exec"
"path/filepath"
"reflect"
"strconv"
"strings"
"github.com/sirupsen/logrus"
"github.com/urfave/cli"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/getsops/sops/v3"
"github.com/getsops/sops/v3/aes"
"github.com/getsops/sops/v3/age"
_ "github.com/getsops/sops/v3/audit"
"github.com/getsops/sops/v3/azkv"
"github.com/getsops/sops/v3/cmd/sops/codes"
"github.com/getsops/sops/v3/cmd/sops/common"
"github.com/getsops/sops/v3/cmd/sops/subcommand/exec"
filestatuscmd "github.com/getsops/sops/v3/cmd/sops/subcommand/filestatus"
"github.com/getsops/sops/v3/cmd/sops/subcommand/groups"
keyservicecmd "github.com/getsops/sops/v3/cmd/sops/subcommand/keyservice"
publishcmd "github.com/getsops/sops/v3/cmd/sops/subcommand/publish"
"github.com/getsops/sops/v3/cmd/sops/subcommand/updatekeys"
"github.com/getsops/sops/v3/config"
"github.com/getsops/sops/v3/gcpkms"
"github.com/getsops/sops/v3/hckms"
"github.com/getsops/sops/v3/hcvault"
"github.com/getsops/sops/v3/keys"
"github.com/getsops/sops/v3/keyservice"
"github.com/getsops/sops/v3/kms"
"github.com/getsops/sops/v3/logging"
"github.com/getsops/sops/v3/pgp"
"github.com/getsops/sops/v3/stores"
"github.com/getsops/sops/v3/stores/dotenv"
"github.com/getsops/sops/v3/stores/json"
"github.com/getsops/sops/v3/version"
)
var (
log *logrus.Logger
// Whether the config file warning was already shown to the user.
// Used and set by findConfigFile().
showedConfigFileWarning bool
)
func init() {
log = logging.NewLogger("CMD")
}
func warnMoreThanOnePositionalArgument(c *cli.Context) {
if c.NArg() > 1 {
log.Warn("More than one positional argument provided. Only the first one will be used!")
potentialFlag := ""
for i, value := range c.Args() {
if i > 0 && strings.HasPrefix(value, "-") {
potentialFlag = value
}
}
if potentialFlag != "" {
log.Warn(fmt.Sprintf("Note that one of the ignored positional argument is %q, which looks like a flag. Flags must always be provided before the first positional argument!", potentialFlag))
}
}
}
func main() {
cli.VersionPrinter = version.PrintVersion
app := cli.NewApp()
keyserviceFlags := []cli.Flag{
cli.BoolTFlag{
Name: "enable-local-keyservice",
Usage: "use local key service",
EnvVar: "SOPS_ENABLE_LOCAL_KEYSERVICE",
},
cli.StringSliceFlag{
Name: "keyservice",
Usage: "Specify the key services to use in addition to the local one. Can be specified more than once. Syntax: protocol://address. Example: tcp://myserver.com:5000",
EnvVar: "SOPS_KEYSERVICE",
},
}
app.Name = "sops"
app.Usage = "sops - encrypted file editor with AWS KMS, GCP KMS, HuaweiCloud KMS, Azure Key Vault, age, and GPG support"
app.ArgsUsage = "sops [options] file"
app.Version = version.Version
app.Authors = []cli.Author{
{Name: "CNCF Maintainers"},
}
app.UsageText = `sops is an editor of encrypted files that supports AWS KMS, GCP, HuaweiCloud KMS, AZKV,
PGP, and Age
To encrypt or decrypt a document with AWS KMS, specify the KMS ARN
in the -k flag or in the SOPS_KMS_ARN environment variable.
(you need valid credentials in ~/.aws/credentials or in your env)
To encrypt or decrypt a document with GCP KMS, specify the
GCP KMS resource ID in the --gcp-kms flag or in the SOPS_GCP_KMS_IDS
environment variable.
(You need to setup Google application default credentials. See
https://developers.google.com/identity/protocols/application-default-credentials)
To encrypt or decrypt a document with HuaweiCloud KMS, specify the
HuaweiCloud KMS key ID (format: region:key-uuid) in the --hckms flag or in the
SOPS_HUAWEICLOUD_KMS_IDS environment variable.
(You need to setup HuaweiCloud credentials via environment variables:
HUAWEICLOUD_SDK_AK, HUAWEICLOUD_SDK_SK, HUAWEICLOUD_SDK_PROJECT_ID, or
use credentials file at ~/.huaweicloud/credentials)
To encrypt or decrypt a document with HashiCorp Vault's Transit Secret
Engine, specify the Vault key URI name in the --hc-vault-transit flag
or in the SOPS_VAULT_URIS environment variable (for example
https://vault.example.org:8200/v1/transit/keys/dev, where
'https://vault.example.org:8200' is the vault server, 'transit' the
enginePath, and 'dev' is the name of the key).
(You need to enable the Transit Secrets Engine in Vault. See
https://www.vaultproject.io/docs/secrets/transit/index.html)
To encrypt or decrypt a document with Azure Key Vault, specify the
Azure Key Vault key URL in the --azure-kv flag or in the
SOPS_AZURE_KEYVAULT_URL environment variable.
(Authentication is based on environment variables, see
https://docs.microsoft.com/en-us/go/azure/azure-sdk-go-authorization#use-environment-based-authentication.
The user/sp needs the key/encrypt and key/decrypt permissions.)
To encrypt or decrypt using age, specify the recipient in the -a flag,
or in the SOPS_AGE_RECIPIENTS environment variable.
To encrypt or decrypt using PGP, specify the PGP fingerprint in the
-p flag or in the SOPS_PGP_FP environment variable.
To use multiple KMS or PGP keys, separate them by commas. For example:
$ sops -p "10F2...0A, 85D...B3F21" file.yaml
The -p, -k, --gcp-kms, --hckms, --hc-vault-transit, and --azure-kv flags are only
used to encrypt new documents. Editing or decrypting existing documents
can be done with "sops file" or "sops decrypt file" respectively. The KMS and
PGP keys listed in the encrypted documents are used then. To manage master
keys in existing documents, use the "add-{kms,pgp,gcp-kms,hckms,azure-kv,hc-vault-transit}"
and "rm-{kms,pgp,gcp-kms,hckms,azure-kv,hc-vault-transit}" flags with --rotate
or the updatekeys command.
To use a different GPG binary than the one in your PATH, set SOPS_GPG_EXEC.
To select a different editor than the default (vim), set SOPS_EDITOR or
EDITOR.
Note that flags must always be provided before the filename to operate on.
Otherwise, they will be ignored.
For more information, see the README at https://github.com/getsops/sops`
app.EnableBashCompletion = true
app.Commands = []cli.Command{
{
Name: "completion",
Usage: "Generate shell completion scripts",
Subcommands: []cli.Command{
{
Name: "bash",
Usage: fmt.Sprintf("Generate bash completions. To load completions: `$ source <(%s completion bash)`", app.Name),
Action: func(c *cli.Context) error {
fmt.Fprint(c.App.Writer, GenBashCompletion(app.Name))
return nil
},
},
{
Name: "zsh",
Usage: fmt.Sprintf("Generate zsh completions. To load completions: `$ source <(%s completion zsh)`", app.Name),
Action: func(c *cli.Context) error {
fmt.Fprint(c.App.Writer, GenZshCompletion(app.Name))
return nil
},
}},
},
{
Name: "exec-env",
Usage: "execute a command with decrypted values inserted into the environment",
ArgsUsage: "[file to decrypt] [command to run]",
Flags: append([]cli.Flag{
cli.BoolFlag{
Name: "background",
Usage: "background the process and don't wait for it to complete (DEPRECATED)",
},
cli.BoolFlag{
Name: "pristine",
Usage: "insert only the decrypted values into the environment without forwarding existing environment variables",
},
cli.StringFlag{
Name: "user",
Usage: "the user to run the command as",
},
cli.BoolFlag{
Name: "same-process",
Usage: "run command in the current process instead of in a child process",
},
cli.StringFlag{
Name: "decryption-order",
Usage: "comma separated list of decryption key types",
EnvVar: "SOPS_DECRYPTION_ORDER",
},
}, keyserviceFlags...),
Action: func(c *cli.Context) error {
if c.NArg() != 2 {
return common.NewExitError(fmt.Errorf("error: missing file to decrypt"), codes.ErrorGeneric)
}
fileName := c.Args()[0]
command := c.Args()[1]
inputStore, err := inputStore(c, fileName)
if err != nil {
return toExitError(err)
}
svcs := keyservices(c)
order, err := decryptionOrder(c.String("decryption-order"))
if err != nil {
return toExitError(err)
}
opts := decryptOpts{
OutputStore: &dotenv.Store{},
InputStore: inputStore,
InputPath: fileName,
Cipher: aes.NewCipher(),
KeyServices: svcs,
DecryptionOrder: order,
IgnoreMAC: c.Bool("ignore-mac"),
}
if c.Bool("background") {
log.Warn("exec-env's --background option is deprecated and will be removed in a future version of sops")
if c.Bool("same-process") {
return common.NewExitError("Error: The --same-process flag cannot be used with --background", codes.ErrorConflictingParameters)
}
}
tree, err := decryptTree(opts)
if err != nil {
return toExitError(err)
}
var env []string
for _, item := range tree.Branches[0] {
if stores.IsComplexValue(item.Value) {
return cli.NewExitError(fmt.Errorf("cannot use complex value in environment; offending key %s", item.Key), codes.ErrorGeneric)
}
if _, ok := item.Key.(sops.Comment); ok {
continue
}
key, ok := item.Key.(string)
if !ok {
return cli.NewExitError(fmt.Errorf("cannot use non-string keys in environment, got %T", item.Key), codes.ErrorGeneric)
}
if strings.Contains(key, "=") {
return cli.NewExitError(fmt.Errorf("cannot use keys with '=' in environment: %s", key), codes.ErrorGeneric)
}
value, ok := item.Value.(string)
if !ok {
value = stores.ValToString(item.Value)
}
env = append(env, fmt.Sprintf("%s=%s", key, value))
}
if err := exec.ExecWithEnv(exec.ExecOpts{
Command: command,
Plaintext: []byte{},
Background: c.Bool("background"),
Pristine: c.Bool("pristine"),
User: c.String("user"),
SameProcess: c.Bool("same-process"),
Env: env,
}); err != nil {
return toExitError(err)
}
return nil
},
},
{
Name: "exec-file",
Usage: "execute a command with the decrypted contents as a temporary file",
ArgsUsage: "[file to decrypt] [command to run]",
Flags: append([]cli.Flag{
cli.BoolFlag{
Name: "background",
Usage: "background the process and don't wait for it to complete (DEPRECATED)",
},
cli.BoolFlag{
Name: "no-fifo",
Usage: "use a regular file instead of a fifo to temporarily hold the decrypted contents",
},
cli.StringFlag{
Name: "user",
Usage: "the user to run the command as",
},
cli.StringFlag{
Name: "input-type",
Usage: "currently ini, json, yaml, dotenv and binary are supported. If not set, sops will use the file's extension to determine the type",
},
cli.StringFlag{
Name: "output-type",
Usage: "currently ini, json, yaml, dotenv and binary are supported. If not set, sops will use the input file's extension to determine the output format",
},
cli.StringFlag{
Name: "filename",
Usage: fmt.Sprintf("filename for the temporarily file (default: %s)", exec.FallbackFilename),
},
cli.StringFlag{
Name: "decryption-order",
Usage: "comma separated list of decryption key types",
EnvVar: "SOPS_DECRYPTION_ORDER",
},
}, keyserviceFlags...),
Action: func(c *cli.Context) error {
if c.NArg() != 2 {
return common.NewExitError(fmt.Errorf("error: missing file to decrypt"), codes.ErrorGeneric)
}
fileName := c.Args()[0]
command := c.Args()[1]
inputStore, err := inputStore(c, fileName)
if err != nil {
return toExitError(err)
}
outputStore, err := outputStore(c, fileName)
if err != nil {
return toExitError(err)
}
svcs := keyservices(c)
order, err := decryptionOrder(c.String("decryption-order"))
if err != nil {
return toExitError(err)
}
opts := decryptOpts{
OutputStore: outputStore,
InputStore: inputStore,
InputPath: fileName,
Cipher: aes.NewCipher(),
KeyServices: svcs,
DecryptionOrder: order,
IgnoreMAC: c.Bool("ignore-mac"),
}
output, err := decrypt(opts)
if err != nil {
return toExitError(err)
}
if c.Bool("background") {
log.Warn("exec-file's --background option is deprecated and will be removed in a future version of sops")
}
if err := exec.ExecWithFile(exec.ExecOpts{
Command: command,
Plaintext: output,
Background: c.Bool("background"),
Fifo: !c.Bool("no-fifo"),
User: c.String("user"),
Filename: c.String("filename"),
}); err != nil {
return toExitError(err)
}
return nil
},
},
{
Name: "publish",
Usage: "Publish sops file or directory to a configured destination",
ArgsUsage: `file`,
Flags: append([]cli.Flag{
cli.BoolFlag{
Name: "yes, y",
Usage: `pre-approve all changes and run non-interactively`,
},
cli.BoolFlag{
Name: "omit-extensions",
Usage: "Omit file extensions in destination path when publishing sops file to configured destinations",
},
cli.BoolFlag{
Name: "recursive",
Usage: "If the source path is a directory, publish all its content recursively",
},
cli.BoolFlag{
Name: "verbose",
Usage: "Enable verbose logging output",
},
cli.StringFlag{
Name: "decryption-order",
Usage: "comma separated list of decryption key types",
EnvVar: "SOPS_DECRYPTION_ORDER",
},
}, keyserviceFlags...),
Action: func(c *cli.Context) error {
if c.Bool("verbose") || c.GlobalBool("verbose") {
logging.SetLevel(logrus.DebugLevel)
}
var configPath string
var err error
if c.GlobalString("config") != "" {
configPath = c.GlobalString("config")
} else {
configPath, err = findConfigFile()
if err != nil {
return common.NewExitError(err, codes.ErrorGeneric)
}
}
if c.NArg() < 1 {
return common.NewExitError("Error: no file specified", codes.NoFileSpecified)
}
warnMoreThanOnePositionalArgument(c)
path := c.Args()[0]
info, err := os.Stat(path)
if err != nil {
return toExitError(err)
}
if info.IsDir() && !c.Bool("recursive") {
return fmt.Errorf("can't operate on a directory without --recursive flag.")
}
order, err := decryptionOrder(c.String("decryption-order"))
if err != nil {
return toExitError(err)
}
err = filepath.Walk(path, func(subPath string, info os.FileInfo, err error) error {
if err != nil {
return toExitError(err)
}
if !info.IsDir() {
inputStore, err := inputStore(c, subPath)
if err != nil {
return toExitError(err)
}
err = publishcmd.Run(publishcmd.Opts{
ConfigPath: configPath,
InputPath: subPath,
RootPath: path,
Cipher: aes.NewCipher(),
KeyServices: keyservices(c),
DecryptionOrder: order,
InputStore: inputStore,
Interactive: !c.Bool("yes"),
OmitExtensions: c.Bool("omit-extensions"),
Recursive: c.Bool("recursive"),
})
if cliErr, ok := err.(*cli.ExitError); ok && cliErr != nil {
return cliErr
} else if err != nil {
return common.NewExitError(err, codes.ErrorGeneric)
}
}
return nil
})
if err != nil {
return toExitError(err)
}
return nil
},
},
{
Name: "keyservice",
Usage: "start a SOPS key service server",
Flags: []cli.Flag{
cli.StringFlag{
Name: "network, net",
Usage: "network to listen on, e.g. 'tcp' or 'unix'",
Value: "tcp",
},
cli.StringFlag{
Name: "address, addr",
Usage: "address to listen on, e.g. '127.0.0.1:5000' or '/tmp/sops.sock'",
Value: "127.0.0.1:5000",
},
cli.BoolFlag{
Name: "prompt",
Usage: "Prompt user to confirm every incoming request",
},
cli.BoolFlag{
Name: "verbose",
Usage: "Enable verbose logging output",
},
},
Action: func(c *cli.Context) error {
if c.Bool("verbose") || c.GlobalBool("verbose") {
logging.SetLevel(logrus.DebugLevel)
}
err := keyservicecmd.Run(keyservicecmd.Opts{
Network: c.String("network"),
Address: c.String("address"),
Prompt: c.Bool("prompt"),
})
if err != nil {
log.Errorf("Error running keyservice: %s", err)
return err
}
return nil
},
},
{
Name: "filestatus",
Usage: "check the status of the file, returning encryption status",
ArgsUsage: `file`,
Flags: []cli.Flag{
cli.StringFlag{
Name: "input-type",
Usage: "currently ini, json, yaml, dotenv and binary are supported. If not set, sops will use the file's extension to determine the type",
},
},
Action: func(c *cli.Context) error {
if c.NArg() < 1 {
return common.NewExitError("Error: no file specified", codes.NoFileSpecified)
}
fileName := c.Args()[0]
inputStore, err := inputStore(c, fileName)
if err != nil {
return toExitError(err)
}
opts := filestatuscmd.Opts{
InputStore: inputStore,
InputPath: fileName,
}
status, err := filestatuscmd.FileStatus(opts)
if err != nil {
return err
}
json, err := encodingjson.Marshal(status)
if err != nil {
return common.NewExitError(err, codes.ErrorGeneric)
}
fmt.Println(string(json))
return nil
},
},
{
Name: "groups",
Usage: "modify the groups on a SOPS file",
Subcommands: []cli.Command{
{
Name: "add",
Usage: "add a new group to a SOPS file",
Flags: append([]cli.Flag{
cli.StringFlag{
Name: "file, f",
Usage: "the file to add the group to",
},
cli.StringSliceFlag{
Name: "pgp",
Usage: "the PGP fingerprints the new group should contain. Can be specified more than once",
},
cli.StringSliceFlag{
Name: "kms",
Usage: "the KMS ARNs the new group should contain. Can be specified more than once",
},
cli.StringFlag{
Name: "aws-profile",
Usage: "The AWS profile to use for requests to AWS",
},
cli.StringSliceFlag{
Name: "gcp-kms",
Usage: "the GCP KMS Resource ID the new group should contain. Can be specified more than once",
},
cli.StringSliceFlag{
Name: "hckms",
Usage: "the HuaweiCloud KMS key ID (format: region:key-uuid) the new group should contain. Can be specified more than once",
},
cli.StringSliceFlag{
Name: "azure-kv",
Usage: "the Azure Key Vault key URL the new group should contain. Can be specified more than once",
},
cli.StringSliceFlag{
Name: "hc-vault-transit",
Usage: "the full vault path to the key used to encrypt/decrypt. Make you choose and configure a key with encryption/decryption enabled (e.g. 'https://vault.example.org:8200/v1/transit/keys/dev'). Can be specified more than once",
},
cli.StringSliceFlag{
Name: "age",
Usage: "the age recipient the new group should contain. Can be specified more than once",
},
cli.BoolFlag{
Name: "in-place, i",
Usage: "write output back to the same file instead of stdout",
},
cli.IntFlag{
Name: "shamir-secret-sharing-threshold",
Usage: "the number of master keys required to retrieve the data key with shamir",
},
cli.StringFlag{
Name: "encryption-context",
Usage: "comma separated list of KMS encryption context key:value pairs",
},
}, keyserviceFlags...),
Action: func(c *cli.Context) error {
pgpFps := c.StringSlice("pgp")
kmsArns := c.StringSlice("kms")
gcpKmses := c.StringSlice("gcp-kms")
vaultURIs := c.StringSlice("hc-vault-transit")
azkvs := c.StringSlice("azure-kv")
ageRecipients := c.StringSlice("age")
if c.NArg() != 0 {
return common.NewExitError(fmt.Errorf("error: no positional arguments allowed"), codes.ErrorGeneric)
}
var group sops.KeyGroup
for _, fp := range pgpFps {
group = append(group, pgp.NewMasterKeyFromFingerprint(fp))
}
for _, arn := range kmsArns {
group = append(group, kms.NewMasterKeyFromArn(arn, kms.ParseKMSContext(c.String("encryption-context")), c.String("aws-profile")))
}
for _, kms := range gcpKmses {
group = append(group, gcpkms.NewMasterKeyFromResourceID(kms))
}
for _, uri := range vaultURIs {
k, err := hcvault.NewMasterKeyFromURI(uri)
if err != nil {
log.WithError(err).Error("Failed to add key")
continue
}
group = append(group, k)
}
for _, url := range azkvs {
k, err := azkv.NewMasterKeyFromURL(url)
if err != nil {
log.WithError(err).Error("Failed to add key")
continue
}
group = append(group, k)
}
for _, recipient := range ageRecipients {
keys, err := age.MasterKeysFromRecipients(recipient)
if err != nil {
log.WithError(err).Error("Failed to add key")
continue
}
for _, key := range keys {
group = append(group, key)
}
}
inputStore, err := inputStore(c, c.String("file"))
if err != nil {
return toExitError(err)
}
outputStore, err := outputStore(c, c.String("file"))
if err != nil {
return toExitError(err)
}
return groups.Add(groups.AddOpts{
InputPath: c.String("file"),
InPlace: c.Bool("in-place"),
InputStore: inputStore,
OutputStore: outputStore,
Group: group,
GroupThreshold: c.Int("shamir-secret-sharing-threshold"),
KeyServices: keyservices(c),
})
},
},
{
Name: "delete",
Usage: "delete a key group from a SOPS file",
Flags: append([]cli.Flag{
cli.StringFlag{
Name: "file, f",
Usage: "the file to add the group to",
},
cli.BoolFlag{
Name: "in-place, i",
Usage: "write output back to the same file instead of stdout",
},
cli.IntFlag{
Name: "shamir-secret-sharing-threshold",
Usage: "the number of master keys required to retrieve the data key with shamir",
},
}, keyserviceFlags...),
ArgsUsage: `[index]`,
Action: func(c *cli.Context) error {
if c.NArg() != 1 {
return common.NewExitError(fmt.Errorf("error: exactly one positional argument (index) required"), codes.ErrorGeneric)
}
group, err := strconv.ParseUint(c.Args().First(), 10, 32)
if err != nil {
return fmt.Errorf("failed to parse [index] argument: %s", err)
}
inputStore, err := inputStore(c, c.String("file"))
if err != nil {
return toExitError(err)
}
outputStore, err := outputStore(c, c.String("file"))
if err != nil {
return toExitError(err)
}
return groups.Delete(groups.DeleteOpts{
InputPath: c.String("file"),
InPlace: c.Bool("in-place"),
InputStore: inputStore,
OutputStore: outputStore,
Group: uint(group),
GroupThreshold: c.Int("shamir-secret-sharing-threshold"),
KeyServices: keyservices(c),
})
},
},
},
},
{
Name: "updatekeys",
Usage: "update the keys of SOPS files using the config file",
ArgsUsage: `file`,
Flags: append([]cli.Flag{
cli.BoolFlag{
Name: "yes, y",
Usage: `pre-approve all changes and run non-interactively`,
},
cli.StringFlag{
Name: "input-type",
Usage: "currently ini, json, yaml, dotenv and binary are supported. If not set, sops will use the file's extension to determine the type",
},
}, keyserviceFlags...),
Action: func(c *cli.Context) error {
var err error
var configPath string
if c.GlobalString("config") != "" {
configPath = c.GlobalString("config")
} else {
configPath, err = findConfigFile()
if err != nil {
return common.NewExitError(err, codes.ErrorGeneric)
}
}
if c.NArg() < 1 {
return common.NewExitError("Error: no file specified", codes.NoFileSpecified)
}
failedCounter := 0
for _, path := range c.Args() {
err := updatekeys.UpdateKeys(updatekeys.Opts{
InputPath: path,
ShamirThreshold: c.Int("shamir-secret-sharing-threshold"),
KeyServices: keyservices(c),
Interactive: !c.Bool("yes"),
ConfigPath: configPath,
InputType: c.String("input-type"),
})
if c.NArg() == 1 {
// a single argument was given, keep compatibility of the error
if cliErr, ok := err.(*cli.ExitError); ok && cliErr != nil {
return cliErr
} else if err != nil {
return common.NewExitError(err, codes.ErrorGeneric)
}
}
// multiple arguments given (patched functionality),
// finish updating of remaining files and fail afterwards
if err != nil {
failedCounter++
log.Error(err)
}
}
if failedCounter > 0 {
return common.NewExitError(fmt.Errorf("failed updating %d key(s)", failedCounter), codes.ErrorGeneric)
}
return nil
},
},
{
Name: "decrypt",
Usage: "decrypt a file, and output the results to stdout. If no filename is provided, stdin will be used.",
ArgsUsage: `[file]`,
Flags: append([]cli.Flag{
cli.BoolFlag{
Name: "in-place, i",
Usage: "write output back to the same file instead of stdout",
},
cli.StringFlag{
Name: "extract",
Usage: "extract a specific key or branch from the input document. Example: --extract '[\"somekey\"][0]'",
},
cli.StringFlag{
Name: "output",
Usage: "Save the output after decryption to the file specified",
},
cli.StringFlag{
Name: "input-type",
Usage: "currently json, yaml, dotenv and binary are supported. If not set, sops will use the file's extension to determine the type",
},
cli.StringFlag{
Name: "output-type",
Usage: "currently json, yaml, dotenv and binary are supported. If not set, sops will use the input file's extension to determine the output format",
},
cli.BoolFlag{
Name: "ignore-mac",
Usage: "ignore Message Authentication Code during decryption",
},
cli.StringFlag{
Name: "filename-override",
Usage: "Use this filename instead of the provided argument for loading configuration, and for determining input type and output type. Should be provided when reading from stdin.",
},
cli.StringFlag{
Name: "decryption-order",
Usage: "comma separated list of decryption key types",
EnvVar: "SOPS_DECRYPTION_ORDER",
},
}, keyserviceFlags...),
Action: func(c *cli.Context) error {
if c.Bool("verbose") {
logging.SetLevel(logrus.DebugLevel)
}
readFromStdin := c.NArg() == 0
if readFromStdin && c.Bool("in-place") {
return common.NewExitError("Error: cannot use --in-place when reading from stdin", codes.ErrorConflictingParameters)
}
warnMoreThanOnePositionalArgument(c)
if c.Bool("in-place") && c.String("output") != "" {
return common.NewExitError("Error: cannot operate on both --output and --in-place", codes.ErrorConflictingParameters)
}
var fileName string
var err error
if !readFromStdin {
fileName, err = filepath.Abs(c.Args()[0])
if err != nil {
return toExitError(err)
}
if _, err := os.Stat(fileName); os.IsNotExist(err) {
return common.NewExitError(fmt.Sprintf("Error: cannot operate on non-existent file %q", fileName), codes.NoFileSpecified)
}
}
fileNameOverride := c.String("filename-override")
if fileNameOverride == "" {
fileNameOverride = fileName
} else {
fileNameOverride, err = filepath.Abs(fileNameOverride)
if err != nil {
return toExitError(err)
}
}
inputStore, err := inputStore(c, fileNameOverride)
if err != nil {
return toExitError(err)
}
outputStore, err := outputStore(c, fileNameOverride)
if err != nil {
return toExitError(err)
}
svcs := keyservices(c)
order, err := decryptionOrder(c.String("decryption-order"))
if err != nil {
return toExitError(err)
}
var extract []interface{}
extract, err = parseTreePath(c.String("extract"))
if err != nil {
return common.NewExitError(fmt.Errorf("error parsing --extract path: %s", err), codes.InvalidTreePathFormat)
}
output, err := decrypt(decryptOpts{
OutputStore: outputStore,
InputStore: inputStore,
InputPath: fileName,
ReadFromStdin: readFromStdin,
Cipher: aes.NewCipher(),
Extract: extract,
KeyServices: svcs,
DecryptionOrder: order,
IgnoreMAC: c.Bool("ignore-mac"),
})
if err != nil {
return toExitError(err)
}
// We open the file *after* the operations on the tree have been
// executed to avoid truncating it when there's errors
if c.Bool("in-place") {
file, err := os.Create(fileName)
if err != nil {
return common.NewExitError(fmt.Sprintf("Could not open in-place file for writing: %s", err), codes.CouldNotWriteOutputFile)
}
defer file.Close()
_, err = file.Write(output)
if err != nil {
return toExitError(err)
}
log.Info("File written successfully")
return nil
}
outputFile := os.Stdout
if c.String("output") != "" {
file, err := os.Create(c.String("output"))
if err != nil {
return common.NewExitError(fmt.Sprintf("Could not open output file for writing: %s", err), codes.CouldNotWriteOutputFile)
}
defer file.Close()
outputFile = file
}
_, err = outputFile.Write(output)
return toExitError(err)
},
},
{
Name: "encrypt",
Usage: "encrypt a file, and output the results to stdout. If no filename is provided, stdin will be used.",
ArgsUsage: `[file]`,
Flags: append([]cli.Flag{
cli.BoolFlag{
Name: "in-place, i",
Usage: "write output back to the same file instead of stdout",
},
cli.StringFlag{
Name: "output",
Usage: "Save the output after encryption to the file specified",
},
cli.StringFlag{
Name: "kms, k",
Usage: "comma separated list of KMS ARNs",
EnvVar: "SOPS_KMS_ARN",
},
cli.StringFlag{
Name: "aws-profile",
Usage: "The AWS profile to use for requests to AWS",
},
cli.StringFlag{
Name: "gcp-kms",
Usage: "comma separated list of GCP KMS resource IDs",
EnvVar: "SOPS_GCP_KMS_IDS",
},
cli.StringFlag{
Name: "hckms",
Usage: "comma separated list of HuaweiCloud KMS key IDs (format: region:key-uuid)",
EnvVar: "SOPS_HUAWEICLOUD_KMS_IDS",
},
cli.StringFlag{
Name: "azure-kv",
Usage: "comma separated list of Azure Key Vault URLs",
EnvVar: "SOPS_AZURE_KEYVAULT_URLS",
},
cli.StringFlag{
Name: "hc-vault-transit",
Usage: "comma separated list of vault's key URI (e.g. 'https://vault.example.org:8200/v1/transit/keys/dev')",
EnvVar: "SOPS_VAULT_URIS",
},
cli.StringFlag{
Name: "pgp, p",
Usage: "comma separated list of PGP fingerprints",
EnvVar: "SOPS_PGP_FP",
},
cli.StringFlag{
Name: "age, a",
Usage: "comma separated list of age recipients",
EnvVar: "SOPS_AGE_RECIPIENTS",
},
cli.StringFlag{
Name: "input-type",
Usage: "currently json, yaml, dotenv and binary are supported. If not set, sops will use the file's extension to determine the type",
},
cli.StringFlag{
Name: "output-type",
Usage: "currently json, yaml, dotenv and binary are supported. If not set, sops will use the input file's extension to determine the output format",
},
cli.StringFlag{
Name: "unencrypted-suffix",
Usage: "override the unencrypted key suffix.",
},
cli.StringFlag{
Name: "encrypted-suffix",
Usage: "override the encrypted key suffix. When empty, all keys will be encrypted, unless otherwise marked with unencrypted-suffix.",
},
cli.StringFlag{
Name: "unencrypted-regex",
Usage: "set the unencrypted key regex. When specified, only keys matching the regex will be left unencrypted.",
},
cli.StringFlag{
Name: "encrypted-regex",
Usage: "set the encrypted key regex. When specified, only keys matching the regex will be encrypted.",
},
cli.StringFlag{
Name: "encryption-context",
Usage: "comma separated list of KMS encryption context key:value pairs",
},