otr.go 35 KB

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