forked from theupdateframework/go-tuf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
local_store.go
741 lines (650 loc) · 18.1 KB
/
local_store.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
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
package tuf
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"log"
"os"
"path/filepath"
"strings"
"github.com/secure-systems-lab/go-securesystemslib/encrypted"
"github.com/theupdateframework/go-tuf/data"
"github.com/theupdateframework/go-tuf/internal/fsutil"
"github.com/theupdateframework/go-tuf/internal/sets"
"github.com/theupdateframework/go-tuf/pkg/keys"
"github.com/theupdateframework/go-tuf/util"
)
type LocalStore interface {
// GetMeta returns a map from metadata file names (e.g. root.json) to their raw JSON payload or an error.
GetMeta() (map[string]json.RawMessage, error)
// SetMeta is used to update a metadata file name with a JSON payload.
SetMeta(name string, meta json.RawMessage) error
// WalkStagedTargets calls targetsFn for each staged target file in paths.
// If paths is empty, all staged target files will be walked.
WalkStagedTargets(paths []string, targetsFn TargetsWalkFunc) error
// FileIsStaged determines if a metadata file is currently staged, to avoid incrementing
// version numbers repeatedly while staged.
FileIsStaged(filename string) bool
// Commit is used to publish staged files to the repository
//
// This will also reset the staged meta to signal incrementing version numbers.
// TUF 1.0 requires that the root metadata version numbers in the repository does not
// gaps. To avoid this, we will only increment the number once until we commit.
Commit(bool, map[string]int64, map[string]data.Hashes) error
// GetSigners return a list of signers for a role.
// This may include revoked keys, so the signers should not
// be used without filtering.
GetSigners(role string) ([]keys.Signer, error)
// SaveSigner adds a signer to a role.
SaveSigner(role string, signer keys.Signer) error
// SignersForRole return a list of signing keys for a role.
SignersForKeyIDs(keyIDs []string) []keys.Signer
// Clean is used to remove all staged manifests.
Clean() error
}
type PassphraseChanger interface {
// ChangePassphrase changes the passphrase for a role keys file.
ChangePassphrase(string) error
}
func MemoryStore(meta map[string]json.RawMessage, files map[string][]byte) LocalStore {
if meta == nil {
meta = make(map[string]json.RawMessage)
}
return &memoryStore{
meta: meta,
stagedMeta: make(map[string]json.RawMessage),
files: files,
signerForKeyID: make(map[string]keys.Signer),
keyIDsForRole: make(map[string][]string),
}
}
type memoryStore struct {
meta map[string]json.RawMessage
stagedMeta map[string]json.RawMessage
files map[string][]byte
signerForKeyID map[string]keys.Signer
keyIDsForRole map[string][]string
}
func (m *memoryStore) GetMeta() (map[string]json.RawMessage, error) {
meta := make(map[string]json.RawMessage, len(m.meta)+len(m.stagedMeta))
for key, value := range m.meta {
meta[key] = value
}
for key, value := range m.stagedMeta {
meta[key] = value
}
return meta, nil
}
func (m *memoryStore) SetMeta(name string, meta json.RawMessage) error {
m.stagedMeta[name] = meta
return nil
}
func (m *memoryStore) FileIsStaged(name string) bool {
_, ok := m.stagedMeta[name]
return ok
}
func (m *memoryStore) WalkStagedTargets(paths []string, targetsFn TargetsWalkFunc) error {
if len(paths) == 0 {
for path, data := range m.files {
if err := targetsFn(path, bytes.NewReader(data)); err != nil {
return err
}
}
return nil
}
for _, path := range paths {
data, ok := m.files[path]
if !ok {
return ErrFileNotFound{path}
}
if err := targetsFn(path, bytes.NewReader(data)); err != nil {
return err
}
}
return nil
}
func (m *memoryStore) Commit(consistentSnapshot bool, versions map[string]int64, hashes map[string]data.Hashes) error {
for name, meta := range m.stagedMeta {
paths := computeMetadataPaths(consistentSnapshot, name, versions)
for _, path := range paths {
m.meta[path] = meta
}
// Remove from staged metadata.
// This will prompt incrementing version numbers again now that we've
// successfully committed the metadata to the local store.
delete(m.stagedMeta, name)
}
return nil
}
func (m *memoryStore) GetSigners(role string) ([]keys.Signer, error) {
keyIDs, ok := m.keyIDsForRole[role]
if ok {
return m.SignersForKeyIDs(keyIDs), nil
}
return nil, nil
}
func (m *memoryStore) SaveSigner(role string, signer keys.Signer) error {
keyIDs := signer.PublicData().IDs()
for _, keyID := range keyIDs {
m.signerForKeyID[keyID] = signer
}
mergedKeyIDs := sets.DeduplicateStrings(append(m.keyIDsForRole[role], keyIDs...))
m.keyIDsForRole[role] = mergedKeyIDs
return nil
}
func (m *memoryStore) SignersForKeyIDs(keyIDs []string) []keys.Signer {
signers := []keys.Signer{}
keyIDsSeen := map[string]struct{}{}
for _, keyID := range keyIDs {
signer, ok := m.signerForKeyID[keyID]
if !ok {
continue
}
addSigner := false
for _, skid := range signer.PublicData().IDs() {
if _, seen := keyIDsSeen[skid]; !seen {
addSigner = true
}
keyIDsSeen[skid] = struct{}{}
}
if addSigner {
signers = append(signers, signer)
}
}
return signers
}
func (m *memoryStore) Clean() error {
return nil
}
type persistedKeys struct {
Encrypted bool `json:"encrypted"`
Data json.RawMessage `json:"data"`
}
type StoreOpts struct {
Logger *log.Logger
PassFunc util.PassphraseFunc
}
func FileSystemStore(dir string, p util.PassphraseFunc) LocalStore {
return &fileSystemStore{
dir: dir,
passphraseFunc: p,
logger: log.New(io.Discard, "", 0),
signerForKeyID: make(map[string]keys.Signer),
keyIDsForRole: make(map[string][]string),
}
}
func FileSystemStoreWithOpts(dir string, opts ...StoreOpts) LocalStore {
store := &fileSystemStore{
dir: dir,
passphraseFunc: nil,
logger: log.New(io.Discard, "", 0),
signerForKeyID: make(map[string]keys.Signer),
keyIDsForRole: make(map[string][]string),
}
for _, opt := range opts {
if opt.Logger != nil {
store.logger = opt.Logger
}
if opt.PassFunc != nil {
store.passphraseFunc = opt.PassFunc
}
}
return store
}
type fileSystemStore struct {
dir string
passphraseFunc util.PassphraseFunc
logger *log.Logger
signerForKeyID map[string]keys.Signer
keyIDsForRole map[string][]string
}
func (f *fileSystemStore) repoDir() string {
return filepath.Join(f.dir, "repository")
}
func (f *fileSystemStore) stagedDir() string {
return filepath.Join(f.dir, "staged")
}
func (f *fileSystemStore) GetMeta() (map[string]json.RawMessage, error) {
// Build a map of metadata names (e.g. root.json) to their full paths
// (whether in the committed repo dir, or in the staged repo dir).
metaPaths := map[string]string{}
rd := f.repoDir()
committed, err := os.ReadDir(f.repoDir())
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return nil, fmt.Errorf("could not list repo dir: %w", err)
}
for _, e := range committed {
imf, err := fsutil.IsMetaFile(e)
if err != nil {
return nil, err
}
if imf {
name := e.Name()
metaPaths[name] = filepath.Join(rd, name)
}
}
sd := f.stagedDir()
staged, err := os.ReadDir(sd)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return nil, fmt.Errorf("could not list staged dir: %w", err)
}
for _, e := range staged {
imf, err := fsutil.IsMetaFile(e)
if err != nil {
return nil, err
}
if imf {
name := e.Name()
metaPaths[name] = filepath.Join(sd, name)
}
}
meta := make(map[string]json.RawMessage)
for name, path := range metaPaths {
f, err := os.ReadFile(path)
if err != nil {
return nil, err
}
meta[name] = f
}
return meta, nil
}
func (f *fileSystemStore) SetMeta(name string, meta json.RawMessage) error {
if err := f.createDirs(); err != nil {
return err
}
if err := util.AtomicallyWriteFile(filepath.Join(f.stagedDir(), name), meta, 0644); err != nil {
return err
}
return nil
}
func (f *fileSystemStore) FileIsStaged(name string) bool {
_, err := os.Stat(filepath.Join(f.stagedDir(), name))
return err == nil
}
func (f *fileSystemStore) createDirs() error {
for _, dir := range []string{"keys", "repository", "staged/targets"} {
if err := os.MkdirAll(filepath.Join(f.dir, dir), 0755); err != nil {
return err
}
}
return nil
}
func (f *fileSystemStore) WalkStagedTargets(paths []string, targetsFn TargetsWalkFunc) error {
if len(paths) == 0 {
walkFunc := func(fpath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() || !info.Mode().IsRegular() {
return nil
}
rel, err := filepath.Rel(filepath.Join(f.stagedDir(), "targets"), fpath)
if err != nil {
return err
}
file, err := os.Open(fpath)
if err != nil {
return err
}
defer file.Close()
return targetsFn(filepath.ToSlash(rel), file)
}
return filepath.Walk(filepath.Join(f.stagedDir(), "targets"), walkFunc)
}
// check all the files exist before processing any files
for _, path := range paths {
realFilepath := filepath.Join(f.stagedDir(), "targets", path)
if _, err := os.Stat(realFilepath); err != nil {
if os.IsNotExist(err) {
return ErrFileNotFound{realFilepath}
}
return err
}
}
for _, path := range paths {
realFilepath := filepath.Join(f.stagedDir(), "targets", path)
file, err := os.Open(realFilepath)
if err != nil {
if os.IsNotExist(err) {
return ErrFileNotFound{realFilepath}
}
return err
}
err = targetsFn(path, file)
file.Close()
if err != nil {
return err
}
}
return nil
}
func (f *fileSystemStore) createRepoFile(path string) (*os.File, error) {
dst := filepath.Join(f.repoDir(), path)
if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil {
return nil, err
}
return os.Create(dst)
}
func (f *fileSystemStore) Commit(consistentSnapshot bool, versions map[string]int64, hashes map[string]data.Hashes) error {
isTarget := func(path string) bool {
return strings.HasPrefix(path, "targets/")
}
copyToRepo := func(fpath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() || !info.Mode().IsRegular() {
return nil
}
rel, err := filepath.Rel(f.stagedDir(), fpath)
if err != nil {
return err
}
relpath := filepath.ToSlash(rel)
var paths []string
if isTarget(relpath) {
paths = computeTargetPaths(consistentSnapshot, relpath, hashes)
} else {
paths = computeMetadataPaths(consistentSnapshot, relpath, versions)
}
var files []io.Writer
for _, path := range paths {
file, err := f.createRepoFile(path)
if err != nil {
return err
}
defer file.Close()
files = append(files, file)
}
staged, err := os.Open(fpath)
if err != nil {
return err
}
defer staged.Close()
if _, err = io.Copy(io.MultiWriter(files...), staged); err != nil {
return err
}
return nil
}
// Checks if target file should be deleted
needsRemoval := func(fpath string) bool {
if consistentSnapshot {
// strip out the hash
name := strings.SplitN(filepath.Base(fpath), ".", 2)
if len(name) != 2 || name[1] == "" {
return false
}
fpath = filepath.Join(filepath.Dir(fpath), name[1])
}
_, ok := hashes[filepath.ToSlash(fpath)]
return !ok
}
// Checks if folder is empty
folderNeedsRemoval := func(fpath string) bool {
f, err := os.Open(fpath)
if err != nil {
return false
}
defer f.Close()
_, err = f.Readdirnames(1)
return err == io.EOF
}
removeFile := func(fpath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
rel, err := filepath.Rel(f.repoDir(), fpath)
if err != nil {
return err
}
relpath := filepath.ToSlash(rel)
if !info.IsDir() && isTarget(relpath) && needsRemoval(rel) {
// Delete the target file
if err := os.Remove(fpath); err != nil {
return err
}
// Delete the target folder too if it's empty
targetFolder := filepath.Dir(fpath)
if folderNeedsRemoval(targetFolder) {
if err := os.Remove(targetFolder); err != nil {
return err
}
}
}
return nil
}
if err := filepath.Walk(f.stagedDir(), copyToRepo); err != nil {
return err
}
if err := filepath.Walk(f.repoDir(), removeFile); err != nil {
return err
}
return f.Clean()
}
func (f *fileSystemStore) GetSigners(role string) ([]keys.Signer, error) {
keyIDs, ok := f.keyIDsForRole[role]
if ok {
return f.SignersForKeyIDs(keyIDs), nil
}
privKeys, _, err := f.loadPrivateKeys(role)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
signers := []keys.Signer{}
for _, key := range privKeys {
signer, err := keys.GetSigner(key)
if err != nil {
return nil, err
}
// Cache the signers.
for _, keyID := range signer.PublicData().IDs() {
f.keyIDsForRole[role] = append(f.keyIDsForRole[role], keyID)
f.signerForKeyID[keyID] = signer
}
signers = append(signers, signer)
}
return signers, nil
}
func (f *fileSystemStore) SignersForKeyIDs(keyIDs []string) []keys.Signer {
signers := []keys.Signer{}
keyIDsSeen := map[string]struct{}{}
for _, keyID := range keyIDs {
signer, ok := f.signerForKeyID[keyID]
if !ok {
continue
}
addSigner := false
for _, skid := range signer.PublicData().IDs() {
if _, seen := keyIDsSeen[skid]; !seen {
addSigner = true
}
keyIDsSeen[skid] = struct{}{}
}
if addSigner {
signers = append(signers, signer)
}
}
return signers
}
// ChangePassphrase changes the passphrase for a role keys file. Implements
// PassphraseChanger interface.
func (f *fileSystemStore) ChangePassphrase(role string) error {
// No need to proceed if passphrase func is not set
if f.passphraseFunc == nil {
return ErrPassphraseRequired{role}
}
// Read the existing keys (if any)
// If encrypted, will prompt for existing passphrase
keys, _, err := f.loadPrivateKeys(role)
if err != nil {
if os.IsNotExist(err) {
f.logger.Printf("Failed to change passphrase. Missing keys file for %s role. \n", role)
}
return err
}
// Prompt for new passphrase
pass, err := f.passphraseFunc(role, true, true)
if err != nil {
return err
}
// Proceed saving the keys
pk := &persistedKeys{Encrypted: true}
pk.Data, err = encrypted.Marshal(keys, pass)
if err != nil {
return err
}
data, err := json.MarshalIndent(pk, "", "\t")
if err != nil {
return err
}
if err := util.AtomicallyWriteFile(f.keysPath(role), append(data, '\n'), 0600); err != nil {
return err
}
f.logger.Printf("Successfully changed passphrase for %s keys file\n", role)
return nil
}
func (f *fileSystemStore) SaveSigner(role string, signer keys.Signer) error {
if err := f.createDirs(); err != nil {
return err
}
// add the key to the existing keys (if any)
privKeys, pass, err := f.loadPrivateKeys(role)
if err != nil && !os.IsNotExist(err) {
return err
}
key, err := signer.MarshalPrivateKey()
if err != nil {
return err
}
privKeys = append(privKeys, key)
// if loadPrivateKeys didn't return a passphrase (because no keys yet exist)
// and passphraseFunc is set, get the passphrase so the keys file can
// be encrypted later (passphraseFunc being nil indicates the keys file
// should not be encrypted)
if pass == nil && f.passphraseFunc != nil {
pass, err = f.passphraseFunc(role, true, false)
if err != nil {
return err
}
}
pk := &persistedKeys{}
if pass != nil {
pk.Data, err = encrypted.Marshal(privKeys, pass)
if err != nil {
return err
}
pk.Encrypted = true
} else {
pk.Data, err = json.MarshalIndent(privKeys, "", "\t")
if err != nil {
return err
}
}
data, err := json.MarshalIndent(pk, "", "\t")
if err != nil {
return err
}
if err := util.AtomicallyWriteFile(f.keysPath(role), append(data, '\n'), 0600); err != nil {
return err
}
// Merge privKeys into f.keyIDsForRole and register signers with
// f.signerForKeyID.
keyIDsForRole := f.keyIDsForRole[role]
for _, key := range privKeys {
signer, err := keys.GetSigner(key)
if err != nil {
return err
}
keyIDs := signer.PublicData().IDs()
for _, keyID := range keyIDs {
f.signerForKeyID[keyID] = signer
}
keyIDsForRole = append(keyIDsForRole, keyIDs...)
}
f.keyIDsForRole[role] = sets.DeduplicateStrings(keyIDsForRole)
return nil
}
// loadPrivateKeys loads keys for the given role and returns them along with the
// passphrase (if read) so that callers don't need to re-read it.
func (f *fileSystemStore) loadPrivateKeys(role string) ([]*data.PrivateKey, []byte, error) {
file, err := os.Open(f.keysPath(role))
if err != nil {
return nil, nil, err
}
defer file.Close()
pk := &persistedKeys{}
if err := json.NewDecoder(file).Decode(pk); err != nil {
return nil, nil, err
}
var keys []*data.PrivateKey
if !pk.Encrypted {
if err := json.Unmarshal(pk.Data, &keys); err != nil {
return nil, nil, err
}
return keys, nil, nil
}
// the keys are encrypted so cannot be loaded if passphraseFunc is not set
if f.passphraseFunc == nil {
return nil, nil, ErrPassphraseRequired{role}
}
// try the empty string as the password first
pass := []byte("")
if err := encrypted.Unmarshal(pk.Data, &keys, pass); err != nil {
pass, err = f.passphraseFunc(role, false, false)
if err != nil {
return nil, nil, err
}
if err = encrypted.Unmarshal(pk.Data, &keys, pass); err != nil {
return nil, nil, err
}
}
return keys, pass, nil
}
func (f *fileSystemStore) keysPath(role string) string {
return filepath.Join(f.dir, "keys", role+".json")
}
func (f *fileSystemStore) Clean() error {
_, err := os.Stat(filepath.Join(f.repoDir(), "root.json"))
if os.IsNotExist(err) {
return ErrNewRepository
} else if err != nil {
return err
}
if err := os.RemoveAll(f.stagedDir()); err != nil {
return err
}
return os.MkdirAll(filepath.Join(f.stagedDir(), "targets"), 0755)
}
func computeTargetPaths(consistentSnapshot bool, name string, hashes map[string]data.Hashes) []string {
if consistentSnapshot {
return util.HashedPaths(name, hashes[name])
} else {
return []string{name}
}
}
func computeMetadataPaths(consistentSnapshot bool, name string, versions map[string]int64) []string {
copyVersion := false
switch name {
case "root.json":
copyVersion = true
case "timestamp.json":
copyVersion = false
default:
if consistentSnapshot {
copyVersion = true
} else {
copyVersion = false
}
}
paths := []string{name}
if copyVersion {
paths = append(paths, util.VersionedPath(name, versions[name]))
}
return paths
}