forked from privacybydesign/irmago
-
Notifications
You must be signed in to change notification settings - Fork 0
/
schemes.go
1543 lines (1364 loc) · 45.5 KB
/
schemes.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
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 irma
import (
"bytes"
"crypto/ecdsa"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/privacybydesign/gabi/signed"
"github.com/privacybydesign/irmago/internal/common"
"github.com/sirupsen/logrus"
"github.com/go-errors/errors"
)
var DefaultSchemes = [2]SchemePointer{
{
URL: "https://privacybydesign.foundation/schememanager/irma-demo",
Publickey: []byte(`-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEHVnmAY+kGkFZn7XXozdI4HY8GOjm
54ngh4chTfn6WsTCf2w5rprfIqML61z2VTE4k8yJ0Z1QbyW6cdaao8obTQ==
-----END PUBLIC KEY-----`),
},
{
URL: "https://privacybydesign.foundation/schememanager/pbdf",
Publickey: []byte(`-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAELzHV5ipBimWpuZIDaQQd+KmNpNop
dpBeCqpDwf+Grrw9ReODb6nwlsPJ/c/gqLnc+Y3sKOAJ2bFGI+jHBSsglg==
-----END PUBLIC KEY-----`),
},
}
type (
// SchemePointer points to a remote IRMA scheme, containing information to download the scheme,
// including its (pinned) public key.
SchemePointer struct {
URL string // URL to download scheme from
Type SchemeType
Publickey []byte // Public key of scheme against which to verify files after they have been downloaded
}
Scheme interface {
id() string
idx() SchemeManagerIndex
setIdx(idx SchemeManagerIndex)
url() string
timestamp() Timestamp
setTimestamp(t Timestamp)
setStatus(status SchemeManagerStatus)
path() string
setPath(path string)
parseContents(conf *Configuration) error
validate(conf *Configuration) (error, SchemeManagerStatus)
update() error
handleUpdateFile(conf *Configuration, path, filename string, bts []byte, transport *HTTPTransport, _ *IrmaIdentifierSet) error
delete(conf *Configuration) error
add(conf *Configuration)
addError(conf *Configuration, err error)
deleteError(conf *Configuration, err error)
present(id string, conf *Configuration) bool
typ() SchemeType
purge(conf *Configuration)
}
// SchemeFileHash encodes the SHA256 hash of an authenticated
// file under a scheme within the configuration folder.
SchemeFileHash []byte
// SchemeManagerIndex is a (signed) list of files under a scheme
// along with their SHA266 hash
SchemeManagerIndex map[string]SchemeFileHash
SchemeManagerStatus string
SchemeManagerError struct {
Scheme string
Status SchemeManagerStatus
Err error
}
SchemeType string
)
type DependencyChain []CredentialTypeIdentifier
const (
SchemeManagerStatusValid = SchemeManagerStatus("Valid")
SchemeManagerStatusUnprocessed = SchemeManagerStatus("Unprocessed")
SchemeManagerStatusInvalidIndex = SchemeManagerStatus("InvalidIndex")
SchemeManagerStatusInvalidSignature = SchemeManagerStatus("InvalidSignature")
SchemeManagerStatusParsingError = SchemeManagerStatus("ParsingError")
SchemeManagerStatusContentParsingError = SchemeManagerStatus("ContentParsingError")
SchemeTypeIssuer = SchemeType("issuer")
SchemeTypeRequestor = SchemeType("requestor")
maxDepComplexity = 25
)
func (conf *Configuration) DownloadDefaultSchemes() error {
Logger.Info("downloading default schemes (may take a while)")
for _, s := range DefaultSchemes {
Logger.WithFields(logrus.Fields{"url": s.URL}).Debugf("Downloading scheme")
if err := conf.installScheme(s.URL, s.Publickey, ""); err != nil {
return err
}
}
Logger.Info("Finished downloading schemes")
return nil
}
// InstallSchemeManager downloads and adds the specified scheme to this Configuration,
// provided its signature is valid against the specified key.
func (conf *Configuration) InstallScheme(url string, publickey []byte) error {
if len(publickey) == 0 {
return errors.New("no public key specified")
}
return conf.installScheme(url, publickey, "")
}
// DangerousTOFUInstallScheme downloads and adds the specified scheme to this Configuration,
// downloading and trusting its public key from the scheme's remote URL.
func (conf *Configuration) DangerousTOFUInstallScheme(url string) error {
return conf.installScheme(url, nil, "")
}
func (conf *Configuration) AutoUpdateSchemes(interval uint) {
Logger.Infof("Updating schemes every %d minutes", interval)
update := func() {
if err := conf.UpdateSchemes(); err != nil {
Logger.Error("Scheme autoupdater failed: ")
if e, ok := err.(*errors.Error); ok {
Logger.Error(e.ErrorStack())
} else {
Logger.Errorf("%s %s", reflect.TypeOf(err).String(), err.Error())
}
}
}
conf.Scheduler.Every(uint64(interval)).Minutes().Do(update)
// Run first update after a small delay
go func() {
<-time.NewTimer(200 * time.Millisecond).C
update()
}()
}
func (conf *Configuration) UpdateSchemes() error {
for _, scheme := range conf.SchemeManagers {
if err := conf.UpdateScheme(scheme, nil); err != nil {
return err
}
}
for _, scheme := range conf.RequestorSchemes {
if err := conf.UpdateScheme(scheme, nil); err != nil {
return err
}
}
return nil
}
// UpdateScheme syncs the stored version within the irma_configuration directory
// with the remote version at the scheme's URL, downloading and storing
// new and modified files, according to the index files of both versions.
// It stores the identifiers of new or updated entities in the second parameter.
func (conf *Configuration) UpdateScheme(scheme Scheme, downloaded *IrmaIdentifierSet) error {
if conf.readOnly {
return errors.New("cannot update a read-only configuration")
}
if scheme == nil {
return errors.Errorf("Cannot update unknown scheme")
}
var (
typ = string(scheme.typ())
id = scheme.id()
schemepath = scheme.path()
)
Logger.WithFields(logrus.Fields{"scheme": id, "type": typ}).Info("checking for updates")
shouldUpdate, _, index, err := conf.checkRemoteScheme(scheme)
if err != nil {
return err
}
if !shouldUpdate {
return nil
}
// As long as we can write to the scheme directory, we guarantee that either
// - updating succeeded, and the updated scheme on disk has been verified and parsed
// without error into the corrent conf instance.
// - if any error occurs, then neither the scheme on disk nor its data in the current
// conf instance is touched.
// We do this by creating a temporary copy on disk of the scheme, which we then update,
// verify, and parse into another *Configuration instance. Only after all possible errors have
// occurred do we modify the scheme on disk and in memory.
// copy the scheme on disk to a new temporary directory
dir, newschemepath, err := conf.tempSchemeCopy(scheme)
if err != nil {
return err
}
defer func() {
_ = os.RemoveAll(dir)
}()
// iterate over the index and download new and changed files into the temp dir
if err = conf.updateSchemeFiles(scheme, index, newschemepath, downloaded); err != nil {
return err
}
// verify the updated scheme in the temp dir
var newconf *Configuration
if newconf, err = NewConfiguration(dir, ConfigurationOptions{}); err != nil {
return err
}
if scheme, err = newconf.ParseSchemeFolder(newschemepath); err != nil {
return err
}
if err = scheme.update(); err != nil {
return err
}
// replace old scheme on disk with the new one from the temp dir
if err = conf.updateSchemeDir(scheme, schemepath, newschemepath); err != nil {
return err
}
scheme.purge(conf)
conf.join(newconf)
return nil
}
func (conf *Configuration) ParseSchemeFolder(dir string) (scheme Scheme, serr error) {
var (
status SchemeManagerStatus
err error
id string
)
scheme, status, err = conf.parseSchemeDescription(dir)
if scheme != nil {
id = scheme.id()
}
if err != nil {
serr = &SchemeManagerError{Scheme: id, Status: status, Err: err}
return
}
// From this point, we keep the scheme in our map even if it has an error. The user must check that
// scheme.Status == SchemeManagerStatusValid, aka "Valid" before using any scheme for
// anything, and handle accordingly.
scheme.add(conf)
defer func() {
if serr != nil {
scheme.setStatus(serr.(*SchemeManagerError).Status)
}
scheme.addError(conf, serr)
}()
// validate scheme contents
if err, status := scheme.validate(conf); err != nil {
serr = &SchemeManagerError{Scheme: id, Status: status, Err: err}
return
}
err = scheme.parseContents(conf)
if err != nil {
serr = &SchemeManagerError{Scheme: id, Err: err, Status: SchemeManagerStatusContentParsingError}
return
}
scheme.setStatus(SchemeManagerStatusValid)
return
}
// Unexported scheme helpers that work for all scheme types (issuer or requestor) follow.
// These deal with what schemes have in common: verifying the signature; authenticating
// contained files against the (signed) index; and downloading, (re)installing
// and updating them against the remote.
// The code that deals with the scheme contents, of which the structure differs per scheme type,
// is found further below as helpers on the scheme structs. This includes modifying the
// various maps on Configuration instances.
func (conf *Configuration) updateSchemeFiles(
scheme Scheme, index SchemeManagerIndex, newschemepath string, downloaded *IrmaIdentifierSet,
) error {
var (
transport = NewHTTPTransport(scheme.url(), true)
oldIndex = scheme.idx()
id = scheme.id()
)
for path, newHash := range index {
pathStripped := path[len(id)+1:] // strip scheme name
fullpath := filepath.Join(newschemepath, pathStripped)
oldHash, known := oldIndex[path]
var have bool
have, err := common.PathExists(fullpath)
if err != nil {
return err
}
if known && have && oldHash.Equal(newHash) {
continue // nothing to do, we already have this file
}
// Ensure that the folder in which to write the file exists
if err = os.MkdirAll(filepath.Dir(fullpath), 0700); err != nil {
return err
}
// Download the new file, store it in our scheme
var bts []byte
if bts, err = downloadSignedFile(transport, newschemepath, pathStripped, newHash); err != nil {
return err
}
// handle file contents per scheme type
if err = scheme.handleUpdateFile(conf, newschemepath, pathStripped, bts, transport, downloaded); err != nil {
return err
}
}
return nil
}
func (conf *Configuration) parseSchemeDescription(dir string) (Scheme, SchemeManagerStatus, error) {
filename, err := common.SchemeFilename(dir)
if err != nil {
return nil, SchemeManagerStatusParsingError, err
}
index, err, _ := conf.parseIndex(dir)
if err != nil {
return nil, SchemeManagerStatusParsingError, err
}
bts, found, err := conf.readSignedFile(index, dir, filename)
if !found {
return nil, SchemeManagerStatusParsingError, errors.New("scheme file not found in index")
}
if err != nil {
return nil, SchemeManagerStatusParsingError, err
}
_, typ, err := common.SchemeInfo(filename, bts)
if err != nil {
return nil, SchemeManagerStatusParsingError, err
}
scheme := newScheme(SchemeType(typ))
scheme.setIdx(index)
scheme.setPath(dir)
// read scheme description
var exists bool
exists, err = conf.parseSchemeFile(scheme, filename, scheme)
if err != nil || !exists {
return scheme, SchemeManagerStatusParsingError, err
}
if index.Scheme() != scheme.id() {
return scheme, SchemeManagerStatusParsingError, errors.Errorf("cannot use index of scheme %s for scheme %s", index.Scheme(), scheme.id())
}
var ts *Timestamp
ts, exists, err = readTimestamp(filepath.Join(dir, "timestamp"))
if err != nil || !exists {
return scheme, SchemeManagerStatusParsingError, errors.WrapPrefix(err, "Could not read scheme manager timestamp", 0)
}
scheme.setTimestamp(*ts)
return scheme, SchemeManagerStatusValid, nil
}
func (conf *Configuration) parseSchemeFile(
scheme Scheme, path string, description interface{},
) (bool, error) {
abs := filepath.Join(scheme.path(), path)
if _, err := os.Stat(abs); err != nil {
return false, nil
}
bts, found, err := conf.readSignedFile(scheme.idx(), scheme.path(), path)
if !found {
return false, errors.Errorf("File %s (%s) not present in scheme index", path, abs)
}
if err != nil {
return true, err
}
return true, common.Unmarshal(filepath.Base(path), bts, description)
}
func (conf *Configuration) reinstallScheme(scheme Scheme) (err error) {
if conf.readOnly {
return errors.New("cannot install scheme into a read-only configuration")
}
defer func() {
scheme.deleteError(conf, err)
}()
// first try remote
if err = conf.reinstallSchemeFromRemote(scheme); err == nil {
return nil
}
// didn't work, try from assets
err = conf.reinstallSchemeFromAssets(scheme)
return
}
func (conf *Configuration) reinstallSchemeFromAssets(scheme Scheme) error {
if err := scheme.delete(conf); err != nil {
return err
}
if _, err := conf.copyFromAssets(filepath.Base(scheme.path())); err != nil {
return err
}
_, err := conf.ParseSchemeFolder(scheme.path())
return err
}
func (conf *Configuration) reinstallSchemeFromRemote(scheme Scheme) error {
if conf.readOnly {
return errors.New("cannot install scheme into a read-only configuration")
}
pkbts, err := ioutil.ReadFile(filepath.Join(scheme.path(), "pk.pem"))
if err != nil {
return err
}
if err = scheme.delete(conf); err != nil {
return err
}
return conf.installScheme(scheme.url(), pkbts, filepath.Base(scheme.path()))
}
// newSchemeDir returns the name of a newly created directory into which a scheme can be installed:
// the parameter dir if specified, otherwise the first of the following that does not already exist:
// $scheme, $scheme-0, $scheme-1, ...
func (conf *Configuration) newSchemeDir(id, dir string) (string, error) {
dirGiven := dir != ""
if !dirGiven {
dir = id
}
path := filepath.Join(conf.Path, dir)
exists, err := common.PathExists(path)
if err != nil {
return "", err
}
if !exists {
return path, common.EnsureDirectoryExists(path)
}
if dirGiven {
return "", errors.New("cannot install scheme: specified directory not empty")
}
for i := 0; ; i++ {
path = filepath.Join(conf.Path, dir+"-"+strconv.Itoa(i))
exists, err := common.PathExists(dir)
if err != nil {
return "", err
}
if !exists {
return path, common.EnsureDirectoryExists(path)
}
}
}
func (conf *Configuration) installScheme(url string, publickey []byte, dir string) error {
if conf.readOnly {
return errors.New("cannot install scheme into a read-only configuration")
}
scheme, err := downloadScheme(url)
if err != nil {
return err
}
id := scheme.id()
if scheme.present(id, conf) {
return errors.New("cannot install an already existing scheme")
}
path, err := conf.newSchemeDir(id, dir)
if err != nil {
return err
}
scheme.setPath(path)
if publickey != nil {
if err := common.SaveFile(filepath.Join(path, "pk.pem"), publickey); err != nil {
return err
}
} else {
if _, err := downloadFile(NewHTTPTransport(url, true), path, "pk.pem"); err != nil {
return err
}
}
if scheme.id() != id {
return errors.Errorf("scheme has id %s but expected %s", scheme.id(), id)
}
scheme.add(conf)
return conf.UpdateScheme(scheme, nil)
}
func (conf *Configuration) checkRemoteScheme(scheme Scheme) (bool, *Timestamp, SchemeManagerIndex, error) {
timestamp, indexbts, sigbts, index, err := conf.checkRemoteTimestamp(scheme)
if err != nil {
return false, nil, nil, err
}
id := scheme.id()
typ := string(scheme.typ())
timestampdiff := int64(timestamp.Sub(scheme.timestamp()))
if timestampdiff == 0 {
Logger.WithFields(logrus.Fields{"scheme": id, "type": typ}).Info("scheme is up-to-date, not updating")
return false, nil, index, nil
} else if timestampdiff < 0 {
Logger.WithFields(logrus.Fields{"scheme": id, "type": typ}).Info("local scheme is newer than remote, not updating")
return false, nil, index, nil
}
// timestampdiff > 0
Logger.WithFields(logrus.Fields{"scheme": id, "type": typ}).Info("scheme is outdated, updating")
// save the index and its signature against which we authenticated the timestamp
// for future use: as they are themselves not in the index, the loop below doesn't touch them
if err = conf.writeIndex(scheme.path(), indexbts, sigbts); err != nil {
return false, nil, nil, err
}
return true, timestamp, index, nil
}
func (conf *Configuration) checkRemoteTimestamp(scheme Scheme) (
*Timestamp, []byte, []byte, SchemeManagerIndex, error,
) {
t := NewHTTPTransport(scheme.url(), true)
indexbts, err := t.GetBytes("index")
if err != nil {
return nil, nil, nil, nil, err
}
sig, err := t.GetBytes("index.sig")
if err != nil {
return nil, nil, nil, nil, err
}
timestampbts, err := t.GetBytes("timestamp")
if err != nil {
return nil, nil, nil, nil, err
}
pk, err := conf.schemePublicKey(scheme.path())
if err != nil {
return nil, nil, nil, nil, err
}
// Verify signature and the timestamp hash in the index
if err = signed.Verify(pk, indexbts, sig); err != nil {
return nil, nil, nil, nil, err
}
index := SchemeManagerIndex(make(map[string]SchemeFileHash))
if err = index.FromString(string(indexbts)); err != nil {
return nil, nil, nil, nil, err
}
sha := sha256.Sum256(timestampbts)
if !bytes.Equal(index[scheme.id()+"/timestamp"], sha[:]) {
return nil, nil, nil, nil, errors.Errorf("signature over timestamp is not valid")
}
timestamp, err := parseTimestamp(timestampbts)
if err != nil {
return nil, nil, nil, nil, err
}
return timestamp, indexbts, sig, index, nil
}
func (conf *Configuration) writeIndex(dest string, indexbts, sigbts []byte) error {
if err := common.EnsureDirectoryExists(dest); err != nil {
return err
}
if err := common.SaveFile(filepath.Join(dest, "index"), indexbts); err != nil {
return err
}
return common.SaveFile(filepath.Join(dest, "index.sig"), sigbts)
}
func (conf *Configuration) isUpToDate(subdir string) (bool, error) {
if conf.assets == "" || conf.readOnly {
return true, nil
}
newTime, exists, err := readTimestamp(filepath.Join(conf.assets, subdir, "timestamp"))
if err != nil || !exists {
return true, errors.WrapPrefix(err, "Could not read asset timestamp of scheme "+subdir, 0)
}
// The storage version of the manager does not need to have a timestamp. If it does not, it is outdated.
oldTime, exists, err := readTimestamp(filepath.Join(conf.Path, subdir, "timestamp"))
if err != nil {
return true, err
}
return exists && !newTime.After(*oldTime), nil
}
func (conf *Configuration) copyFromAssets(subdir string) (bool, error) {
if conf.assets == "" || conf.readOnly {
return false, nil
}
// Remove old version; we want an exact copy of the assets version
// not a merge of the assets version and the storage version
if err := os.RemoveAll(filepath.Join(conf.Path, subdir)); err != nil {
return false, err
}
return true, common.CopyDirectory(
filepath.Join(conf.assets, subdir),
filepath.Join(conf.Path, subdir),
)
}
// verifySignature verifies the signature on the scheme index file
// (which contains the SHA256 hashes of all files under this scheme,
// which are used for verifying file authenticity).
func (conf *Configuration) verifySignature(dir string) (err error) {
defer func() {
if r := recover(); r != nil {
if e, ok := r.(error); ok {
err = errors.Errorf("Scheme manager index signature failed to verify: %s", e.Error())
} else {
err = errors.New("Scheme manager index signature failed to verify")
}
}
}()
if err := common.AssertPathExists(filepath.Join(dir, "index"), filepath.Join(dir, "index.sig"), filepath.Join(dir, "pk.pem")); err != nil {
return errors.New("Missing scheme manager index file, signature, or public key")
}
// Read and hash index file
indexbts, err := ioutil.ReadFile(filepath.Join(dir, "index"))
if err != nil {
return err
}
// Read and parse scheme public key
pk, err := conf.schemePublicKey(dir)
if err != nil {
return err
}
// Read and parse signature
sig, err := ioutil.ReadFile(filepath.Join(dir, "index.sig"))
if err != nil {
return err
}
return signed.Verify(pk, indexbts, sig)
}
func (conf *Configuration) schemePublicKey(dir string) (*ecdsa.PublicKey, error) {
pkbts, err := ioutil.ReadFile(filepath.Join(dir, "pk.pem"))
if err != nil {
return nil, err
}
return signed.UnmarshalPemPublicKey(pkbts)
}
// readSignedFile reads the file at the specified path
// and verifies its authenticity by checking that the file hash
// is present in the (signed) scheme index file.
func (conf *Configuration) readSignedFile(index SchemeManagerIndex, base string, path string) ([]byte, bool, error) {
signedHash, ok := index[index.Scheme()+"/"+filepath.ToSlash(path)]
if !ok {
return nil, false, nil
}
bts, err := conf.readHashedFile(filepath.Join(base, path), signedHash)
return bts, true, err
}
func (conf *Configuration) readHashedFile(path string, hash SchemeFileHash) ([]byte, error) {
bts, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
computedHash := sha256.Sum256(bts)
if !bytes.Equal(computedHash[:], hash) {
return nil, errors.Errorf("Hash of %s does not match scheme manager index", path)
}
return bts, nil
}
// parseIndex parses the index file of the specified manager.
func (conf *Configuration) parseIndex(dir string) (SchemeManagerIndex, error, SchemeManagerStatus) {
if err := conf.verifySignature(dir); err != nil {
return nil, err, SchemeManagerStatusInvalidSignature
}
path := filepath.Join(dir, "index")
if err := common.AssertPathExists(path); err != nil {
return nil, fmt.Errorf("missing scheme manager index file; tried %s", path), SchemeManagerStatusInvalidIndex
}
indexbts, err := ioutil.ReadFile(path)
if err != nil {
return nil, err, SchemeManagerStatusInvalidIndex
}
index := SchemeManagerIndex(make(map[string]SchemeFileHash))
if err = index.FromString(string(indexbts)); err != nil {
return nil, err, SchemeManagerStatusInvalidIndex
}
if err = conf.checkUnsignedFiles(dir, index); err != nil {
return nil, err, SchemeManagerStatusContentParsingError
}
return index, nil, SchemeManagerStatusValid
}
func (conf *Configuration) checkUnsignedFiles(dir string, index SchemeManagerIndex) error {
return common.WalkDir(dir, func(path string, info os.FileInfo) error {
relpath, err := filepath.Rel(dir, path)
if err != nil {
return err
}
schemepath := filepath.Join(index.Scheme(), relpath)
for _, ex := range sigExceptions {
if ex.MatchString(filepath.ToSlash(schemepath)) {
return nil
}
}
if info.IsDir() {
if !dirInScheme(index, schemepath) {
conf.Warnings = append(conf.Warnings, "Ignored dir: "+schemepath)
}
} else {
if _, ok := index[schemepath]; !ok {
conf.Warnings = append(conf.Warnings, "Ignored file: "+schemepath)
}
}
return nil
})
}
func downloadSignedFile(
transport *HTTPTransport, base, path string, hash SchemeFileHash,
) ([]byte, error) {
b, err := transport.GetBytes(path)
if err != nil {
return nil, err
}
sha := sha256.Sum256(b)
if hash != nil && !bytes.Equal(hash, sha[:]) {
return nil, errors.Errorf("Signature over new file %s is not valid", path)
}
dest := filepath.Join(base, filepath.FromSlash(path))
if err = common.EnsureDirectoryExists(filepath.Dir(dest)); err != nil {
return nil, err
}
return b, common.SaveFile(dest, b)
}
func downloadFile(transport *HTTPTransport, base, path string) ([]byte, error) {
return downloadSignedFile(transport, base, path, nil)
}
func dirInScheme(index SchemeManagerIndex, dir string) bool {
for indexpath := range index {
if strings.HasPrefix(indexpath, dir) {
return true
}
}
return false
}
func downloadScheme(url string) (Scheme, error) {
if url[len(url)-1] == '/' {
url = url[:len(url)-1]
}
var filenames = common.SchemeFilenames
for _, filename := range common.SchemeFilenames {
if strings.HasSuffix(url, "/"+filename) {
filenames = []string{filename}
}
}
var scheme Scheme
for _, filename := range filenames {
u := url
if strings.HasSuffix(url, "/"+filename) {
u = url[:len(url)-1-len(filename)]
}
b, err := NewHTTPTransport(u, true).GetBytes(filename)
if err != nil {
if err.(*SessionError).RemoteStatus == 404 {
continue
}
return nil, err
}
_, typ, err := common.SchemeInfo(filename, b)
if err != nil {
return nil, err
}
scheme = newScheme(SchemeType(typ))
return scheme, common.Unmarshal(filename, b, scheme)
}
return nil, errors.New("no scheme description file found")
}
func (conf *Configuration) tempSchemeCopy(scheme Scheme) (string, string, error) {
dir, err := ioutil.TempDir(filepath.Dir(scheme.path()), "tempscheme")
if err != nil {
return "", "", err
}
newschemepath := filepath.Join(dir, scheme.id())
if err = common.EnsureDirectoryExists(newschemepath); err != nil {
return "", "", err
}
if err = common.CopyDirectory(scheme.path(), newschemepath); err != nil {
return "", "", err
}
return dir, newschemepath, nil
}
// Move oldscheme to a temp dir in the same directory als oldscheme;
// move newscheme to the location of oldscheme; and delete oldscheme.
// If the first move works then the second one should too, so this will either entirely succeed
// or leave the old scheme untouched.
func (conf *Configuration) updateSchemeDir(scheme Scheme, oldscheme, newscheme string) error {
// Create a directory in the same directory as oldscheme,
// this is to make sure os.Rename does not fail with an "invalid cross-device link" error.
tmp, err := ioutil.TempDir(filepath.Dir(oldscheme), "oldscheme")
if err != nil {
return err
}
defer func() {
_ = os.RemoveAll(tmp)
}()
if err = os.Rename(oldscheme, filepath.Join(tmp, scheme.id())); err != nil {
return err
}
if err = os.Rename(newscheme, oldscheme); err != nil {
return err
}
scheme.setPath(oldscheme)
return nil
}
var (
// These files never occur in a scheme's index
sigExceptions = []*regexp.Regexp{
regexp.MustCompile(`/.git(/.*)?`),
regexp.MustCompile(`^.*?/pk\.pem$`),
regexp.MustCompile(`^.*?/sk\.pem$`),
regexp.MustCompile(`^.*?/index`),
regexp.MustCompile(`^.*?/index\.sig`),
regexp.MustCompile(`^.*?/AUTHORS$`),
regexp.MustCompile(`^.*?/LICENSE$`),
regexp.MustCompile(`^.*?/README\.md$`),
regexp.MustCompile(`^.*?/.*?/PrivateKeys$`),
regexp.MustCompile(`^.*?/.*?/PrivateKeys/\d+.xml$`),
regexp.MustCompile(`^.*?/assets/?\w*(\.png)?$`),
regexp.MustCompile(`\.DS_Store$`),
}
issPattern = regexp.MustCompile("^([^/]+)/description\\.xml")
credPattern = regexp.MustCompile("([^/]+)/Issues/([^/]+)/description\\.xml")
keyPattern = regexp.MustCompile("([^/]+)/PublicKeys/(\\d+)\\.xml")
)
func newScheme(typ SchemeType) Scheme {
switch typ {
case SchemeTypeIssuer:
return &SchemeManager{Status: SchemeManagerStatusUnprocessed}
case SchemeTypeRequestor:
return &RequestorScheme{Status: SchemeManagerStatusUnprocessed}
default:
panic("newScheme() does not support scheme type " + typ)
}
}
// Identifier returns the identifier of the specified scheme.
func (scheme *SchemeManager) Identifier() SchemeManagerIdentifier {
return NewSchemeManagerIdentifier(scheme.ID)
}
// Distributed indicates if this scheme uses a keyshare server.
func (scheme *SchemeManager) Distributed() bool {
return len(scheme.KeyshareServer) > 0
}
func (scheme *SchemeManager) id() string { return scheme.ID }
func (scheme *SchemeManager) idx() SchemeManagerIndex { return scheme.index }
func (scheme *SchemeManager) setIdx(idx SchemeManagerIndex) { scheme.index = idx }
func (scheme *SchemeManager) url() string { return scheme.URL }
func (scheme *SchemeManager) timestamp() Timestamp { return scheme.Timestamp }
func (scheme *SchemeManager) setTimestamp(t Timestamp) { scheme.Timestamp = t }
func (scheme *SchemeManager) setStatus(s SchemeManagerStatus) { scheme.Status = s }
func (scheme *SchemeManager) path() string { return scheme.storagepath }
func (scheme *SchemeManager) setPath(path string) { scheme.storagepath = path }
func (scheme *SchemeManager) parseContents(conf *Configuration) error {
err := common.IterateSubfolders(scheme.path(), func(dir string, _ os.FileInfo) error {
issuer := &Issuer{}
exists, err := conf.parseSchemeFile(scheme, filepath.Join(filepath.Base(dir), "description.xml"), issuer)
if err != nil {
return err
}
if !exists {
return nil
}
if issuer.XMLVersion < 4 {
return errors.New("Unsupported issuer description")
}
if len(issuer.Languages) == 0 {
issuer.Languages = scheme.Languages
}
if err = conf.validateIssuer(scheme, issuer, dir); err != nil {
return err
}
conf.Issuers[issuer.Identifier()] = issuer
return scheme.parseCredentialsFolder(conf, issuer, filepath.Join(dir, "Issues"))
})
if err != nil {
return err
}
// validate that there are no circular dependencies
for _, credType := range conf.CredentialTypes {
if credType.SchemeManagerID == scheme.ID {
if err := credType.validateDependencies(conf, []CredentialTypeIdentifier{}, credType.Identifier()); err != nil {
return err
}
}
}
return nil
}
var (
errCircDep = errors.Errorf("No valid dependency branch could be built. There might be a circular dependency.")
)
func (ct CredentialType) validateDependencies(conf *Configuration, validatedDeps DependencyChain, toBeChecked CredentialTypeIdentifier) error {
if len(validatedDeps) >= maxDepComplexity {
return errors.New("dependency tree too complex: " + validatedDeps.String())
}
for _, discon := range conf.CredentialTypes[ct.Identifier()].Dependencies {
disconSatisfied := false
for _, con := range discon {
conSatisfied := true
for _, item := range con {
if conf.CredentialTypes[item].SchemeManagerID != ct.SchemeManagerID {
return errors.Errorf("credential type %s in scheme %s has dependency outside the scheme: %s",
ct.Identifier().String(), ct.SchemeManagerID, conf.CredentialTypes[item].Identifier().String())
}
// all items need to be valid for middle to be valid
if toBeChecked == item {
conSatisfied = false
break
}
if conf.CredentialTypes[item].Dependencies != nil {
if e := conf.CredentialTypes[item].validateDependencies(conf, append(validatedDeps, item), toBeChecked); e != nil {
if e == errCircDep {
conSatisfied = false
break
} else {
return e
}
}
}
}
if conSatisfied {
disconSatisfied = true
}
}
if !disconSatisfied {
return errCircDep
}
}
return nil
}
func (d DependencyChain) contains(item CredentialTypeIdentifier) bool {
for _, dep := range d {
if dep == item {
return true