otr.go 35 KB

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