otr.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368
  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.
  4. // Package otr implements the Off The Record protocol as specified in
  5. // http://www.cypherpunks.ca/otr/Protocol-v2-3.1.0.html
  6. package otr
  7. import (
  8. "bytes"
  9. "crypto/aes"
  10. "crypto/cipher"
  11. "crypto/dsa"
  12. "crypto/hmac"
  13. "crypto/rand"
  14. "crypto/sha1"
  15. "crypto/sha256"
  16. "crypto/subtle"
  17. "encoding/base64"
  18. "encoding/hex"
  19. "errors"
  20. "hash"
  21. "io"
  22. "math/big"
  23. "strconv"
  24. )
  25. // SecurityChange describes a change in the security state of a Conversation.
  26. type SecurityChange int
  27. const (
  28. NoChange SecurityChange = iota
  29. // NewKeys indicates that a key exchange has completed. This occurs
  30. // when a conversation first becomes encrypted, and when the keys are
  31. // renegotiated within an encrypted conversation.
  32. NewKeys
  33. // SMPSecretNeeded indicates that the peer has started an
  34. // authentication and that we need to supply a secret. Call SMPQuestion
  35. // to get the optional, human readable challenge and then Authenticate
  36. // to supply the matching secret.
  37. SMPSecretNeeded
  38. // SMPComplete indicates that an authentication completed. The identity
  39. // of the peer has now been confirmed.
  40. SMPComplete
  41. // SMPFailed indicates that an authentication failed.
  42. SMPFailed
  43. // ConversationEnded indicates that the peer ended the secure
  44. // conversation.
  45. ConversationEnded
  46. )
  47. // QueryMessage can be sent to a peer to start an OTR conversation.
  48. var QueryMessage = []byte("?OTRv2?")
  49. var (
  50. fragmentPartSeparator = []byte(",")
  51. fragmentPrefix = []byte("?OTR,")
  52. msgPrefix = []byte("?OTR:")
  53. queryMarker = []byte("?OTR")
  54. )
  55. // isQuery attempts to parse an OTR query from msg and returns the greatest
  56. // common version, or 0 if msg is not an OTR query.
  57. func isQuery(msg []byte) (greatestCommonVersion int) {
  58. pos := bytes.Index(msg, queryMarker)
  59. if pos == -1 {
  60. return 0
  61. }
  62. for i, c := range msg[pos+len(queryMarker):] {
  63. if i == 0 {
  64. if c == '?' {
  65. // Indicates support for version 1, but we don't
  66. // implement that.
  67. continue
  68. }
  69. if c != 'v' {
  70. // Invalid message
  71. return 0
  72. }
  73. continue
  74. }
  75. if c == '?' {
  76. // End of message
  77. return
  78. }
  79. if c == ' ' || c == '\t' {
  80. // Probably an invalid message
  81. return 0
  82. }
  83. if c == '2' {
  84. greatestCommonVersion = 2
  85. }
  86. }
  87. return 0
  88. }
  89. const (
  90. statePlaintext = iota
  91. stateEncrypted
  92. stateFinished
  93. )
  94. const (
  95. authStateNone = iota
  96. authStateAwaitingDHKey
  97. authStateAwaitingRevealSig
  98. authStateAwaitingSig
  99. )
  100. const (
  101. msgTypeDHCommit = 2
  102. msgTypeData = 3
  103. msgTypeDHKey = 10
  104. msgTypeRevealSig = 17
  105. msgTypeSig = 18
  106. )
  107. const (
  108. // If the requested fragment size is less than this, it will be ignored.
  109. minFragmentSize = 18
  110. // Messages are padded to a multiple of this number of bytes.
  111. paddingGranularity = 256
  112. // The number of bytes in a Diffie-Hellman private value (320-bits).
  113. dhPrivateBytes = 40
  114. // The number of bytes needed to represent an element of the DSA
  115. // subgroup (160-bits).
  116. dsaSubgroupBytes = 20
  117. // The number of bytes of the MAC that are sent on the wire (160-bits).
  118. macPrefixBytes = 20
  119. )
  120. // These are the global, common group parameters for OTR.
  121. var (
  122. p *big.Int // group prime
  123. g *big.Int // group generator
  124. q *big.Int // group order
  125. pMinus2 *big.Int
  126. )
  127. func init() {
  128. p, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF", 16)
  129. q, _ = new(big.Int).SetString("7FFFFFFFFFFFFFFFE487ED5110B4611A62633145C06E0E68948127044533E63A0105DF531D89CD9128A5043CC71A026EF7CA8CD9E69D218D98158536F92F8A1BA7F09AB6B6A8E122F242DABB312F3F637A262174D31BF6B585FFAE5B7A035BF6F71C35FDAD44CFD2D74F9208BE258FF324943328F6722D9EE1003E5C50B1DF82CC6D241B0E2AE9CD348B1FD47E9267AFC1B2AE91EE51D6CB0E3179AB1042A95DCF6A9483B84B4B36B3861AA7255E4C0278BA36046511B993FFFFFFFFFFFFFFFF", 16)
  130. g = new(big.Int).SetInt64(2)
  131. pMinus2 = new(big.Int).Sub(p, g)
  132. }
  133. // Conversation represents a relation with a peer. The zero value is a valid
  134. // Conversation, although PrivateKey must be set.
  135. //
  136. // When communicating with a peer, all inbound messages should be passed to
  137. // Conversation.Receive and all outbound messages to Conversation.Send. The
  138. // Conversation will take care of maintaining the encryption state and
  139. // negotiating encryption as needed.
  140. type Conversation struct {
  141. // PrivateKey contains the private key to use to sign key exchanges.
  142. PrivateKey *PrivateKey
  143. // Rand can be set to override the entropy source. Otherwise,
  144. // crypto/rand will be used.
  145. Rand io.Reader
  146. // If FragmentSize is set, all messages produced by Receive and Send
  147. // will be fragmented into messages of, at most, this number of bytes.
  148. FragmentSize int
  149. // Once Receive has returned NewKeys once, the following fields are
  150. // valid.
  151. SSID [8]byte
  152. TheirPublicKey PublicKey
  153. state, authState int
  154. r [16]byte
  155. x, y *big.Int
  156. gx, gy *big.Int
  157. gxBytes []byte
  158. digest [sha256.Size]byte
  159. revealKeys, sigKeys akeKeys
  160. myKeyId uint32
  161. myCurrentDHPub *big.Int
  162. myCurrentDHPriv *big.Int
  163. myLastDHPub *big.Int
  164. myLastDHPriv *big.Int
  165. theirKeyId uint32
  166. theirCurrentDHPub *big.Int
  167. theirLastDHPub *big.Int
  168. keySlots [4]keySlot
  169. myCounter [8]byte
  170. theirLastCtr [8]byte
  171. oldMACs []byte
  172. k, n int // fragment state
  173. frag []byte
  174. smp smpState
  175. }
  176. // A keySlot contains key material for a specific (their keyid, my keyid) pair.
  177. type keySlot struct {
  178. // used is true if this slot is valid. If false, it's free for reuse.
  179. used bool
  180. theirKeyId uint32
  181. myKeyId uint32
  182. sendAESKey, recvAESKey []byte
  183. sendMACKey, recvMACKey []byte
  184. theirLastCtr [8]byte
  185. }
  186. // akeKeys are generated during key exchange. There's one set for the reveal
  187. // signature message and another for the signature message. In the protocol
  188. // spec the latter are indicated with a prime mark.
  189. type akeKeys struct {
  190. c [16]byte
  191. m1, m2 [32]byte
  192. }
  193. func (c *Conversation) rand() io.Reader {
  194. if c.Rand != nil {
  195. return c.Rand
  196. }
  197. return rand.Reader
  198. }
  199. func (c *Conversation) randMPI(buf []byte) *big.Int {
  200. _, err := io.ReadFull(c.rand(), buf)
  201. if err != nil {
  202. panic("otr: short read from random source")
  203. }
  204. return new(big.Int).SetBytes(buf)
  205. }
  206. // tlv represents the type-length value from the protocol.
  207. type tlv struct {
  208. typ, length uint16
  209. data []byte
  210. }
  211. const (
  212. tlvTypePadding = 0
  213. tlvTypeDisconnected = 1
  214. tlvTypeSMP1 = 2
  215. tlvTypeSMP2 = 3
  216. tlvTypeSMP3 = 4
  217. tlvTypeSMP4 = 5
  218. tlvTypeSMPAbort = 6
  219. tlvTypeSMP1WithQuestion = 7
  220. )
  221. // Receive handles a message from a peer. It returns a human readable message,
  222. // an indicator of whether that message was encrypted, a hint about the
  223. // encryption state and zero or more messages to send back to the peer.
  224. // These messages do not need to be passed to Send before transmission.
  225. func (c *Conversation) Receive(in []byte) (out []byte, encrypted bool, change SecurityChange, toSend [][]byte, err error) {
  226. if bytes.HasPrefix(in, fragmentPrefix) {
  227. in, err = c.processFragment(in)
  228. if in == nil || err != nil {
  229. return
  230. }
  231. }
  232. if bytes.HasPrefix(in, msgPrefix) && in[len(in)-1] == '.' {
  233. in = in[len(msgPrefix) : len(in)-1]
  234. } else if version := isQuery(in); version > 0 {
  235. c.authState = authStateAwaitingDHKey
  236. toSend = c.encode(c.generateDHCommit())
  237. return
  238. } else {
  239. // plaintext message
  240. out = in
  241. return
  242. }
  243. msg := make([]byte, base64.StdEncoding.DecodedLen(len(in)))
  244. msgLen, err := base64.StdEncoding.Decode(msg, in)
  245. if err != nil {
  246. err = errors.New("otr: invalid base64 encoding in message")
  247. return
  248. }
  249. msg = msg[:msgLen]
  250. // The first two bytes are the protocol version (2)
  251. if len(msg) < 3 || msg[0] != 0 || msg[1] != 2 {
  252. err = errors.New("otr: invalid OTR message")
  253. return
  254. }
  255. msgType := int(msg[2])
  256. msg = msg[3:]
  257. switch msgType {
  258. case msgTypeDHCommit:
  259. switch c.authState {
  260. case authStateNone:
  261. c.authState = authStateAwaitingRevealSig
  262. if err = c.processDHCommit(msg); err != nil {
  263. return
  264. }
  265. toSend = c.encode(c.generateDHKey())
  266. return
  267. case authStateAwaitingDHKey:
  268. // This is a 'SYN-crossing'. The greater digest wins.
  269. var cmp int
  270. if cmp, err = c.compareToDHCommit(msg); err != nil {
  271. return
  272. }
  273. if cmp > 0 {
  274. // We win. Retransmit DH commit.
  275. toSend = c.encode(c.serializeDHCommit())
  276. return
  277. } else {
  278. // They win. We forget about our DH commit.
  279. c.authState = authStateAwaitingRevealSig
  280. if err = c.processDHCommit(msg); err != nil {
  281. return
  282. }
  283. toSend = c.encode(c.generateDHKey())
  284. return
  285. }
  286. case authStateAwaitingRevealSig:
  287. if err = c.processDHCommit(msg); err != nil {
  288. return
  289. }
  290. toSend = c.encode(c.serializeDHKey())
  291. case authStateAwaitingSig:
  292. if err = c.processDHCommit(msg); err != nil {
  293. return
  294. }
  295. toSend = c.encode(c.generateDHKey())
  296. c.authState = authStateAwaitingRevealSig
  297. default:
  298. panic("bad state")
  299. }
  300. case msgTypeDHKey:
  301. switch c.authState {
  302. case authStateAwaitingDHKey:
  303. var isSame bool
  304. if isSame, err = c.processDHKey(msg); err != nil {
  305. return
  306. }
  307. if isSame {
  308. err = errors.New("otr: unexpected duplicate DH key")
  309. return
  310. }
  311. toSend = c.encode(c.generateRevealSig())
  312. c.authState = authStateAwaitingSig
  313. case authStateAwaitingSig:
  314. var isSame bool
  315. if isSame, err = c.processDHKey(msg); err != nil {
  316. return
  317. }
  318. if isSame {
  319. toSend = c.encode(c.serializeDHKey())
  320. }
  321. }
  322. case msgTypeRevealSig:
  323. if c.authState != authStateAwaitingRevealSig {
  324. return
  325. }
  326. if err = c.processRevealSig(msg); err != nil {
  327. return
  328. }
  329. toSend = c.encode(c.generateSig())
  330. c.authState = authStateNone
  331. c.state = stateEncrypted
  332. change = NewKeys
  333. case msgTypeSig:
  334. if c.authState != authStateAwaitingSig {
  335. return
  336. }
  337. if err = c.processSig(msg); err != nil {
  338. return
  339. }
  340. c.authState = authStateNone
  341. c.state = stateEncrypted
  342. change = NewKeys
  343. case msgTypeData:
  344. if c.state != stateEncrypted {
  345. err = errors.New("otr: encrypted message received without encrypted session established")
  346. return
  347. }
  348. var tlvs []tlv
  349. out, tlvs, err = c.processData(msg)
  350. encrypted = true
  351. EachTLV:
  352. for _, inTLV := range tlvs {
  353. switch inTLV.typ {
  354. case tlvTypeDisconnected:
  355. change = ConversationEnded
  356. break EachTLV
  357. case tlvTypeSMP1, tlvTypeSMP2, tlvTypeSMP3, tlvTypeSMP4, tlvTypeSMPAbort, tlvTypeSMP1WithQuestion:
  358. var reply tlv
  359. var complete bool
  360. reply, complete, err = c.processSMP(inTLV)
  361. if err == smpSecretMissingError {
  362. err = nil
  363. change = SMPSecretNeeded
  364. c.smp.saved = &inTLV
  365. return
  366. } else if err == smpFailureError {
  367. err = nil
  368. change = SMPFailed
  369. return
  370. }
  371. if complete {
  372. change = SMPComplete
  373. }
  374. if reply.typ != 0 {
  375. toSend = c.encode(c.generateData(nil, &reply))
  376. }
  377. break EachTLV
  378. default:
  379. // skip unknown TLVs
  380. }
  381. }
  382. default:
  383. err = errors.New("otr: unknown message type " + strconv.Itoa(msgType))
  384. }
  385. return
  386. }
  387. // Send takes a human readable message from the local user, possibly encrypts
  388. // it and returns zero one or more messages to send to the peer.
  389. func (c *Conversation) Send(msg []byte) ([][]byte, error) {
  390. switch c.state {
  391. case statePlaintext:
  392. return [][]byte{msg}, nil
  393. case stateEncrypted:
  394. return c.encode(c.generateData(msg, nil)), nil
  395. case stateFinished:
  396. return nil, errors.New("otr: cannot send message because secure conversation has finished")
  397. }
  398. return nil, errors.New("otr: cannot send message in current state")
  399. }
  400. // SMPQuestion returns the human readable challenge question from the peer.
  401. // It's only valid after Receive has returned SMPSecretNeeded.
  402. func (c *Conversation) SMPQuestion() string {
  403. return c.smp.question
  404. }
  405. // Authenticate begins an authentication with the peer. Authentication involves
  406. // an optional challenge message and a shared secret. The authentication
  407. // proceeds until either Receive returns SMPComplete, SMPSecretNeeded (which
  408. // indicates that a new authentication is happening and thus this one was
  409. // aborted) or SMPFailed.
  410. func (c *Conversation) Authenticate(question string, mutualSecret []byte) (toSend [][]byte, err error) {
  411. if c.state != stateEncrypted {
  412. err = errors.New("otr: can't authenticate a peer without a secure conversation established")
  413. return
  414. }
  415. if c.smp.saved != nil {
  416. c.calcSMPSecret(mutualSecret, false /* they started it */)
  417. var out tlv
  418. var complete bool
  419. out, complete, err = c.processSMP(*c.smp.saved)
  420. if complete {
  421. panic("SMP completed on the first message")
  422. }
  423. c.smp.saved = nil
  424. if out.typ != 0 {
  425. toSend = c.encode(c.generateData(nil, &out))
  426. }
  427. return
  428. }
  429. c.calcSMPSecret(mutualSecret, true /* we started it */)
  430. outs := c.startSMP(question)
  431. for _, out := range outs {
  432. toSend = append(toSend, c.encode(c.generateData(nil, &out))...)
  433. }
  434. return
  435. }
  436. var fragmentError = errors.New("otr: invalid OTR fragment")
  437. // processFragment processes a fragmented OTR message and possibly returns a
  438. // complete message. Fragmented messages look like "?OTR,k,n,msg," where k is
  439. // the fragment number (starting from 1), n is the number of fragments in this
  440. // message and msg is a substring of the base64 encoded message.
  441. func (c *Conversation) processFragment(in []byte) (out []byte, err error) {
  442. in = in[len(fragmentPrefix):] // remove "?OTR,"
  443. parts := bytes.Split(in, fragmentPartSeparator)
  444. if len(parts) != 4 || len(parts[3]) != 0 {
  445. return nil, fragmentError
  446. }
  447. k, err := strconv.Atoi(string(parts[0]))
  448. if err != nil {
  449. return nil, fragmentError
  450. }
  451. n, err := strconv.Atoi(string(parts[1]))
  452. if err != nil {
  453. return nil, fragmentError
  454. }
  455. if k < 1 || n < 1 || k > n {
  456. return nil, fragmentError
  457. }
  458. if k == 1 {
  459. c.frag = append(c.frag[:0], parts[2]...)
  460. c.k, c.n = k, n
  461. } else if n == c.n && k == c.k+1 {
  462. c.frag = append(c.frag, parts[2]...)
  463. c.k++
  464. } else {
  465. c.frag = c.frag[:0]
  466. c.n, c.k = 0, 0
  467. }
  468. if c.n > 0 && c.k == c.n {
  469. c.n, c.k = 0, 0
  470. return c.frag, nil
  471. }
  472. return nil, nil
  473. }
  474. func (c *Conversation) generateDHCommit() []byte {
  475. _, err := io.ReadFull(c.rand(), c.r[:])
  476. if err != nil {
  477. panic("otr: short read from random source")
  478. }
  479. var xBytes [dhPrivateBytes]byte
  480. c.x = c.randMPI(xBytes[:])
  481. c.gx = new(big.Int).Exp(g, c.x, p)
  482. c.gy = nil
  483. c.gxBytes = appendMPI(nil, c.gx)
  484. h := sha256.New()
  485. h.Write(c.gxBytes)
  486. h.Sum(c.digest[:0])
  487. aesCipher, err := aes.NewCipher(c.r[:])
  488. if err != nil {
  489. panic(err.Error())
  490. }
  491. var iv [aes.BlockSize]byte
  492. ctr := cipher.NewCTR(aesCipher, iv[:])
  493. ctr.XORKeyStream(c.gxBytes, c.gxBytes)
  494. return c.serializeDHCommit()
  495. }
  496. func (c *Conversation) serializeDHCommit() []byte {
  497. var ret []byte
  498. ret = appendU16(ret, 2) // protocol version
  499. ret = append(ret, msgTypeDHCommit)
  500. ret = appendData(ret, c.gxBytes)
  501. ret = appendData(ret, c.digest[:])
  502. return ret
  503. }
  504. func (c *Conversation) processDHCommit(in []byte) error {
  505. var ok1, ok2 bool
  506. c.gxBytes, in, ok1 = getData(in)
  507. digest, in, ok2 := getData(in)
  508. if !ok1 || !ok2 || len(in) > 0 {
  509. return errors.New("otr: corrupt DH commit message")
  510. }
  511. copy(c.digest[:], digest)
  512. return nil
  513. }
  514. func (c *Conversation) compareToDHCommit(in []byte) (int, error) {
  515. _, in, ok1 := getData(in)
  516. digest, in, ok2 := getData(in)
  517. if !ok1 || !ok2 || len(in) > 0 {
  518. return 0, errors.New("otr: corrupt DH commit message")
  519. }
  520. return bytes.Compare(c.digest[:], digest), nil
  521. }
  522. func (c *Conversation) generateDHKey() []byte {
  523. var yBytes [dhPrivateBytes]byte
  524. c.y = c.randMPI(yBytes[:])
  525. c.gy = new(big.Int).Exp(g, c.y, p)
  526. return c.serializeDHKey()
  527. }
  528. func (c *Conversation) serializeDHKey() []byte {
  529. var ret []byte
  530. ret = appendU16(ret, 2) // protocol version
  531. ret = append(ret, msgTypeDHKey)
  532. ret = appendMPI(ret, c.gy)
  533. return ret
  534. }
  535. func (c *Conversation) processDHKey(in []byte) (isSame bool, err error) {
  536. gy, in, ok := getMPI(in)
  537. if !ok {
  538. err = errors.New("otr: corrupt DH key message")
  539. return
  540. }
  541. if gy.Cmp(g) < 0 || gy.Cmp(pMinus2) > 0 {
  542. err = errors.New("otr: DH value out of range")
  543. return
  544. }
  545. if c.gy != nil {
  546. isSame = c.gy.Cmp(gy) == 0
  547. return
  548. }
  549. c.gy = gy
  550. return
  551. }
  552. func (c *Conversation) generateEncryptedSignature(keys *akeKeys, xFirst bool) ([]byte, []byte) {
  553. var xb []byte
  554. xb = c.PrivateKey.PublicKey.Serialize(xb)
  555. var verifyData []byte
  556. if xFirst {
  557. verifyData = appendMPI(verifyData, c.gx)
  558. verifyData = appendMPI(verifyData, c.gy)
  559. } else {
  560. verifyData = appendMPI(verifyData, c.gy)
  561. verifyData = appendMPI(verifyData, c.gx)
  562. }
  563. verifyData = append(verifyData, xb...)
  564. verifyData = appendU32(verifyData, c.myKeyId)
  565. mac := hmac.New(sha256.New, keys.m1[:])
  566. mac.Write(verifyData)
  567. mb := mac.Sum(nil)
  568. xb = appendU32(xb, c.myKeyId)
  569. xb = append(xb, c.PrivateKey.Sign(c.rand(), mb)...)
  570. aesCipher, err := aes.NewCipher(keys.c[:])
  571. if err != nil {
  572. panic(err.Error())
  573. }
  574. var iv [aes.BlockSize]byte
  575. ctr := cipher.NewCTR(aesCipher, iv[:])
  576. ctr.XORKeyStream(xb, xb)
  577. mac = hmac.New(sha256.New, keys.m2[:])
  578. encryptedSig := appendData(nil, xb)
  579. mac.Write(encryptedSig)
  580. return encryptedSig, mac.Sum(nil)
  581. }
  582. func (c *Conversation) generateRevealSig() []byte {
  583. s := new(big.Int).Exp(c.gy, c.x, p)
  584. c.calcAKEKeys(s)
  585. c.myKeyId++
  586. encryptedSig, mac := c.generateEncryptedSignature(&c.revealKeys, true /* gx comes first */)
  587. c.myCurrentDHPub = c.gx
  588. c.myCurrentDHPriv = c.x
  589. c.rotateDHKeys()
  590. incCounter(&c.myCounter)
  591. var ret []byte
  592. ret = appendU16(ret, 2)
  593. ret = append(ret, msgTypeRevealSig)
  594. ret = appendData(ret, c.r[:])
  595. ret = append(ret, encryptedSig...)
  596. ret = append(ret, mac[:20]...)
  597. return ret
  598. }
  599. func (c *Conversation) processEncryptedSig(encryptedSig, theirMAC []byte, keys *akeKeys, xFirst bool) error {
  600. mac := hmac.New(sha256.New, keys.m2[:])
  601. mac.Write(appendData(nil, encryptedSig))
  602. myMAC := mac.Sum(nil)[:20]
  603. if len(myMAC) != len(theirMAC) || subtle.ConstantTimeCompare(myMAC, theirMAC) == 0 {
  604. return errors.New("bad signature MAC in encrypted signature")
  605. }
  606. aesCipher, err := aes.NewCipher(keys.c[:])
  607. if err != nil {
  608. panic(err.Error())
  609. }
  610. var iv [aes.BlockSize]byte
  611. ctr := cipher.NewCTR(aesCipher, iv[:])
  612. ctr.XORKeyStream(encryptedSig, encryptedSig)
  613. sig := encryptedSig
  614. sig, ok1 := c.TheirPublicKey.Parse(sig)
  615. keyId, sig, ok2 := getU32(sig)
  616. if !ok1 || !ok2 {
  617. return errors.New("otr: corrupt encrypted signature")
  618. }
  619. var verifyData []byte
  620. if xFirst {
  621. verifyData = appendMPI(verifyData, c.gx)
  622. verifyData = appendMPI(verifyData, c.gy)
  623. } else {
  624. verifyData = appendMPI(verifyData, c.gy)
  625. verifyData = appendMPI(verifyData, c.gx)
  626. }
  627. verifyData = c.TheirPublicKey.Serialize(verifyData)
  628. verifyData = appendU32(verifyData, keyId)
  629. mac = hmac.New(sha256.New, keys.m1[:])
  630. mac.Write(verifyData)
  631. mb := mac.Sum(nil)
  632. sig, ok1 = c.TheirPublicKey.Verify(mb, sig)
  633. if !ok1 {
  634. return errors.New("bad signature in encrypted signature")
  635. }
  636. if len(sig) > 0 {
  637. return errors.New("corrupt encrypted signature")
  638. }
  639. c.theirKeyId = keyId
  640. zero(c.theirLastCtr[:])
  641. return nil
  642. }
  643. func (c *Conversation) processRevealSig(in []byte) error {
  644. r, in, ok1 := getData(in)
  645. encryptedSig, in, ok2 := getData(in)
  646. theirMAC := in
  647. if !ok1 || !ok2 || len(theirMAC) != 20 {
  648. return errors.New("otr: corrupt reveal signature message")
  649. }
  650. aesCipher, err := aes.NewCipher(r)
  651. if err != nil {
  652. return errors.New("otr: cannot create AES cipher from reveal signature message: " + err.Error())
  653. }
  654. var iv [aes.BlockSize]byte
  655. ctr := cipher.NewCTR(aesCipher, iv[:])
  656. ctr.XORKeyStream(c.gxBytes, c.gxBytes)
  657. h := sha256.New()
  658. h.Write(c.gxBytes)
  659. digest := h.Sum(nil)
  660. if len(digest) != len(c.digest) || subtle.ConstantTimeCompare(digest, c.digest[:]) == 0 {
  661. return errors.New("otr: bad commit MAC in reveal signature message")
  662. }
  663. var rest []byte
  664. c.gx, rest, ok1 = getMPI(c.gxBytes)
  665. if !ok1 || len(rest) > 0 {
  666. return errors.New("otr: gx corrupt after decryption")
  667. }
  668. if c.gx.Cmp(g) < 0 || c.gx.Cmp(pMinus2) > 0 {
  669. return errors.New("otr: DH value out of range")
  670. }
  671. s := new(big.Int).Exp(c.gx, c.y, p)
  672. c.calcAKEKeys(s)
  673. if err := c.processEncryptedSig(encryptedSig, theirMAC, &c.revealKeys, true /* gx comes first */); err != nil {
  674. return errors.New("otr: in reveal signature message: " + err.Error())
  675. }
  676. c.theirCurrentDHPub = c.gx
  677. c.theirLastDHPub = nil
  678. return nil
  679. }
  680. func (c *Conversation) generateSig() []byte {
  681. c.myKeyId++
  682. encryptedSig, mac := c.generateEncryptedSignature(&c.sigKeys, false /* gy comes first */)
  683. c.myCurrentDHPub = c.gy
  684. c.myCurrentDHPriv = c.y
  685. c.rotateDHKeys()
  686. incCounter(&c.myCounter)
  687. var ret []byte
  688. ret = appendU16(ret, 2)
  689. ret = append(ret, msgTypeSig)
  690. ret = append(ret, encryptedSig...)
  691. ret = append(ret, mac[:macPrefixBytes]...)
  692. return ret
  693. }
  694. func (c *Conversation) processSig(in []byte) error {
  695. encryptedSig, in, ok1 := getData(in)
  696. theirMAC := in
  697. if !ok1 || len(theirMAC) != macPrefixBytes {
  698. return errors.New("otr: corrupt signature message")
  699. }
  700. if err := c.processEncryptedSig(encryptedSig, theirMAC, &c.sigKeys, false /* gy comes first */); err != nil {
  701. return errors.New("otr: in signature message: " + err.Error())
  702. }
  703. c.theirCurrentDHPub = c.gy
  704. c.theirLastDHPub = nil
  705. return nil
  706. }
  707. func (c *Conversation) rotateDHKeys() {
  708. // evict slots using our retired key id
  709. for i := range c.keySlots {
  710. slot := &c.keySlots[i]
  711. if slot.used && slot.myKeyId == c.myKeyId-1 {
  712. slot.used = false
  713. c.oldMACs = append(c.oldMACs, slot.sendMACKey...)
  714. c.oldMACs = append(c.oldMACs, slot.recvMACKey...)
  715. }
  716. }
  717. c.myLastDHPriv = c.myCurrentDHPriv
  718. c.myLastDHPub = c.myCurrentDHPub
  719. var xBytes [dhPrivateBytes]byte
  720. c.myCurrentDHPriv = c.randMPI(xBytes[:])
  721. c.myCurrentDHPub = new(big.Int).Exp(g, c.myCurrentDHPriv, p)
  722. c.myKeyId++
  723. }
  724. func (c *Conversation) processData(in []byte) (out []byte, tlvs []tlv, err error) {
  725. origIn := in
  726. flags, in, ok1 := getU8(in)
  727. theirKeyId, in, ok2 := getU32(in)
  728. myKeyId, in, ok3 := getU32(in)
  729. y, in, ok4 := getMPI(in)
  730. counter, in, ok5 := getNBytes(in, 8)
  731. encrypted, in, ok6 := getData(in)
  732. macedData := origIn[:len(origIn)-len(in)]
  733. theirMAC, in, ok7 := getNBytes(in, macPrefixBytes)
  734. _, in, ok8 := getData(in)
  735. if !ok1 || !ok2 || !ok3 || !ok4 || !ok5 || !ok6 || !ok7 || !ok8 || len(in) > 0 {
  736. err = errors.New("otr: corrupt data message")
  737. return
  738. }
  739. ignoreErrors := flags&1 != 0
  740. slot, err := c.calcDataKeys(myKeyId, theirKeyId)
  741. if err != nil {
  742. if ignoreErrors {
  743. err = nil
  744. }
  745. return
  746. }
  747. mac := hmac.New(sha1.New, slot.recvMACKey)
  748. mac.Write([]byte{0, 2, 3})
  749. mac.Write(macedData)
  750. myMAC := mac.Sum(nil)
  751. if len(myMAC) != len(theirMAC) || subtle.ConstantTimeCompare(myMAC, theirMAC) == 0 {
  752. if !ignoreErrors {
  753. err = errors.New("otr: bad MAC on data message")
  754. }
  755. return
  756. }
  757. if bytes.Compare(counter, slot.theirLastCtr[:]) <= 0 {
  758. err = errors.New("otr: counter regressed")
  759. return
  760. }
  761. copy(slot.theirLastCtr[:], counter)
  762. var iv [aes.BlockSize]byte
  763. copy(iv[:], counter)
  764. aesCipher, err := aes.NewCipher(slot.recvAESKey)
  765. if err != nil {
  766. panic(err.Error())
  767. }
  768. ctr := cipher.NewCTR(aesCipher, iv[:])
  769. ctr.XORKeyStream(encrypted, encrypted)
  770. decrypted := encrypted
  771. if myKeyId == c.myKeyId {
  772. c.rotateDHKeys()
  773. }
  774. if theirKeyId == c.theirKeyId {
  775. // evict slots using their retired key id
  776. for i := range c.keySlots {
  777. slot := &c.keySlots[i]
  778. if slot.used && slot.theirKeyId == theirKeyId-1 {
  779. slot.used = false
  780. c.oldMACs = append(c.oldMACs, slot.sendMACKey...)
  781. c.oldMACs = append(c.oldMACs, slot.recvMACKey...)
  782. }
  783. }
  784. c.theirLastDHPub = c.theirCurrentDHPub
  785. c.theirKeyId++
  786. c.theirCurrentDHPub = y
  787. }
  788. if nulPos := bytes.IndexByte(decrypted, 0); nulPos >= 0 {
  789. out = decrypted[:nulPos]
  790. tlvData := decrypted[nulPos+1:]
  791. for len(tlvData) > 0 {
  792. var t tlv
  793. var ok1, ok2, ok3 bool
  794. t.typ, tlvData, ok1 = getU16(tlvData)
  795. t.length, tlvData, ok2 = getU16(tlvData)
  796. t.data, tlvData, ok3 = getNBytes(tlvData, int(t.length))
  797. if !ok1 || !ok2 || !ok3 {
  798. err = errors.New("otr: corrupt tlv data")
  799. }
  800. tlvs = append(tlvs, t)
  801. }
  802. } else {
  803. out = decrypted
  804. }
  805. return
  806. }
  807. func (c *Conversation) generateData(msg []byte, extra *tlv) []byte {
  808. slot, err := c.calcDataKeys(c.myKeyId-1, c.theirKeyId)
  809. if err != nil {
  810. panic("otr: failed to generate sending keys: " + err.Error())
  811. }
  812. var plaintext []byte
  813. plaintext = append(plaintext, msg...)
  814. plaintext = append(plaintext, 0)
  815. padding := paddingGranularity - ((len(plaintext) + 4) % paddingGranularity)
  816. plaintext = appendU16(plaintext, tlvTypePadding)
  817. plaintext = appendU16(plaintext, uint16(padding))
  818. for i := 0; i < padding; i++ {
  819. plaintext = append(plaintext, 0)
  820. }
  821. if extra != nil {
  822. plaintext = appendU16(plaintext, extra.typ)
  823. plaintext = appendU16(plaintext, uint16(len(extra.data)))
  824. plaintext = append(plaintext, extra.data...)
  825. }
  826. encrypted := make([]byte, len(plaintext))
  827. var iv [aes.BlockSize]byte
  828. copy(iv[:], c.myCounter[:])
  829. aesCipher, err := aes.NewCipher(slot.sendAESKey)
  830. if err != nil {
  831. panic(err.Error())
  832. }
  833. ctr := cipher.NewCTR(aesCipher, iv[:])
  834. ctr.XORKeyStream(encrypted, plaintext)
  835. var ret []byte
  836. ret = appendU16(ret, 2)
  837. ret = append(ret, msgTypeData)
  838. ret = append(ret, 0 /* flags */)
  839. ret = appendU32(ret, c.myKeyId-1)
  840. ret = appendU32(ret, c.theirKeyId)
  841. ret = appendMPI(ret, c.myCurrentDHPub)
  842. ret = append(ret, c.myCounter[:]...)
  843. ret = appendData(ret, encrypted)
  844. mac := hmac.New(sha1.New, slot.sendMACKey)
  845. mac.Write(ret)
  846. ret = append(ret, mac.Sum(nil)[:macPrefixBytes]...)
  847. ret = appendData(ret, c.oldMACs)
  848. c.oldMACs = nil
  849. incCounter(&c.myCounter)
  850. return ret
  851. }
  852. func incCounter(counter *[8]byte) {
  853. for i := 7; i >= 0; i-- {
  854. counter[i]++
  855. if counter[i] > 0 {
  856. break
  857. }
  858. }
  859. }
  860. // calcDataKeys computes the keys used to encrypt a data message given the key
  861. // IDs.
  862. func (c *Conversation) calcDataKeys(myKeyId, theirKeyId uint32) (slot *keySlot, err error) {
  863. // Check for a cache hit.
  864. for i := range c.keySlots {
  865. slot = &c.keySlots[i]
  866. if slot.used && slot.theirKeyId == theirKeyId && slot.myKeyId == myKeyId {
  867. return
  868. }
  869. }
  870. // Find an empty slot to write into.
  871. slot = nil
  872. for i := range c.keySlots {
  873. if !c.keySlots[i].used {
  874. slot = &c.keySlots[i]
  875. break
  876. }
  877. }
  878. if slot == nil {
  879. err = errors.New("otr: internal error: no key slots")
  880. return
  881. }
  882. var myPriv, myPub, theirPub *big.Int
  883. if myKeyId == c.myKeyId {
  884. myPriv = c.myCurrentDHPriv
  885. myPub = c.myCurrentDHPub
  886. } else if myKeyId == c.myKeyId-1 {
  887. myPriv = c.myLastDHPriv
  888. myPub = c.myLastDHPub
  889. } else {
  890. err = errors.New("otr: peer requested keyid " + strconv.FormatUint(uint64(myKeyId), 10) + " when I'm on " + strconv.FormatUint(uint64(c.myKeyId), 10))
  891. return
  892. }
  893. if theirKeyId == c.theirKeyId {
  894. theirPub = c.theirCurrentDHPub
  895. } else if theirKeyId == c.theirKeyId-1 && c.theirLastDHPub != nil {
  896. theirPub = c.theirLastDHPub
  897. } else {
  898. err = errors.New("otr: peer requested keyid " + strconv.FormatUint(uint64(myKeyId), 10) + " when they're on " + strconv.FormatUint(uint64(c.myKeyId), 10))
  899. return
  900. }
  901. var sendPrefixByte, recvPrefixByte [1]byte
  902. if myPub.Cmp(theirPub) > 0 {
  903. // we're the high end
  904. sendPrefixByte[0], recvPrefixByte[0] = 1, 2
  905. } else {
  906. // we're the low end
  907. sendPrefixByte[0], recvPrefixByte[0] = 2, 1
  908. }
  909. s := new(big.Int).Exp(theirPub, myPriv, p)
  910. sBytes := appendMPI(nil, s)
  911. h := sha1.New()
  912. h.Write(sendPrefixByte[:])
  913. h.Write(sBytes)
  914. slot.sendAESKey = h.Sum(slot.sendAESKey[:0])[:16]
  915. h.Reset()
  916. h.Write(slot.sendAESKey)
  917. slot.sendMACKey = h.Sum(slot.sendMACKey[:0])
  918. h.Reset()
  919. h.Write(recvPrefixByte[:])
  920. h.Write(sBytes)
  921. slot.recvAESKey = h.Sum(slot.recvAESKey[:0])[:16]
  922. h.Reset()
  923. h.Write(slot.recvAESKey)
  924. slot.recvMACKey = h.Sum(slot.recvMACKey[:0])
  925. zero(slot.theirLastCtr[:])
  926. return
  927. }
  928. func (c *Conversation) calcAKEKeys(s *big.Int) {
  929. mpi := appendMPI(nil, s)
  930. h := sha256.New()
  931. var cBytes [32]byte
  932. hashWithPrefix(c.SSID[:], 0, mpi, h)
  933. hashWithPrefix(cBytes[:], 1, mpi, h)
  934. copy(c.revealKeys.c[:], cBytes[:16])
  935. copy(c.sigKeys.c[:], cBytes[16:])
  936. hashWithPrefix(c.revealKeys.m1[:], 2, mpi, h)
  937. hashWithPrefix(c.revealKeys.m2[:], 3, mpi, h)
  938. hashWithPrefix(c.sigKeys.m1[:], 4, mpi, h)
  939. hashWithPrefix(c.sigKeys.m2[:], 5, mpi, h)
  940. }
  941. func hashWithPrefix(out []byte, prefix byte, in []byte, h hash.Hash) {
  942. h.Reset()
  943. var p [1]byte
  944. p[0] = prefix
  945. h.Write(p[:])
  946. h.Write(in)
  947. if len(out) == h.Size() {
  948. h.Sum(out[:0])
  949. } else {
  950. digest := h.Sum(nil)
  951. copy(out, digest)
  952. }
  953. }
  954. func (c *Conversation) encode(msg []byte) [][]byte {
  955. b64 := make([]byte, base64.StdEncoding.EncodedLen(len(msg))+len(msgPrefix)+1)
  956. base64.StdEncoding.Encode(b64[len(msgPrefix):], msg)
  957. copy(b64, msgPrefix)
  958. b64[len(b64)-1] = '.'
  959. if c.FragmentSize < minFragmentSize || len(b64) <= c.FragmentSize {
  960. // We can encode this in a single fragment.
  961. return [][]byte{b64}
  962. }
  963. // We have to fragment this message.
  964. var ret [][]byte
  965. bytesPerFragment := c.FragmentSize - minFragmentSize
  966. numFragments := (len(b64) + bytesPerFragment) / bytesPerFragment
  967. for i := 0; i < numFragments; i++ {
  968. frag := []byte("?OTR," + strconv.Itoa(i+1) + "," + strconv.Itoa(numFragments) + ",")
  969. todo := bytesPerFragment
  970. if todo > len(b64) {
  971. todo = len(b64)
  972. }
  973. frag = append(frag, b64[:todo]...)
  974. b64 = b64[todo:]
  975. frag = append(frag, ',')
  976. ret = append(ret, frag)
  977. }
  978. return ret
  979. }
  980. type PublicKey struct {
  981. dsa.PublicKey
  982. }
  983. func (pk *PublicKey) Parse(in []byte) ([]byte, bool) {
  984. var ok bool
  985. var pubKeyType uint16
  986. if pubKeyType, in, ok = getU16(in); !ok || pubKeyType != 0 {
  987. return nil, false
  988. }
  989. if pk.P, in, ok = getMPI(in); !ok {
  990. return nil, false
  991. }
  992. if pk.Q, in, ok = getMPI(in); !ok {
  993. return nil, false
  994. }
  995. if pk.G, in, ok = getMPI(in); !ok {
  996. return nil, false
  997. }
  998. if pk.Y, in, ok = getMPI(in); !ok {
  999. return nil, false
  1000. }
  1001. return in, true
  1002. }
  1003. func (pk *PublicKey) Serialize(in []byte) []byte {
  1004. in = appendU16(in, 0)
  1005. in = appendMPI(in, pk.P)
  1006. in = appendMPI(in, pk.Q)
  1007. in = appendMPI(in, pk.G)
  1008. in = appendMPI(in, pk.Y)
  1009. return in
  1010. }
  1011. // Fingerprint returns the 20-byte, binary fingerprint of the PublicKey.
  1012. func (pk *PublicKey) Fingerprint() []byte {
  1013. b := pk.Serialize(nil)
  1014. h := sha1.New()
  1015. h.Write(b[2:])
  1016. return h.Sum(nil)
  1017. }
  1018. func (pk *PublicKey) Verify(hashed, sig []byte) ([]byte, bool) {
  1019. if len(sig) != 2*dsaSubgroupBytes {
  1020. return nil, false
  1021. }
  1022. r := new(big.Int).SetBytes(sig[:dsaSubgroupBytes])
  1023. s := new(big.Int).SetBytes(sig[dsaSubgroupBytes:])
  1024. ok := dsa.Verify(&pk.PublicKey, hashed, r, s)
  1025. return sig[dsaSubgroupBytes*2:], ok
  1026. }
  1027. type PrivateKey struct {
  1028. PublicKey
  1029. dsa.PrivateKey
  1030. }
  1031. func (priv *PrivateKey) Sign(rand io.Reader, hashed []byte) []byte {
  1032. r, s, err := dsa.Sign(rand, &priv.PrivateKey, hashed)
  1033. if err != nil {
  1034. panic(err.Error())
  1035. }
  1036. rBytes := r.Bytes()
  1037. sBytes := s.Bytes()
  1038. if len(rBytes) > dsaSubgroupBytes || len(sBytes) > dsaSubgroupBytes {
  1039. panic("DSA signature too large")
  1040. }
  1041. out := make([]byte, 2*dsaSubgroupBytes)
  1042. copy(out[dsaSubgroupBytes-len(rBytes):], rBytes)
  1043. copy(out[len(out)-len(sBytes):], sBytes)
  1044. return out
  1045. }
  1046. func (priv *PrivateKey) Serialize(in []byte) []byte {
  1047. in = priv.PublicKey.Serialize(in)
  1048. in = appendMPI(in, priv.PrivateKey.X)
  1049. return in
  1050. }
  1051. func (priv *PrivateKey) Parse(in []byte) ([]byte, bool) {
  1052. in, ok := priv.PublicKey.Parse(in)
  1053. if !ok {
  1054. return in, ok
  1055. }
  1056. priv.PrivateKey.PublicKey = priv.PublicKey.PublicKey
  1057. priv.PrivateKey.X, in, ok = getMPI(in)
  1058. return in, ok
  1059. }
  1060. func (priv *PrivateKey) Generate(rand io.Reader) {
  1061. if err := dsa.GenerateParameters(&priv.PrivateKey.PublicKey.Parameters, rand, dsa.L1024N160); err != nil {
  1062. panic(err.Error())
  1063. }
  1064. if err := dsa.GenerateKey(&priv.PrivateKey, rand); err != nil {
  1065. panic(err.Error())
  1066. }
  1067. priv.PublicKey.PublicKey = priv.PrivateKey.PublicKey
  1068. }
  1069. func notHex(r rune) bool {
  1070. if r >= '0' && r <= '9' ||
  1071. r >= 'a' && r <= 'f' ||
  1072. r >= 'A' && r <= 'F' {
  1073. return false
  1074. }
  1075. return true
  1076. }
  1077. // Import parses the contents of a libotr private key file.
  1078. func (priv *PrivateKey) Import(in []byte) bool {
  1079. mpiStart := []byte(" #")
  1080. mpis := make([]*big.Int, 5)
  1081. for i := 0; i < len(mpis); i++ {
  1082. start := bytes.Index(in, mpiStart)
  1083. if start == -1 {
  1084. return false
  1085. }
  1086. in = in[start+len(mpiStart):]
  1087. end := bytes.IndexFunc(in, notHex)
  1088. if end == -1 {
  1089. return false
  1090. }
  1091. hexBytes := in[:end]
  1092. in = in[end:]
  1093. if len(hexBytes)&1 != 0 {
  1094. return false
  1095. }
  1096. mpiBytes := make([]byte, len(hexBytes)/2)
  1097. if _, err := hex.Decode(mpiBytes, hexBytes); err != nil {
  1098. return false
  1099. }
  1100. mpis[i] = new(big.Int).SetBytes(mpiBytes)
  1101. }
  1102. priv.PrivateKey.P = mpis[0]
  1103. priv.PrivateKey.Q = mpis[1]
  1104. priv.PrivateKey.G = mpis[2]
  1105. priv.PrivateKey.Y = mpis[3]
  1106. priv.PrivateKey.X = mpis[4]
  1107. priv.PublicKey.PublicKey = priv.PrivateKey.PublicKey
  1108. a := new(big.Int).Exp(priv.PrivateKey.G, priv.PrivateKey.X, priv.PrivateKey.P)
  1109. return a.Cmp(priv.PrivateKey.Y) == 0
  1110. }
  1111. func getU8(in []byte) (uint8, []byte, bool) {
  1112. if len(in) < 1 {
  1113. return 0, in, false
  1114. }
  1115. return in[0], in[1:], true
  1116. }
  1117. func getU16(in []byte) (uint16, []byte, bool) {
  1118. if len(in) < 2 {
  1119. return 0, in, false
  1120. }
  1121. r := uint16(in[0])<<8 | uint16(in[1])
  1122. return r, in[2:], true
  1123. }
  1124. func getU32(in []byte) (uint32, []byte, bool) {
  1125. if len(in) < 4 {
  1126. return 0, in, false
  1127. }
  1128. r := uint32(in[0])<<24 | uint32(in[1])<<16 | uint32(in[2])<<8 | uint32(in[3])
  1129. return r, in[4:], true
  1130. }
  1131. func getMPI(in []byte) (*big.Int, []byte, bool) {
  1132. l, in, ok := getU32(in)
  1133. if !ok || uint32(len(in)) < l {
  1134. return nil, in, false
  1135. }
  1136. r := new(big.Int).SetBytes(in[:l])
  1137. return r, in[l:], true
  1138. }
  1139. func getData(in []byte) ([]byte, []byte, bool) {
  1140. l, in, ok := getU32(in)
  1141. if !ok || uint32(len(in)) < l {
  1142. return nil, in, false
  1143. }
  1144. return in[:l], in[l:], true
  1145. }
  1146. func getNBytes(in []byte, n int) ([]byte, []byte, bool) {
  1147. if len(in) < n {
  1148. return nil, in, false
  1149. }
  1150. return in[:n], in[n:], true
  1151. }
  1152. func appendU16(out []byte, v uint16) []byte {
  1153. out = append(out, byte(v>>8), byte(v))
  1154. return out
  1155. }
  1156. func appendU32(out []byte, v uint32) []byte {
  1157. out = append(out, byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
  1158. return out
  1159. }
  1160. func appendData(out, v []byte) []byte {
  1161. out = appendU32(out, uint32(len(v)))
  1162. out = append(out, v...)
  1163. return out
  1164. }
  1165. func appendMPI(out []byte, v *big.Int) []byte {
  1166. vBytes := v.Bytes()
  1167. out = appendU32(out, uint32(len(vBytes)))
  1168. out = append(out, vBytes...)
  1169. return out
  1170. }
  1171. func appendMPIs(out []byte, mpis ...*big.Int) []byte {
  1172. for _, mpi := range mpis {
  1173. out = appendMPI(out, mpi)
  1174. }
  1175. return out
  1176. }
  1177. func zero(b []byte) {
  1178. for i := range b {
  1179. b[i] = 0
  1180. }
  1181. }