1 // Copyright 2012 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package otr implements the Off The Record protocol as specified in
6 // http://www.cypherpunks.ca/otr/Protocol-v2-3.1.0.html
7 package otr // import "golang.org/x/crypto/otr"
28 // SecurityChange describes a change in the security state of a Conversation.
29 type SecurityChange int
32 NoChange SecurityChange = iota
33 // NewKeys indicates that a key exchange has completed. This occurs
34 // when a conversation first becomes encrypted, and when the keys are
35 // renegotiated within an encrypted conversation.
37 // SMPSecretNeeded indicates that the peer has started an
38 // authentication and that we need to supply a secret. Call SMPQuestion
39 // to get the optional, human readable challenge and then Authenticate
40 // to supply the matching secret.
42 // SMPComplete indicates that an authentication completed. The identity
43 // of the peer has now been confirmed.
45 // SMPFailed indicates that an authentication failed.
47 // ConversationEnded indicates that the peer ended the secure
52 // QueryMessage can be sent to a peer to start an OTR conversation.
53 var QueryMessage = "?OTRv2?"
55 // ErrorPrefix can be used to make an OTR error by appending an error message
57 var ErrorPrefix = "?OTR Error:"
60 fragmentPartSeparator = []byte(",")
61 fragmentPrefix = []byte("?OTR,")
62 msgPrefix = []byte("?OTR:")
63 queryMarker = []byte("?OTR")
66 // isQuery attempts to parse an OTR query from msg and returns the greatest
67 // common version, or 0 if msg is not an OTR query.
68 func isQuery(msg []byte) (greatestCommonVersion int) {
69 pos := bytes.Index(msg, queryMarker)
73 for i, c := range msg[pos+len(queryMarker):] {
76 // Indicates support for version 1, but we don't
94 if c == ' ' || c == '\t' {
95 // Probably an invalid message
100 greatestCommonVersion = 2
108 statePlaintext = iota
115 authStateAwaitingDHKey
116 authStateAwaitingRevealSig
124 msgTypeRevealSig = 17
129 // If the requested fragment size is less than this, it will be ignored.
131 // Messages are padded to a multiple of this number of bytes.
132 paddingGranularity = 256
133 // The number of bytes in a Diffie-Hellman private value (320-bits).
135 // The number of bytes needed to represent an element of the DSA
136 // subgroup (160-bits).
137 dsaSubgroupBytes = 20
138 // The number of bytes of the MAC that are sent on the wire (160-bits).
142 // These are the global, common group parameters for OTR.
144 p *big.Int // group prime
145 g *big.Int // group generator
146 q *big.Int // group order
151 p, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF", 16)
152 q, _ = new(big.Int).SetString("7FFFFFFFFFFFFFFFE487ED5110B4611A62633145C06E0E68948127044533E63A0105DF531D89CD9128A5043CC71A026EF7CA8CD9E69D218D98158536F92F8A1BA7F09AB6B6A8E122F242DABB312F3F637A262174D31BF6B585FFAE5B7A035BF6F71C35FDAD44CFD2D74F9208BE258FF324943328F6722D9EE1003E5C50B1DF82CC6D241B0E2AE9CD348B1FD47E9267AFC1B2AE91EE51D6CB0E3179AB1042A95DCF6A9483B84B4B36B3861AA7255E4C0278BA36046511B993FFFFFFFFFFFFFFFF", 16)
153 g = new(big.Int).SetInt64(2)
154 pMinus2 = new(big.Int).Sub(p, g)
157 // Conversation represents a relation with a peer. The zero value is a valid
158 // Conversation, although PrivateKey must be set.
160 // When communicating with a peer, all inbound messages should be passed to
161 // Conversation.Receive and all outbound messages to Conversation.Send. The
162 // Conversation will take care of maintaining the encryption state and
163 // negotiating encryption as needed.
164 type Conversation struct {
165 // PrivateKey contains the private key to use to sign key exchanges.
166 PrivateKey *PrivateKey
168 // Rand can be set to override the entropy source. Otherwise,
169 // crypto/rand will be used.
171 // If FragmentSize is set, all messages produced by Receive and Send
172 // will be fragmented into messages of, at most, this number of bytes.
175 // Once Receive has returned NewKeys once, the following fields are
178 TheirPublicKey PublicKey
186 digest [sha256.Size]byte
188 revealKeys, sigKeys akeKeys
191 myCurrentDHPub *big.Int
192 myCurrentDHPriv *big.Int
194 myLastDHPriv *big.Int
197 theirCurrentDHPub *big.Int
198 theirLastDHPub *big.Int
206 k, n int // fragment state
212 // A keySlot contains key material for a specific (their keyid, my keyid) pair.
213 type keySlot struct {
214 // used is true if this slot is valid. If false, it's free for reuse.
218 sendAESKey, recvAESKey []byte
219 sendMACKey, recvMACKey []byte
223 // akeKeys are generated during key exchange. There's one set for the reveal
224 // signature message and another for the signature message. In the protocol
225 // spec the latter are indicated with a prime mark.
226 type akeKeys struct {
231 func (c *Conversation) rand() io.Reader {
238 func (c *Conversation) randMPI(buf []byte) *big.Int {
239 _, err := io.ReadFull(c.rand(), buf)
241 panic("otr: short read from random source")
244 return new(big.Int).SetBytes(buf)
247 // tlv represents the type-length value from the protocol.
255 tlvTypeDisconnected = 1
261 tlvTypeSMP1WithQuestion = 7
264 // Receive handles a message from a peer. It returns a human readable message,
265 // an indicator of whether that message was encrypted, a hint about the
266 // encryption state and zero or more messages to send back to the peer.
267 // These messages do not need to be passed to Send before transmission.
268 func (c *Conversation) Receive(in []byte) (out []byte, encrypted bool, change SecurityChange, toSend [][]byte, err error) {
269 if bytes.HasPrefix(in, fragmentPrefix) {
270 in, err = c.processFragment(in)
271 if in == nil || err != nil {
276 if bytes.HasPrefix(in, msgPrefix) && in[len(in)-1] == '.' {
277 in = in[len(msgPrefix) : len(in)-1]
278 } else if version := isQuery(in); version > 0 {
279 c.authState = authStateAwaitingDHKey
281 toSend = c.encode(c.generateDHCommit())
289 msg := make([]byte, base64.StdEncoding.DecodedLen(len(in)))
290 msgLen, err := base64.StdEncoding.Decode(msg, in)
292 err = errors.New("otr: invalid base64 encoding in message")
297 // The first two bytes are the protocol version (2)
298 if len(msg) < 3 || msg[0] != 0 || msg[1] != 2 {
299 err = errors.New("otr: invalid OTR message")
303 msgType := int(msg[2])
307 case msgTypeDHCommit:
310 c.authState = authStateAwaitingRevealSig
311 if err = c.processDHCommit(msg); err != nil {
315 toSend = c.encode(c.generateDHKey())
317 case authStateAwaitingDHKey:
318 // This is a 'SYN-crossing'. The greater digest wins.
320 if cmp, err = c.compareToDHCommit(msg); err != nil {
324 // We win. Retransmit DH commit.
325 toSend = c.encode(c.serializeDHCommit())
328 // They win. We forget about our DH commit.
329 c.authState = authStateAwaitingRevealSig
330 if err = c.processDHCommit(msg); err != nil {
334 toSend = c.encode(c.generateDHKey())
337 case authStateAwaitingRevealSig:
338 if err = c.processDHCommit(msg); err != nil {
341 toSend = c.encode(c.serializeDHKey())
342 case authStateAwaitingSig:
343 if err = c.processDHCommit(msg); err != nil {
347 toSend = c.encode(c.generateDHKey())
348 c.authState = authStateAwaitingRevealSig
354 case authStateAwaitingDHKey:
356 if isSame, err = c.processDHKey(msg); err != nil {
360 err = errors.New("otr: unexpected duplicate DH key")
363 toSend = c.encode(c.generateRevealSig())
364 c.authState = authStateAwaitingSig
365 case authStateAwaitingSig:
367 if isSame, err = c.processDHKey(msg); err != nil {
371 toSend = c.encode(c.serializeDHKey())
374 case msgTypeRevealSig:
375 if c.authState != authStateAwaitingRevealSig {
378 if err = c.processRevealSig(msg); err != nil {
381 toSend = c.encode(c.generateSig())
382 c.authState = authStateNone
383 c.state = stateEncrypted
386 if c.authState != authStateAwaitingSig {
389 if err = c.processSig(msg); err != nil {
392 c.authState = authStateNone
393 c.state = stateEncrypted
396 if c.state != stateEncrypted {
397 err = errors.New("otr: encrypted message received without encrypted session established")
401 out, tlvs, err = c.processData(msg)
405 for _, inTLV := range tlvs {
407 case tlvTypeDisconnected:
408 change = ConversationEnded
409 c.state = stateFinished
411 case tlvTypeSMP1, tlvTypeSMP2, tlvTypeSMP3, tlvTypeSMP4, tlvTypeSMPAbort, tlvTypeSMP1WithQuestion:
414 reply, complete, err = c.processSMP(inTLV)
415 if err == smpSecretMissingError {
417 change = SMPSecretNeeded
421 if err == smpFailureError {
428 toSend = c.encode(c.generateData(nil, &reply))
436 err = errors.New("otr: unknown message type " + strconv.Itoa(msgType))
442 // Send takes a human readable message from the local user, possibly encrypts
443 // it and returns zero one or more messages to send to the peer.
444 func (c *Conversation) Send(msg []byte) ([][]byte, error) {
447 return [][]byte{msg}, nil
449 return c.encode(c.generateData(msg, nil)), nil
451 return nil, errors.New("otr: cannot send message because secure conversation has finished")
454 return nil, errors.New("otr: cannot send message in current state")
457 // SMPQuestion returns the human readable challenge question from the peer.
458 // It's only valid after Receive has returned SMPSecretNeeded.
459 func (c *Conversation) SMPQuestion() string {
460 return c.smp.question
463 // Authenticate begins an authentication with the peer. Authentication involves
464 // an optional challenge message and a shared secret. The authentication
465 // proceeds until either Receive returns SMPComplete, SMPSecretNeeded (which
466 // indicates that a new authentication is happening and thus this one was
467 // aborted) or SMPFailed.
468 func (c *Conversation) Authenticate(question string, mutualSecret []byte) (toSend [][]byte, err error) {
469 if c.state != stateEncrypted {
470 err = errors.New("otr: can't authenticate a peer without a secure conversation established")
474 if c.smp.saved != nil {
475 c.calcSMPSecret(mutualSecret, false /* they started it */)
479 out, complete, err = c.processSMP(*c.smp.saved)
481 panic("SMP completed on the first message")
485 toSend = c.encode(c.generateData(nil, &out))
490 c.calcSMPSecret(mutualSecret, true /* we started it */)
491 outs := c.startSMP(question)
492 for _, out := range outs {
493 toSend = append(toSend, c.encode(c.generateData(nil, &out))...)
498 // End ends a secure conversation by generating a termination message for
499 // the peer and switches to unencrypted communication.
500 func (c *Conversation) End() (toSend [][]byte) {
505 c.state = statePlaintext
506 return c.encode(c.generateData(nil, &tlv{typ: tlvTypeDisconnected}))
508 c.state = statePlaintext
514 // IsEncrypted returns true if a message passed to Send would be encrypted
515 // before transmission. This result remains valid until the next call to
516 // Receive or End, which may change the state of the Conversation.
517 func (c *Conversation) IsEncrypted() bool {
518 return c.state == stateEncrypted
521 var fragmentError = errors.New("otr: invalid OTR fragment")
523 // processFragment processes a fragmented OTR message and possibly returns a
524 // complete message. Fragmented messages look like "?OTR,k,n,msg," where k is
525 // the fragment number (starting from 1), n is the number of fragments in this
526 // message and msg is a substring of the base64 encoded message.
527 func (c *Conversation) processFragment(in []byte) (out []byte, err error) {
528 in = in[len(fragmentPrefix):] // remove "?OTR,"
529 parts := bytes.Split(in, fragmentPartSeparator)
530 if len(parts) != 4 || len(parts[3]) != 0 {
531 return nil, fragmentError
534 k, err := strconv.Atoi(string(parts[0]))
536 return nil, fragmentError
539 n, err := strconv.Atoi(string(parts[1]))
541 return nil, fragmentError
544 if k < 1 || n < 1 || k > n {
545 return nil, fragmentError
549 c.frag = append(c.frag[:0], parts[2]...)
551 } else if n == c.n && k == c.k+1 {
552 c.frag = append(c.frag, parts[2]...)
559 if c.n > 0 && c.k == c.n {
567 func (c *Conversation) generateDHCommit() []byte {
568 _, err := io.ReadFull(c.rand(), c.r[:])
570 panic("otr: short read from random source")
573 var xBytes [dhPrivateBytes]byte
574 c.x = c.randMPI(xBytes[:])
575 c.gx = new(big.Int).Exp(g, c.x, p)
577 c.gxBytes = appendMPI(nil, c.gx)
583 aesCipher, err := aes.NewCipher(c.r[:])
588 var iv [aes.BlockSize]byte
589 ctr := cipher.NewCTR(aesCipher, iv[:])
590 ctr.XORKeyStream(c.gxBytes, c.gxBytes)
592 return c.serializeDHCommit()
595 func (c *Conversation) serializeDHCommit() []byte {
597 ret = appendU16(ret, 2) // protocol version
598 ret = append(ret, msgTypeDHCommit)
599 ret = appendData(ret, c.gxBytes)
600 ret = appendData(ret, c.digest[:])
604 func (c *Conversation) processDHCommit(in []byte) error {
606 c.gxBytes, in, ok1 = getData(in)
607 digest, in, ok2 := getData(in)
608 if !ok1 || !ok2 || len(in) > 0 {
609 return errors.New("otr: corrupt DH commit message")
611 copy(c.digest[:], digest)
615 func (c *Conversation) compareToDHCommit(in []byte) (int, error) {
616 _, in, ok1 := getData(in)
617 digest, in, ok2 := getData(in)
618 if !ok1 || !ok2 || len(in) > 0 {
619 return 0, errors.New("otr: corrupt DH commit message")
621 return bytes.Compare(c.digest[:], digest), nil
624 func (c *Conversation) generateDHKey() []byte {
625 var yBytes [dhPrivateBytes]byte
626 c.y = c.randMPI(yBytes[:])
627 c.gy = new(big.Int).Exp(g, c.y, p)
628 return c.serializeDHKey()
631 func (c *Conversation) serializeDHKey() []byte {
633 ret = appendU16(ret, 2) // protocol version
634 ret = append(ret, msgTypeDHKey)
635 ret = appendMPI(ret, c.gy)
639 func (c *Conversation) processDHKey(in []byte) (isSame bool, err error) {
640 gy, in, ok := getMPI(in)
642 err = errors.New("otr: corrupt DH key message")
645 if gy.Cmp(g) < 0 || gy.Cmp(pMinus2) > 0 {
646 err = errors.New("otr: DH value out of range")
650 isSame = c.gy.Cmp(gy) == 0
657 func (c *Conversation) generateEncryptedSignature(keys *akeKeys, xFirst bool) ([]byte, []byte) {
659 xb = c.PrivateKey.PublicKey.Serialize(xb)
661 var verifyData []byte
663 verifyData = appendMPI(verifyData, c.gx)
664 verifyData = appendMPI(verifyData, c.gy)
666 verifyData = appendMPI(verifyData, c.gy)
667 verifyData = appendMPI(verifyData, c.gx)
669 verifyData = append(verifyData, xb...)
670 verifyData = appendU32(verifyData, c.myKeyId)
672 mac := hmac.New(sha256.New, keys.m1[:])
673 mac.Write(verifyData)
676 xb = appendU32(xb, c.myKeyId)
677 xb = append(xb, c.PrivateKey.Sign(c.rand(), mb)...)
679 aesCipher, err := aes.NewCipher(keys.c[:])
683 var iv [aes.BlockSize]byte
684 ctr := cipher.NewCTR(aesCipher, iv[:])
685 ctr.XORKeyStream(xb, xb)
687 mac = hmac.New(sha256.New, keys.m2[:])
688 encryptedSig := appendData(nil, xb)
689 mac.Write(encryptedSig)
691 return encryptedSig, mac.Sum(nil)
694 func (c *Conversation) generateRevealSig() []byte {
695 s := new(big.Int).Exp(c.gy, c.x, p)
699 encryptedSig, mac := c.generateEncryptedSignature(&c.revealKeys, true /* gx comes first */)
701 c.myCurrentDHPub = c.gx
702 c.myCurrentDHPriv = c.x
704 incCounter(&c.myCounter)
707 ret = appendU16(ret, 2)
708 ret = append(ret, msgTypeRevealSig)
709 ret = appendData(ret, c.r[:])
710 ret = append(ret, encryptedSig...)
711 ret = append(ret, mac[:20]...)
715 func (c *Conversation) processEncryptedSig(encryptedSig, theirMAC []byte, keys *akeKeys, xFirst bool) error {
716 mac := hmac.New(sha256.New, keys.m2[:])
717 mac.Write(appendData(nil, encryptedSig))
718 myMAC := mac.Sum(nil)[:20]
720 if len(myMAC) != len(theirMAC) || subtle.ConstantTimeCompare(myMAC, theirMAC) == 0 {
721 return errors.New("bad signature MAC in encrypted signature")
724 aesCipher, err := aes.NewCipher(keys.c[:])
728 var iv [aes.BlockSize]byte
729 ctr := cipher.NewCTR(aesCipher, iv[:])
730 ctr.XORKeyStream(encryptedSig, encryptedSig)
733 sig, ok1 := c.TheirPublicKey.Parse(sig)
734 keyId, sig, ok2 := getU32(sig)
736 return errors.New("otr: corrupt encrypted signature")
739 var verifyData []byte
741 verifyData = appendMPI(verifyData, c.gx)
742 verifyData = appendMPI(verifyData, c.gy)
744 verifyData = appendMPI(verifyData, c.gy)
745 verifyData = appendMPI(verifyData, c.gx)
747 verifyData = c.TheirPublicKey.Serialize(verifyData)
748 verifyData = appendU32(verifyData, keyId)
750 mac = hmac.New(sha256.New, keys.m1[:])
751 mac.Write(verifyData)
754 sig, ok1 = c.TheirPublicKey.Verify(mb, sig)
756 return errors.New("bad signature in encrypted signature")
759 return errors.New("corrupt encrypted signature")
763 zero(c.theirLastCtr[:])
767 func (c *Conversation) processRevealSig(in []byte) error {
768 r, in, ok1 := getData(in)
769 encryptedSig, in, ok2 := getData(in)
771 if !ok1 || !ok2 || len(theirMAC) != 20 {
772 return errors.New("otr: corrupt reveal signature message")
775 aesCipher, err := aes.NewCipher(r)
777 return errors.New("otr: cannot create AES cipher from reveal signature message: " + err.Error())
779 var iv [aes.BlockSize]byte
780 ctr := cipher.NewCTR(aesCipher, iv[:])
781 ctr.XORKeyStream(c.gxBytes, c.gxBytes)
785 if len(digest) != len(c.digest) || subtle.ConstantTimeCompare(digest, c.digest[:]) == 0 {
786 return errors.New("otr: bad commit MAC in reveal signature message")
789 c.gx, rest, ok1 = getMPI(c.gxBytes)
790 if !ok1 || len(rest) > 0 {
791 return errors.New("otr: gx corrupt after decryption")
793 if c.gx.Cmp(g) < 0 || c.gx.Cmp(pMinus2) > 0 {
794 return errors.New("otr: DH value out of range")
796 s := new(big.Int).Exp(c.gx, c.y, p)
799 if err := c.processEncryptedSig(encryptedSig, theirMAC, &c.revealKeys, true /* gx comes first */); err != nil {
800 return errors.New("otr: in reveal signature message: " + err.Error())
803 c.theirCurrentDHPub = c.gx
804 c.theirLastDHPub = nil
809 func (c *Conversation) generateSig() []byte {
812 encryptedSig, mac := c.generateEncryptedSignature(&c.sigKeys, false /* gy comes first */)
814 c.myCurrentDHPub = c.gy
815 c.myCurrentDHPriv = c.y
817 incCounter(&c.myCounter)
820 ret = appendU16(ret, 2)
821 ret = append(ret, msgTypeSig)
822 ret = append(ret, encryptedSig...)
823 ret = append(ret, mac[:macPrefixBytes]...)
827 func (c *Conversation) processSig(in []byte) error {
828 encryptedSig, in, ok1 := getData(in)
830 if !ok1 || len(theirMAC) != macPrefixBytes {
831 return errors.New("otr: corrupt signature message")
834 if err := c.processEncryptedSig(encryptedSig, theirMAC, &c.sigKeys, false /* gy comes first */); err != nil {
835 return errors.New("otr: in signature message: " + err.Error())
838 c.theirCurrentDHPub = c.gy
839 c.theirLastDHPub = nil
844 func (c *Conversation) rotateDHKeys() {
845 // evict slots using our retired key id
846 for i := range c.keySlots {
847 slot := &c.keySlots[i]
848 if slot.used && slot.myKeyId == c.myKeyId-1 {
850 c.oldMACs = append(c.oldMACs, slot.recvMACKey...)
854 c.myLastDHPriv = c.myCurrentDHPriv
855 c.myLastDHPub = c.myCurrentDHPub
857 var xBytes [dhPrivateBytes]byte
858 c.myCurrentDHPriv = c.randMPI(xBytes[:])
859 c.myCurrentDHPub = new(big.Int).Exp(g, c.myCurrentDHPriv, p)
863 func (c *Conversation) processData(in []byte) (out []byte, tlvs []tlv, err error) {
865 flags, in, ok1 := getU8(in)
866 theirKeyId, in, ok2 := getU32(in)
867 myKeyId, in, ok3 := getU32(in)
868 y, in, ok4 := getMPI(in)
869 counter, in, ok5 := getNBytes(in, 8)
870 encrypted, in, ok6 := getData(in)
871 macedData := origIn[:len(origIn)-len(in)]
872 theirMAC, in, ok7 := getNBytes(in, macPrefixBytes)
873 _, in, ok8 := getData(in)
874 if !ok1 || !ok2 || !ok3 || !ok4 || !ok5 || !ok6 || !ok7 || !ok8 || len(in) > 0 {
875 err = errors.New("otr: corrupt data message")
879 ignoreErrors := flags&1 != 0
881 slot, err := c.calcDataKeys(myKeyId, theirKeyId)
889 mac := hmac.New(sha1.New, slot.recvMACKey)
890 mac.Write([]byte{0, 2, 3})
892 myMAC := mac.Sum(nil)
893 if len(myMAC) != len(theirMAC) || subtle.ConstantTimeCompare(myMAC, theirMAC) == 0 {
895 err = errors.New("otr: bad MAC on data message")
900 if bytes.Compare(counter, slot.theirLastCtr[:]) <= 0 {
901 err = errors.New("otr: counter regressed")
904 copy(slot.theirLastCtr[:], counter)
906 var iv [aes.BlockSize]byte
908 aesCipher, err := aes.NewCipher(slot.recvAESKey)
912 ctr := cipher.NewCTR(aesCipher, iv[:])
913 ctr.XORKeyStream(encrypted, encrypted)
914 decrypted := encrypted
916 if myKeyId == c.myKeyId {
919 if theirKeyId == c.theirKeyId {
920 // evict slots using their retired key id
921 for i := range c.keySlots {
922 slot := &c.keySlots[i]
923 if slot.used && slot.theirKeyId == theirKeyId-1 {
925 c.oldMACs = append(c.oldMACs, slot.recvMACKey...)
929 c.theirLastDHPub = c.theirCurrentDHPub
931 c.theirCurrentDHPub = y
934 if nulPos := bytes.IndexByte(decrypted, 0); nulPos >= 0 {
935 out = decrypted[:nulPos]
936 tlvData := decrypted[nulPos+1:]
937 for len(tlvData) > 0 {
939 var ok1, ok2, ok3 bool
941 t.typ, tlvData, ok1 = getU16(tlvData)
942 t.length, tlvData, ok2 = getU16(tlvData)
943 t.data, tlvData, ok3 = getNBytes(tlvData, int(t.length))
944 if !ok1 || !ok2 || !ok3 {
945 err = errors.New("otr: corrupt tlv data")
948 tlvs = append(tlvs, t)
957 func (c *Conversation) generateData(msg []byte, extra *tlv) []byte {
958 slot, err := c.calcDataKeys(c.myKeyId-1, c.theirKeyId)
960 panic("otr: failed to generate sending keys: " + err.Error())
964 plaintext = append(plaintext, msg...)
965 plaintext = append(plaintext, 0)
967 padding := paddingGranularity - ((len(plaintext) + 4) % paddingGranularity)
968 plaintext = appendU16(plaintext, tlvTypePadding)
969 plaintext = appendU16(plaintext, uint16(padding))
970 for i := 0; i < padding; i++ {
971 plaintext = append(plaintext, 0)
975 plaintext = appendU16(plaintext, extra.typ)
976 plaintext = appendU16(plaintext, uint16(len(extra.data)))
977 plaintext = append(plaintext, extra.data...)
980 encrypted := make([]byte, len(plaintext))
982 var iv [aes.BlockSize]byte
983 copy(iv[:], c.myCounter[:])
984 aesCipher, err := aes.NewCipher(slot.sendAESKey)
988 ctr := cipher.NewCTR(aesCipher, iv[:])
989 ctr.XORKeyStream(encrypted, plaintext)
992 ret = appendU16(ret, 2)
993 ret = append(ret, msgTypeData)
994 ret = append(ret, 0 /* flags */)
995 ret = appendU32(ret, c.myKeyId-1)
996 ret = appendU32(ret, c.theirKeyId)
997 ret = appendMPI(ret, c.myCurrentDHPub)
998 ret = append(ret, c.myCounter[:]...)
999 ret = appendData(ret, encrypted)
1001 mac := hmac.New(sha1.New, slot.sendMACKey)
1003 ret = append(ret, mac.Sum(nil)[:macPrefixBytes]...)
1004 ret = appendData(ret, c.oldMACs)
1006 incCounter(&c.myCounter)
1011 func incCounter(counter *[8]byte) {
1012 for i := 7; i >= 0; i-- {
1020 // calcDataKeys computes the keys used to encrypt a data message given the key
1022 func (c *Conversation) calcDataKeys(myKeyId, theirKeyId uint32) (slot *keySlot, err error) {
1023 // Check for a cache hit.
1024 for i := range c.keySlots {
1025 slot = &c.keySlots[i]
1026 if slot.used && slot.theirKeyId == theirKeyId && slot.myKeyId == myKeyId {
1031 // Find an empty slot to write into.
1033 for i := range c.keySlots {
1034 if !c.keySlots[i].used {
1035 slot = &c.keySlots[i]
1040 return nil, errors.New("otr: internal error: no more key slots")
1043 var myPriv, myPub, theirPub *big.Int
1045 if myKeyId == c.myKeyId {
1046 myPriv = c.myCurrentDHPriv
1047 myPub = c.myCurrentDHPub
1048 } else if myKeyId == c.myKeyId-1 {
1049 myPriv = c.myLastDHPriv
1050 myPub = c.myLastDHPub
1052 err = errors.New("otr: peer requested keyid " + strconv.FormatUint(uint64(myKeyId), 10) + " when I'm on " + strconv.FormatUint(uint64(c.myKeyId), 10))
1056 if theirKeyId == c.theirKeyId {
1057 theirPub = c.theirCurrentDHPub
1058 } else if theirKeyId == c.theirKeyId-1 && c.theirLastDHPub != nil {
1059 theirPub = c.theirLastDHPub
1061 err = errors.New("otr: peer requested keyid " + strconv.FormatUint(uint64(myKeyId), 10) + " when they're on " + strconv.FormatUint(uint64(c.myKeyId), 10))
1065 var sendPrefixByte, recvPrefixByte [1]byte
1067 if myPub.Cmp(theirPub) > 0 {
1068 // we're the high end
1069 sendPrefixByte[0], recvPrefixByte[0] = 1, 2
1071 // we're the low end
1072 sendPrefixByte[0], recvPrefixByte[0] = 2, 1
1075 s := new(big.Int).Exp(theirPub, myPriv, p)
1076 sBytes := appendMPI(nil, s)
1079 h.Write(sendPrefixByte[:])
1081 slot.sendAESKey = h.Sum(slot.sendAESKey[:0])[:16]
1084 h.Write(slot.sendAESKey)
1085 slot.sendMACKey = h.Sum(slot.sendMACKey[:0])
1088 h.Write(recvPrefixByte[:])
1090 slot.recvAESKey = h.Sum(slot.recvAESKey[:0])[:16]
1093 h.Write(slot.recvAESKey)
1094 slot.recvMACKey = h.Sum(slot.recvMACKey[:0])
1096 slot.theirKeyId = theirKeyId
1097 slot.myKeyId = myKeyId
1100 zero(slot.theirLastCtr[:])
1104 func (c *Conversation) calcAKEKeys(s *big.Int) {
1105 mpi := appendMPI(nil, s)
1109 hashWithPrefix(c.SSID[:], 0, mpi, h)
1111 hashWithPrefix(cBytes[:], 1, mpi, h)
1112 copy(c.revealKeys.c[:], cBytes[:16])
1113 copy(c.sigKeys.c[:], cBytes[16:])
1115 hashWithPrefix(c.revealKeys.m1[:], 2, mpi, h)
1116 hashWithPrefix(c.revealKeys.m2[:], 3, mpi, h)
1117 hashWithPrefix(c.sigKeys.m1[:], 4, mpi, h)
1118 hashWithPrefix(c.sigKeys.m2[:], 5, mpi, h)
1121 func hashWithPrefix(out []byte, prefix byte, in []byte, h hash.Hash) {
1127 if len(out) == h.Size() {
1130 digest := h.Sum(nil)
1135 func (c *Conversation) encode(msg []byte) [][]byte {
1136 b64 := make([]byte, base64.StdEncoding.EncodedLen(len(msg))+len(msgPrefix)+1)
1137 base64.StdEncoding.Encode(b64[len(msgPrefix):], msg)
1138 copy(b64, msgPrefix)
1139 b64[len(b64)-1] = '.'
1141 if c.FragmentSize < minFragmentSize || len(b64) <= c.FragmentSize {
1142 // We can encode this in a single fragment.
1143 return [][]byte{b64}
1146 // We have to fragment this message.
1148 bytesPerFragment := c.FragmentSize - minFragmentSize
1149 numFragments := (len(b64) + bytesPerFragment) / bytesPerFragment
1151 for i := 0; i < numFragments; i++ {
1152 frag := []byte("?OTR," + strconv.Itoa(i+1) + "," + strconv.Itoa(numFragments) + ",")
1153 todo := bytesPerFragment
1154 if todo > len(b64) {
1157 frag = append(frag, b64[:todo]...)
1159 frag = append(frag, ',')
1160 ret = append(ret, frag)
1166 func (c *Conversation) reset() {
1169 for i := range c.keySlots {
1170 c.keySlots[i].used = false
1174 type PublicKey struct {
1178 func (pk *PublicKey) Parse(in []byte) ([]byte, bool) {
1180 var pubKeyType uint16
1182 if pubKeyType, in, ok = getU16(in); !ok || pubKeyType != 0 {
1185 if pk.P, in, ok = getMPI(in); !ok {
1188 if pk.Q, in, ok = getMPI(in); !ok {
1191 if pk.G, in, ok = getMPI(in); !ok {
1194 if pk.Y, in, ok = getMPI(in); !ok {
1201 func (pk *PublicKey) Serialize(in []byte) []byte {
1202 in = appendU16(in, 0)
1203 in = appendMPI(in, pk.P)
1204 in = appendMPI(in, pk.Q)
1205 in = appendMPI(in, pk.G)
1206 in = appendMPI(in, pk.Y)
1210 // Fingerprint returns the 20-byte, binary fingerprint of the PublicKey.
1211 func (pk *PublicKey) Fingerprint() []byte {
1212 b := pk.Serialize(nil)
1218 func (pk *PublicKey) Verify(hashed, sig []byte) ([]byte, bool) {
1219 if len(sig) != 2*dsaSubgroupBytes {
1222 r := new(big.Int).SetBytes(sig[:dsaSubgroupBytes])
1223 s := new(big.Int).SetBytes(sig[dsaSubgroupBytes:])
1224 ok := dsa.Verify(&pk.PublicKey, hashed, r, s)
1225 return sig[dsaSubgroupBytes*2:], ok
1228 type PrivateKey struct {
1233 func (priv *PrivateKey) Sign(rand io.Reader, hashed []byte) []byte {
1234 r, s, err := dsa.Sign(rand, &priv.PrivateKey, hashed)
1240 if len(rBytes) > dsaSubgroupBytes || len(sBytes) > dsaSubgroupBytes {
1241 panic("DSA signature too large")
1244 out := make([]byte, 2*dsaSubgroupBytes)
1245 copy(out[dsaSubgroupBytes-len(rBytes):], rBytes)
1246 copy(out[len(out)-len(sBytes):], sBytes)
1250 func (priv *PrivateKey) Serialize(in []byte) []byte {
1251 in = priv.PublicKey.Serialize(in)
1252 in = appendMPI(in, priv.PrivateKey.X)
1256 func (priv *PrivateKey) Parse(in []byte) ([]byte, bool) {
1257 in, ok := priv.PublicKey.Parse(in)
1261 priv.PrivateKey.PublicKey = priv.PublicKey.PublicKey
1262 priv.PrivateKey.X, in, ok = getMPI(in)
1266 func (priv *PrivateKey) Generate(rand io.Reader) {
1267 if err := dsa.GenerateParameters(&priv.PrivateKey.PublicKey.Parameters, rand, dsa.L1024N160); err != nil {
1270 if err := dsa.GenerateKey(&priv.PrivateKey, rand); err != nil {
1273 priv.PublicKey.PublicKey = priv.PrivateKey.PublicKey
1276 func notHex(r rune) bool {
1277 if r >= '0' && r <= '9' ||
1278 r >= 'a' && r <= 'f' ||
1279 r >= 'A' && r <= 'F' {
1286 // Import parses the contents of a libotr private key file.
1287 func (priv *PrivateKey) Import(in []byte) bool {
1288 mpiStart := []byte(" #")
1290 mpis := make([]*big.Int, 5)
1292 for i := 0; i < len(mpis); i++ {
1293 start := bytes.Index(in, mpiStart)
1297 in = in[start+len(mpiStart):]
1298 end := bytes.IndexFunc(in, notHex)
1302 hexBytes := in[:end]
1305 if len(hexBytes)&1 != 0 {
1309 mpiBytes := make([]byte, len(hexBytes)/2)
1310 if _, err := hex.Decode(mpiBytes, hexBytes); err != nil {
1314 mpis[i] = new(big.Int).SetBytes(mpiBytes)
1317 for _, mpi := range mpis {
1318 if mpi.Sign() <= 0 {
1323 priv.PrivateKey.P = mpis[0]
1324 priv.PrivateKey.Q = mpis[1]
1325 priv.PrivateKey.G = mpis[2]
1326 priv.PrivateKey.Y = mpis[3]
1327 priv.PrivateKey.X = mpis[4]
1328 priv.PublicKey.PublicKey = priv.PrivateKey.PublicKey
1330 a := new(big.Int).Exp(priv.PrivateKey.G, priv.PrivateKey.X, priv.PrivateKey.P)
1331 return a.Cmp(priv.PrivateKey.Y) == 0
1334 func getU8(in []byte) (uint8, []byte, bool) {
1338 return in[0], in[1:], true
1341 func getU16(in []byte) (uint16, []byte, bool) {
1345 r := uint16(in[0])<<8 | uint16(in[1])
1346 return r, in[2:], true
1349 func getU32(in []byte) (uint32, []byte, bool) {
1353 r := uint32(in[0])<<24 | uint32(in[1])<<16 | uint32(in[2])<<8 | uint32(in[3])
1354 return r, in[4:], true
1357 func getMPI(in []byte) (*big.Int, []byte, bool) {
1358 l, in, ok := getU32(in)
1359 if !ok || uint32(len(in)) < l {
1360 return nil, in, false
1362 r := new(big.Int).SetBytes(in[:l])
1363 return r, in[l:], true
1366 func getData(in []byte) ([]byte, []byte, bool) {
1367 l, in, ok := getU32(in)
1368 if !ok || uint32(len(in)) < l {
1369 return nil, in, false
1371 return in[:l], in[l:], true
1374 func getNBytes(in []byte, n int) ([]byte, []byte, bool) {
1376 return nil, in, false
1378 return in[:n], in[n:], true
1381 func appendU16(out []byte, v uint16) []byte {
1382 out = append(out, byte(v>>8), byte(v))
1386 func appendU32(out []byte, v uint32) []byte {
1387 out = append(out, byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
1391 func appendData(out, v []byte) []byte {
1392 out = appendU32(out, uint32(len(v)))
1393 out = append(out, v...)
1397 func appendMPI(out []byte, v *big.Int) []byte {
1399 out = appendU32(out, uint32(len(vBytes)))
1400 out = append(out, vBytes...)
1404 func appendMPIs(out []byte, mpis ...*big.Int) []byte {
1405 for _, mpi := range mpis {
1406 out = appendMPI(out, mpi)
1411 func zero(b []byte) {