forked from elb3k/crypto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
otr.go
1419 lines (1225 loc) · 35.4 KB
/
otr.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 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package otr implements the Off The Record protocol as specified in
// http://www.cypherpunks.ca/otr/Protocol-v2-3.1.0.html
//
// The version of OTR implemented by this package has been deprecated
// (https://bugs.otr.im/lib/libotr/issues/140). An implementation of OTRv3 is
// available at https://github.com/coyim/otr3.
package otr // import "golang.org/x/crypto/otr"
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/dsa"
"crypto/hmac"
"crypto/rand"
"crypto/sha1"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"errors"
"hash"
"io"
"math/big"
"strconv"
)
// SecurityChange describes a change in the security state of a Conversation.
type SecurityChange int
const (
NoChange SecurityChange = iota
// NewKeys indicates that a key exchange has completed. This occurs
// when a conversation first becomes encrypted, and when the keys are
// renegotiated within an encrypted conversation.
NewKeys
// SMPSecretNeeded indicates that the peer has started an
// authentication and that we need to supply a secret. Call SMPQuestion
// to get the optional, human readable challenge and then Authenticate
// to supply the matching secret.
SMPSecretNeeded
// SMPComplete indicates that an authentication completed. The identity
// of the peer has now been confirmed.
SMPComplete
// SMPFailed indicates that an authentication failed.
SMPFailed
// ConversationEnded indicates that the peer ended the secure
// conversation.
ConversationEnded
)
// QueryMessage can be sent to a peer to start an OTR conversation.
var QueryMessage = "?OTRv2?"
// ErrorPrefix can be used to make an OTR error by appending an error message
// to it.
var ErrorPrefix = "?OTR Error:"
var (
fragmentPartSeparator = []byte(",")
fragmentPrefix = []byte("?OTR,")
msgPrefix = []byte("?OTR:")
queryMarker = []byte("?OTR")
)
// isQuery attempts to parse an OTR query from msg and returns the greatest
// common version, or 0 if msg is not an OTR query.
func isQuery(msg []byte) (greatestCommonVersion int) {
pos := bytes.Index(msg, queryMarker)
if pos == -1 {
return 0
}
for i, c := range msg[pos+len(queryMarker):] {
if i == 0 {
if c == '?' {
// Indicates support for version 1, but we don't
// implement that.
continue
}
if c != 'v' {
// Invalid message
return 0
}
continue
}
if c == '?' {
// End of message
return
}
if c == ' ' || c == '\t' {
// Probably an invalid message
return 0
}
if c == '2' {
greatestCommonVersion = 2
}
}
return 0
}
const (
statePlaintext = iota
stateEncrypted
stateFinished
)
const (
authStateNone = iota
authStateAwaitingDHKey
authStateAwaitingRevealSig
authStateAwaitingSig
)
const (
msgTypeDHCommit = 2
msgTypeData = 3
msgTypeDHKey = 10
msgTypeRevealSig = 17
msgTypeSig = 18
)
const (
// If the requested fragment size is less than this, it will be ignored.
minFragmentSize = 18
// Messages are padded to a multiple of this number of bytes.
paddingGranularity = 256
// The number of bytes in a Diffie-Hellman private value (320-bits).
dhPrivateBytes = 40
// The number of bytes needed to represent an element of the DSA
// subgroup (160-bits).
dsaSubgroupBytes = 20
// The number of bytes of the MAC that are sent on the wire (160-bits).
macPrefixBytes = 20
)
// These are the global, common group parameters for OTR.
var (
p *big.Int // group prime
g *big.Int // group generator
q *big.Int // group order
pMinus2 *big.Int
)
func init() {
p, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF", 16)
q, _ = new(big.Int).SetString("7FFFFFFFFFFFFFFFE487ED5110B4611A62633145C06E0E68948127044533E63A0105DF531D89CD9128A5043CC71A026EF7CA8CD9E69D218D98158536F92F8A1BA7F09AB6B6A8E122F242DABB312F3F637A262174D31BF6B585FFAE5B7A035BF6F71C35FDAD44CFD2D74F9208BE258FF324943328F6722D9EE1003E5C50B1DF82CC6D241B0E2AE9CD348B1FD47E9267AFC1B2AE91EE51D6CB0E3179AB1042A95DCF6A9483B84B4B36B3861AA7255E4C0278BA36046511B993FFFFFFFFFFFFFFFF", 16)
g = new(big.Int).SetInt64(2)
pMinus2 = new(big.Int).Sub(p, g)
}
// Conversation represents a relation with a peer. The zero value is a valid
// Conversation, although PrivateKey must be set.
//
// When communicating with a peer, all inbound messages should be passed to
// Conversation.Receive and all outbound messages to Conversation.Send. The
// Conversation will take care of maintaining the encryption state and
// negotiating encryption as needed.
type Conversation struct {
// PrivateKey contains the private key to use to sign key exchanges.
PrivateKey *PrivateKey
// Rand can be set to override the entropy source. Otherwise,
// crypto/rand will be used.
Rand io.Reader
// If FragmentSize is set, all messages produced by Receive and Send
// will be fragmented into messages of, at most, this number of bytes.
FragmentSize int
// Once Receive has returned NewKeys once, the following fields are
// valid.
SSID [8]byte
TheirPublicKey PublicKey
state, authState int
r [16]byte
x, y *big.Int
gx, gy *big.Int
gxBytes []byte
digest [sha256.Size]byte
revealKeys, sigKeys akeKeys
myKeyId uint32
myCurrentDHPub *big.Int
myCurrentDHPriv *big.Int
myLastDHPub *big.Int
myLastDHPriv *big.Int
theirKeyId uint32
theirCurrentDHPub *big.Int
theirLastDHPub *big.Int
keySlots [4]keySlot
myCounter [8]byte
theirLastCtr [8]byte
oldMACs []byte
k, n int // fragment state
frag []byte
smp smpState
}
// A keySlot contains key material for a specific (their keyid, my keyid) pair.
type keySlot struct {
// used is true if this slot is valid. If false, it's free for reuse.
used bool
theirKeyId uint32
myKeyId uint32
sendAESKey, recvAESKey []byte
sendMACKey, recvMACKey []byte
theirLastCtr [8]byte
}
// akeKeys are generated during key exchange. There's one set for the reveal
// signature message and another for the signature message. In the protocol
// spec the latter are indicated with a prime mark.
type akeKeys struct {
c [16]byte
m1, m2 [32]byte
}
func (c *Conversation) rand() io.Reader {
if c.Rand != nil {
return c.Rand
}
return rand.Reader
}
func (c *Conversation) randMPI(buf []byte) *big.Int {
_, err := io.ReadFull(c.rand(), buf)
if err != nil {
panic("otr: short read from random source")
}
return new(big.Int).SetBytes(buf)
}
// tlv represents the type-length value from the protocol.
type tlv struct {
typ, length uint16
data []byte
}
const (
tlvTypePadding = 0
tlvTypeDisconnected = 1
tlvTypeSMP1 = 2
tlvTypeSMP2 = 3
tlvTypeSMP3 = 4
tlvTypeSMP4 = 5
tlvTypeSMPAbort = 6
tlvTypeSMP1WithQuestion = 7
)
// Receive handles a message from a peer. It returns a human readable message,
// an indicator of whether that message was encrypted, a hint about the
// encryption state and zero or more messages to send back to the peer.
// These messages do not need to be passed to Send before transmission.
func (c *Conversation) Receive(in []byte) (out []byte, encrypted bool, change SecurityChange, toSend [][]byte, err error) {
if bytes.HasPrefix(in, fragmentPrefix) {
in, err = c.processFragment(in)
if in == nil || err != nil {
return
}
}
if bytes.HasPrefix(in, msgPrefix) && in[len(in)-1] == '.' {
in = in[len(msgPrefix) : len(in)-1]
} else if version := isQuery(in); version > 0 {
c.authState = authStateAwaitingDHKey
c.reset()
toSend = c.encode(c.generateDHCommit())
return
} else {
// plaintext message
out = in
return
}
msg := make([]byte, base64.StdEncoding.DecodedLen(len(in)))
msgLen, err := base64.StdEncoding.Decode(msg, in)
if err != nil {
err = errors.New("otr: invalid base64 encoding in message")
return
}
msg = msg[:msgLen]
// The first two bytes are the protocol version (2)
if len(msg) < 3 || msg[0] != 0 || msg[1] != 2 {
err = errors.New("otr: invalid OTR message")
return
}
msgType := int(msg[2])
msg = msg[3:]
switch msgType {
case msgTypeDHCommit:
switch c.authState {
case authStateNone:
c.authState = authStateAwaitingRevealSig
if err = c.processDHCommit(msg); err != nil {
return
}
c.reset()
toSend = c.encode(c.generateDHKey())
return
case authStateAwaitingDHKey:
// This is a 'SYN-crossing'. The greater digest wins.
var cmp int
if cmp, err = c.compareToDHCommit(msg); err != nil {
return
}
if cmp > 0 {
// We win. Retransmit DH commit.
toSend = c.encode(c.serializeDHCommit())
return
} else {
// They win. We forget about our DH commit.
c.authState = authStateAwaitingRevealSig
if err = c.processDHCommit(msg); err != nil {
return
}
c.reset()
toSend = c.encode(c.generateDHKey())
return
}
case authStateAwaitingRevealSig:
if err = c.processDHCommit(msg); err != nil {
return
}
toSend = c.encode(c.serializeDHKey())
case authStateAwaitingSig:
if err = c.processDHCommit(msg); err != nil {
return
}
c.reset()
toSend = c.encode(c.generateDHKey())
c.authState = authStateAwaitingRevealSig
default:
panic("bad state")
}
case msgTypeDHKey:
switch c.authState {
case authStateAwaitingDHKey:
var isSame bool
if isSame, err = c.processDHKey(msg); err != nil {
return
}
if isSame {
err = errors.New("otr: unexpected duplicate DH key")
return
}
toSend = c.encode(c.generateRevealSig())
c.authState = authStateAwaitingSig
case authStateAwaitingSig:
var isSame bool
if isSame, err = c.processDHKey(msg); err != nil {
return
}
if isSame {
toSend = c.encode(c.serializeDHKey())
}
}
case msgTypeRevealSig:
if c.authState != authStateAwaitingRevealSig {
return
}
if err = c.processRevealSig(msg); err != nil {
return
}
toSend = c.encode(c.generateSig())
c.authState = authStateNone
c.state = stateEncrypted
change = NewKeys
case msgTypeSig:
if c.authState != authStateAwaitingSig {
return
}
if err = c.processSig(msg); err != nil {
return
}
c.authState = authStateNone
c.state = stateEncrypted
change = NewKeys
case msgTypeData:
if c.state != stateEncrypted {
err = errors.New("otr: encrypted message received without encrypted session established")
return
}
var tlvs []tlv
out, tlvs, err = c.processData(msg)
encrypted = true
EachTLV:
for _, inTLV := range tlvs {
switch inTLV.typ {
case tlvTypeDisconnected:
change = ConversationEnded
c.state = stateFinished
break EachTLV
case tlvTypeSMP1, tlvTypeSMP2, tlvTypeSMP3, tlvTypeSMP4, tlvTypeSMPAbort, tlvTypeSMP1WithQuestion:
var reply tlv
var complete bool
reply, complete, err = c.processSMP(inTLV)
if err == smpSecretMissingError {
err = nil
change = SMPSecretNeeded
c.smp.saved = &inTLV
return
}
if err == smpFailureError {
err = nil
change = SMPFailed
} else if complete {
change = SMPComplete
}
if reply.typ != 0 {
toSend = c.encode(c.generateData(nil, &reply))
}
break EachTLV
default:
// skip unknown TLVs
}
}
default:
err = errors.New("otr: unknown message type " + strconv.Itoa(msgType))
}
return
}
// Send takes a human readable message from the local user, possibly encrypts
// it and returns zero one or more messages to send to the peer.
func (c *Conversation) Send(msg []byte) ([][]byte, error) {
switch c.state {
case statePlaintext:
return [][]byte{msg}, nil
case stateEncrypted:
return c.encode(c.generateData(msg, nil)), nil
case stateFinished:
return nil, errors.New("otr: cannot send message because secure conversation has finished")
}
return nil, errors.New("otr: cannot send message in current state")
}
// SMPQuestion returns the human readable challenge question from the peer.
// It's only valid after Receive has returned SMPSecretNeeded.
func (c *Conversation) SMPQuestion() string {
return c.smp.question
}
// Authenticate begins an authentication with the peer. Authentication involves
// an optional challenge message and a shared secret. The authentication
// proceeds until either Receive returns SMPComplete, SMPSecretNeeded (which
// indicates that a new authentication is happening and thus this one was
// aborted) or SMPFailed.
func (c *Conversation) Authenticate(question string, mutualSecret []byte) (toSend [][]byte, err error) {
if c.state != stateEncrypted {
err = errors.New("otr: can't authenticate a peer without a secure conversation established")
return
}
if c.smp.saved != nil {
c.calcSMPSecret(mutualSecret, false /* they started it */)
var out tlv
var complete bool
out, complete, err = c.processSMP(*c.smp.saved)
if complete {
panic("SMP completed on the first message")
}
c.smp.saved = nil
if out.typ != 0 {
toSend = c.encode(c.generateData(nil, &out))
}
return
}
c.calcSMPSecret(mutualSecret, true /* we started it */)
outs := c.startSMP(question)
for _, out := range outs {
toSend = append(toSend, c.encode(c.generateData(nil, &out))...)
}
return
}
// End ends a secure conversation by generating a termination message for
// the peer and switches to unencrypted communication.
func (c *Conversation) End() (toSend [][]byte) {
switch c.state {
case statePlaintext:
return nil
case stateEncrypted:
c.state = statePlaintext
return c.encode(c.generateData(nil, &tlv{typ: tlvTypeDisconnected}))
case stateFinished:
c.state = statePlaintext
return nil
}
panic("unreachable")
}
// IsEncrypted returns true if a message passed to Send would be encrypted
// before transmission. This result remains valid until the next call to
// Receive or End, which may change the state of the Conversation.
func (c *Conversation) IsEncrypted() bool {
return c.state == stateEncrypted
}
var fragmentError = errors.New("otr: invalid OTR fragment")
// processFragment processes a fragmented OTR message and possibly returns a
// complete message. Fragmented messages look like "?OTR,k,n,msg," where k is
// the fragment number (starting from 1), n is the number of fragments in this
// message and msg is a substring of the base64 encoded message.
func (c *Conversation) processFragment(in []byte) (out []byte, err error) {
in = in[len(fragmentPrefix):] // remove "?OTR,"
parts := bytes.Split(in, fragmentPartSeparator)
if len(parts) != 4 || len(parts[3]) != 0 {
return nil, fragmentError
}
k, err := strconv.Atoi(string(parts[0]))
if err != nil {
return nil, fragmentError
}
n, err := strconv.Atoi(string(parts[1]))
if err != nil {
return nil, fragmentError
}
if k < 1 || n < 1 || k > n {
return nil, fragmentError
}
if k == 1 {
c.frag = append(c.frag[:0], parts[2]...)
c.k, c.n = k, n
} else if n == c.n && k == c.k+1 {
c.frag = append(c.frag, parts[2]...)
c.k++
} else {
c.frag = c.frag[:0]
c.n, c.k = 0, 0
}
if c.n > 0 && c.k == c.n {
c.n, c.k = 0, 0
return c.frag, nil
}
return nil, nil
}
func (c *Conversation) generateDHCommit() []byte {
_, err := io.ReadFull(c.rand(), c.r[:])
if err != nil {
panic("otr: short read from random source")
}
var xBytes [dhPrivateBytes]byte
c.x = c.randMPI(xBytes[:])
c.gx = new(big.Int).Exp(g, c.x, p)
c.gy = nil
c.gxBytes = appendMPI(nil, c.gx)
h := sha256.New()
h.Write(c.gxBytes)
h.Sum(c.digest[:0])
aesCipher, err := aes.NewCipher(c.r[:])
if err != nil {
panic(err.Error())
}
var iv [aes.BlockSize]byte
ctr := cipher.NewCTR(aesCipher, iv[:])
ctr.XORKeyStream(c.gxBytes, c.gxBytes)
return c.serializeDHCommit()
}
func (c *Conversation) serializeDHCommit() []byte {
var ret []byte
ret = appendU16(ret, 2) // protocol version
ret = append(ret, msgTypeDHCommit)
ret = appendData(ret, c.gxBytes)
ret = appendData(ret, c.digest[:])
return ret
}
func (c *Conversation) processDHCommit(in []byte) error {
var ok1, ok2 bool
c.gxBytes, in, ok1 = getData(in)
digest, in, ok2 := getData(in)
if !ok1 || !ok2 || len(in) > 0 {
return errors.New("otr: corrupt DH commit message")
}
copy(c.digest[:], digest)
return nil
}
func (c *Conversation) compareToDHCommit(in []byte) (int, error) {
_, in, ok1 := getData(in)
digest, in, ok2 := getData(in)
if !ok1 || !ok2 || len(in) > 0 {
return 0, errors.New("otr: corrupt DH commit message")
}
return bytes.Compare(c.digest[:], digest), nil
}
func (c *Conversation) generateDHKey() []byte {
var yBytes [dhPrivateBytes]byte
c.y = c.randMPI(yBytes[:])
c.gy = new(big.Int).Exp(g, c.y, p)
return c.serializeDHKey()
}
func (c *Conversation) serializeDHKey() []byte {
var ret []byte
ret = appendU16(ret, 2) // protocol version
ret = append(ret, msgTypeDHKey)
ret = appendMPI(ret, c.gy)
return ret
}
func (c *Conversation) processDHKey(in []byte) (isSame bool, err error) {
gy, _, ok := getMPI(in)
if !ok {
err = errors.New("otr: corrupt DH key message")
return
}
if gy.Cmp(g) < 0 || gy.Cmp(pMinus2) > 0 {
err = errors.New("otr: DH value out of range")
return
}
if c.gy != nil {
isSame = c.gy.Cmp(gy) == 0
return
}
c.gy = gy
return
}
func (c *Conversation) generateEncryptedSignature(keys *akeKeys, xFirst bool) ([]byte, []byte) {
var xb []byte
xb = c.PrivateKey.PublicKey.Serialize(xb)
var verifyData []byte
if xFirst {
verifyData = appendMPI(verifyData, c.gx)
verifyData = appendMPI(verifyData, c.gy)
} else {
verifyData = appendMPI(verifyData, c.gy)
verifyData = appendMPI(verifyData, c.gx)
}
verifyData = append(verifyData, xb...)
verifyData = appendU32(verifyData, c.myKeyId)
mac := hmac.New(sha256.New, keys.m1[:])
mac.Write(verifyData)
mb := mac.Sum(nil)
xb = appendU32(xb, c.myKeyId)
xb = append(xb, c.PrivateKey.Sign(c.rand(), mb)...)
aesCipher, err := aes.NewCipher(keys.c[:])
if err != nil {
panic(err.Error())
}
var iv [aes.BlockSize]byte
ctr := cipher.NewCTR(aesCipher, iv[:])
ctr.XORKeyStream(xb, xb)
mac = hmac.New(sha256.New, keys.m2[:])
encryptedSig := appendData(nil, xb)
mac.Write(encryptedSig)
return encryptedSig, mac.Sum(nil)
}
func (c *Conversation) generateRevealSig() []byte {
s := new(big.Int).Exp(c.gy, c.x, p)
c.calcAKEKeys(s)
c.myKeyId++
encryptedSig, mac := c.generateEncryptedSignature(&c.revealKeys, true /* gx comes first */)
c.myCurrentDHPub = c.gx
c.myCurrentDHPriv = c.x
c.rotateDHKeys()
incCounter(&c.myCounter)
var ret []byte
ret = appendU16(ret, 2)
ret = append(ret, msgTypeRevealSig)
ret = appendData(ret, c.r[:])
ret = append(ret, encryptedSig...)
ret = append(ret, mac[:20]...)
return ret
}
func (c *Conversation) processEncryptedSig(encryptedSig, theirMAC []byte, keys *akeKeys, xFirst bool) error {
mac := hmac.New(sha256.New, keys.m2[:])
mac.Write(appendData(nil, encryptedSig))
myMAC := mac.Sum(nil)[:20]
if len(myMAC) != len(theirMAC) || subtle.ConstantTimeCompare(myMAC, theirMAC) == 0 {
return errors.New("bad signature MAC in encrypted signature")
}
aesCipher, err := aes.NewCipher(keys.c[:])
if err != nil {
panic(err.Error())
}
var iv [aes.BlockSize]byte
ctr := cipher.NewCTR(aesCipher, iv[:])
ctr.XORKeyStream(encryptedSig, encryptedSig)
sig := encryptedSig
sig, ok1 := c.TheirPublicKey.Parse(sig)
keyId, sig, ok2 := getU32(sig)
if !ok1 || !ok2 {
return errors.New("otr: corrupt encrypted signature")
}
var verifyData []byte
if xFirst {
verifyData = appendMPI(verifyData, c.gx)
verifyData = appendMPI(verifyData, c.gy)
} else {
verifyData = appendMPI(verifyData, c.gy)
verifyData = appendMPI(verifyData, c.gx)
}
verifyData = c.TheirPublicKey.Serialize(verifyData)
verifyData = appendU32(verifyData, keyId)
mac = hmac.New(sha256.New, keys.m1[:])
mac.Write(verifyData)
mb := mac.Sum(nil)
sig, ok1 = c.TheirPublicKey.Verify(mb, sig)
if !ok1 {
return errors.New("bad signature in encrypted signature")
}
if len(sig) > 0 {
return errors.New("corrupt encrypted signature")
}
c.theirKeyId = keyId
zero(c.theirLastCtr[:])
return nil
}
func (c *Conversation) processRevealSig(in []byte) error {
r, in, ok1 := getData(in)
encryptedSig, in, ok2 := getData(in)
theirMAC := in
if !ok1 || !ok2 || len(theirMAC) != 20 {
return errors.New("otr: corrupt reveal signature message")
}
aesCipher, err := aes.NewCipher(r)
if err != nil {
return errors.New("otr: cannot create AES cipher from reveal signature message: " + err.Error())
}
var iv [aes.BlockSize]byte
ctr := cipher.NewCTR(aesCipher, iv[:])
ctr.XORKeyStream(c.gxBytes, c.gxBytes)
h := sha256.New()
h.Write(c.gxBytes)
digest := h.Sum(nil)
if len(digest) != len(c.digest) || subtle.ConstantTimeCompare(digest, c.digest[:]) == 0 {
return errors.New("otr: bad commit MAC in reveal signature message")
}
var rest []byte
c.gx, rest, ok1 = getMPI(c.gxBytes)
if !ok1 || len(rest) > 0 {
return errors.New("otr: gx corrupt after decryption")
}
if c.gx.Cmp(g) < 0 || c.gx.Cmp(pMinus2) > 0 {
return errors.New("otr: DH value out of range")
}
s := new(big.Int).Exp(c.gx, c.y, p)
c.calcAKEKeys(s)
if err := c.processEncryptedSig(encryptedSig, theirMAC, &c.revealKeys, true /* gx comes first */); err != nil {
return errors.New("otr: in reveal signature message: " + err.Error())
}
c.theirCurrentDHPub = c.gx
c.theirLastDHPub = nil
return nil
}
func (c *Conversation) generateSig() []byte {
c.myKeyId++
encryptedSig, mac := c.generateEncryptedSignature(&c.sigKeys, false /* gy comes first */)
c.myCurrentDHPub = c.gy
c.myCurrentDHPriv = c.y
c.rotateDHKeys()
incCounter(&c.myCounter)
var ret []byte
ret = appendU16(ret, 2)
ret = append(ret, msgTypeSig)
ret = append(ret, encryptedSig...)
ret = append(ret, mac[:macPrefixBytes]...)
return ret
}
func (c *Conversation) processSig(in []byte) error {
encryptedSig, in, ok1 := getData(in)
theirMAC := in
if !ok1 || len(theirMAC) != macPrefixBytes {
return errors.New("otr: corrupt signature message")
}
if err := c.processEncryptedSig(encryptedSig, theirMAC, &c.sigKeys, false /* gy comes first */); err != nil {
return errors.New("otr: in signature message: " + err.Error())
}
c.theirCurrentDHPub = c.gy
c.theirLastDHPub = nil
return nil
}
func (c *Conversation) rotateDHKeys() {
// evict slots using our retired key id
for i := range c.keySlots {
slot := &c.keySlots[i]
if slot.used && slot.myKeyId == c.myKeyId-1 {
slot.used = false
c.oldMACs = append(c.oldMACs, slot.recvMACKey...)
}
}
c.myLastDHPriv = c.myCurrentDHPriv
c.myLastDHPub = c.myCurrentDHPub
var xBytes [dhPrivateBytes]byte
c.myCurrentDHPriv = c.randMPI(xBytes[:])
c.myCurrentDHPub = new(big.Int).Exp(g, c.myCurrentDHPriv, p)
c.myKeyId++
}
func (c *Conversation) processData(in []byte) (out []byte, tlvs []tlv, err error) {
origIn := in
flags, in, ok1 := getU8(in)
theirKeyId, in, ok2 := getU32(in)
myKeyId, in, ok3 := getU32(in)
y, in, ok4 := getMPI(in)
counter, in, ok5 := getNBytes(in, 8)
encrypted, in, ok6 := getData(in)
macedData := origIn[:len(origIn)-len(in)]
theirMAC, in, ok7 := getNBytes(in, macPrefixBytes)
_, in, ok8 := getData(in)
if !ok1 || !ok2 || !ok3 || !ok4 || !ok5 || !ok6 || !ok7 || !ok8 || len(in) > 0 {
err = errors.New("otr: corrupt data message")
return
}
ignoreErrors := flags&1 != 0
slot, err := c.calcDataKeys(myKeyId, theirKeyId)
if err != nil {
if ignoreErrors {
err = nil
}
return
}
mac := hmac.New(sha1.New, slot.recvMACKey)
mac.Write([]byte{0, 2, 3})
mac.Write(macedData)
myMAC := mac.Sum(nil)
if len(myMAC) != len(theirMAC) || subtle.ConstantTimeCompare(myMAC, theirMAC) == 0 {
if !ignoreErrors {
err = errors.New("otr: bad MAC on data message")
}
return
}
if bytes.Compare(counter, slot.theirLastCtr[:]) <= 0 {
err = errors.New("otr: counter regressed")
return
}
copy(slot.theirLastCtr[:], counter)
var iv [aes.BlockSize]byte
copy(iv[:], counter)
aesCipher, err := aes.NewCipher(slot.recvAESKey)
if err != nil {
panic(err.Error())
}
ctr := cipher.NewCTR(aesCipher, iv[:])
ctr.XORKeyStream(encrypted, encrypted)
decrypted := encrypted
if myKeyId == c.myKeyId {
c.rotateDHKeys()
}
if theirKeyId == c.theirKeyId {
// evict slots using their retired key id
for i := range c.keySlots {
slot := &c.keySlots[i]
if slot.used && slot.theirKeyId == theirKeyId-1 {
slot.used = false
c.oldMACs = append(c.oldMACs, slot.recvMACKey...)
}
}
c.theirLastDHPub = c.theirCurrentDHPub
c.theirKeyId++
c.theirCurrentDHPub = y
}
if nulPos := bytes.IndexByte(decrypted, 0); nulPos >= 0 {
out = decrypted[:nulPos]
tlvData := decrypted[nulPos+1:]
for len(tlvData) > 0 {
var t tlv
var ok1, ok2, ok3 bool
t.typ, tlvData, ok1 = getU16(tlvData)
t.length, tlvData, ok2 = getU16(tlvData)
t.data, tlvData, ok3 = getNBytes(tlvData, int(t.length))
if !ok1 || !ok2 || !ok3 {
err = errors.New("otr: corrupt tlv data")
return
}
tlvs = append(tlvs, t)
}
} else {
out = decrypted
}
return
}
func (c *Conversation) generateData(msg []byte, extra *tlv) []byte {
slot, err := c.calcDataKeys(c.myKeyId-1, c.theirKeyId)
if err != nil {
panic("otr: failed to generate sending keys: " + err.Error())
}
var plaintext []byte
plaintext = append(plaintext, msg...)
plaintext = append(plaintext, 0)
padding := paddingGranularity - ((len(plaintext) + 4) % paddingGranularity)
plaintext = appendU16(plaintext, tlvTypePadding)
plaintext = appendU16(plaintext, uint16(padding))
for i := 0; i < padding; i++ {
plaintext = append(plaintext, 0)
}
if extra != nil {
plaintext = appendU16(plaintext, extra.typ)
plaintext = appendU16(plaintext, uint16(len(extra.data)))
plaintext = append(plaintext, extra.data...)
}
encrypted := make([]byte, len(plaintext))
var iv [aes.BlockSize]byte
copy(iv[:], c.myCounter[:])
aesCipher, err := aes.NewCipher(slot.sendAESKey)
if err != nil {
panic(err.Error())
}
ctr := cipher.NewCTR(aesCipher, iv[:])
ctr.XORKeyStream(encrypted, plaintext)
var ret []byte
ret = appendU16(ret, 2)
ret = append(ret, msgTypeData)
ret = append(ret, 0 /* flags */)
ret = appendU32(ret, c.myKeyId-1)
ret = appendU32(ret, c.theirKeyId)