/
boxer.go
2272 lines (2041 loc) · 80.1 KB
/
boxer.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 the included BSD license.
package chat
import (
"bytes"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"flag"
"fmt"
"sort"
"sync"
"time"
"golang.org/x/crypto/nacl/box"
"golang.org/x/crypto/nacl/secretbox"
"golang.org/x/net/context"
"golang.org/x/sync/errgroup"
"github.com/keybase/client/go/chat/globals"
"github.com/keybase/client/go/chat/signencrypt"
"github.com/keybase/client/go/chat/storage"
"github.com/keybase/client/go/chat/types"
"github.com/keybase/client/go/chat/utils"
"github.com/keybase/client/go/ephemeral"
"github.com/keybase/client/go/kbcrypto"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/logger"
"github.com/keybase/client/go/protocol/chat1"
"github.com/keybase/client/go/protocol/gregor1"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/client/go/teambot"
"github.com/keybase/client/go/teams"
"github.com/keybase/clockwork"
"github.com/keybase/go-codec/codec"
"github.com/keybase/go-crypto/ed25519"
)
const CurrentMessageBoxedVersion = chat1.MessageBoxedVersion_V2
var publicCryptKey keybase1.CryptKey
func init() {
// publicCryptKey is a zero key used for public chat messages.
var zero [libkb.NaclDHKeySecretSize]byte
publicCryptKey = keybase1.CryptKey{
KeyGeneration: 1,
Key: keybase1.Bytes32(zero),
}
}
type Boxer struct {
utils.DebugLabeler
globals.Contextified
boxVersionForTesting *chat1.MessageBoxedVersion
// Replaceable for testing.
// Normally set to normal implementations.
hashV1 func(data []byte) chat1.Hash
// Slots for replacing with test implementations.
// These are normally nil.
testingValidSenderKey func(context.Context, gregor1.UID, []byte, gregor1.Time) (revoked *gregor1.Time, unboxingErr types.UnboxingError)
testingGetSenderInfoLocal func(context.Context, gregor1.UID, gregor1.DeviceID) (senderUsername string, senderDeviceName string, senderDeviceType keybase1.DeviceTypeV2)
// Post-process signatures and signencrypts
testingSignatureMangle func([]byte) []byte
clock clockwork.Clock
}
func NewBoxer(g *globals.Context) *Boxer {
return &Boxer{
DebugLabeler: utils.NewDebugLabeler(g.ExternalG(), "Boxer", false),
hashV1: hashSha256V1,
Contextified: globals.NewContextified(g),
clock: clockwork.NewRealClock(),
}
}
func (b *Boxer) SetClock(clock clockwork.Clock) {
b.clock = clock
}
func (b *Boxer) log() logger.Logger {
return b.G().GetLog()
}
func (b *Boxer) makeErrorMessageFromPieces(ctx context.Context, err types.UnboxingError,
msgID chat1.MessageID, msgType chat1.MessageType, ctime gregor1.Time,
sender gregor1.UID, senderDevice gregor1.DeviceID, botUID *gregor1.UID,
isEphemeral bool, explodedBy *string, etime gregor1.Time) chat1.MessageUnboxed {
e := chat1.MessageUnboxedError{
ErrType: err.ExportType(),
ErrMsg: err.Error(),
InternalErrMsg: err.InternalError(),
VersionKind: err.VersionKind(),
VersionNumber: err.VersionNumber(),
IsCritical: err.IsCritical(),
MessageID: msgID,
MessageType: msgType,
Ctime: ctime,
IsEphemeral: isEphemeral,
ExplodedBy: explodedBy,
Etime: etime,
BotUsername: b.getBotInfoLocal(ctx, botUID),
}
e.SenderUsername, e.SenderDeviceName, e.SenderDeviceType = b.getSenderInfoLocal(ctx,
sender, senderDevice)
return chat1.NewMessageUnboxedWithError(e)
}
func (b *Boxer) makeErrorMessage(ctx context.Context, msg chat1.MessageBoxed, err types.UnboxingError) chat1.MessageUnboxed {
return b.makeErrorMessageFromPieces(ctx, err, msg.GetMessageID(), msg.GetMessageType(),
msg.ServerHeader.Ctime, msg.ClientHeader.Sender, msg.ClientHeader.SenderDevice,
msg.ClientHeader.BotUID,
msg.IsEphemeral(), msg.ExplodedBy(), msg.Etime())
}
func (b *Boxer) detectPermanentError(conv types.UnboxConversationInfo, err error, tlfName string) types.UnboxingError {
// Check for team not exist error that is in raw form
if aerr, ok := err.(libkb.AppStatusError); ok {
switch keybase1.StatusCode(aerr.Code) {
case keybase1.StatusCode_SCTeamNotFound:
return NewPermanentUnboxingError(err)
default:
// Nothing to do.
}
}
if _, ok := IsRekeyError(err); ok && conv.GetFinalizeInfo() != nil {
return NewPermanentUnboxingError(err)
}
// Check if we have a permanent or tranisent team read error. Transient
// errors, are converted to rekey errors later.
if teams.IsTeamReadError(err) {
switch err.Error() {
case "Root team has been deleted",
"Root team has been abandoned: All members have left or reset",
"Root team is not active":
return NewPermanentUnboxingError(err)
default:
return NewTransientUnboxingError(err)
}
}
switch err := err.(type) {
case libkb.UserDeletedError:
if len(err.Msg) == 0 {
err.Msg = fmt.Sprintf("user deleted in chat '%v'", tlfName)
}
return NewPermanentUnboxingError(err)
case teams.TeamDoesNotExistError,
teams.KBFSKeyGenerationError,
libkb.KeyMaskNotFoundError,
libkb.AssertionCheckError,
DecryptionKeyNotFoundError,
NotAuthenticatedForThisDeviceError,
InvalidMACError,
ImpteamBadteamError,
teambot.TeambotPermanentKeyError:
return NewPermanentUnboxingError(err)
case ephemeral.EphemeralKeyError:
// Normalize error message with EphemeralUnboxingError
ekErr := NewEphemeralUnboxingError(err)
if err.IsPermanent() {
return NewPermanentUnboxingError(ekErr)
}
return NewTransientUnboxingError(ekErr)
}
// Check for no space left on device errors
if libkb.IsNoSpaceOnDeviceError(err) {
return NewPermanentUnboxingError(err)
}
// transient error. Rekey errors come through here
return NewTransientUnboxingError(err)
}
type basicUnboxConversationInfo struct {
convID chat1.ConversationID
membersType chat1.ConversationMembersType
finalizeInfo *chat1.ConversationFinalizeInfo
visibility keybase1.TLFVisibility
}
var _ types.UnboxConversationInfo = (*basicUnboxConversationInfo)(nil)
func newBasicUnboxConversationInfo(convID chat1.ConversationID,
membersType chat1.ConversationMembersType, finalizeInfo *chat1.ConversationFinalizeInfo,
visibility keybase1.TLFVisibility) *basicUnboxConversationInfo {
return &basicUnboxConversationInfo{
convID: convID,
membersType: membersType,
finalizeInfo: finalizeInfo,
visibility: visibility,
}
}
func (b *basicUnboxConversationInfo) GetConvID() chat1.ConversationID {
return b.convID
}
func (b *basicUnboxConversationInfo) GetMembersType() chat1.ConversationMembersType {
return b.membersType
}
func (b *basicUnboxConversationInfo) GetFinalizeInfo() *chat1.ConversationFinalizeInfo {
return b.finalizeInfo
}
func (b *basicUnboxConversationInfo) GetExpunge() *chat1.Expunge {
return nil
}
func (b *basicUnboxConversationInfo) GetMaxDeletedUpTo() chat1.MessageID {
return 0
}
func (b *basicUnboxConversationInfo) IsPublic() bool {
return b.visibility == keybase1.TLFVisibility_PUBLIC
}
func (b *basicUnboxConversationInfo) GetMaxMessage(chat1.MessageType) (chat1.MessageSummary, error) {
return chat1.MessageSummary{}, nil
}
type extraInboxUnboxConversationInfo struct {
convID chat1.ConversationID
membersType chat1.ConversationMembersType
visibility keybase1.TLFVisibility
}
var _ types.UnboxConversationInfo = (*extraInboxUnboxConversationInfo)(nil)
func newExtraInboxUnboxConverstionInfo(convID chat1.ConversationID, membersType chat1.ConversationMembersType,
visibility keybase1.TLFVisibility) *extraInboxUnboxConversationInfo {
return &extraInboxUnboxConversationInfo{
convID: convID,
membersType: membersType,
visibility: visibility,
}
}
func (p *extraInboxUnboxConversationInfo) GetConvID() chat1.ConversationID {
return p.convID
}
func (p *extraInboxUnboxConversationInfo) GetMembersType() chat1.ConversationMembersType {
return p.membersType
}
func (p *extraInboxUnboxConversationInfo) GetFinalizeInfo() *chat1.ConversationFinalizeInfo {
return nil
}
func (p *extraInboxUnboxConversationInfo) GetExpunge() *chat1.Expunge {
return nil
}
func (p *extraInboxUnboxConversationInfo) GetMaxDeletedUpTo() chat1.MessageID {
return 0
}
func (p *extraInboxUnboxConversationInfo) IsPublic() bool {
return p.visibility == keybase1.TLFVisibility_PUBLIC
}
func (p *extraInboxUnboxConversationInfo) GetMaxMessage(chat1.MessageType) (chat1.MessageSummary, error) {
return chat1.MessageSummary{}, nil
}
func (b *Boxer) getEffectiveMembersType(ctx context.Context, boxed chat1.MessageBoxed,
convMembersType chat1.ConversationMembersType) chat1.ConversationMembersType {
switch convMembersType {
case chat1.ConversationMembersType_IMPTEAMUPGRADE:
if boxed.KBFSEncrypted() {
b.Debug(ctx, "getEffectiveMembersType: overruling %v conv with KBFS keys", convMembersType)
return chat1.ConversationMembersType_KBFS
}
default:
// Nothing to do for other conv types.
}
return convMembersType
}
var errBoxerUnavailableMessage = NewPermanentUnboxingError(errors.New("message not available"))
func (b *Boxer) castInternalError(ierr types.UnboxingError) error {
err, ok := ierr.(error)
if ok {
return err
}
return nil
}
// UnboxMessage unboxes a chat1.MessageBoxed into a chat1.MessageUnboxed. It
// finds the appropriate keybase1.CryptKey, decrypts the message, and verifies
// several things:
// - The message's signature is valid.
// - (TODO) The signing KID was valid when the signature was made.
// - (TODO) The signing KID belongs to the sending device.
// - (TODO) The sending device belongs to the sender.
// [Note that we do currently check the KID -> UID relationship,
// independent of the device ID.]
// - (TODO) The sender has write permission in the TLF.
// - (TODO) The TLF name, public flag, and finalized info resolve to the TLF ID.
// - The conversation ID derives from the ConversationIDTriple.
// - The body hash is not a replay from another message we know about.
// - The prev pointers are consistent with other messages we know about.
// - (TODO) The prev pointers are not absurdly ancient.
// - The ClientHeader provided with the BoxedMessage matches the one we decrypt.
//
// The first return value is unusable if the err != nil. Returns (_, err) for
// non-permanent errors, and (MessageUnboxedError, nil) for permanent errors.
// Permanent errors can be cached and must be treated as a value to deal with,
// whereas temporary errors are transient failures.
func (b *Boxer) UnboxMessage(ctx context.Context, boxed chat1.MessageBoxed, conv types.UnboxConversationInfo,
info *types.BoxerEncryptionInfo) (m chat1.MessageUnboxed, uberr types.UnboxingError) {
ctx = libkb.WithLogTag(ctx, "CHTUNBOX")
var err error
defer b.Trace(ctx, &err, "UnboxMessage(%s, %d)", conv.GetConvID(),
boxed.GetMessageID())()
defer func() { err = b.castInternalError(uberr) }()
// Check to see if the context has been cancelled
select {
case <-ctx.Done():
return m, NewTransientUnboxingError(ctx.Err())
default:
}
// if the server message doesn't have a TLFID, then it isn't available to us. This is most commonly
// used when restricted bots try to read messages not encrypted for them.
if boxed.ClientHeader.Conv.Tlfid.IsNil() {
return b.makeErrorMessage(ctx, boxed, errBoxerUnavailableMessage), nil
}
// If we don't have an rtime, add one.
if boxed.ServerHeader.Rtime == nil {
now := gregor1.ToTime(b.clock.Now())
boxed.ServerHeader.Rtime = &now
}
tlfName := boxed.ClientHeader.TLFNameExpanded(conv.GetFinalizeInfo())
if conv.IsPublic() != boxed.ClientHeader.TlfPublic {
return b.makeErrorMessage(ctx, boxed,
NewPermanentUnboxingError(fmt.Errorf("visibility mismatch: %v != %v", conv.IsPublic(),
boxed.ClientHeader.TlfPublic))), nil
}
if info == nil {
info = new(types.BoxerEncryptionInfo)
keyMembersType := b.getEffectiveMembersType(ctx, boxed, conv.GetMembersType())
encryptionKey, err := globals.CtxKeyFinder(ctx, b.G()).FindForDecryption(ctx,
tlfName, boxed.ClientHeader.Conv.Tlfid, conv.GetMembersType(),
conv.IsPublic(), boxed.KeyGeneration,
keyMembersType == chat1.ConversationMembersType_KBFS, boxed.ClientHeader.BotUID)
if err != nil {
// Post-process error from this
uberr = b.detectPermanentError(conv, err, tlfName)
if uberr.IsPermanent() {
return b.makeErrorMessage(ctx, boxed, uberr), nil
}
return chat1.MessageUnboxed{}, uberr
}
// If the message is exploding, load the ephemeral key.
var ephemeralKey types.EphemeralCryptKey
if boxed.IsEphemeral() {
ephemeralKey, err = globals.CtxKeyFinder(ctx, b.G()).EphemeralKeyForDecryption(
b.G().MetaContext(ctx), tlfName, boxed.ClientHeader.Conv.Tlfid, conv.GetMembersType(),
boxed.ClientHeader.TlfPublic, boxed.ClientHeader.BotUID,
boxed.EphemeralMetadata().Generation, &boxed.ServerHeader.Ctime)
if err != nil {
b.Debug(ctx, "failed to get a key for ephemeral message: msgID: %d err: %v", boxed.ServerHeader.MessageID, err)
uberr = b.detectPermanentError(conv, err, tlfName)
if uberr.IsPermanent() {
return b.makeErrorMessage(ctx, boxed, uberr), nil
}
return chat1.MessageUnboxed{}, uberr
}
}
info.Key = encryptionKey
info.EphemeralKey = ephemeralKey
}
unboxed, ierr := b.unbox(ctx, boxed, conv, info.Key, info.EphemeralKey)
if ierr == nil {
ierr = b.checkInvariants(ctx, conv.GetConvID(), boxed, unboxed)
}
if ierr != nil {
b.Debug(ctx, "failed to unbox message: msgID: %d err: %s", boxed.ServerHeader.MessageID,
ierr.Error())
if ierr.IsPermanent() {
return b.makeErrorMessage(ctx, boxed, ierr), nil
}
return chat1.MessageUnboxed{}, ierr
}
return chat1.NewMessageUnboxedWithValid(*unboxed), nil
}
func (b *Boxer) checkInvariants(ctx context.Context, convID chat1.ConversationID, boxed chat1.MessageBoxed, unboxed *chat1.MessageUnboxedValid) types.UnboxingError {
// Check that the ConversationIDTriple in the signed message header matches
// the conversation ID we were expecting.
if !unboxed.ClientHeader.Conv.Derivable(convID) {
err := fmt.Errorf("conversation ID mismatch: header: %x convID: %s",
unboxed.ClientHeader.Conv.Hash(), convID)
return NewPermanentUnboxingError(err)
}
// Check that message type on the client header matches the body
body := unboxed.MessageBody
if !body.IsNil() {
bodyTyp, err := body.MessageType()
if err != nil {
return NewPermanentUnboxingError(err)
}
if unboxed.ClientHeader.MessageType != bodyTyp {
err := fmt.Errorf("client header message type does not match body: %v(header) != %v(body)",
unboxed.ClientHeader.MessageType, bodyTyp)
return NewPermanentUnboxingError(err)
}
}
// Make sure the body hash is unique to this message, and then record it.
// This detects attempts by the server to replay a message. Right now we
// use a "first writer wins" rule here, though we could also consider a
// "duplication invalidates both" rule if we wanted to be stricter. Note
// that this only prevents replays of messages you *know about*. There's
// currently nothing stopping the server from replaying an ancient message
// if you're never going to fetch enough history to notice.
//
// But...wait...why aren't we using the header hash here? It covers more
// stuff, and we're using it below, when we check the consistency of
// messages and prev pointers...
//
// The reason we can't use the header hash to prevent replays is that it's
// a hash *of* a signature, rather than a hash that's *been signed*.
// Unfortunately, most signature schemes are "malleable" in some way,
// depending on the implementation. See
// http://crypto.stackexchange.com/a/14719/21442. If I have the shared
// encryption key (and recall that in public chats, everyone does), I can
// decrypt the message, twiddle your signature into another valid signature
// over the same plaintext, reencrypt the whole thing, and pass it off as a
// new valid message with a seemingly new signature and therefore a unique
// header hash. Because the body hash is unique to each message (derived
// from a random nonce), and because it's *inside* the signature, we use
// that to detect replays instead.
replayErr := storage.CheckAndRecordBodyHash(ctx, b.G(), unboxed.BodyHash, boxed.ServerHeader.MessageID, convID)
if replayErr != nil {
b.Debug(ctx, "UnboxMessage found a replayed body hash: %s", replayErr)
return NewPermanentUnboxingError(replayErr)
}
// Make sure the header hash and prev pointers of this message are
// consistent with every other message we've seen, and record them.
//
// The discussion above explains why we have to use the body hash there to
// prevent replays. But we need to use the header hash here, because it's
// the only thing that covers the entire message. The goal isn't to prevent
// the creation of new messages (as it was above), but to prevent an old
// message from changing.
prevPtrErr := storage.CheckAndRecordPrevPointer(ctx, b.G(), boxed.ServerHeader.MessageID, convID, unboxed.HeaderHash)
if prevPtrErr != nil {
b.Debug(ctx, "UnboxMessage found an inconsistent header hash: %s", prevPtrErr)
return NewPermanentUnboxingError(prevPtrErr)
}
for _, prevPtr := range unboxed.ClientHeader.Prev {
prevPtrErr := storage.CheckAndRecordPrevPointer(ctx, b.G(), prevPtr.Id, convID, prevPtr.Hash)
if prevPtrErr != nil {
b.Debug(ctx, "UnboxMessage found an inconsistent prev pointer: %s", prevPtrErr)
return NewPermanentUnboxingError(prevPtrErr)
}
}
return nil
}
func (b *Boxer) unbox(ctx context.Context, boxed chat1.MessageBoxed,
conv types.UnboxConversationInfo, encryptionKey types.CryptKey,
ephemeralKey types.EphemeralCryptKey) (*chat1.MessageUnboxedValid, types.UnboxingError) {
switch boxed.Version {
case chat1.MessageBoxedVersion_VNONE, chat1.MessageBoxedVersion_V1:
res, err := b.unboxV1(ctx, boxed, conv, encryptionKey)
if err != nil {
b.Debug(ctx, "error unboxing message version: %v", boxed.Version)
}
return res, err
// V3 is the same as V2, except that it indicates exploding message support.
// V4 is the same as V3, except if pairwise MACs are included, then the sender signing key is a dummy.
case chat1.MessageBoxedVersion_V2, chat1.MessageBoxedVersion_V3, chat1.MessageBoxedVersion_V4:
res, err := b.unboxV2orV3orV4(ctx, boxed, conv, encryptionKey, ephemeralKey)
if err != nil {
b.Debug(ctx, "error unboxing message version: %v, %s", boxed.Version, err)
}
return res, err
// NOTE: When adding new versions here, you must also update
// chat1/extras.go so MessageUnboxedError.ParseableVersion understands the
// new max version
default:
return nil,
NewPermanentUnboxingError(NewMessageBoxedVersionError(boxed.Version))
}
}
func (b *Boxer) headerUnsupported(ctx context.Context, headerVersion chat1.HeaderPlaintextVersion,
header chat1.HeaderPlaintext) chat1.HeaderPlaintextUnsupported {
switch headerVersion {
case chat1.HeaderPlaintextVersion_V2:
return header.V2()
case chat1.HeaderPlaintextVersion_V3:
return header.V3()
case chat1.HeaderPlaintextVersion_V4:
return header.V4()
case chat1.HeaderPlaintextVersion_V5:
return header.V5()
case chat1.HeaderPlaintextVersion_V6:
return header.V6()
case chat1.HeaderPlaintextVersion_V7:
return header.V7()
case chat1.HeaderPlaintextVersion_V8:
return header.V8()
case chat1.HeaderPlaintextVersion_V9:
return header.V9()
case chat1.HeaderPlaintextVersion_V10:
return header.V10()
default:
b.Debug(ctx, "headerUnsupported: unknown version: %v", headerVersion)
return chat1.HeaderPlaintextUnsupported{
Mi: chat1.HeaderPlaintextMetaInfo{
Crit: true,
},
}
}
}
func (b *Boxer) bodyUnsupported(ctx context.Context, bodyVersion chat1.BodyPlaintextVersion,
body chat1.BodyPlaintext) chat1.BodyPlaintextUnsupported {
switch bodyVersion {
case chat1.BodyPlaintextVersion_V3:
return body.V3()
case chat1.BodyPlaintextVersion_V4:
return body.V4()
case chat1.BodyPlaintextVersion_V5:
return body.V5()
case chat1.BodyPlaintextVersion_V6:
return body.V6()
case chat1.BodyPlaintextVersion_V7:
return body.V7()
case chat1.BodyPlaintextVersion_V8:
return body.V8()
case chat1.BodyPlaintextVersion_V9:
return body.V9()
case chat1.BodyPlaintextVersion_V10:
return body.V10()
default:
b.Debug(ctx, "bodyUnsupported: unknown version: %v", bodyVersion)
return chat1.BodyPlaintextUnsupported{
Mi: chat1.BodyPlaintextMetaInfo{
Crit: true,
},
}
}
}
// unboxV1 unboxes a chat1.MessageBoxed into a keybase1.Message given
// a keybase1.CryptKey.
func (b *Boxer) unboxV1(ctx context.Context, boxed chat1.MessageBoxed,
conv types.UnboxConversationInfo, encryptionKey types.CryptKey) (*chat1.MessageUnboxedValid, types.UnboxingError) {
var err error
if boxed.ServerHeader == nil {
return nil, NewPermanentUnboxingError(errors.New("nil ServerHeader in MessageBoxed"))
}
if len(boxed.VerifyKey) != 0 {
return nil, NewPermanentUnboxingError(errors.New("populated VerifyKey in MBV1"))
}
// compute the header hash
headerHash := b.hashV1(boxed.HeaderCiphertext.E)
// Whether the body is missing (deleted)
skipBodyVerification := (len(boxed.BodyCiphertext.E) == 0)
// TODO We should check whether the body is allowed to have been deleted by checking
// that there is in fact a message that deleted it.
// We should fetch that message and check its signed body.
// That involves fetching a message whose ID is not known here.
// decrypt body
// will remain empty if the body was deleted
var bodyVersioned chat1.BodyPlaintext
if !skipBodyVerification {
packedBody, err := b.open(boxed.BodyCiphertext, libkb.NaclSecretBoxKey(encryptionKey.Material()))
if err != nil {
return nil, NewPermanentUnboxingError(err)
}
if err := b.unmarshal(packedBody, &bodyVersioned); err != nil {
return nil, NewPermanentUnboxingError(err)
}
}
// decrypt header
packedHeader, err := b.open(boxed.HeaderCiphertext.AsEncrypted(), libkb.NaclSecretBoxKey(encryptionKey.Material()))
if err != nil {
return nil, NewPermanentUnboxingError(err)
}
var header chat1.HeaderPlaintext
if err := b.unmarshal(packedHeader, &header); err != nil {
return nil, NewPermanentUnboxingError(err)
}
// verify the message
validity, ierr := b.verifyMessageV1(ctx, header, boxed, skipBodyVerification)
if ierr != nil {
return nil, ierr
}
// create a chat1.MessageClientHeader from versioned HeaderPlaintext
var clientHeader chat1.MessageClientHeaderVerified
headerVersion, err := header.Version()
if err != nil {
return nil, NewPermanentUnboxingError(err)
}
rtime := gregor1.ToTime(b.clock.Now())
if boxed.ServerHeader.Rtime != nil {
rtime = *boxed.ServerHeader.Rtime
}
var headerSignature *chat1.SignatureInfo
var bodyHash chat1.Hash
switch headerVersion {
case chat1.HeaderPlaintextVersion_V1:
// Verified above in verifyMessageV1
headerSignature = header.V1().HeaderSignature
hp := header.V1()
bodyHash = hp.BodyHash
clientHeader = chat1.MessageClientHeaderVerified{
Conv: hp.Conv,
TlfName: hp.TlfName,
TlfPublic: hp.TlfPublic,
MessageType: hp.MessageType,
Prev: hp.Prev,
Sender: hp.Sender,
SenderDevice: hp.SenderDevice,
// MerkleRoot is not expected to be in any v1 messages. Ignore it.
MerkleRoot: nil,
OutboxID: hp.OutboxID,
OutboxInfo: hp.OutboxInfo,
KbfsCryptKeysUsed: hp.KbfsCryptKeysUsed,
Rtime: rtime,
}
// NOTE: When adding new versions here, you must also update
// chat1/extras.go so MessageUnboxedError.ParseableVersion understands the
// new max version
default:
return nil,
NewPermanentUnboxingError(NewHeaderVersionError(headerVersion,
b.headerUnsupported(ctx, headerVersion, header)))
}
// Check for sender match on the inner and outer header.
if !clientHeader.Sender.Eq(boxed.ClientHeader.Sender) {
return nil, NewPermanentUnboxingError(fmt.Errorf("sender does not match"))
}
if !bytes.Equal(clientHeader.SenderDevice.Bytes(), boxed.ClientHeader.SenderDevice.Bytes()) {
return nil, NewPermanentUnboxingError(fmt.Errorf("sender device does not match"))
}
// Any of (senderUsername, senderDeviceName, senderDeviceType) could be empty strings because of non-critical failures.
senderUsername, senderDeviceName, senderDeviceType := b.getSenderInfoLocal(
ctx, clientHeader.Sender, clientHeader.SenderDevice)
// create a chat1.MessageBody from versioned chat1.BodyPlaintext
// Will remain empty if the body was deleted.
var body chat1.MessageBody
if !skipBodyVerification {
bodyVersion, err := bodyVersioned.Version()
if err != nil {
return nil, NewPermanentUnboxingError(err)
}
switch bodyVersion {
case chat1.BodyPlaintextVersion_V1:
body = bodyVersioned.V1().MessageBody
// NOTE: When adding new versions here, you must also update
// chat1/extras.go so MessageUnboxedError.ParseableVersion understands the
// new max version
default:
return nil,
NewPermanentUnboxingError(NewBodyVersionError(bodyVersion,
b.bodyUnsupported(ctx, bodyVersion, bodyVersioned)))
}
}
// Get at mention usernames
atMentions, atMentionUsernames, maybeRes, chanMention, channelNameMentions :=
b.getAtMentionInfo(ctx, clientHeader.Conv.Tlfid, clientHeader.Conv.TopicType, conv, body)
ierr = b.compareHeadersMBV1(ctx, boxed.ClientHeader, clientHeader)
if ierr != nil {
return nil, ierr
}
// create an unboxed message
return &chat1.MessageUnboxedValid{
ClientHeader: clientHeader,
ServerHeader: *boxed.ServerHeader,
MessageBody: body,
SenderUsername: senderUsername,
SenderDeviceName: senderDeviceName,
SenderDeviceType: senderDeviceType,
BodyHash: bodyHash,
HeaderHash: headerHash,
HeaderSignature: headerSignature,
VerificationKey: &validity.validationKey,
SenderDeviceRevokedAt: validity.senderDeviceRevokedAt,
AtMentions: atMentions,
AtMentionUsernames: atMentionUsernames,
ChannelMention: chanMention,
ChannelNameMentions: channelNameMentions,
MaybeMentions: maybeRes,
BotUsername: b.getBotInfoLocal(ctx, clientHeader.BotUID),
Emojis: b.getEmojis(ctx, clientHeader.Conv.TopicType, body),
}, nil
}
func (b *Boxer) memberCtime(mctx libkb.MetaContext, conv types.UnboxConversationInfo, tlfID chat1.TLFID, tlfName string) (*keybase1.Time, error) {
team, err := NewTeamLoader(b.G().ExternalG()).loadTeam(mctx.Ctx(), tlfID, tlfName,
conv.GetMembersType(), conv.IsPublic(), nil)
if err != nil {
return nil, err
}
uv, err := mctx.G().GetMeUV(mctx.Ctx())
if err != nil {
return nil, err
}
return team.MemberCtime(mctx.Ctx(), uv), nil
}
func (b *Boxer) validatePairwiseMAC(ctx context.Context, boxed chat1.MessageBoxed,
conv types.UnboxConversationInfo, headerHash chat1.Hash) (senderKey []byte, err error) {
defer b.Trace(ctx, &err, "validatePairwiseMAC")()
// First, find a MAC that matches our receiving device encryption KID.
ourDeviceKeyNacl, err := b.G().ActiveDevice.NaclEncryptionKey()
if err != nil {
return nil, err
}
messageMAC, found := boxed.ClientHeader.PairwiseMacs[ourDeviceKeyNacl.GetKID()]
if !found {
// This is an error users will actually see when they've just joined a
// team or added a new device.
mctx := b.G().MetaContext(ctx)
memberCtime, err := b.memberCtime(mctx, conv, boxed.ClientHeader.Conv.Tlfid, boxed.ClientHeader.TlfName)
if err != nil {
b.Debug(ctx, "Unable to get member ctime: %v", err)
}
return nil, NewNotAuthenticatedForThisDeviceError(mctx,
memberCtime, boxed.ServerHeader.Ctime)
}
// Second, load the device encryption KID for the sender.
senderUID, err := keybase1.UIDFromSlice(boxed.ClientHeader.Sender)
if err != nil {
return nil, err
}
senderDeviceID, err := keybase1.DeviceIDFromSlice(boxed.ClientHeader.SenderDevice)
if err != nil {
return nil, err
}
// Use the loading function that hits the server if-and-only-if we don't
// have the given deviceID in cache.
senderUPAK, err := b.G().GetUPAKLoader().LoadUPAKWithDeviceID(ctx, senderUID, senderDeviceID)
if err != nil {
return nil, err
}
senderEncryptionKID := senderUPAK.Current.FindEncryptionKIDFromDeviceID(senderDeviceID)
if senderEncryptionKID.IsNil() {
for _, upk := range senderUPAK.PastIncarnations {
senderEncryptionKID = upk.FindEncryptionKIDFromDeviceID(senderDeviceID)
if !senderEncryptionKID.IsNil() {
break
}
}
if senderEncryptionKID.IsNil() {
return nil, fmt.Errorf("failed to find encryption key for device %s", senderDeviceID.String())
}
}
senderDeviceDHKeyNacl, err := libkb.ImportDHKeypairFromKID(senderEncryptionKID)
if err != nil {
return nil, err
}
// Finally, validate the MAC.
computedMAC := makeOnePairwiseMAC(*ourDeviceKeyNacl.Private, senderDeviceDHKeyNacl.Public, headerHash)
if !hmac.Equal(messageMAC, computedMAC) {
return nil, NewInvalidMACError()
}
return senderEncryptionKID.ToBytes(), nil
}
func (b *Boxer) ResolveSkippedUnboxed(ctx context.Context, msg chat1.MessageUnboxed) (res chat1.MessageUnboxed, modified bool, err types.UnboxingError) {
if !msg.IsValid() {
return msg, false, nil
}
if msg.Valid().VerificationKey == nil {
return msg, false, nil
}
// verify sender key
revokedAt, ierr := b.ValidSenderKey(ctx, msg.Valid().ClientHeader.Sender, *msg.Valid().VerificationKey,
msg.Valid().ServerHeader.Ctime)
if ierr != nil {
if ierr.IsPermanent() {
return b.makeErrorMessageFromPieces(ctx, ierr, msg.GetMessageID(), msg.GetMessageType(),
msg.Valid().ServerHeader.Ctime, msg.Valid().ClientHeader.Sender,
msg.Valid().ClientHeader.SenderDevice,
msg.Valid().ClientHeader.BotUID, msg.Valid().IsEphemeral(),
msg.Valid().ExplodedBy(), msg.Valid().Etime()), true, nil
}
return msg, false, ierr
}
mvalid := msg.Valid()
mvalid.SenderDeviceRevokedAt = revokedAt
return chat1.NewMessageUnboxedWithValid(mvalid), revokedAt != nil, nil
}
func (b *Boxer) ResolveSkippedUnboxeds(ctx context.Context, msgs []chat1.MessageUnboxed) (res []chat1.MessageUnboxed, modifiedMap map[chat1.MessageID]bool, err types.UnboxingError) {
modifiedMap = make(map[chat1.MessageID]bool)
for _, msg := range msgs {
rmsg, modified, err := b.ResolveSkippedUnboxed(ctx, msg)
if err != nil {
return res, modifiedMap, err
}
modifiedMap[rmsg.GetMessageID()] = modified
res = append(res, rmsg)
}
return res, modifiedMap, nil
}
func (b *Boxer) unboxV2orV3orV4(ctx context.Context, boxed chat1.MessageBoxed,
conv types.UnboxConversationInfo, baseEncryptionKey types.CryptKey,
ephemeralKey types.EphemeralCryptKey) (*chat1.MessageUnboxedValid, types.UnboxingError) {
if boxed.ServerHeader == nil {
return nil, NewPermanentUnboxingError(errors.New("nil ServerHeader in MessageBoxed"))
}
// Compute the header hash
headerHash, ierr := b.makeHeaderHash(boxed.HeaderCiphertext.AsSignEncrypted())
if ierr != nil {
return nil, ierr
}
// Regular messages use the same encryption key for the header and for the
// body. Exploding messages use a derived ephemeral key for the body.
headerEncryptionKey, err := libkb.DeriveSymmetricKey(
libkb.NaclSecretBoxKey(baseEncryptionKey.Material()), libkb.EncryptionReasonChatMessage)
if err != nil {
return nil, NewPermanentUnboxingError(err)
}
bodyEncryptionKey := headerEncryptionKey
if boxed.IsEphemeral() {
bodyEncryptionKey, err = libkb.DeriveFromSecret(ephemeralKey.Material(), libkb.DeriveReasonTeamEKExplodingChat)
if err != nil {
return nil, NewPermanentUnboxingError(err)
}
}
// Validate verification key against unverified sender id.
// Later it is asserted that the claimed and signing sender are the same.
// ValidSenderKey uses the server-given ctime, but emits senderDeviceRevokedAt as a workaround.
// See ValidSenderKey for details.
if boxed.VerifyKey == nil {
return nil, NewPermanentUnboxingError(libkb.NoKeyError{Msg: "sender key missing"})
}
// This will be the message's signing key in the normal case, and the
// sending device's encryption key in the pairwise MAC case.
senderKeyToValidate := boxed.VerifyKey
// When pairwise MACs are present (in practice only on exploding messages,
// but in theory we support them anywhere), we validate the one that's
// intended for our device, and error out if it's missing or invalid. If it
// is valid, then we *don't* validate the message signing key. That is,
// even though signEncryptOpen will check a signature in the end, we no
// longer care what signing key it's using.
if len(boxed.ClientHeader.PairwiseMacs) > 0 {
if boxed.Version != chat1.MessageBoxedVersion_V3 && !bytes.Equal(boxed.VerifyKey, dummySigningKey().GetKID().ToBytes()) {
return nil, NewPermanentUnboxingError(fmt.Errorf("expected dummy signing key (%s), got %s", dummySigningKey().GetKID(), hex.EncodeToString(boxed.VerifyKey)))
}
senderKeyToValidate, err = b.validatePairwiseMAC(ctx, boxed, conv, headerHash)
if err != nil {
// Return a transient error if possible
return nil, b.detectPermanentError(conv, err, boxed.ClientHeader.TlfName)
}
} else if bytes.Equal(boxed.VerifyKey, dummySigningKey().GetKID().ToBytes()) {
// Note that this can happen if the server is stripping MACs for some
// reason, for example if you're testing against an out-of-date server
// version.
return nil, NewPermanentUnboxingError(fmt.Errorf("unexpected dummy signing key with no pairwise MACs present"))
}
// If we validated a pairwise MAC above, then senderKeyToValidate will be
// the sender's device encryption key, instead of the VerifyKey from the
// message. In this case, ValidSenderKey is just fetching revocation info for us.
var senderDeviceRevokedAt *gregor1.Time
switch globals.CtxUnboxMode(ctx) {
case types.UnboxModeFull:
senderDeviceRevokedAt, ierr = b.ValidSenderKey(
ctx, boxed.ClientHeader.Sender, senderKeyToValidate, boxed.ServerHeader.Ctime)
if ierr != nil {
return nil, ierr
}
case types.UnboxModeQuick:
// we skip this check in quick mode, the idea is we will do it later asynchonously so we can
// deliver messages quicker to the UI.
}
// Open header and verify against VerifyKey
headerPacked, err := b.signEncryptOpen(boxed.HeaderCiphertext.AsSignEncrypted(), headerEncryptionKey,
boxed.VerifyKey, kbcrypto.SignaturePrefixChatMBv2)
if err != nil {
return nil, NewPermanentUnboxingError(err)
}
var headerVersioned chat1.HeaderPlaintext
err = b.unmarshal(headerPacked, &headerVersioned)
if err != nil {
return nil, NewPermanentUnboxingError(err)
}
// Unversion header
// Also check that the HeaderSignature field from MessageBoxed V1 is nil
// This object has been signed
clientHeader, bodyHashSigned, ierr := b.unversionHeaderMBV2(ctx, boxed.ServerHeader, headerVersioned)
if ierr != nil {
return nil, ierr
}
// Whether the body is missing (deleted)
isBodyDeleted := (len(boxed.BodyCiphertext.E) == 0)
// TODO We should check whether the body is allowed to have been deleted by checking
// that there is in fact a message that deleted it.
// We should fetch that message and check its signed body.
// That involves fetching a message whose ID is not known here.
// Verify body hash
// The hash of the encrypted body must match that signed into the header.
if !isBodyDeleted {
ierr = b.verifyBodyHash(ctx, boxed.BodyCiphertext, bodyHashSigned)
if ierr != nil {
return nil, ierr
}
}
// Compare the signed and unsigned header.
// Checks that [Sender, SenderDevice] match, and other things.
ierr = b.compareHeadersMBV2orV3(ctx, boxed.ClientHeader, clientHeader, boxed.Version)
if ierr != nil {
return nil, ierr
}
// Decrypt body
// If the body is deleted, this is left blank.
var body chat1.MessageBody
if !isBodyDeleted {
bodyPacked, err := b.open(boxed.BodyCiphertext, bodyEncryptionKey)
if err != nil {
return nil, NewPermanentUnboxingError(err)
}
var bodyVersioned chat1.BodyPlaintext
err = b.unmarshal(bodyPacked, &bodyVersioned)
if err != nil {
return nil, NewPermanentUnboxingError(err)
}
// Unversion the body
body, ierr = b.unversionBody(ctx, bodyVersioned)
if ierr != nil {
return nil, ierr
}
}
// Get sender info
// Any of (senderUsername, senderDeviceName, senderDeviceType) could be empty strings because of non-critical failures.
senderUsername, senderDeviceName, senderDeviceType := b.getSenderInfoLocal(
ctx, clientHeader.Sender, clientHeader.SenderDevice)
// Get at mention usernames
atMentions, atMentionUsernames, maybeRes, chanMention, channelNameMentions :=
b.getAtMentionInfo(ctx, clientHeader.Conv.Tlfid, clientHeader.Conv.TopicType, conv, body)
clientHeader.HasPairwiseMacs = len(boxed.ClientHeader.PairwiseMacs) > 0
// create an unboxed message