forked from keybase/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
md_ops.go
1571 lines (1438 loc) · 51.4 KB
/
md_ops.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
// Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libkbfs
import (
"fmt"
"sync"
"time"
"github.com/keybase/client/go/kbfs/data"
"github.com/keybase/client/go/kbfs/idutil"
"github.com/keybase/client/go/kbfs/kbfsblock"
"github.com/keybase/client/go/kbfs/kbfscrypto"
"github.com/keybase/client/go/kbfs/kbfsmd"
"github.com/keybase/client/go/kbfs/tlf"
"github.com/keybase/client/go/kbfs/tlfhandle"
kbname "github.com/keybase/client/go/kbun"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/logger"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/pkg/errors"
"golang.org/x/net/context"
"golang.org/x/sync/errgroup"
)
const (
maxAllowedMerkleGapServer = 13 * time.Hour
// Our contract with the server states that it won't accept KBFS
// writes if more than 13 hours have passed since the last Merkle
// roots (both global and KBFS) were published. Add some padding
// to that, and if we see any gaps larger than this, we will know
// we shouldn't be trusting the server. TODO: reduce this once
// merkle computation is faster.
maxAllowedMerkleGap = maxAllowedMerkleGapServer + 15*time.Minute
// merkleGapEnforcementStartString indicates when the mdserver
// started rejecting new writes based on the lack of recent merkle
// updates (according to `maxAllowedMerkleGap` above).
merkleGapEnforcementStartString = "2018-06-14T16:21:30-07:00"
)
var merkleGapEnforcementStart time.Time
func init() {
var err error
merkleGapEnforcementStart, err = time.Parse(
"2006-01-02T15:04:05-07:00", merkleGapEnforcementStartString)
if err != nil {
// Can never happen without a bad global const string.
panic(err)
}
}
// MDOpsStandard provides plaintext RootMetadata objects to upper
// layers, and processes RootMetadataSigned objects (encrypted and
// signed) suitable for passing to/from the MDServer backend.
type MDOpsStandard struct {
config Config
log logger.Logger
vlog *libkb.VDebugLog
lock sync.Mutex
// For each TLF, maps an MD revision representing the next MD
// after a device revoke, with the minimum revision number that's
// been validated in chain up to the given MD revision. That is,
// for TLF 1, if we have a next revision of 1000, and we've
// validated that MDs 100-1000 form a valid chain, then the map
// would contain: {1: {1000: 100}}
leafChainsValidated map[tlf.ID]map[kbfsmd.Revision]kbfsmd.Revision
}
// NewMDOpsStandard returns a new MDOpsStandard
func NewMDOpsStandard(config Config) *MDOpsStandard {
log := config.MakeLogger("")
return &MDOpsStandard{
config: config,
log: log,
vlog: config.MakeVLogger(log),
leafChainsValidated: make(
map[tlf.ID]map[kbfsmd.Revision]kbfsmd.Revision),
}
}
// convertVerifyingKeyError gives a better error when the TLF was
// signed by a key that is no longer associated with the last writer.
func (md *MDOpsStandard) convertVerifyingKeyError(ctx context.Context,
rmds *RootMetadataSigned, handle *tlfhandle.Handle, err error) error {
if _, ok := err.(VerifyingKeyNotFoundError); !ok {
return err
}
tlf := handle.GetCanonicalPath()
writer, nameErr := md.config.KBPKI().GetNormalizedUsername(
ctx, rmds.MD.LastModifyingWriter().AsUserOrTeam(),
md.config.OfflineAvailabilityForPath(tlf))
if nameErr != nil {
writer = kbname.NormalizedUsername("uid: " +
rmds.MD.LastModifyingWriter().String())
}
md.log.CDebugf(ctx, "Unverifiable update for TLF %s: %+v",
rmds.MD.TlfID(), err)
return UnverifiableTlfUpdateError{tlf, writer, err}
}
type ctxMDOpsSkipKeyVerificationType int
// This context key indicates that we should skip verification of
// revoked keys, to avoid recursion issues. Any resulting MD
// that skips verification shouldn't be trusted or cached.
const ctxMDOpsSkipKeyVerification ctxMDOpsSkipKeyVerificationType = 1
func (md *MDOpsStandard) decryptMerkleLeaf(
ctx context.Context, rmd ReadOnlyRootMetadata,
kbfsRoot *kbfsmd.MerkleRoot, leafBytes []byte) (
leaf *kbfsmd.MerkleLeaf, err error) {
var eLeaf kbfsmd.EncryptedMerkleLeaf
err = md.config.Codec().Decode(leafBytes, &eLeaf)
if err != nil {
return nil, err
}
if rmd.TypeForKeying() == tlf.TeamKeying {
// For teams, only the Keybase service has access to the
// private key that can decrypt the data, so send the request
// over to the crypto client.
cryptoLeaf := kbfscrypto.MakeEncryptedMerkleLeaf(
eLeaf.Version, eLeaf.EncryptedData, kbfsRoot.Nonce)
teamID := rmd.GetTlfHandle().FirstResolvedWriter().AsTeamOrBust()
// The merkle tree doesn't yet record which team keygen is
// used to encrypt a merkle leaf, so just use 1 as the min
// number and let the service scan. In the future, we should
// have the server record the keygen in the merkle leaf header
// and use that instead. (Note that "team keygen" is
// completely separate from "application keygen", so we can't
// just use `rmd.LatestKeyGeneration()` here.)
minKeyGen := keybase1.PerTeamKeyGeneration(1)
md.vlog.CLogf(
ctx, libkb.VLog1,
"Decrypting Merkle leaf for team %s with min key generation %d",
teamID, minKeyGen)
leafBytes, err := md.config.Crypto().DecryptTeamMerkleLeaf(
ctx, teamID, *kbfsRoot.EPubKey, cryptoLeaf, minKeyGen)
if err != nil {
return nil, err
}
var leaf kbfsmd.MerkleLeaf
if err := md.config.Codec().Decode(leafBytes, &leaf); err != nil {
return nil, err
}
return &leaf, nil
}
// The private key we need to decrypt the leaf does not live in
// key bundles; it lives only in the MDs that were part of a
// specific keygen. But we don't yet know what the keygen was, or
// what MDs were part of it, except that they have to have a
// larger revision number than the given `rmd`. So all we can do
// is iterate up from `rmd`, looking for a key that will unlock
// the leaf.
//
// Luckily, in the common case we'll be trying to verify the head
// of the folder, so we should be able to use
// rmd.data.TLFPrivateKey.
// Fetch the latest MD so we have all possible TLF crypt keys
// available to this device.
head, err := md.getForTLF(
ctx, rmd.TlfID(), rmd.BID(), rmd.MergedStatus(), nil)
if err != nil {
return nil, err
}
var uid keybase1.UID
if rmd.TlfID().Type() != tlf.Public {
session, err := md.config.KBPKI().GetCurrentSession(ctx)
if err != nil {
return nil, err
}
uid = session.UID
}
currRmd := rmd
for {
// If currRmd isn't readable, keep fetching MDs until it can
// be read. Then try currRmd.data.TLFPrivateKey to decrypt
// the leaf. If it doesn't work, fetch MDs until we find the
// next keygen, and continue the loop.
privKey := currRmd.data.TLFPrivateKey
if !currRmd.IsReadable() {
pmd, err := decryptMDPrivateData(
ctx, md.config.Codec(), md.config.Crypto(),
md.config.BlockCache(), md.config.BlockOps(),
md.config.KeyManager(), md.config.KBPKI(), md.config,
md.config.Mode(), uid, currRmd.GetSerializedPrivateMetadata(),
currRmd, head.ReadOnlyRootMetadata, md.log)
if err != nil {
return nil, err
}
privKey = pmd.TLFPrivateKey
}
currKeyGen := currRmd.LatestKeyGeneration()
if privKey == (kbfscrypto.TLFPrivateKey{}) {
return nil, errors.Errorf(
"Can't get TLF private key for key generation %d", currKeyGen)
}
mLeaf, err := eLeaf.Decrypt(
md.config.Codec(), privKey, kbfsRoot.Nonce, *kbfsRoot.EPubKey)
switch errors.Cause(err).(type) {
case nil:
return &mLeaf, nil
case libkb.DecryptionError:
// Fall-through to try another key generation.
default:
return nil, err
}
md.vlog.CLogf(
ctx, libkb.VLog1, "Key generation %d didn't work; searching for "+
"the next one", currKeyGen)
fetchLoop:
for {
start := currRmd.Revision() + 1
end := start + maxMDsAtATime - 1 // range is inclusive
nextRMDs, err := getMergedMDUpdatesWithEnd(
ctx, md.config, currRmd.TlfID(), start, end, nil)
if err != nil {
return nil, err
}
for _, nextRmd := range nextRMDs {
if nextRmd.LatestKeyGeneration() > currKeyGen {
md.vlog.CLogf(
ctx, libkb.VLog1, "Revision %d has key gen %d",
nextRmd.Revision(), nextRmd.LatestKeyGeneration())
currRmd = nextRmd.ReadOnlyRootMetadata
break fetchLoop
}
}
if len(nextRMDs) < maxMDsAtATime {
md.log.CDebugf(ctx,
"We tried all revisions and couldn't find a working keygen")
return nil, errors.Errorf("Can't decrypt merkle leaf")
}
currRmd = nextRMDs[len(nextRMDs)-1].ReadOnly()
}
}
}
func (md *MDOpsStandard) makeMerkleLeaf(
ctx context.Context, rmd ReadOnlyRootMetadata,
kbfsRoot *kbfsmd.MerkleRoot, leafBytes []byte) (
leaf *kbfsmd.MerkleLeaf, err error) {
if rmd.TlfID().Type() != tlf.Public {
return md.decryptMerkleLeaf(ctx, rmd, kbfsRoot, leafBytes)
}
var mLeaf kbfsmd.MerkleLeaf
err = md.config.Codec().Decode(leafBytes, &mLeaf)
if err != nil {
return nil, err
}
return &mLeaf, nil
}
func mdToMerkleTreeID(irmd ImmutableRootMetadata) keybase1.MerkleTreeID {
switch irmd.TlfID().Type() {
case tlf.Private:
return keybase1.MerkleTreeID_KBFS_PRIVATE
case tlf.Public:
return keybase1.MerkleTreeID_KBFS_PUBLIC
case tlf.SingleTeam:
return keybase1.MerkleTreeID_KBFS_PRIVATETEAM
default:
panic(fmt.Sprintf("Unexpected TLF keying type: %d",
irmd.TypeForKeying()))
}
}
func (md *MDOpsStandard) checkMerkleTimes(ctx context.Context,
latestRootTime time.Time, kbfsRoot *kbfsmd.MerkleRoot,
timeToCheck time.Time, allowedGapSinceMerkle time.Duration) error {
var latestKbfsTime time.Time
if kbfsRoot != nil {
latestKbfsTime = time.Unix(kbfsRoot.Timestamp, 0)
}
rootGap := timeToCheck.Sub(latestRootTime)
kbfsGap := timeToCheck.Sub(latestKbfsTime)
gapBound := allowedGapSinceMerkle
// A negative gap means that we expect the merkle roots to have
// happened second.
if allowedGapSinceMerkle < 0 {
if rootGap > 0 || kbfsGap > 0 {
return errors.Errorf(
"Roots were unexpectedly made before event being checked, "+
"timeToCheck=%s, latestRootTime=%s, latestKbfsTime=%s",
timeToCheck.Format(time.RFC3339Nano),
latestRootTime.Format(time.RFC3339Nano),
latestKbfsTime.Format(time.RFC3339Nano))
}
rootGap = -rootGap
kbfsGap = -kbfsGap
gapBound = -gapBound
}
// If it's been too long since the last published Merkle root,
// we can't trust what the server told us.
if rootGap > gapBound {
return errors.Errorf("Gap too large between event and global Merkle "+
"roots: gap=%s, timeToCheck=%s, latestRootTime=%s",
allowedGapSinceMerkle,
timeToCheck.Format(time.RFC3339Nano),
latestRootTime.Format(time.RFC3339Nano))
}
if kbfsGap > gapBound {
return errors.Errorf("Gap too large between event and KBFS Merkle "+
"roots: gap=%s, timeToCheck=%s, latestRootTime=%s",
allowedGapSinceMerkle,
timeToCheck.Format(time.RFC3339Nano),
latestKbfsTime.Format(time.RFC3339Nano))
}
return nil
}
// startOfValidatedChainForLeaf returns the earliest revision in the
// chain leading up to `leafRev` that's been validated so far. If no
// validations have occurred yet, it returns `leafRev`.
func (md *MDOpsStandard) startOfValidatedChainForLeaf(
tlfID tlf.ID, leafRev kbfsmd.Revision) kbfsmd.Revision {
md.lock.Lock()
defer md.lock.Unlock()
revs, ok := md.leafChainsValidated[tlfID]
if !ok {
return leafRev
}
min, ok := revs[leafRev]
if !ok {
return leafRev
}
return min
}
func (md *MDOpsStandard) mdserver(ctx context.Context) (
mds MDServer, err error) {
// The init code sets the MDOps before it sets the MDServer, and
// so it might be used before the MDServer is available (e.g., if
// the Keybase service is established before the MDServer is set,
// and it tries to look up handles for the user's public and
// private TLFs). So just wait until it's available, which should
// be happen very quickly.
first := true
for mds = md.config.MDServer(); mds == nil; mds = md.config.MDServer() {
if first {
md.log.CDebugf(ctx, "Waiting for mdserver")
first = false
}
time.Sleep(10 * time.Millisecond)
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
}
return mds, nil
}
func (md *MDOpsStandard) checkRevisionCameBeforeMerkle(
ctx context.Context, rmds *RootMetadataSigned,
verifyingKey kbfscrypto.VerifyingKey, irmd ImmutableRootMetadata,
root keybase1.MerkleRootV2, timeToCheck time.Time) (err error) {
ctx = context.WithValue(ctx, ctxMDOpsSkipKeyVerification, struct{}{})
// This gives us the KBFS merkle root that comes after the KBFS merkle
// root right after the one included by `root`. In other words, if the
// KBFS merkle root included in `root` is K0, the returned KBFS merkle
// root `kbfsRoot` here would be K2.
//
// Since `root` is the merkle root included by the revoke signature,
// anything written by the revoked device after K2 is not legit. The reason
// why we don't check K1 is that when K1 was built, it's possible that it
// only included writes happening right before the revoke happened. For
// example:
//
// - 8:00am mdmerkle starts to run
// - 8:01am mdmerkle scans TLF /keybase/private/alice
// - 8:02am Alice's device "Playstation 4" writes to her TLF
// /keybase/private/alice
// - 8:03am Alice revokes her device "Playstation 4", referencing a
// global merkle root that includes KBFS merkle K0
// - 8:07am mdmerkle finishes building the merkle tree and publish K1,
// which includes the head MD from /keybase/private/alice from 8:01,
// the one before the write happened at 8:02am.
// - 9:00am mdmerkle starts to run again, producing a KBFS merkle tree
// K2.
//
// Looking at the per TLF metadata chain, the writes happened at 8:02
// happened after the MD included in K1, but it was before the revoke and
// was legit. So we have to compare with K2 instead of K1.
//
// To protect against a malicious server indefinitely halting building
// KBFS merkle trees with the purpose of slipping in malicious writes
// from a revoked device, we have a "contract" with the mdserver that
// any writes happening after a grace period of
// `maxAllowedMerkleGapServer` after the last KBFS merkle tree was
// published should be rejected. In other words, KBFS should become
// readonly if `maxAllowedMerkleGapServer` has passed since last KBFS
// merkle tree was published. We add a small error window to it, and
// enforce in the client that any MD with a gap greater than
// `maxAllowedMerkleGap` since last KBFS merkle tree is illegal.
//
// However there's no way get a trustable timestamp for the metadata
// update happening at 8:02am when we haven't verified that metadata yet,
// we have to proxy it to some sort of ordering from merkle trees. Here we
// are using K2 as that proxy. Since we already need to guarantee the
// metadata in question has to happen before K2, we just need to make sure
// K2 happens within `maxAllowedMerkleGap` since the revoke happened.
//
// Unfortunately this means if mdmerkle takes longer than
// `maxAllowedMerkleGap` to build two trees, and a device both writes to a
// TLF and then gets revoked within that gap (and those writes are the most
// recent writes to the TLF), there's no way for us to know for sure the
// write is legit, from merkle tree perspective, and future reads of the
// TLF will fail without manual intervention.
kbfsRoot, merkleNodes, rootSeqno, err :=
md.config.MDCache().GetNextMD(rmds.MD.TlfID(), root.Seqno)
switch errors.Cause(err).(type) {
case nil:
case NextMDNotCachedError:
md.vlog.CLogf(
ctx, libkb.VLog1, "Finding next MD for TLF %s after global root %d",
rmds.MD.TlfID(), root.Seqno)
mdserv, err := md.mdserver(ctx)
if err != nil {
return err
}
kbfsRoot, merkleNodes, rootSeqno, err =
mdserv.FindNextMD(ctx, rmds.MD.TlfID(), root.Seqno)
if err != nil {
return err
}
err = md.config.MDCache().PutNextMD(
rmds.MD.TlfID(), root.Seqno, kbfsRoot, merkleNodes, rootSeqno)
if err != nil {
return err
}
default:
return err
}
if len(merkleNodes) == 0 {
// This can happen legitimately if we are still inside the
// error window and no new merkle trees have been made yet, or
// the server could be lying to us.
md.log.CDebugf(ctx, "The server claims there haven't been any "+
"KBFS merkle trees published since the merkle root")
// Check the most recent global merkle root and KBFS merkle
// root ctimes and make sure they fall within the expected
// error window with respect to the revocation.
_, latestRootTime, err := md.config.KBPKI().GetCurrentMerkleRoot(ctx)
if err != nil {
return err
}
treeID := mdToMerkleTreeID(irmd)
// TODO: cache the latest KBFS merkle root somewhere for a while?
mdserv, err := md.mdserver(ctx)
if err != nil {
return err
}
latestKbfsRoot, err := mdserv.GetMerkleRootLatest(ctx, treeID)
if err != nil {
return err
}
serverOffset, _ := mdserv.OffsetFromServerTime()
if (serverOffset < 0 && serverOffset < -time.Hour) ||
(serverOffset > 0 && serverOffset > time.Hour) {
return errors.Errorf("The offset between the server clock "+
"and the local clock is too large to check the revocation "+
"time: %s", serverOffset)
}
currServerTime := md.config.Clock().Now().Add(-serverOffset)
err = md.checkMerkleTimes(
ctx, latestRootTime, latestKbfsRoot, currServerTime,
maxAllowedMerkleGap)
if err != nil {
return err
}
// Verify the chain up to the current head. By using `ctx`,
// we'll avoid infinite loops in the writer-key-checking code
// by skipping revoked key verification. This is ok, because
// we only care about the hash chain for the purposes of
// verifying `irmd`.
chain, err := getMergedMDUpdates(
ctx, md.config, irmd.TlfID(), irmd.Revision()+1, nil)
if err != nil {
return err
}
if len(chain) > 0 {
err = irmd.CheckValidSuccessor(
irmd.mdID, chain[0].ReadOnlyRootMetadata)
if err != nil {
return err
}
}
// TODO: Also eventually check the blockchain-published merkles to
// make sure the server isn't lying (though that will have a
// much larger error window).
return nil
}
if !timeToCheck.IsZero() {
// Check the gap between the event and the global/KBFS roots
// that include the event, to make sure they fall within the
// expected error window. The server didn't begin enforcing this
// until some time into KBFS's existence though.
if timeToCheck.After(merkleGapEnforcementStart) {
// TODO(KBFS-2954): get the right root time for the
// corresponding global root.
latestRootTime := time.Unix(kbfsRoot.Timestamp, 0)
// This is to make sure kbfsRoot is built within
// maxAllowedMerkleGap from timeToCheck (which is the from the
// revoke signature). As mentioned in the large comment block
// above, since there's no other way to get a trustable time from
// this particular metadata update when we don't trust it yet, we
// use the "happens before K2" check below as a proxy, and make
// sure K2 is within the gap.
err = md.checkMerkleTimes(
ctx, latestRootTime, kbfsRoot, timeToCheck,
// Check the gap from the reverse direction, to make sure the
// roots were made _after_ the revoke within the gap.
-maxAllowedMerkleGap)
if err != nil {
return err
}
}
}
md.vlog.CLogf(
ctx, libkb.VLog1,
"Next KBFS merkle root is %d, included in global merkle root seqno=%d",
kbfsRoot.SeqNo, rootSeqno)
// Decode (and possibly decrypt) the leaf node, so we can see what
// the given MD revision number was for the MD that followed the
// revoke.
leaf, err := md.makeMerkleLeaf(
ctx, irmd.ReadOnlyRootMetadata, kbfsRoot,
merkleNodes[len(merkleNodes)-1])
if err != nil {
return err
}
// If the given revision comes after the merkle leaf revision,
// then don't verify it.
//
// In the context of the large comment at the beginning of this method,
// this is to check a write happens before K2.
if irmd.Revision() > leaf.Revision {
return MDWrittenAfterRevokeError{
irmd.TlfID(), irmd.Revision(), leaf.Revision, verifyingKey}
} else if irmd.Revision() == leaf.Revision {
return nil
}
// Otherwise it's valid, as long as there's a valid chain of MD
// revisions between the two. First, see which chain we've
// already validated, and if this revision falls in that chain,
// we're done. Otherwise, just fetch the part of the chain we
// haven't validated yet.
newChainEnd := md.startOfValidatedChainForLeaf(irmd.TlfID(), leaf.Revision)
if newChainEnd <= irmd.Revision() {
return nil
}
// By using `ctx`, we'll avoid infinite loops in the
// writer-key-checking code by skipping revoked key verification.
// This is ok, because we only care about the hash chain for the
// purposes of verifying `irmd`.
md.vlog.CLogf(
ctx, libkb.VLog1, "Validating MD chain for TLF %s between %d and %d",
irmd.TlfID(), irmd.Revision()+1, newChainEnd)
chain, err := getMergedMDUpdatesWithEnd(
ctx, md.config, irmd.TlfID(), irmd.Revision()+1, newChainEnd, nil)
if err != nil {
return err
}
if len(chain) == 0 {
return errors.Errorf("Unexpectedly found no revisions "+
"after %d, even though the merkle tree includes revision %d",
irmd.Revision(), leaf.Revision)
}
err = irmd.CheckValidSuccessor(irmd.mdID, chain[0].ReadOnlyRootMetadata)
if err != nil {
return err
}
// Cache this verified chain for later use.
md.lock.Lock()
defer md.lock.Unlock()
revs, ok := md.leafChainsValidated[irmd.TlfID()]
if !ok {
revs = make(map[kbfsmd.Revision]kbfsmd.Revision)
md.leafChainsValidated[irmd.TlfID()] = revs
}
revs[leaf.Revision] = irmd.Revision()
return nil
}
func (md *MDOpsStandard) verifyKey(
ctx context.Context, rmds *RootMetadataSigned,
uid keybase1.UID, verifyingKey kbfscrypto.VerifyingKey,
irmd ImmutableRootMetadata) (cacheable bool, err error) {
err = md.config.KBPKI().HasVerifyingKey(
ctx, uid, verifyingKey, rmds.untrustedServerTimestamp,
md.config.OfflineAvailabilityForID(irmd.TlfID()))
var info idutil.RevokedKeyInfo
switch e := errors.Cause(err).(type) {
case nil:
return true, nil
case RevokedDeviceVerificationError:
if ctx.Value(ctxMDOpsSkipKeyVerification) != nil {
md.vlog.CLogf(
ctx, libkb.VLog1,
"Skipping revoked key verification due to recursion")
return false, nil
}
if e.info.MerkleRoot.Seqno <= 0 {
md.log.CDebugf(ctx, "Can't verify an MD written by a revoked "+
"device if there's no valid root seqno to check: %+v", e)
return true, nil
}
info = e.info
// Fall through to check via the merkle tree.
default:
return false, err
}
md.vlog.CLogf(
ctx, libkb.VLog1, "Revision %d for %s was signed by a device that was "+
"revoked at time=%d,root=%d; checking via Merkle",
irmd.Revision(), irmd.TlfID(), info.Time, info.MerkleRoot.Seqno)
err = md.checkRevisionCameBeforeMerkle(
ctx, rmds, verifyingKey, irmd, info.MerkleRoot,
keybase1.FromTime(info.Time))
if err != nil {
return false, err
}
return true, nil
}
func (md *MDOpsStandard) verifyWriterKey(ctx context.Context,
rmds *RootMetadataSigned, irmd ImmutableRootMetadata, handle *tlfhandle.Handle,
getRangeLock *sync.Mutex) error {
if !rmds.MD.IsWriterMetadataCopiedSet() {
// Skip verifying the writer key if it's the same as the
// overall signer's key (which must be verified elsewhere).
if rmds.GetWriterMetadataSigInfo().VerifyingKey ==
rmds.SigInfo.VerifyingKey {
return nil
}
_, err := md.verifyKey(
ctx, rmds, rmds.MD.LastModifyingWriter(),
rmds.GetWriterMetadataSigInfo().VerifyingKey, irmd)
if err != nil {
return md.convertVerifyingKeyError(ctx, rmds, handle, err)
}
return nil
}
// The writer metadata can be copied only for rekeys or
// finalizations, neither of which should happen while
// unmerged.
if rmds.MD.MergedStatus() != kbfsmd.Merged {
return errors.Errorf("Revision %d for %s has a copied writer "+
"metadata, but is unexpectedly not merged",
rmds.MD.RevisionNumber(), rmds.MD.TlfID())
}
if getRangeLock != nil {
// If there are multiple goroutines, we don't want to risk
// several concurrent requests to the MD server, just in case
// there are several revisions with copied writer MD in this
// range.
//
// TODO: bugs could result in thousands (or more) copied MD
// updates in a row (i.e., too many to fit in the cache). We
// could do something more sophisticated here where once one
// goroutine finds the copied MD, it stores it somewhere so
// the other goroutines don't have to also search through all
// the same MD updates (which may have been evicted from the
// cache in the meantime). Also, maybe copied writer MDs
// should include the original revision number so we don't
// have to search like this.
getRangeLock.Lock()
defer getRangeLock.Unlock()
}
// The server timestamp on rmds does not reflect when the
// writer MD was actually signed, since it was copied from a
// previous revision. Search backwards for the most recent
// uncopied writer MD to get the right timestamp.
for prevRev := rmds.MD.RevisionNumber() - 1; prevRev >= kbfsmd.RevisionInitial; prevRev-- {
// Recursively call into MDOps. Note that in the case where
// we were already fetching a range of MDs, this could do
// extra work by downloading the same MDs twice (for those
// that aren't yet in the cache). That should be so rare that
// it's not worth optimizing.
rmd, err := getSingleMD(ctx, md.config, rmds.MD.TlfID(),
rmds.MD.BID(), prevRev, rmds.MD.MergedStatus(), nil)
if err != nil {
return err
}
if !rmd.IsWriterMetadataCopiedSet() {
// We want to compare the writer signature of
// rmds with that of prevMDs[i]. However, we've
// already dropped prevMDs[i]'s writer
// signature. We can just verify prevMDs[i]'s
// writer metadata with rmds's signature,
// though.
buf, err := rmd.GetSerializedWriterMetadata(md.config.Codec())
if err != nil {
return err
}
err = kbfscrypto.Verify(
buf, rmds.GetWriterMetadataSigInfo())
if err != nil {
return errors.Errorf("Could not verify "+
"uncopied writer metadata "+
"from revision %d of folder "+
"%s with signature from "+
"revision %d: %v",
rmd.Revision(),
rmds.MD.TlfID(),
rmds.MD.RevisionNumber(), err)
}
// The fact the fact that we were able to process this
// MD correctly means that we already verified its key
// at the correct timestamp, so we're good.
return nil
}
}
return errors.Errorf(
"Couldn't find uncopied MD previous to "+
"revision %d of folder %s for checking the writer "+
"timestamp", rmds.MD.RevisionNumber(), rmds.MD.TlfID())
}
type merkleBasedTeamChecker struct {
teamMembershipChecker
md *MDOpsStandard
rmds *RootMetadataSigned
irmd ImmutableRootMetadata
notCacheable bool
}
func (mbtc merkleBasedTeamChecker) IsTeamWriter(
ctx context.Context, tid keybase1.TeamID, uid keybase1.UID,
verifyingKey kbfscrypto.VerifyingKey,
offline keybase1.OfflineAvailability) (bool, error) {
isCurrentWriter, err := mbtc.teamMembershipChecker.IsTeamWriter(
ctx, tid, uid, verifyingKey, offline)
if err != nil {
return false, err
}
if isCurrentWriter {
return true, nil
}
if ctx.Value(ctxMDOpsSkipKeyVerification) != nil {
// Don't cache this fake verification.
mbtc.notCacheable = true
mbtc.md.vlog.CLogf(
ctx, libkb.VLog1,
"Skipping old team writership verification due to recursion")
return true, nil
}
// The user is not currently a writer of the team, but maybe they
// were at the time this MD was written. Find out the global
// merkle root where they were no longer a writer, and make sure
// this revision came before that.
mbtc.md.vlog.CLogf(
ctx, libkb.VLog1, "User %s is no longer a writer of team %s; "+
"checking merkle trees to verify they were a writer at the time the "+
"MD was written.", uid, tid)
root, err := mbtc.teamMembershipChecker.NoLongerTeamWriter(
ctx, tid, mbtc.irmd.TlfID().Type(), uid, verifyingKey, offline)
switch e := errors.Cause(err).(type) {
case nil:
// TODO(CORE-8199): pass in the time for the writer downgrade.
err = mbtc.md.checkRevisionCameBeforeMerkle(
ctx, mbtc.rmds, verifyingKey, mbtc.irmd, root, time.Time{})
if err != nil {
return false, err
}
case libkb.MerkleClientError:
if e.IsOldTree() {
mbtc.md.vlog.CLogf(
ctx, libkb.VLog1, "Merkle root is too old for checking "+
"the revoked key: %+v", err)
} else {
return false, err
}
default:
return false, err
}
return true, nil
}
func (mbtc merkleBasedTeamChecker) IsTeamReader(
ctx context.Context, tid keybase1.TeamID, uid keybase1.UID,
offline keybase1.OfflineAvailability) (
bool, error) {
if mbtc.irmd.TlfID().Type() == tlf.Public {
return true, nil
}
isCurrentReader, err := mbtc.teamMembershipChecker.IsTeamReader(
ctx, tid, uid, offline)
if err != nil {
return false, err
}
if isCurrentReader {
return true, nil
}
// We don't yet have a way to check for past readership based on
// the Merkle tree, so for now return true. This isn't too bad,
// since this is only called for checking the last modifying user
// of an update (the last modifying _writer_ is tested with the
// above function). TODO: fix this once historic team readership
// is available in the service.
mbtc.md.vlog.CLogf(
ctx, libkb.VLog1,
"Faking old readership for user %s in team %s", uid, tid)
return true, nil
}
// processMetadata converts the given rmds to an
// ImmutableRootMetadata. After this function is called, rmds
// shouldn't be used.
func (md *MDOpsStandard) processMetadata(ctx context.Context,
handle *tlfhandle.Handle, rmds *RootMetadataSigned, extra kbfsmd.ExtraMetadata,
getRangeLock *sync.Mutex) (ImmutableRootMetadata, error) {
// First, construct the ImmutableRootMetadata object, even before
// we validate the writer or the keys, because the irmd will be
// used in that process to check for valid successors.
// Get the UID unless this is a public tlf - then proceed with empty uid.
var uid keybase1.UID
if handle.Type() != tlf.Public {
session, err := md.config.KBPKI().GetCurrentSession(ctx)
if err != nil {
return ImmutableRootMetadata{}, err
}
uid = session.UID
}
// TODO: Avoid having to do this type assertion.
brmd, ok := rmds.MD.(kbfsmd.MutableRootMetadata)
if !ok {
return ImmutableRootMetadata{}, kbfsmd.MutableRootMetadataNoImplError{}
}
rmd := makeRootMetadata(brmd, extra, handle)
// Try to decrypt using the keys available in this md. If that
// doesn't work, a future MD may contain more keys and will be
// tried later.
pmd, err := decryptMDPrivateData(
ctx, md.config.Codec(), md.config.Crypto(),
md.config.BlockCache(), md.config.BlockOps(),
md.config.KeyManager(), md.config.KBPKI(), md.config, md.config.Mode(),
uid, rmd.GetSerializedPrivateMetadata(), rmd, rmd, md.log)
if err != nil {
return ImmutableRootMetadata{}, err
}
rmd.data = pmd
mdID, err := kbfsmd.MakeID(md.config.Codec(), rmd.bareMd)
if err != nil {
return ImmutableRootMetadata{}, err
}
localTimestamp := rmds.untrustedServerTimestamp
mdserv, err := md.mdserver(ctx)
if err != nil {
return ImmutableRootMetadata{}, err
}
if offset, ok := mdserv.OffsetFromServerTime(); ok {
localTimestamp = localTimestamp.Add(offset)
}
key := rmds.GetWriterMetadataSigInfo().VerifyingKey
irmd := MakeImmutableRootMetadata(rmd, key, mdID, localTimestamp, true)
// Next, verify validity and signatures. Use a checker that can
// check for writership in the past, using the merkle tree.
checker := merkleBasedTeamChecker{md.config.KBPKI(), md, rmds, irmd, false}
err = rmds.IsValidAndSigned(
ctx, md.config.Codec(), checker, extra,
md.config.OfflineAvailabilityForID(handle.TlfID()))
if err != nil {
return ImmutableRootMetadata{}, MDMismatchError{
rmds.MD.RevisionNumber(), handle.GetCanonicalPath(),
rmds.MD.TlfID(), err,
}
}
// Then, verify the verifying keys. We do this after decrypting
// the MD and making the ImmutableRootMetadata, since we may need
// access to the private metadata when checking the merkle roots,
// and we also need access to the `mdID`.
if err := md.verifyWriterKey(
ctx, rmds, irmd, handle, getRangeLock); err != nil {
return ImmutableRootMetadata{}, err
}
cacheable, err := md.verifyKey(
ctx, rmds, rmds.MD.GetLastModifyingUser(), rmds.SigInfo.VerifyingKey,
irmd)
if err != nil {
return ImmutableRootMetadata{}, md.convertVerifyingKeyError(
ctx, rmds, handle, err)
}
// Make sure the caller doesn't use rmds anymore.
*rmds = RootMetadataSigned{}
if cacheable && !checker.notCacheable {
err = md.config.MDCache().Put(irmd)
if err != nil {
return ImmutableRootMetadata{}, err
}
}
return irmd, nil
}
func (md *MDOpsStandard) getForHandle(ctx context.Context, handle *tlfhandle.Handle,
mStatus kbfsmd.MergeStatus, lockBeforeGet *keybase1.LockID) (
id tlf.ID, rmd ImmutableRootMetadata, err error) {
// If we already know the tlf ID, we shouldn't be calling this
// function.
if handle.TlfID() != tlf.NullID {
return tlf.ID{}, ImmutableRootMetadata{}, errors.Errorf(
"GetForHandle called for %s with non-nil TLF ID %s",
handle.GetCanonicalPath(), handle.TlfID())
}
// Check for handle readership, to give a nice error early.
if handle.Type() == tlf.Private && !handle.IsBackedByTeam() {
session, err := md.config.KBPKI().GetCurrentSession(ctx)
if err != nil {
return tlf.ID{}, ImmutableRootMetadata{}, err
}
if !handle.IsReader(session.UID) {
return tlf.ID{}, ImmutableRootMetadata{},
tlfhandle.NewReadAccessError(
handle, session.Name, handle.GetCanonicalPath())
}
}
md.log.CDebugf(
ctx, "GetForHandle: %s %s", handle.GetCanonicalPath(), mStatus)
defer func() {
// Temporary debugging for KBFS-1921. TODO: remove.
switch {
case err != nil:
md.log.CDebugf(ctx, "GetForHandle done with err=%+v", err)
case rmd != (ImmutableRootMetadata{}):
md.log.CDebugf(ctx, "GetForHandle done, id=%s, revision=%d, "+
"mStatus=%s", id, rmd.Revision(), rmd.MergedStatus())
default:
md.log.CDebugf(
ctx, "GetForHandle done, id=%s, no %s MD revisions yet", id,
mStatus)
}
}()
mdserv, err := md.mdserver(ctx)
if err != nil {
return tlf.ID{}, ImmutableRootMetadata{}, err
}
bh, err := handle.ToBareHandle()