-
Notifications
You must be signed in to change notification settings - Fork 230
Expand file tree
/
Copy pathmain.go
More file actions
1422 lines (1263 loc) · 39.4 KB
/
Copy pathmain.go
File metadata and controls
1422 lines (1263 loc) · 39.4 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 (
"bytes"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
"os"
"os/user"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"syscall"
"time"
"github.com/Mic92/sops-nix/pkgs/sops-install-secrets/sshkeys"
agessh "github.com/Mic92/ssh-to-age"
"github.com/getsops/sops/v3/decrypt"
"github.com/joho/godotenv"
"github.com/mozilla-services/yaml"
"gopkg.in/ini.v1"
)
type secret struct {
Name string `json:"name"`
Key string `json:"key"`
Path string `json:"path"`
Owner *string `json:"owner,omitempty"`
UID int `json:"uid"`
Group *string `json:"group,omitempty"`
GID int `json:"gid"`
SopsFile string `json:"sopsFile"`
Format FormatType `json:"format"`
Mode string `json:"mode"`
RestartUnits []string `json:"restartUnits"`
ReloadUnits []string `json:"reloadUnits"`
value []byte
mode os.FileMode
owner int
group int
}
type loggingConfig struct {
KeyImport bool `json:"keyImport"`
SecretChanges bool `json:"secretChanges"`
}
type template struct {
Name string `json:"name"`
Content string `json:"content"`
Path string `json:"path"`
Mode string `json:"mode"`
Owner *string `json:"owner,omitempty"`
UID int `json:"uid"`
Group *string `json:"group,omitempty"`
GID int `json:"gid"`
File string `json:"file"`
RestartUnits []string `json:"restartUnits"`
ReloadUnits []string `json:"reloadUnits"`
value []byte
mode os.FileMode
content string
owner int
group int
}
type manifest struct {
Secrets []secret `json:"secrets"`
Templates []template `json:"templates"`
PlaceholderBySecretName map[string]string `json:"placeholderBySecretName"`
SecretsMountPoint string `json:"secretsMountPoint"`
SymlinkPath string `json:"symlinkPath"`
KeepGenerations int `json:"keepGenerations"`
SSHKeyPaths []string `json:"sshKeyPaths"`
GnupgHome string `json:"gnupgHome"`
AgeKeyFile string `json:"ageKeyFile"`
AgeSSHKeyFile string `json:"ageSshKeyFile"`
AgeSSHKeyCmd string `json:"ageSshKeyCmd"`
AgeSSHKeyPaths []string `json:"ageSshKeyPaths"`
UseTmpfs bool `json:"useTmpfs"`
UserMode bool `json:"userMode"`
Logging loggingConfig `json:"logging"`
}
type secretFile struct {
cipherText []byte
keys map[string]interface{}
/// First secret that defined this secretFile, used for error messages
firstSecret *secret
}
type FormatType string
const (
Yaml FormatType = "yaml"
JSON FormatType = "json"
Binary FormatType = "binary"
Dotenv FormatType = "dotenv"
Ini FormatType = "ini"
)
func IsValidFormat(format string) bool {
switch format {
case string(Yaml),
string(JSON),
string(Binary),
string(Dotenv),
string(Ini):
return true
default:
return false
}
}
func (f *FormatType) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
t := FormatType(s)
switch t {
case "":
*f = Yaml
case Yaml, JSON, Binary, Dotenv, Ini:
*f = t
}
return nil
}
func (f FormatType) MarshalJSON() ([]byte, error) {
return json.Marshal(string(f))
}
type CheckMode string
const (
Manifest CheckMode = "manifest"
SopsFile CheckMode = "sopsfile"
Off CheckMode = "off"
)
type options struct {
checkMode CheckMode
manifest string
ignorePasswd bool
}
type appContext struct {
manifest manifest
secretFiles map[string]secretFile
secretByPlaceholder map[string]*secret
checkMode CheckMode
ignorePasswd bool
}
// Keep this in sync with `modules/sops/templates/default.nix`
const RenderedSubdir string = "rendered"
func readManifest(path string) (*manifest, error) {
file, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("failed to open manifest: %w", err)
}
defer file.Close()
dec := json.NewDecoder(file)
var m manifest
if err := dec.Decode(&m); err != nil {
return nil, fmt.Errorf("failed to parse manifest: %w", err)
}
return &m, nil
}
func linksAreEqual(linkTarget, targetFile string, info os.FileInfo, owner int, group int) bool {
validUG := true
if stat, ok := info.Sys().(*syscall.Stat_t); ok {
validUG = validUG && int(stat.Uid) == owner
validUG = validUG && int(stat.Gid) == group
} else {
panic("Failed to cast fileInfo Sys() to *syscall.Stat_t. This is possibly an unsupported OS.")
}
return linkTarget == targetFile && validUG
}
func SecureSymlinkChown(targetFile string, path string, owner int, group int) error {
// Create a temp directory to house the symlink while we change it's
// ownership. `os.MkdirTemp` creates a directory with the permissions 0700.
// The temp dir is created in the same parent directory of the final
// symlink, because the later `os.Rename` operation won't work across disk
// devices.
dir, err := os.MkdirTemp(filepath.Dir(path), "")
if err != nil {
return fmt.Errorf("cannot create temporary symlink directory: %w", err)
}
defer os.RemoveAll(dir)
// Create symlink to `targetFile` in the temp dir, before chowning it.
tmpSymlink := filepath.Join(dir, filepath.Base(path))
if err = os.Symlink(targetFile, tmpSymlink); err != nil {
return fmt.Errorf(
"cannot create symlink '%s' (pointing to '%s'): %w", path, targetFile, err)
}
err = os.Lchown(tmpSymlink, owner, group)
if err != nil {
return fmt.Errorf(
"cannot change owner of symlink '%s' (pointing to '%s') to owner/group: %d/%d: %w",
tmpSymlink, targetFile, owner, group, err)
}
// Move the chowned symlink to it's final location.
err = os.Rename(tmpSymlink, path)
if err != nil {
return fmt.Errorf("cannot move symlink '%s' to '%s': %w", tmpSymlink, path, err)
}
return nil
}
func createSymlink(targetFile string, path string, owner int, group int, userMode bool) error {
for {
stat, err := os.Lstat(path)
if os.IsNotExist(err) {
if !userMode {
if err = SecureSymlinkChown(targetFile, path, owner, group); err != nil {
return fmt.Errorf("cannot chown symlink '%s': %w", path, err)
}
} else if err = os.Symlink(targetFile, path); err != nil {
return fmt.Errorf("cannot create symlink '%s': %w", path, err)
}
return nil
} else if err != nil {
return fmt.Errorf("cannot stat '%s': %w", path, err)
}
if stat.Mode()&os.ModeSymlink == os.ModeSymlink {
linkTarget, err := os.Readlink(path)
if os.IsNotExist(err) {
continue
} else if err != nil {
return fmt.Errorf("cannot read symlink '%s': %w", path, err)
} else if linksAreEqual(linkTarget, targetFile, stat, owner, group) {
return nil
}
}
if err := os.Remove(path); err != nil {
return fmt.Errorf("cannot override %s: %w", path, err)
}
}
}
func symlinkSecretsAndTemplates(targetDir string, secrets []secret, templates []template, userMode bool) error {
for _, secret := range secrets {
targetFile := filepath.Join(targetDir, secret.Name)
if targetFile == secret.Path {
continue
}
parent := filepath.Dir(secret.Path)
if err := os.MkdirAll(parent, os.ModePerm); err != nil {
return fmt.Errorf("cannot create parent directory of '%s': %w", secret.Path, err)
}
if err := createSymlink(targetFile, secret.Path, secret.owner, secret.group, userMode); err != nil {
return fmt.Errorf("failed to symlink secret '%s': %w", secret.Path, err)
}
}
for _, template := range templates {
targetFile := filepath.Join(targetDir, RenderedSubdir, template.Name)
if targetFile == template.Path {
continue
}
parent := filepath.Dir(template.Path)
if err := os.MkdirAll(parent, os.ModePerm); err != nil {
return fmt.Errorf("cannot create parent directory of '%s': %w", template.Path, err)
}
if err := createSymlink(targetFile, template.Path, template.owner, template.group, userMode); err != nil {
return fmt.Errorf("failed to symlink template '%s': %w", template.Path, err)
}
}
return nil
}
type plainData struct {
data map[string]interface{}
binary []byte
}
func recurseSecretKey(keys map[string]interface{}, wantedKey string) (string, error) {
var val interface{}
var ok bool
currentKey := wantedKey
currentData := keys
keyUntilNow := ""
for {
slashIndex := strings.IndexByte(currentKey, '/')
if slashIndex == -1 {
// We got to the end
val, ok = currentData[currentKey]
if !ok {
if keyUntilNow != "" {
keyUntilNow += "/"
}
return "", fmt.Errorf("the key '%s%s' cannot be found", keyUntilNow, currentKey)
}
break
}
thisKey := currentKey[:slashIndex]
if keyUntilNow == "" {
keyUntilNow = thisKey
} else {
keyUntilNow += "/" + thisKey
}
currentKey = currentKey[(slashIndex + 1):]
val, ok = currentData[thisKey]
if !ok {
return "", fmt.Errorf("the key '%s' cannot be found", keyUntilNow)
}
var valWithWrongType map[interface{}]interface{}
valWithWrongType, ok = val.(map[interface{}]interface{})
if !ok {
return "", fmt.Errorf("key '%s' does not refer to a dictionary", keyUntilNow)
}
currentData = make(map[string]interface{})
for key, value := range valWithWrongType {
currentData[key.(string)] = value
}
}
strVal, ok := val.(string)
if !ok {
return "", fmt.Errorf("the value of key '%s' is not a string", keyUntilNow)
}
return strVal, nil
}
func decryptSecret(s *secret, sourceFiles map[string]plainData) error {
sourceFile := sourceFiles[s.SopsFile]
if sourceFile.data == nil || sourceFile.binary == nil {
plain, err := decrypt.File(s.SopsFile, string(s.Format))
if err != nil {
return fmt.Errorf("failed to decrypt '%s': %w", s.SopsFile, err)
}
switch s.Format {
case Binary, Dotenv, Ini:
sourceFile.binary = plain
case Yaml:
if s.Key == "" {
sourceFile.binary = plain
} else {
if err := yaml.Unmarshal(plain, &sourceFile.data); err != nil {
return fmt.Errorf("Cannot parse yaml of '%s': %w", s.SopsFile, err)
}
}
case JSON:
if s.Key == "" {
sourceFile.binary = plain
} else {
if err := json.Unmarshal(plain, &sourceFile.data); err != nil {
return fmt.Errorf("Cannot parse json of '%s': %w", s.SopsFile, err)
}
}
default:
return fmt.Errorf("secret of type %s in %s is not supported", s.Format, s.SopsFile)
}
}
switch s.Format {
case Binary, Dotenv, Ini:
s.value = sourceFile.binary
case Yaml, JSON:
if s.Key == "" {
s.value = sourceFile.binary
} else {
strVal, err := recurseSecretKey(sourceFile.data, s.Key)
if err != nil {
return fmt.Errorf("secret %s in %s is not valid: %w", s.Name, s.SopsFile, err)
}
s.value = []byte(strVal)
}
}
sourceFiles[s.SopsFile] = sourceFile
return nil
}
func decryptSecrets(secrets []secret) error {
sourceFiles := make(map[string]plainData)
for i := range secrets {
if err := decryptSecret(&secrets[i], sourceFiles); err != nil {
return err
}
}
return nil
}
const (
RamfsMagic int32 = -2054924042
TmpfsMagic int32 = 16914836
)
func prepareSecretsDir(secretMountpoint string, linkName string, keysGID int, userMode bool) (*string, error) {
var generation uint64
linkTarget, err := os.Readlink(linkName)
if err == nil {
if strings.HasPrefix(linkTarget, secretMountpoint) {
targetBasename := filepath.Base(linkTarget)
generation, err = strconv.ParseUint(targetBasename, 10, 64)
if err != nil {
return nil, fmt.Errorf("cannot parse %s of %s as a number: %w", targetBasename, linkTarget, err)
}
}
} else if !os.IsNotExist(err) {
if _, err2 := os.Lstat(linkName); err2 != nil {
return nil, fmt.Errorf("cannot access %s: %w", linkName, err)
}
// if `/run/secrets` exists, but is not a symlink, we need to remove it
if err = os.RemoveAll(linkName); err != nil {
return nil, fmt.Errorf("cannot remove %s: %w", linkName, err)
}
}
generation++
dir := filepath.Join(secretMountpoint, strconv.Itoa(int(generation)))
if _, err := os.Stat(dir); !os.IsNotExist(err) {
if err := os.RemoveAll(dir); err != nil {
return nil, fmt.Errorf("cannot remove existing %s: %w", dir, err)
}
}
if err := os.Mkdir(dir, os.FileMode(0o751)); err != nil {
return nil, fmt.Errorf("mkdir(): %w", err)
}
if !userMode {
if err := os.Chown(dir, 0, int(keysGID)); err != nil {
return nil, fmt.Errorf("cannot change owner/group of '%s' to 0/%d: %w", dir, keysGID, err)
}
}
return &dir, nil
}
func createParentDirs(parent string, target string, keysGID int, userMode bool) error {
dirs := strings.Split(filepath.Dir(target), "/")
pathSoFar := parent
for _, dir := range dirs {
pathSoFar = filepath.Join(pathSoFar, dir)
if err := os.MkdirAll(pathSoFar, 0o751); err != nil {
return fmt.Errorf("cannot create directory '%s' for %s: %w", pathSoFar, filepath.Join(parent, target), err)
}
if !userMode {
if err := os.Chown(pathSoFar, 0, int(keysGID)); err != nil {
return fmt.Errorf("cannot own directory '%s' for %s: %w", pathSoFar, filepath.Join(parent, target), err)
}
}
}
return nil
}
func writeSecrets(secretDir string, secrets []secret, keysGID int, userMode bool) error {
for _, secret := range secrets {
fp := filepath.Join(secretDir, secret.Name)
if err := createParentDirs(secretDir, secret.Name, keysGID, userMode); err != nil {
return err
}
if err := os.WriteFile(fp, []byte(secret.value), secret.mode); err != nil {
return fmt.Errorf("cannot write %s: %w", fp, err)
}
if !userMode {
if err := os.Chown(fp, secret.owner, secret.group); err != nil {
return fmt.Errorf("cannot change owner/group of '%s' to %d/%d: %w", fp, secret.owner, secret.group, err)
}
}
}
return nil
}
func lookupGroup(groupname string) (int, error) {
group, err := user.LookupGroup(groupname)
if err != nil {
return 0, fmt.Errorf("failed to lookup 'keys' group: %w", err)
}
gid, err := strconv.ParseInt(group.Gid, 10, 64)
if err != nil {
return 0, fmt.Errorf("cannot parse keys gid %s: %w", group.Gid, err)
}
return int(gid), nil
}
func lookupKeysGroup() (int, error) {
gid, err1 := lookupGroup("keys")
if err1 == nil {
return gid, nil
}
gid, err2 := lookupGroup("nogroup")
if err2 == nil {
return gid, nil
}
return 0, fmt.Errorf("can't find group 'keys' nor 'nogroup' (%w)", err2)
}
func (app *appContext) loadSopsFile(s *secret) (*secretFile, error) {
if app.checkMode == Manifest {
return &secretFile{firstSecret: s}, nil
}
cipherText, err := os.ReadFile(s.SopsFile)
if err != nil {
return nil, fmt.Errorf("failed reading %s: %w", s.SopsFile, err)
}
var keys map[string]interface{}
switch s.Format {
case Binary:
if err := json.Unmarshal(cipherText, &keys); err != nil {
return nil, fmt.Errorf("cannot parse json of '%s': %w", s.SopsFile, err)
}
return &secretFile{cipherText: cipherText, firstSecret: s}, nil
case Yaml:
if err := yaml.Unmarshal(cipherText, &keys); err != nil {
return nil, fmt.Errorf("cannot parse yaml of '%s': %w", s.SopsFile, err)
}
case Dotenv:
env, err := godotenv.Unmarshal(string(cipherText))
if err != nil {
return nil, fmt.Errorf("cannot parse dotenv of '%s': %w", s.SopsFile, err)
}
keys = map[string]interface{}{}
for k, v := range env {
keys[k] = v
}
case JSON:
if err := json.Unmarshal(cipherText, &keys); err != nil {
return nil, fmt.Errorf("cannot parse json of '%s': %w", s.SopsFile, err)
}
case Ini:
_, err := ini.Load(bytes.NewReader(cipherText))
if err != nil {
return nil, fmt.Errorf("cannot parse ini of '%s': %w", s.SopsFile, err)
}
// TODO: we do not actually check the contents of the ini here...
}
return &secretFile{
cipherText: cipherText,
keys: keys,
firstSecret: s,
}, nil
}
func (app *appContext) validateSopsFile(s *secret, file *secretFile) error {
if file.firstSecret.Format != s.Format {
return fmt.Errorf("secret %s defined the format of %s as %s, but it was specified as %s in %s before",
s.Name, s.SopsFile, s.Format,
file.firstSecret.Format, file.firstSecret.Name)
}
if app.checkMode != Manifest && !(s.Format == Binary || s.Format == Dotenv || s.Format == Ini) && s.Key != "" {
_, err := recurseSecretKey(file.keys, s.Key)
if err != nil {
return fmt.Errorf("secret %s in %s is not valid: %w", s.Name, s.SopsFile, err)
}
}
return nil
}
func validateMode(mode string) (os.FileMode, error) {
parsed, err := strconv.ParseUint(mode, 8, 16)
if err != nil {
return 0, fmt.Errorf("invalid number in mode: %s: %w", mode, err)
}
return os.FileMode(parsed), nil
}
func validateOwner(owner string) (int, error) {
lookedUp, err := user.Lookup(owner)
if err != nil {
return 0, fmt.Errorf("failed to lookup user '%s': %w", owner, err)
}
ownerNr, err := strconv.ParseUint(lookedUp.Uid, 10, 64)
if err != nil {
return 0, fmt.Errorf("cannot parse uid %s: %w", lookedUp.Uid, err)
}
return int(ownerNr), nil
}
func validateGroup(group string) (int, error) {
lookedUp, err := user.LookupGroup(group)
if err != nil {
return 0, fmt.Errorf("failed to lookup group '%s': %w", group, err)
}
groupNr, err := strconv.ParseUint(lookedUp.Gid, 10, 64)
if err != nil {
return 0, fmt.Errorf("cannot parse gid %s: %w", lookedUp.Gid, err)
}
return int(groupNr), nil
}
func (app *appContext) validateSecret(secret *secret) error {
mode, err := validateMode(secret.Mode)
if err != nil {
return err
}
secret.mode = mode
if app.ignorePasswd || os.Getenv("NIXOS_ACTION") == "dry-activate" {
secret.owner = 0
secret.group = 0
} else if app.checkMode == Off || app.ignorePasswd {
if secret.Owner == nil {
secret.owner = secret.UID
} else {
owner, err := validateOwner(*secret.Owner)
if err != nil {
return err
}
secret.owner = owner
}
if secret.Group == nil {
secret.group = secret.GID
} else {
group, err := validateGroup(*secret.Group)
if err != nil {
return err
}
secret.group = group
}
}
if secret.Format == "" {
secret.Format = "yaml"
}
if !IsValidFormat(string(secret.Format)) {
return fmt.Errorf("unsupported format %s for secret %s", secret.Format, secret.Name)
}
file, ok := app.secretFiles[secret.SopsFile]
if !ok {
maybeFile, err := app.loadSopsFile(secret)
if err != nil {
return err
}
app.secretFiles[secret.SopsFile] = *maybeFile
file = *maybeFile
}
return app.validateSopsFile(secret, &file)
}
func renderTemplates(templates []template, secretByPlaceholder map[string]*secret) {
for i := range templates {
template := &templates[i]
rendered := renderTemplate(&template.content, secretByPlaceholder)
template.value = []byte(rendered)
}
}
func renderTemplate(content *string, secretByPlaceholder map[string]*secret) string {
rendered := *content
for placeholder, secret := range secretByPlaceholder {
rendered = strings.ReplaceAll(rendered, placeholder, string(secret.value))
}
return rendered
}
func (app *appContext) validateTemplate(template *template) error {
mode, err := validateMode(template.Mode)
if err != nil {
return err
}
template.mode = mode
if app.ignorePasswd || os.Getenv("NIXOS_ACTION") == "dry-activate" {
template.owner = 0
template.group = 0
} else if app.checkMode == Off || app.ignorePasswd {
if template.Owner == nil {
template.owner = template.UID
} else {
owner, err := validateOwner(*template.Owner)
if err != nil {
return err
}
template.owner = owner
}
if template.Group == nil {
template.group = template.GID
} else {
group, err := validateGroup(*template.Group)
if err != nil {
return err
}
template.group = group
}
}
var templateText string
if template.Content != "" {
templateText = template.Content
} else if template.File != "" {
templateBytes, err := os.ReadFile(template.File)
if err != nil {
return fmt.Errorf("cannot read %s: %w", template.File, err)
}
templateText = string(templateBytes)
} else {
return fmt.Errorf("neither content nor file was specified for template %s", template.Name)
}
template.content = templateText
return nil
}
func (app *appContext) validateManifest() error {
m := &app.manifest
if m.GnupgHome != "" {
errorFmt := "gnupgHome and %s were specified in the manifest. " +
"Both options are mutually exclusive."
if len(m.SSHKeyPaths) > 0 {
return fmt.Errorf(errorFmt, "sshKeyPaths")
}
if m.AgeKeyFile != "" {
return fmt.Errorf(errorFmt, "ageKeyFile")
}
}
for i := range m.Secrets {
secret := &m.Secrets[i]
if err := app.validateSecret(secret); err != nil {
return err
}
// The Nix module only defines placeholders for secrets if there are
// templates.
if len(m.Templates) > 0 {
placeholder, present := m.PlaceholderBySecretName[secret.Name]
if !present {
return fmt.Errorf("placeholder for %s not found in manifest", secret.Name)
}
app.secretByPlaceholder[placeholder] = secret
}
}
for i := range m.Templates {
template := &m.Templates[i]
if err := app.validateTemplate(template); err != nil {
return err
}
}
return nil
}
func atomicSymlink(oldname, newname string) error {
if err := os.MkdirAll(filepath.Dir(newname), 0o755); err != nil {
return fmt.Errorf("cannot create directory %s: %w", filepath.Dir(newname), err)
}
// Fast path: if newname does not exist yet, we can skip the whole dance
// below.
if err := os.Symlink(oldname, newname); err == nil || !os.IsExist(err) {
return err
}
// We need to use ioutil.TempDir, as we cannot overwrite a ioutil.TempFile,
// and removing+symlinking creates a TOCTOU race.
d, err := os.MkdirTemp(filepath.Dir(newname), "."+filepath.Base(newname))
if err != nil {
return fmt.Errorf("cannot create temporary directory: %w", err)
}
defer func() {
os.RemoveAll(d)
}()
symlink := filepath.Join(d, "tmp.symlink")
if err := os.Symlink(oldname, symlink); err != nil {
return fmt.Errorf("cannot create symlink %s: %w", symlink, err)
}
if err := os.Rename(symlink, newname); err != nil {
return fmt.Errorf("cannot rename %s to %s: %w", symlink, newname, err)
}
return nil
}
func pruneGenerations(secretsMountPoint, secretsDir string, keepGenerations int) error {
if keepGenerations == 0 {
return nil // Nothing to prune
}
// Prepare our failsafe
currentGeneration, err := strconv.Atoi(path.Base(secretsDir))
if err != nil {
return fmt.Errorf("logic error, current generation is not numeric: %w", err)
}
// Read files in the mount directory
file, err := os.Open(secretsMountPoint)
if err != nil {
return fmt.Errorf("cannot open %s: %w", secretsMountPoint, err)
}
defer file.Close()
generations, err := file.Readdirnames(0)
if err != nil {
return fmt.Errorf("cannot read %s: %w", secretsMountPoint, err)
}
for _, generationName := range generations {
generationNum, err := strconv.Atoi(generationName)
// Not a number? Not relevant
if err != nil {
continue
}
// Not strictly necessary but a good failsafe to
// make sure we don't prune the current generation
if generationNum == currentGeneration {
continue
}
if currentGeneration-keepGenerations >= generationNum {
os.RemoveAll(path.Join(secretsMountPoint, generationName))
}
}
return nil
}
func importSSHKeys(logcfg loggingConfig, keyPaths []string, gpgHome string) error {
secringPath := filepath.Join(gpgHome, "secring.gpg")
pubringPath := filepath.Join(gpgHome, "pubring.gpg")
secring, err := os.OpenFile(secringPath, os.O_WRONLY|os.O_CREATE, 0o600)
if err != nil {
return fmt.Errorf("cannot create %s: %w", secringPath, err)
}
defer secring.Close()
pubring, err := os.OpenFile(pubringPath, os.O_WRONLY|os.O_CREATE, 0o600)
if err != nil {
return fmt.Errorf("cannot create %s: %w", pubringPath, err)
}
defer pubring.Close()
for _, p := range keyPaths {
sshKey, err := os.ReadFile(p)
if err != nil {
fmt.Fprintf(os.Stderr, "Cannot read ssh key '%s': %s\n", p, err)
continue
}
gpgKey, err := sshkeys.SSHPrivateKeyToPGP(sshKey)
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
continue
}
if err := gpgKey.SerializePrivate(secring, nil); err != nil {
fmt.Fprintf(os.Stderr, "Cannot write secring: %s\n", err)
continue
}
if err := gpgKey.Serialize(pubring); err != nil {
fmt.Fprintf(os.Stderr, "Cannot write pubring: %s\n", err)
continue
}
if logcfg.KeyImport {
fmt.Printf("%s: Imported %s as GPG key with fingerprint %s\n", path.Base(os.Args[0]), p, hex.EncodeToString(gpgKey.PrimaryKey.Fingerprint[:]))
}
}
return nil
}
func importAgeSSHKeys(logcfg loggingConfig, keyPaths []string, ageFile os.File) error {
for _, p := range keyPaths {
// Read the key
sshKey, err := os.ReadFile(p)
if err != nil {
fmt.Fprintf(os.Stderr, "Cannot read ssh key '%s': %s\n", p, err)
continue
}
// Convert the key to age
privKey, pubKey, err := agessh.SSHPrivateKeyToAge(sshKey, []byte{})
if err != nil {
fmt.Fprintf(os.Stderr, "Cannot convert ssh key '%s': %s\n", p, err)
continue
}
// Append it to the file
_, err = ageFile.WriteString(*privKey + "\n")
if err != nil {
fmt.Fprintf(os.Stderr, "Cannot write key to age file: %s\n", err)
continue
}
if logcfg.KeyImport {
fmt.Fprintf(os.Stderr, "%s: Imported %s as age key with fingerprint %s\n", path.Base(os.Args[0]), p, *pubKey)
continue
}
}
return nil
}
// Like filepath.Walk but symlink-aware.
// Inspired by https://github.com/facebookarchive/symwalk
func symlinkWalk(filename string, linkDirname string, walkFn filepath.WalkFunc) error {
symWalkFunc := func(path string, info os.FileInfo, err error) error {
if fname, err := filepath.Rel(filename, path); err == nil {
path = filepath.Join(linkDirname, fname)
} else {
return err
}
if err == nil && info.Mode()&os.ModeSymlink == os.ModeSymlink {
finalPath, err := filepath.EvalSymlinks(path)
if err != nil {
return err
}
info, err := os.Lstat(finalPath)
if err != nil {
return walkFn(path, info, err)
}
if info.IsDir() {
return symlinkWalk(finalPath, path, walkFn)
}
}
return walkFn(path, info, err)
}
return filepath.Walk(filename, symWalkFunc)
}
func handleModifications(isDry bool, logcfg loggingConfig, symlinkPath string, secretDir string, secrets []secret, templates []template) error {
var restart []string
var reload []string
newSecrets := make(map[string]bool)
modifiedSecrets := make(map[string]bool)
removedSecrets := make(map[string]bool)
newTemplates := make(map[string]bool)
modifiedTemplates := make(map[string]bool)
removedTemplates := make(map[string]bool)
// When the symlink path does not exist yet, we are being run in stage-2-init.sh
// where switch-to-configuration is not run so the services would only be restarted
// the next time switch-to-configuration is run.
if _, err := os.Stat(symlinkPath); os.IsNotExist(err) {
return nil
}
// Find modified/new secrets
for _, secret := range secrets {
oldPath := filepath.Join(symlinkPath, secret.Name)
newPath := filepath.Join(secretDir, secret.Name)
// Read the old file
oldData, err := os.ReadFile(oldPath)
if err != nil {
if os.IsNotExist(err) {
// File did not exist before
restart = append(restart, secret.RestartUnits...)
reload = append(reload, secret.ReloadUnits...)
newSecrets[secret.Name] = true
continue
}
return err
}
// Read the new file
newData, err := os.ReadFile(newPath)
if err != nil {
return err
}
if !bytes.Equal(oldData, newData) {
restart = append(restart, secret.RestartUnits...)
reload = append(reload, secret.ReloadUnits...)
modifiedSecrets[secret.Name] = true
}
}
// Find modified/new templates
for _, template := range templates {
oldPath := filepath.Join(symlinkPath, RenderedSubdir, template.Name)
newPath := filepath.Join(secretDir, RenderedSubdir, template.Name)
// Read the old file
oldData, err := os.ReadFile(oldPath)
if err != nil {
if os.IsNotExist(err) {
// File did not exist before
restart = append(restart, template.RestartUnits...)
reload = append(reload, template.ReloadUnits...)