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
8 // The version of OTR implemented by this package has been deprecated
9 // (https://bugs.otr.im/lib/libotr/issues/140). An implementation of OTRv3 is
10 // available at https://github.com/coyim/otr3.
11 package otr // import "golang.org/x/crypto/otr"
32 // SecurityChange describes a change in the security state of a Conversation.
33 type SecurityChange int
36 NoChange SecurityChange = iota
37 // NewKeys indicates that a key exchange has completed. This occurs
38 // when a conversation first becomes encrypted, and when the keys are
39 // renegotiated within an encrypted conversation.
41 // SMPSecretNeeded indicates that the peer has started an
42 // authentication and that we need to supply a secret. Call SMPQuestion
43 // to get the optional, human readable challenge and then Authenticate
44 // to supply the matching secret.
46 // SMPComplete indicates that an authentication completed. The identity
47 // of the peer has now been confirmed.
49 // SMPFailed indicates that an authentication failed.
51 // ConversationEnded indicates that the peer ended the secure
56 // QueryMessage can be sent to a peer to start an OTR conversation.
57 var QueryMessage = "?OTRv2?"
59 // ErrorPrefix can be used to make an OTR error by appending an error message
61 var ErrorPrefix = "?OTR Error:"
64 fragmentPartSeparator = []byte(",")
65 fragmentPrefix = []byte("?OTR,")
66 msgPrefix = []byte("?OTR:")
67 queryMarker = []byte("?OTR")
70 // isQuery attempts to parse an OTR query from msg and returns the greatest
71 // common version, or 0 if msg is not an OTR query.
72 func isQuery(msg []byte) (greatestCommonVersion int) {
73 pos := bytes.Index(msg, queryMarker)
77 for i, c := range msg[pos+len(queryMarker):] {
80 // Indicates support for version 1, but we don't
98 if c == ' ' || c == '\t' {
99 // Probably an invalid message
104 greatestCommonVersion = 2
112 statePlaintext = iota
119 authStateAwaitingDHKey
120 authStateAwaitingRevealSig
128 msgTypeRevealSig = 17
133 // If the requested fragment size is less than this, it will be ignored.
135 // Messages are padded to a multiple of this number of bytes.
136 paddingGranularity = 256
137 // The number of bytes in a Diffie-Hellman private value (320-bits).
139 // The number of bytes needed to represent an element of the DSA
140 // subgroup (160-bits).
141 dsaSubgroupBytes = 20
142 // The number of bytes of the MAC that are sent on the wire (160-bits).
146 // These are the global, common group parameters for OTR.
148 p *big.Int // group prime
149 g *big.Int // group generator
150 q *big.Int // group order
155 p, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF", 16)
156 q, _ = new(big.Int).SetString("7FFFFFFFFFFFFFFFE487ED5110B4611A62633145C06E0E68948127044533E63A0105DF531D89CD9128A5043CC71A026EF7CA8CD9E69D218D98158536F92F8A1BA7F09AB6B6A8E122F242DABB312F3F637A262174D31BF6B585FFAE5B7A035BF6F71C35FDAD44CFD2D74F9208BE258FF324943328F6722D9EE1003E5C50B1DF82CC6D241B0E2AE9CD348B1FD47E9267AFC1B2AE91EE51D6CB0E3179AB1042A95DCF6A9483B84B4B36B3861AA7255E4C0278BA36046511B993FFFFFFFFFFFFFFFF", 16)
157 g = new(big.Int).SetInt64(2)
158 pMinus2 = new(big.Int).Sub(p, g)
161 // Conversation represents a relation with a peer. The zero value is a valid
162 // Conversation, although PrivateKey must be set.
164 // When communicating with a peer, all inbound messages should be passed to
165 // Conversation.Receive and all outbound messages to Conversation.Send. The
166 // Conversation will take care of maintaining the encryption state and
167 // negotiating encryption as needed.
168 type Conversation struct {
169 // PrivateKey contains the private key to use to sign key exchanges.
170 PrivateKey *PrivateKey
172 // Rand can be set to override the entropy source. Otherwise,
173 // crypto/rand will be used.
175 // If FragmentSize is set, all messages produced by Receive and Send
176 // will be fragmented into messages of, at most, this number of bytes.
179 // Once Receive has returned NewKeys once, the following fields are
182 TheirPublicKey PublicKey
190 digest [sha256.Size]byte
192 revealKeys, sigKeys akeKeys
195 myCurrentDHPub *big.Int
196 myCurrentDHPriv *big.Int
198 myLastDHPriv *big.Int
201 theirCurrentDHPub *big.Int
202 theirLastDHPub *big.Int
210 k, n int // fragment state
216 // A keySlot contains key material for a specific (their keyid, my keyid) pair.
217 type keySlot struct {
218 // used is true if this slot is valid. If false, it's free for reuse.
222 sendAESKey, recvAESKey []byte
223 sendMACKey, recvMACKey []byte
227 // akeKeys are generated during key exchange. There's one set for the reveal
228 // signature message and another for the signature message. In the protocol
229 // spec the latter are indicated with a prime mark.
230 type akeKeys struct {
235 func (c *Conversation) rand() io.Reader {
242 func (c *Conversation) randMPI(buf []byte) *big.Int {
243 _, err := io.ReadFull(c.rand(), buf)
245 panic("otr: short read from random source")
248 return new(big.Int).SetBytes(buf)
251 // tlv represents the type-length value from the protocol.
259 tlvTypeDisconnected = 1
265 tlvTypeSMP1WithQuestion = 7
268 // Receive handles a message from a peer. It returns a human readable message,
269 // an indicator of whether that message was encrypted, a hint about the
270 // encryption state and zero or more messages to send back to the peer.
271 // These messages do not need to be passed to Send before transmission.
272 func (c *Conversation) Receive(in []byte) (out []byte, encrypted bool, change SecurityChange, toSend [][]byte, err error) {
273 if bytes.HasPrefix(in, fragmentPrefix) {
274 in, err = c.processFragment(in)
275 if in == nil || err != nil {
280 if bytes.HasPrefix(in, msgPrefix) && in[len(in)-1] == '.' {
281 in = in[len(msgPrefix) : len(in)-1]
282 } else if version := isQuery(in); version > 0 {
283 c.authState = authStateAwaitingDHKey
285 toSend = c.encode(c.generateDHCommit())
293 msg := make([]byte, base64.StdEncoding.DecodedLen(len(in)))
294 msgLen, err := base64.StdEncoding.Decode(msg, in)
296 err = errors.New("otr: invalid base64 encoding in message")
301 // The first two bytes are the protocol version (2)
302 if len(msg) < 3 || msg[0] != 0 || msg[1] != 2 {
303 err = errors.New("otr: invalid OTR message")
307 msgType := int(msg[2])
311 case msgTypeDHCommit:
314 c.authState = authStateAwaitingRevealSig
315 if err = c.processDHCommit(msg); err != nil {
319 toSend = c.encode(c.generateDHKey())
321 case authStateAwaitingDHKey:
322 // This is a 'SYN-crossing'. The greater digest wins.
324 if cmp, err = c.compareToDHCommit(msg); err != nil {
328 // We win. Retransmit DH commit.
329 toSend = c.encode(c.serializeDHCommit())
332 // They win. We forget about our DH commit.
333 c.authState = authStateAwaitingRevealSig
334 if err = c.processDHCommit(msg); err != nil {
338 toSend = c.encode(c.generateDHKey())
341 case authStateAwaitingRevealSig:
342 if err = c.processDHCommit(msg); err != nil {
345 toSend = c.encode(c.serializeDHKey())
346 case authStateAwaitingSig:
347 if err = c.processDHCommit(msg); err != nil {
351 toSend = c.encode(c.generateDHKey())
352 c.authState = authStateAwaitingRevealSig
358 case authStateAwaitingDHKey:
360 if isSame, err = c.processDHKey(msg); err != nil {
364 err = errors.New("otr: unexpected duplicate DH key")
367 toSend = c.encode(c.generateRevealSig())
368 c.authState = authStateAwaitingSig
369 case authStateAwaitingSig:
371 if isSame, err = c.processDHKey(msg); err != nil {
375 toSend = c.encode(c.serializeDHKey())
378 case msgTypeRevealSig:
379 if c.authState != authStateAwaitingRevealSig {
382 if err = c.processRevealSig(msg); err != nil {
385 toSend = c.encode(c.generateSig())
386 c.authState = authStateNone
387 c.state = stateEncrypted
390 if c.authState != authStateAwaitingSig {
393 if err = c.processSig(msg); err != nil {
396 c.authState = authStateNone
397 c.state = stateEncrypted
400 if c.state != stateEncrypted {
401 err = errors.New("otr: encrypted message received without encrypted session established")
405 out, tlvs, err = c.processData(msg)
409 for _, inTLV := range tlvs {
411 case tlvTypeDisconnected:
412 change = ConversationEnded
413 c.state = stateFinished
415 case tlvTypeSMP1, tlvTypeSMP2, tlvTypeSMP3, tlvTypeSMP4, tlvTypeSMPAbort, tlvTypeSMP1WithQuestion:
418 reply, complete, err = c.processSMP(inTLV)
419 if err == smpSecretMissingError {
421 change = SMPSecretNeeded
425 if err == smpFailureError {
432 toSend = c.encode(c.generateData(nil, &reply))
440 err = errors.New("otr: unknown message type " + strconv.Itoa(msgType))
446 // Send takes a human readable message from the local user, possibly encrypts
447 // it and returns zero one or more messages to send to the peer.
448 func (c *Conversation) Send(msg []byte) ([][]byte, error) {
451 return [][]byte{msg}, nil
453 return c.encode(c.generateData(msg, nil)), nil
455 return nil, errors.New("otr: cannot send message because secure conversation has finished")
458 return nil, errors.New("otr: cannot send message in current state")
461 // SMPQuestion returns the human readable challenge question from the peer.
462 // It's only valid after Receive has returned SMPSecretNeeded.
463 func (c *Conversation) SMPQuestion() string {
464 return c.smp.question
467 // Authenticate begins an authentication with the peer. Authentication involves
468 // an optional challenge message and a shared secret. The authentication
469 // proceeds until either Receive returns SMPComplete, SMPSecretNeeded (which
470 // indicates that a new authentication is happening and thus this one was
471 // aborted) or SMPFailed.
472 func (c *Conversation) Authenticate(question string, mutualSecret []byte) (toSend [][]byte, err error) {
473 if c.state != stateEncrypted {
474 err = errors.New("otr: can't authenticate a peer without a secure conversation established")
478 if c.smp.saved != nil {
479 c.calcSMPSecret(mutualSecret, false /* they started it */)
483 out, complete, err = c.processSMP(*c.smp.saved)
485 panic("SMP completed on the first message")
489 toSend = c.encode(c.generateData(nil, &out))
494 c.calcSMPSecret(mutualSecret, true /* we started it */)
495 outs := c.startSMP(question)
496 for _, out := range outs {
497 toSend = append(toSend, c.encode(c.generateData(nil, &out))...)
502 // End ends a secure conversation by generating a termination message for
503 // the peer and switches to unencrypted communication.
504 func (c *Conversation) End() (toSend [][]byte) {
509 c.state = statePlaintext
510 return c.encode(c.generateData(nil, &tlv{typ: tlvTypeDisconnected}))
512 c.state = statePlaintext
518 // IsEncrypted returns true if a message passed to Send would be encrypted
519 // before transmission. This result remains valid until the next call to
520 // Receive or End, which may change the state of the Conversation.
521 func (c *Conversation) IsEncrypted() bool {
522 return c.state == stateEncrypted
525 var fragmentError = errors.New("otr: invalid OTR fragment")
527 // processFragment processes a fragmented OTR message and possibly returns a
528 // complete message. Fragmented messages look like "?OTR,k,n,msg," where k is
529 // the fragment number (starting from 1), n is the number of fragments in this
530 // message and msg is a substring of the base64 encoded message.
531 func (c *Conversation) processFragment(in []byte) (out []byte, err error) {
532 in = in[len(fragmentPrefix):] // remove "?OTR,"
533 parts := bytes.Split(in, fragmentPartSeparator)
534 if len(parts) != 4 || len(parts[3]) != 0 {
535 return nil, fragmentError
538 k, err := strconv.Atoi(string(parts[0]))
540 return nil, fragmentError
543 n, err := strconv.Atoi(string(parts[1]))
545 return nil, fragmentError
548 if k < 1 || n < 1 || k > n {
549 return nil, fragmentError
553 c.frag = append(c.frag[:0], parts[2]...)
555 } else if n == c.n && k == c.k+1 {
556 c.frag = append(c.frag, parts[2]...)
563 if c.n > 0 && c.k == c.n {
571 func (c *Conversation) generateDHCommit() []byte {
572 _, err := io.ReadFull(c.rand(), c.r[:])
574 panic("otr: short read from random source")
577 var xBytes [dhPrivateBytes]byte
578 c.x = c.randMPI(xBytes[:])
579 c.gx = new(big.Int).Exp(g, c.x, p)
581 c.gxBytes = appendMPI(nil, c.gx)
587 aesCipher, err := aes.NewCipher(c.r[:])
592 var iv [aes.BlockSize]byte
593 ctr := cipher.NewCTR(aesCipher, iv[:])
594 ctr.XORKeyStream(c.gxBytes, c.gxBytes)
596 return c.serializeDHCommit()
599 func (c *Conversation) serializeDHCommit() []byte {
601 ret = appendU16(ret, 2) // protocol version
602 ret = append(ret, msgTypeDHCommit)
603 ret = appendData(ret, c.gxBytes)
604 ret = appendData(ret, c.digest[:])
608 func (c *Conversation) processDHCommit(in []byte) error {
610 c.gxBytes, in, ok1 = getData(in)
611 digest, in, ok2 := getData(in)
612 if !ok1 || !ok2 || len(in) > 0 {
613 return errors.New("otr: corrupt DH commit message")
615 copy(c.digest[:], digest)
619 func (c *Conversation) compareToDHCommit(in []byte) (int, error) {
620 _, in, ok1 := getData(in)
621 digest, in, ok2 := getData(in)
622 if !ok1 || !ok2 || len(in) > 0 {
623 return 0, errors.New("otr: corrupt DH commit message")
625 return bytes.Compare(c.digest[:], digest), nil
628 func (c *Conversation) generateDHKey() []byte {
629 var yBytes [dhPrivateBytes]byte
630 c.y = c.randMPI(yBytes[:])
631 c.gy = new(big.Int).Exp(g, c.y, p)
632 return c.serializeDHKey()
635 func (c *Conversation) serializeDHKey() []byte {
637 ret = appendU16(ret, 2) // protocol version
638 ret = append(ret, msgTypeDHKey)
639 ret = appendMPI(ret, c.gy)
643 func (c *Conversation) processDHKey(in []byte) (isSame bool, err error) {
644 gy, _, ok := getMPI(in)
646 err = errors.New("otr: corrupt DH key message")
649 if gy.Cmp(g) < 0 || gy.Cmp(pMinus2) > 0 {
650 err = errors.New("otr: DH value out of range")
654 isSame = c.gy.Cmp(gy) == 0
661 func (c *Conversation) generateEncryptedSignature(keys *akeKeys, xFirst bool) ([]byte, []byte) {
663 xb = c.PrivateKey.PublicKey.Serialize(xb)
665 var verifyData []byte
667 verifyData = appendMPI(verifyData, c.gx)
668 verifyData = appendMPI(verifyData, c.gy)
670 verifyData = appendMPI(verifyData, c.gy)
671 verifyData = appendMPI(verifyData, c.gx)
673 verifyData = append(verifyData, xb...)
674 verifyData = appendU32(verifyData, c.myKeyId)
676 mac := hmac.New(sha256.New, keys.m1[:])
677 mac.Write(verifyData)
680 xb = appendU32(xb, c.myKeyId)
681 xb = append(xb, c.PrivateKey.Sign(c.rand(), mb)...)
683 aesCipher, err := aes.NewCipher(keys.c[:])
687 var iv [aes.BlockSize]byte
688 ctr := cipher.NewCTR(aesCipher, iv[:])
689 ctr.XORKeyStream(xb, xb)
691 mac = hmac.New(sha256.New, keys.m2[:])
692 encryptedSig := appendData(nil, xb)
693 mac.Write(encryptedSig)
695 return encryptedSig, mac.Sum(nil)
698 func (c *Conversation) generateRevealSig() []byte {
699 s := new(big.Int).Exp(c.gy, c.x, p)
703 encryptedSig, mac := c.generateEncryptedSignature(&c.revealKeys, true /* gx comes first */)
705 c.myCurrentDHPub = c.gx
706 c.myCurrentDHPriv = c.x
708 incCounter(&c.myCounter)
711 ret = appendU16(ret, 2)
712 ret = append(ret, msgTypeRevealSig)
713 ret = appendData(ret, c.r[:])
714 ret = append(ret, encryptedSig...)
715 ret = append(ret, mac[:20]...)
719 func (c *Conversation) processEncryptedSig(encryptedSig, theirMAC []byte, keys *akeKeys, xFirst bool) error {
720 mac := hmac.New(sha256.New, keys.m2[:])
721 mac.Write(appendData(nil, encryptedSig))
722 myMAC := mac.Sum(nil)[:20]
724 if len(myMAC) != len(theirMAC) || subtle.ConstantTimeCompare(myMAC, theirMAC) == 0 {
725 return errors.New("bad signature MAC in encrypted signature")
728 aesCipher, err := aes.NewCipher(keys.c[:])
732 var iv [aes.BlockSize]byte
733 ctr := cipher.NewCTR(aesCipher, iv[:])
734 ctr.XORKeyStream(encryptedSig, encryptedSig)
737 sig, ok1 := c.TheirPublicKey.Parse(sig)
738 keyId, sig, ok2 := getU32(sig)
740 return errors.New("otr: corrupt encrypted signature")
743 var verifyData []byte
745 verifyData = appendMPI(verifyData, c.gx)
746 verifyData = appendMPI(verifyData, c.gy)
748 verifyData = appendMPI(verifyData, c.gy)
749 verifyData = appendMPI(verifyData, c.gx)
751 verifyData = c.TheirPublicKey.Serialize(verifyData)
752 verifyData = appendU32(verifyData, keyId)
754 mac = hmac.New(sha256.New, keys.m1[:])
755 mac.Write(verifyData)
758 sig, ok1 = c.TheirPublicKey.Verify(mb, sig)
760 return errors.New("bad signature in encrypted signature")
763 return errors.New("corrupt encrypted signature")
767 zero(c.theirLastCtr[:])
771 func (c *Conversation) processRevealSig(in []byte) error {
772 r, in, ok1 := getData(in)
773 encryptedSig, in, ok2 := getData(in)
775 if !ok1 || !ok2 || len(theirMAC) != 20 {
776 return errors.New("otr: corrupt reveal signature message")
779 aesCipher, err := aes.NewCipher(r)
781 return errors.New("otr: cannot create AES cipher from reveal signature message: " + err.Error())
783 var iv [aes.BlockSize]byte
784 ctr := cipher.NewCTR(aesCipher, iv[:])
785 ctr.XORKeyStream(c.gxBytes, c.gxBytes)
789 if len(digest) != len(c.digest) || subtle.ConstantTimeCompare(digest, c.digest[:]) == 0 {
790 return errors.New("otr: bad commit MAC in reveal signature message")
793 c.gx, rest, ok1 = getMPI(c.gxBytes)
794 if !ok1 || len(rest) > 0 {
795 return errors.New("otr: gx corrupt after decryption")
797 if c.gx.Cmp(g) < 0 || c.gx.Cmp(pMinus2) > 0 {
798 return errors.New("otr: DH value out of range")
800 s := new(big.Int).Exp(c.gx, c.y, p)
803 if err := c.processEncryptedSig(encryptedSig, theirMAC, &c.revealKeys, true /* gx comes first */); err != nil {
804 return errors.New("otr: in reveal signature message: " + err.Error())
807 c.theirCurrentDHPub = c.gx
808 c.theirLastDHPub = nil
813 func (c *Conversation) generateSig() []byte {
816 encryptedSig, mac := c.generateEncryptedSignature(&c.sigKeys, false /* gy comes first */)
818 c.myCurrentDHPub = c.gy
819 c.myCurrentDHPriv = c.y
821 incCounter(&c.myCounter)
824 ret = appendU16(ret, 2)
825 ret = append(ret, msgTypeSig)
826 ret = append(ret, encryptedSig...)
827 ret = append(ret, mac[:macPrefixBytes]...)
831 func (c *Conversation) processSig(in []byte) error {
832 encryptedSig, in, ok1 := getData(in)
834 if !ok1 || len(theirMAC) != macPrefixBytes {
835 return errors.New("otr: corrupt signature message")
838 if err := c.processEncryptedSig(encryptedSig, theirMAC, &c.sigKeys, false /* gy comes first */); err != nil {
839 return errors.New("otr: in signature message: " + err.Error())
842 c.theirCurrentDHPub = c.gy
843 c.theirLastDHPub = nil
848 func (c *Conversation) rotateDHKeys() {
849 // evict slots using our retired key id
850 for i := range c.keySlots {
851 slot := &c.keySlots[i]
852 if slot.used && slot.myKeyId == c.myKeyId-1 {
854 c.oldMACs = append(c.oldMACs, slot.recvMACKey...)
858 c.myLastDHPriv = c.myCurrentDHPriv
859 c.myLastDHPub = c.myCurrentDHPub
861 var xBytes [dhPrivateBytes]byte
862 c.myCurrentDHPriv = c.randMPI(xBytes[:])
863 c.myCurrentDHPub = new(big.Int).Exp(g, c.myCurrentDHPriv, p)
867 func (c *Conversation) processData(in []byte) (out []byte, tlvs []tlv, err error) {
869 flags, in, ok1 := getU8(in)
870 theirKeyId, in, ok2 := getU32(in)
871 myKeyId, in, ok3 := getU32(in)
872 y, in, ok4 := getMPI(in)
873 counter, in, ok5 := getNBytes(in, 8)
874 encrypted, in, ok6 := getData(in)
875 macedData := origIn[:len(origIn)-len(in)]
876 theirMAC, in, ok7 := getNBytes(in, macPrefixBytes)
877 _, in, ok8 := getData(in)
878 if !ok1 || !ok2 || !ok3 || !ok4 || !ok5 || !ok6 || !ok7 || !ok8 || len(in) > 0 {
879 err = errors.New("otr: corrupt data message")
883 ignoreErrors := flags&1 != 0
885 slot, err := c.calcDataKeys(myKeyId, theirKeyId)
893 mac := hmac.New(sha1.New, slot.recvMACKey)
894 mac.Write([]byte{0, 2, 3})
896 myMAC := mac.Sum(nil)
897 if len(myMAC) != len(theirMAC) || subtle.ConstantTimeCompare(myMAC, theirMAC) == 0 {
899 err = errors.New("otr: bad MAC on data message")
904 if bytes.Compare(counter, slot.theirLastCtr[:]) <= 0 {
905 err = errors.New("otr: counter regressed")
908 copy(slot.theirLastCtr[:], counter)
910 var iv [aes.BlockSize]byte
912 aesCipher, err := aes.NewCipher(slot.recvAESKey)
916 ctr := cipher.NewCTR(aesCipher, iv[:])
917 ctr.XORKeyStream(encrypted, encrypted)
918 decrypted := encrypted
920 if myKeyId == c.myKeyId {
923 if theirKeyId == c.theirKeyId {
924 // evict slots using their retired key id
925 for i := range c.keySlots {
926 slot := &c.keySlots[i]
927 if slot.used && slot.theirKeyId == theirKeyId-1 {
929 c.oldMACs = append(c.oldMACs, slot.recvMACKey...)
933 c.theirLastDHPub = c.theirCurrentDHPub
935 c.theirCurrentDHPub = y
938 if nulPos := bytes.IndexByte(decrypted, 0); nulPos >= 0 {
939 out = decrypted[:nulPos]
940 tlvData := decrypted[nulPos+1:]
941 for len(tlvData) > 0 {
943 var ok1, ok2, ok3 bool
945 t.typ, tlvData, ok1 = getU16(tlvData)
946 t.length, tlvData, ok2 = getU16(tlvData)
947 t.data, tlvData, ok3 = getNBytes(tlvData, int(t.length))
948 if !ok1 || !ok2 || !ok3 {
949 err = errors.New("otr: corrupt tlv data")
952 tlvs = append(tlvs, t)
961 func (c *Conversation) generateData(msg []byte, extra *tlv) []byte {
962 slot, err := c.calcDataKeys(c.myKeyId-1, c.theirKeyId)
964 panic("otr: failed to generate sending keys: " + err.Error())
968 plaintext = append(plaintext, msg...)
969 plaintext = append(plaintext, 0)
971 padding := paddingGranularity - ((len(plaintext) + 4) % paddingGranularity)
972 plaintext = appendU16(plaintext, tlvTypePadding)
973 plaintext = appendU16(plaintext, uint16(padding))
974 for i := 0; i < padding; i++ {
975 plaintext = append(plaintext, 0)
979 plaintext = appendU16(plaintext, extra.typ)
980 plaintext = appendU16(plaintext, uint16(len(extra.data)))
981 plaintext = append(plaintext, extra.data...)
984 encrypted := make([]byte, len(plaintext))
986 var iv [aes.BlockSize]byte
987 copy(iv[:], c.myCounter[:])
988 aesCipher, err := aes.NewCipher(slot.sendAESKey)
992 ctr := cipher.NewCTR(aesCipher, iv[:])
993 ctr.XORKeyStream(encrypted, plaintext)
996 ret = appendU16(ret, 2)
997 ret = append(ret, msgTypeData)
998 ret = append(ret, 0 /* flags */)
999 ret = appendU32(ret, c.myKeyId-1)
1000 ret = appendU32(ret, c.theirKeyId)
1001 ret = appendMPI(ret, c.myCurrentDHPub)
1002 ret = append(ret, c.myCounter[:]...)
1003 ret = appendData(ret, encrypted)
1005 mac := hmac.New(sha1.New, slot.sendMACKey)
1007 ret = append(ret, mac.Sum(nil)[:macPrefixBytes]...)
1008 ret = appendData(ret, c.oldMACs)
1010 incCounter(&c.myCounter)
1015 func incCounter(counter *[8]byte) {
1016 for i := 7; i >= 0; i-- {
1024 // calcDataKeys computes the keys used to encrypt a data message given the key
1026 func (c *Conversation) calcDataKeys(myKeyId, theirKeyId uint32) (slot *keySlot, err error) {
1027 // Check for a cache hit.
1028 for i := range c.keySlots {
1029 slot = &c.keySlots[i]
1030 if slot.used && slot.theirKeyId == theirKeyId && slot.myKeyId == myKeyId {
1035 // Find an empty slot to write into.
1037 for i := range c.keySlots {
1038 if !c.keySlots[i].used {
1039 slot = &c.keySlots[i]
1044 return nil, errors.New("otr: internal error: no more key slots")
1047 var myPriv, myPub, theirPub *big.Int
1049 if myKeyId == c.myKeyId {
1050 myPriv = c.myCurrentDHPriv
1051 myPub = c.myCurrentDHPub
1052 } else if myKeyId == c.myKeyId-1 {
1053 myPriv = c.myLastDHPriv
1054 myPub = c.myLastDHPub
1056 err = errors.New("otr: peer requested keyid " + strconv.FormatUint(uint64(myKeyId), 10) + " when I'm on " + strconv.FormatUint(uint64(c.myKeyId), 10))
1060 if theirKeyId == c.theirKeyId {
1061 theirPub = c.theirCurrentDHPub
1062 } else if theirKeyId == c.theirKeyId-1 && c.theirLastDHPub != nil {
1063 theirPub = c.theirLastDHPub
1065 err = errors.New("otr: peer requested keyid " + strconv.FormatUint(uint64(myKeyId), 10) + " when they're on " + strconv.FormatUint(uint64(c.myKeyId), 10))
1069 var sendPrefixByte, recvPrefixByte [1]byte
1071 if myPub.Cmp(theirPub) > 0 {
1072 // we're the high end
1073 sendPrefixByte[0], recvPrefixByte[0] = 1, 2
1075 // we're the low end
1076 sendPrefixByte[0], recvPrefixByte[0] = 2, 1
1079 s := new(big.Int).Exp(theirPub, myPriv, p)
1080 sBytes := appendMPI(nil, s)
1083 h.Write(sendPrefixByte[:])
1085 slot.sendAESKey = h.Sum(slot.sendAESKey[:0])[:16]
1088 h.Write(slot.sendAESKey)
1089 slot.sendMACKey = h.Sum(slot.sendMACKey[:0])
1092 h.Write(recvPrefixByte[:])
1094 slot.recvAESKey = h.Sum(slot.recvAESKey[:0])[:16]
1097 h.Write(slot.recvAESKey)
1098 slot.recvMACKey = h.Sum(slot.recvMACKey[:0])
1100 slot.theirKeyId = theirKeyId
1101 slot.myKeyId = myKeyId
1104 zero(slot.theirLastCtr[:])
1108 func (c *Conversation) calcAKEKeys(s *big.Int) {
1109 mpi := appendMPI(nil, s)
1113 hashWithPrefix(c.SSID[:], 0, mpi, h)
1115 hashWithPrefix(cBytes[:], 1, mpi, h)
1116 copy(c.revealKeys.c[:], cBytes[:16])
1117 copy(c.sigKeys.c[:], cBytes[16:])
1119 hashWithPrefix(c.revealKeys.m1[:], 2, mpi, h)
1120 hashWithPrefix(c.revealKeys.m2[:], 3, mpi, h)
1121 hashWithPrefix(c.sigKeys.m1[:], 4, mpi, h)
1122 hashWithPrefix(c.sigKeys.m2[:], 5, mpi, h)
1125 func hashWithPrefix(out []byte, prefix byte, in []byte, h hash.Hash) {
1131 if len(out) == h.Size() {
1134 digest := h.Sum(nil)
1139 func (c *Conversation) encode(msg []byte) [][]byte {
1140 b64 := make([]byte, base64.StdEncoding.EncodedLen(len(msg))+len(msgPrefix)+1)
1141 base64.StdEncoding.Encode(b64[len(msgPrefix):], msg)
1142 copy(b64, msgPrefix)
1143 b64[len(b64)-1] = '.'
1145 if c.FragmentSize < minFragmentSize || len(b64) <= c.FragmentSize {
1146 // We can encode this in a single fragment.
1147 return [][]byte{b64}
1150 // We have to fragment this message.
1152 bytesPerFragment := c.FragmentSize - minFragmentSize
1153 numFragments := (len(b64) + bytesPerFragment) / bytesPerFragment
1155 for i := 0; i < numFragments; i++ {
1156 frag := []byte("?OTR," + strconv.Itoa(i+1) + "," + strconv.Itoa(numFragments) + ",")
1157 todo := bytesPerFragment
1158 if todo > len(b64) {
1161 frag = append(frag, b64[:todo]...)
1163 frag = append(frag, ',')
1164 ret = append(ret, frag)
1170 func (c *Conversation) reset() {
1173 for i := range c.keySlots {
1174 c.keySlots[i].used = false
1178 type PublicKey struct {
1182 func (pk *PublicKey) Parse(in []byte) ([]byte, bool) {
1184 var pubKeyType uint16
1186 if pubKeyType, in, ok = getU16(in); !ok || pubKeyType != 0 {
1189 if pk.P, in, ok = getMPI(in); !ok {
1192 if pk.Q, in, ok = getMPI(in); !ok {
1195 if pk.G, in, ok = getMPI(in); !ok {
1198 if pk.Y, in, ok = getMPI(in); !ok {
1205 func (pk *PublicKey) Serialize(in []byte) []byte {
1206 in = appendU16(in, 0)
1207 in = appendMPI(in, pk.P)
1208 in = appendMPI(in, pk.Q)
1209 in = appendMPI(in, pk.G)
1210 in = appendMPI(in, pk.Y)
1214 // Fingerprint returns the 20-byte, binary fingerprint of the PublicKey.
1215 func (pk *PublicKey) Fingerprint() []byte {
1216 b := pk.Serialize(nil)
1222 func (pk *PublicKey) Verify(hashed, sig []byte) ([]byte, bool) {
1223 if len(sig) != 2*dsaSubgroupBytes {
1226 r := new(big.Int).SetBytes(sig[:dsaSubgroupBytes])
1227 s := new(big.Int).SetBytes(sig[dsaSubgroupBytes:])
1228 ok := dsa.Verify(&pk.PublicKey, hashed, r, s)
1229 return sig[dsaSubgroupBytes*2:], ok
1232 type PrivateKey struct {
1237 func (priv *PrivateKey) Sign(rand io.Reader, hashed []byte) []byte {
1238 r, s, err := dsa.Sign(rand, &priv.PrivateKey, hashed)
1244 if len(rBytes) > dsaSubgroupBytes || len(sBytes) > dsaSubgroupBytes {
1245 panic("DSA signature too large")
1248 out := make([]byte, 2*dsaSubgroupBytes)
1249 copy(out[dsaSubgroupBytes-len(rBytes):], rBytes)
1250 copy(out[len(out)-len(sBytes):], sBytes)
1254 func (priv *PrivateKey) Serialize(in []byte) []byte {
1255 in = priv.PublicKey.Serialize(in)
1256 in = appendMPI(in, priv.PrivateKey.X)
1260 func (priv *PrivateKey) Parse(in []byte) ([]byte, bool) {
1261 in, ok := priv.PublicKey.Parse(in)
1265 priv.PrivateKey.PublicKey = priv.PublicKey.PublicKey
1266 priv.PrivateKey.X, in, ok = getMPI(in)
1270 func (priv *PrivateKey) Generate(rand io.Reader) {
1271 if err := dsa.GenerateParameters(&priv.PrivateKey.PublicKey.Parameters, rand, dsa.L1024N160); err != nil {
1274 if err := dsa.GenerateKey(&priv.PrivateKey, rand); err != nil {
1277 priv.PublicKey.PublicKey = priv.PrivateKey.PublicKey
1280 func notHex(r rune) bool {
1281 if r >= '0' && r <= '9' ||
1282 r >= 'a' && r <= 'f' ||
1283 r >= 'A' && r <= 'F' {
1290 // Import parses the contents of a libotr private key file.
1291 func (priv *PrivateKey) Import(in []byte) bool {
1292 mpiStart := []byte(" #")
1294 mpis := make([]*big.Int, 5)
1296 for i := 0; i < len(mpis); i++ {
1297 start := bytes.Index(in, mpiStart)
1301 in = in[start+len(mpiStart):]
1302 end := bytes.IndexFunc(in, notHex)
1306 hexBytes := in[:end]
1309 if len(hexBytes)&1 != 0 {
1313 mpiBytes := make([]byte, len(hexBytes)/2)
1314 if _, err := hex.Decode(mpiBytes, hexBytes); err != nil {
1318 mpis[i] = new(big.Int).SetBytes(mpiBytes)
1321 for _, mpi := range mpis {
1322 if mpi.Sign() <= 0 {
1327 priv.PrivateKey.P = mpis[0]
1328 priv.PrivateKey.Q = mpis[1]
1329 priv.PrivateKey.G = mpis[2]
1330 priv.PrivateKey.Y = mpis[3]
1331 priv.PrivateKey.X = mpis[4]
1332 priv.PublicKey.PublicKey = priv.PrivateKey.PublicKey
1334 a := new(big.Int).Exp(priv.PrivateKey.G, priv.PrivateKey.X, priv.PrivateKey.P)
1335 return a.Cmp(priv.PrivateKey.Y) == 0
1338 func getU8(in []byte) (uint8, []byte, bool) {
1342 return in[0], in[1:], true
1345 func getU16(in []byte) (uint16, []byte, bool) {
1349 r := uint16(in[0])<<8 | uint16(in[1])
1350 return r, in[2:], true
1353 func getU32(in []byte) (uint32, []byte, bool) {
1357 r := uint32(in[0])<<24 | uint32(in[1])<<16 | uint32(in[2])<<8 | uint32(in[3])
1358 return r, in[4:], true
1361 func getMPI(in []byte) (*big.Int, []byte, bool) {
1362 l, in, ok := getU32(in)
1363 if !ok || uint32(len(in)) < l {
1364 return nil, in, false
1366 r := new(big.Int).SetBytes(in[:l])
1367 return r, in[l:], true
1370 func getData(in []byte) ([]byte, []byte, bool) {
1371 l, in, ok := getU32(in)
1372 if !ok || uint32(len(in)) < l {
1373 return nil, in, false
1375 return in[:l], in[l:], true
1378 func getNBytes(in []byte, n int) ([]byte, []byte, bool) {
1380 return nil, in, false
1382 return in[:n], in[n:], true
1385 func appendU16(out []byte, v uint16) []byte {
1386 out = append(out, byte(v>>8), byte(v))
1390 func appendU32(out []byte, v uint32) []byte {
1391 out = append(out, byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
1395 func appendData(out, v []byte) []byte {
1396 out = appendU32(out, uint32(len(v)))
1397 out = append(out, v...)
1401 func appendMPI(out []byte, v *big.Int) []byte {
1403 out = appendU32(out, uint32(len(vBytes)))
1404 out = append(out, vBytes...)
1408 func appendMPIs(out []byte, mpis ...*big.Int) []byte {
1409 for _, mpi := range mpis {
1410 out = appendMPI(out, mpi)
1415 func zero(b []byte) {