rlpx.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. // Package rlpx implements the RLPx transport protocol.
  17. package rlpx
  18. import (
  19. "bytes"
  20. "crypto/aes"
  21. "crypto/cipher"
  22. "crypto/ecdsa"
  23. "crypto/elliptic"
  24. "crypto/hmac"
  25. "crypto/rand"
  26. "encoding/binary"
  27. "errors"
  28. "fmt"
  29. "hash"
  30. "io"
  31. mrand "math/rand"
  32. "net"
  33. "time"
  34. "github.com/VictoriaMetrics/fastcache"
  35. "github.com/golang/snappy"
  36. "github.com/oxtoacart/bpool"
  37. "golang.org/x/crypto/sha3"
  38. "github.com/ethereum/go-ethereum/crypto"
  39. "github.com/ethereum/go-ethereum/crypto/ecies"
  40. "github.com/ethereum/go-ethereum/rlp"
  41. )
  42. var snappyCache *fastcache.Cache
  43. func init() {
  44. snappyCache = fastcache.New(50 * 1024 * 1024)
  45. }
  46. // Conn is an RLPx network connection. It wraps a low-level network connection. The
  47. // underlying connection should not be used for other activity when it is wrapped by Conn.
  48. //
  49. // Before sending messages, a handshake must be performed by calling the Handshake method.
  50. // This type is not generally safe for concurrent use, but reading and writing of messages
  51. // may happen concurrently after the handshake.
  52. type Conn struct {
  53. dialDest *ecdsa.PublicKey
  54. conn net.Conn
  55. handshake *handshakeState
  56. snappy bool
  57. }
  58. type handshakeState struct {
  59. enc cipher.Stream
  60. dec cipher.Stream
  61. macCipher cipher.Block
  62. egressMAC hash.Hash
  63. ingressMAC hash.Hash
  64. }
  65. // NewConn wraps the given network connection. If dialDest is non-nil, the connection
  66. // behaves as the initiator during the handshake.
  67. func NewConn(conn net.Conn, dialDest *ecdsa.PublicKey) *Conn {
  68. return &Conn{
  69. dialDest: dialDest,
  70. conn: conn,
  71. }
  72. }
  73. // SetSnappy enables or disables snappy compression of messages. This is usually called
  74. // after the devp2p Hello message exchange when the negotiated version indicates that
  75. // compression is available on both ends of the connection.
  76. func (c *Conn) SetSnappy(snappy bool) {
  77. c.snappy = snappy
  78. }
  79. // SetReadDeadline sets the deadline for all future read operations.
  80. func (c *Conn) SetReadDeadline(time time.Time) error {
  81. return c.conn.SetReadDeadline(time)
  82. }
  83. // SetWriteDeadline sets the deadline for all future write operations.
  84. func (c *Conn) SetWriteDeadline(time time.Time) error {
  85. return c.conn.SetWriteDeadline(time)
  86. }
  87. // SetDeadline sets the deadline for all future read and write operations.
  88. func (c *Conn) SetDeadline(time time.Time) error {
  89. return c.conn.SetDeadline(time)
  90. }
  91. // Read reads a message from the connection.
  92. func (c *Conn) Read() (code uint64, data []byte, wireSize int, err error) {
  93. if c.handshake == nil {
  94. panic("can't ReadMsg before handshake")
  95. }
  96. frame, err := c.handshake.readFrame(c.conn)
  97. if err != nil {
  98. return 0, nil, 0, err
  99. }
  100. code, data, err = rlp.SplitUint64(frame)
  101. if err != nil {
  102. return 0, nil, 0, fmt.Errorf("invalid message code: %v", err)
  103. }
  104. wireSize = len(data)
  105. // If snappy is enabled, verify and decompress message.
  106. if c.snappy {
  107. var actualSize int
  108. actualSize, err = snappy.DecodedLen(data)
  109. if err != nil {
  110. return code, nil, 0, err
  111. }
  112. if actualSize > maxUint24 {
  113. return code, nil, 0, errPlainMessageTooLarge
  114. }
  115. data, err = snappy.Decode(nil, data)
  116. }
  117. return code, data, wireSize, err
  118. }
  119. func (h *handshakeState) readFrame(conn io.Reader) ([]byte, error) {
  120. // read the header
  121. headbuf := make([]byte, 32)
  122. if _, err := io.ReadFull(conn, headbuf); err != nil {
  123. return nil, err
  124. }
  125. // verify header mac
  126. shouldMAC := updateMAC(h.ingressMAC, h.macCipher, headbuf[:16])
  127. if !hmac.Equal(shouldMAC, headbuf[16:]) {
  128. return nil, errors.New("bad header MAC")
  129. }
  130. h.dec.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now decrypted
  131. fsize := readInt24(headbuf)
  132. // ignore protocol type for now
  133. // read the frame content
  134. var rsize = fsize // frame size rounded up to 16 byte boundary
  135. if padding := fsize % 16; padding > 0 {
  136. rsize += 16 - padding
  137. }
  138. framebuf := make([]byte, rsize)
  139. if _, err := io.ReadFull(conn, framebuf); err != nil {
  140. return nil, err
  141. }
  142. // read and validate frame MAC. we can re-use headbuf for that.
  143. h.ingressMAC.Write(framebuf)
  144. fmacseed := h.ingressMAC.Sum(nil)
  145. if _, err := io.ReadFull(conn, headbuf[:16]); err != nil {
  146. return nil, err
  147. }
  148. shouldMAC = updateMAC(h.ingressMAC, h.macCipher, fmacseed)
  149. if !hmac.Equal(shouldMAC, headbuf[:16]) {
  150. return nil, errors.New("bad frame MAC")
  151. }
  152. // decrypt frame content
  153. h.dec.XORKeyStream(framebuf, framebuf)
  154. return framebuf[:fsize], nil
  155. }
  156. // Write writes a message to the connection.
  157. //
  158. // Write returns the written size of the message data. This may be less than or equal to
  159. // len(data) depending on whether snappy compression is enabled.
  160. func (c *Conn) Write(code uint64, data []byte) (uint32, error) {
  161. if c.handshake == nil {
  162. panic("can't WriteMsg before handshake")
  163. }
  164. if len(data) > maxUint24 {
  165. return 0, errPlainMessageTooLarge
  166. }
  167. if c.snappy {
  168. if encodedResult, ok := snappyCache.HasGet(nil, data); ok {
  169. data = encodedResult
  170. } else {
  171. encodedData := snappy.Encode(nil, data)
  172. snappyCache.Set(data, encodedData)
  173. data = encodedData
  174. }
  175. }
  176. wireSize := uint32(len(data))
  177. err := c.handshake.writeFrame(c.conn, code, data)
  178. return wireSize, err
  179. }
  180. func (h *handshakeState) writeFrame(conn io.Writer, code uint64, data []byte) error {
  181. ptype, _ := rlp.EncodeToBytes(code)
  182. // write header
  183. headbuf := make([]byte, 32)
  184. fsize := len(ptype) + len(data)
  185. if fsize > maxUint24 {
  186. return errPlainMessageTooLarge
  187. }
  188. putInt24(uint32(fsize), headbuf)
  189. copy(headbuf[3:], zeroHeader)
  190. h.enc.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now encrypted
  191. // write header MAC
  192. copy(headbuf[16:], updateMAC(h.egressMAC, h.macCipher, headbuf[:16]))
  193. if _, err := conn.Write(headbuf); err != nil {
  194. return err
  195. }
  196. // write encrypted frame, updating the egress MAC hash with
  197. // the data written to conn.
  198. tee := cipher.StreamWriter{S: h.enc, W: io.MultiWriter(conn, h.egressMAC)}
  199. if _, err := tee.Write(ptype); err != nil {
  200. return err
  201. }
  202. if _, err := tee.Write(data); err != nil {
  203. return err
  204. }
  205. if padding := fsize % 16; padding > 0 {
  206. if _, err := tee.Write(zero16[:16-padding]); err != nil {
  207. return err
  208. }
  209. }
  210. // write frame MAC. egress MAC hash is up to date because
  211. // frame content was written to it as well.
  212. fmacseed := h.egressMAC.Sum(nil)
  213. mac := updateMAC(h.egressMAC, h.macCipher, fmacseed)
  214. _, err := conn.Write(mac)
  215. return err
  216. }
  217. func readInt24(b []byte) uint32 {
  218. return uint32(b[2]) | uint32(b[1])<<8 | uint32(b[0])<<16
  219. }
  220. func putInt24(v uint32, b []byte) {
  221. b[0] = byte(v >> 16)
  222. b[1] = byte(v >> 8)
  223. b[2] = byte(v)
  224. }
  225. const BpoolMaxSize = 4
  226. var bytepool = bpool.NewBytePool(BpoolMaxSize, aes.BlockSize)
  227. // updateMAC reseeds the given hash with encrypted seed.
  228. // it returns the first 16 bytes of the hash sum after seeding.
  229. func updateMAC(mac hash.Hash, block cipher.Block, seed []byte) []byte {
  230. aesbuf := bytepool.Get()
  231. block.Encrypt(aesbuf, mac.Sum(nil))
  232. for i := range aesbuf {
  233. aesbuf[i] ^= seed[i]
  234. }
  235. mac.Write(aesbuf)
  236. bytepool.Put(aesbuf)
  237. return mac.Sum(nil)[:16]
  238. }
  239. // Handshake performs the handshake. This must be called before any data is written
  240. // or read from the connection.
  241. func (c *Conn) Handshake(prv *ecdsa.PrivateKey) (*ecdsa.PublicKey, error) {
  242. var (
  243. sec Secrets
  244. err error
  245. )
  246. if c.dialDest != nil {
  247. sec, err = initiatorEncHandshake(c.conn, prv, c.dialDest)
  248. } else {
  249. sec, err = receiverEncHandshake(c.conn, prv)
  250. }
  251. if err != nil {
  252. return nil, err
  253. }
  254. c.InitWithSecrets(sec)
  255. return sec.remote, err
  256. }
  257. // InitWithSecrets injects connection secrets as if a handshake had
  258. // been performed. This cannot be called after the handshake.
  259. func (c *Conn) InitWithSecrets(sec Secrets) {
  260. if c.handshake != nil {
  261. panic("can't handshake twice")
  262. }
  263. macc, err := aes.NewCipher(sec.MAC)
  264. if err != nil {
  265. panic("invalid MAC secret: " + err.Error())
  266. }
  267. encc, err := aes.NewCipher(sec.AES)
  268. if err != nil {
  269. panic("invalid AES secret: " + err.Error())
  270. }
  271. // we use an all-zeroes IV for AES because the key used
  272. // for encryption is ephemeral.
  273. iv := make([]byte, encc.BlockSize())
  274. c.handshake = &handshakeState{
  275. enc: cipher.NewCTR(encc, iv),
  276. dec: cipher.NewCTR(encc, iv),
  277. macCipher: macc,
  278. egressMAC: sec.EgressMAC,
  279. ingressMAC: sec.IngressMAC,
  280. }
  281. }
  282. // Close closes the underlying network connection.
  283. func (c *Conn) Close() error {
  284. return c.conn.Close()
  285. }
  286. // Constants for the handshake.
  287. const (
  288. maxUint24 = int(^uint32(0) >> 8)
  289. sskLen = 16 // ecies.MaxSharedKeyLength(pubKey) / 2
  290. sigLen = crypto.SignatureLength // elliptic S256
  291. pubLen = 64 // 512 bit pubkey in uncompressed representation without format byte
  292. shaLen = 32 // hash length (for nonce etc)
  293. authMsgLen = sigLen + shaLen + pubLen + shaLen + 1
  294. authRespLen = pubLen + shaLen + 1
  295. eciesOverhead = 65 /* pubkey */ + 16 /* IV */ + 32 /* MAC */
  296. encAuthMsgLen = authMsgLen + eciesOverhead // size of encrypted pre-EIP-8 initiator handshake
  297. encAuthRespLen = authRespLen + eciesOverhead // size of encrypted pre-EIP-8 handshake reply
  298. )
  299. var (
  300. // this is used in place of actual frame header data.
  301. // TODO: replace this when Msg contains the protocol type code.
  302. zeroHeader = []byte{0xC2, 0x80, 0x80}
  303. // sixteen zero bytes
  304. zero16 = make([]byte, 16)
  305. // errPlainMessageTooLarge is returned if a decompressed message length exceeds
  306. // the allowed 24 bits (i.e. length >= 16MB).
  307. errPlainMessageTooLarge = errors.New("message length >= 16MB")
  308. )
  309. // Secrets represents the connection secrets which are negotiated during the handshake.
  310. type Secrets struct {
  311. AES, MAC []byte
  312. EgressMAC, IngressMAC hash.Hash
  313. remote *ecdsa.PublicKey
  314. }
  315. // encHandshake contains the state of the encryption handshake.
  316. type encHandshake struct {
  317. initiator bool
  318. remote *ecies.PublicKey // remote-pubk
  319. initNonce, respNonce []byte // nonce
  320. randomPrivKey *ecies.PrivateKey // ecdhe-random
  321. remoteRandomPub *ecies.PublicKey // ecdhe-random-pubk
  322. }
  323. // RLPx v4 handshake auth (defined in EIP-8).
  324. type authMsgV4 struct {
  325. gotPlain bool // whether read packet had plain format.
  326. Signature [sigLen]byte
  327. InitiatorPubkey [pubLen]byte
  328. Nonce [shaLen]byte
  329. Version uint
  330. // Ignore additional fields (forward-compatibility)
  331. Rest []rlp.RawValue `rlp:"tail"`
  332. }
  333. // RLPx v4 handshake response (defined in EIP-8).
  334. type authRespV4 struct {
  335. RandomPubkey [pubLen]byte
  336. Nonce [shaLen]byte
  337. Version uint
  338. // Ignore additional fields (forward-compatibility)
  339. Rest []rlp.RawValue `rlp:"tail"`
  340. }
  341. // receiverEncHandshake negotiates a session token on conn.
  342. // it should be called on the listening side of the connection.
  343. //
  344. // prv is the local client's private key.
  345. func receiverEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey) (s Secrets, err error) {
  346. authMsg := new(authMsgV4)
  347. authPacket, err := readHandshakeMsg(authMsg, encAuthMsgLen, prv, conn)
  348. if err != nil {
  349. return s, err
  350. }
  351. h := new(encHandshake)
  352. if err := h.handleAuthMsg(authMsg, prv); err != nil {
  353. return s, err
  354. }
  355. authRespMsg, err := h.makeAuthResp()
  356. if err != nil {
  357. return s, err
  358. }
  359. var authRespPacket []byte
  360. if authMsg.gotPlain {
  361. authRespPacket, err = authRespMsg.sealPlain(h)
  362. } else {
  363. authRespPacket, err = sealEIP8(authRespMsg, h)
  364. }
  365. if err != nil {
  366. return s, err
  367. }
  368. if _, err = conn.Write(authRespPacket); err != nil {
  369. return s, err
  370. }
  371. return h.secrets(authPacket, authRespPacket)
  372. }
  373. func (h *encHandshake) handleAuthMsg(msg *authMsgV4, prv *ecdsa.PrivateKey) error {
  374. // Import the remote identity.
  375. rpub, err := importPublicKey(msg.InitiatorPubkey[:])
  376. if err != nil {
  377. return err
  378. }
  379. h.initNonce = msg.Nonce[:]
  380. h.remote = rpub
  381. // Generate random keypair for ECDH.
  382. // If a private key is already set, use it instead of generating one (for testing).
  383. if h.randomPrivKey == nil {
  384. h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
  385. if err != nil {
  386. return err
  387. }
  388. }
  389. // Check the signature.
  390. token, err := h.staticSharedSecret(prv)
  391. if err != nil {
  392. return err
  393. }
  394. signedMsg := xor(token, h.initNonce)
  395. remoteRandomPub, err := crypto.Ecrecover(signedMsg, msg.Signature[:])
  396. if err != nil {
  397. return err
  398. }
  399. h.remoteRandomPub, _ = importPublicKey(remoteRandomPub)
  400. return nil
  401. }
  402. // secrets is called after the handshake is completed.
  403. // It extracts the connection secrets from the handshake values.
  404. func (h *encHandshake) secrets(auth, authResp []byte) (Secrets, error) {
  405. ecdheSecret, err := h.randomPrivKey.GenerateShared(h.remoteRandomPub, sskLen, sskLen)
  406. if err != nil {
  407. return Secrets{}, err
  408. }
  409. // derive base secrets from ephemeral key agreement
  410. sharedSecret := crypto.Keccak256(ecdheSecret, crypto.Keccak256(h.respNonce, h.initNonce))
  411. aesSecret := crypto.Keccak256(ecdheSecret, sharedSecret)
  412. s := Secrets{
  413. remote: h.remote.ExportECDSA(),
  414. AES: aesSecret,
  415. MAC: crypto.Keccak256(ecdheSecret, aesSecret),
  416. }
  417. // setup sha3 instances for the MACs
  418. mac1 := sha3.NewLegacyKeccak256()
  419. mac1.Write(xor(s.MAC, h.respNonce))
  420. mac1.Write(auth)
  421. mac2 := sha3.NewLegacyKeccak256()
  422. mac2.Write(xor(s.MAC, h.initNonce))
  423. mac2.Write(authResp)
  424. if h.initiator {
  425. s.EgressMAC, s.IngressMAC = mac1, mac2
  426. } else {
  427. s.EgressMAC, s.IngressMAC = mac2, mac1
  428. }
  429. return s, nil
  430. }
  431. // staticSharedSecret returns the static shared secret, the result
  432. // of key agreement between the local and remote static node key.
  433. func (h *encHandshake) staticSharedSecret(prv *ecdsa.PrivateKey) ([]byte, error) {
  434. return ecies.ImportECDSA(prv).GenerateShared(h.remote, sskLen, sskLen)
  435. }
  436. // initiatorEncHandshake negotiates a session token on conn.
  437. // it should be called on the dialing side of the connection.
  438. //
  439. // prv is the local client's private key.
  440. func initiatorEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, remote *ecdsa.PublicKey) (s Secrets, err error) {
  441. h := &encHandshake{initiator: true, remote: ecies.ImportECDSAPublic(remote)}
  442. authMsg, err := h.makeAuthMsg(prv)
  443. if err != nil {
  444. return s, err
  445. }
  446. authPacket, err := sealEIP8(authMsg, h)
  447. if err != nil {
  448. return s, err
  449. }
  450. if _, err = conn.Write(authPacket); err != nil {
  451. return s, err
  452. }
  453. authRespMsg := new(authRespV4)
  454. authRespPacket, err := readHandshakeMsg(authRespMsg, encAuthRespLen, prv, conn)
  455. if err != nil {
  456. return s, err
  457. }
  458. if err := h.handleAuthResp(authRespMsg); err != nil {
  459. return s, err
  460. }
  461. return h.secrets(authPacket, authRespPacket)
  462. }
  463. // makeAuthMsg creates the initiator handshake message.
  464. func (h *encHandshake) makeAuthMsg(prv *ecdsa.PrivateKey) (*authMsgV4, error) {
  465. // Generate random initiator nonce.
  466. h.initNonce = make([]byte, shaLen)
  467. _, err := rand.Read(h.initNonce)
  468. if err != nil {
  469. return nil, err
  470. }
  471. // Generate random keypair to for ECDH.
  472. h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
  473. if err != nil {
  474. return nil, err
  475. }
  476. // Sign known message: static-shared-secret ^ nonce
  477. token, err := h.staticSharedSecret(prv)
  478. if err != nil {
  479. return nil, err
  480. }
  481. signed := xor(token, h.initNonce)
  482. signature, err := crypto.Sign(signed, h.randomPrivKey.ExportECDSA())
  483. if err != nil {
  484. return nil, err
  485. }
  486. msg := new(authMsgV4)
  487. copy(msg.Signature[:], signature)
  488. copy(msg.InitiatorPubkey[:], crypto.FromECDSAPub(&prv.PublicKey)[1:])
  489. copy(msg.Nonce[:], h.initNonce)
  490. msg.Version = 4
  491. return msg, nil
  492. }
  493. func (h *encHandshake) handleAuthResp(msg *authRespV4) (err error) {
  494. h.respNonce = msg.Nonce[:]
  495. h.remoteRandomPub, err = importPublicKey(msg.RandomPubkey[:])
  496. return err
  497. }
  498. func (h *encHandshake) makeAuthResp() (msg *authRespV4, err error) {
  499. // Generate random nonce.
  500. h.respNonce = make([]byte, shaLen)
  501. if _, err = rand.Read(h.respNonce); err != nil {
  502. return nil, err
  503. }
  504. msg = new(authRespV4)
  505. copy(msg.Nonce[:], h.respNonce)
  506. copy(msg.RandomPubkey[:], exportPubkey(&h.randomPrivKey.PublicKey))
  507. msg.Version = 4
  508. return msg, nil
  509. }
  510. func (msg *authMsgV4) decodePlain(input []byte) {
  511. n := copy(msg.Signature[:], input)
  512. n += shaLen // skip sha3(initiator-ephemeral-pubk)
  513. n += copy(msg.InitiatorPubkey[:], input[n:])
  514. copy(msg.Nonce[:], input[n:])
  515. msg.Version = 4
  516. msg.gotPlain = true
  517. }
  518. func (msg *authRespV4) sealPlain(hs *encHandshake) ([]byte, error) {
  519. buf := make([]byte, authRespLen)
  520. n := copy(buf, msg.RandomPubkey[:])
  521. copy(buf[n:], msg.Nonce[:])
  522. return ecies.Encrypt(rand.Reader, hs.remote, buf, nil, nil)
  523. }
  524. func (msg *authRespV4) decodePlain(input []byte) {
  525. n := copy(msg.RandomPubkey[:], input)
  526. copy(msg.Nonce[:], input[n:])
  527. msg.Version = 4
  528. }
  529. var padSpace = make([]byte, 300)
  530. func sealEIP8(msg interface{}, h *encHandshake) ([]byte, error) {
  531. buf := new(bytes.Buffer)
  532. if err := rlp.Encode(buf, msg); err != nil {
  533. return nil, err
  534. }
  535. // pad with random amount of data. the amount needs to be at least 100 bytes to make
  536. // the message distinguishable from pre-EIP-8 handshakes.
  537. pad := padSpace[:mrand.Intn(len(padSpace)-100)+100]
  538. buf.Write(pad)
  539. prefix := make([]byte, 2)
  540. binary.BigEndian.PutUint16(prefix, uint16(buf.Len()+eciesOverhead))
  541. enc, err := ecies.Encrypt(rand.Reader, h.remote, buf.Bytes(), nil, prefix)
  542. return append(prefix, enc...), err
  543. }
  544. type plainDecoder interface {
  545. decodePlain([]byte)
  546. }
  547. func readHandshakeMsg(msg plainDecoder, plainSize int, prv *ecdsa.PrivateKey, r io.Reader) ([]byte, error) {
  548. buf := make([]byte, plainSize)
  549. if _, err := io.ReadFull(r, buf); err != nil {
  550. return buf, err
  551. }
  552. // Attempt decoding pre-EIP-8 "plain" format.
  553. key := ecies.ImportECDSA(prv)
  554. if dec, err := key.Decrypt(buf, nil, nil); err == nil {
  555. msg.decodePlain(dec)
  556. return buf, nil
  557. }
  558. // Could be EIP-8 format, try that.
  559. prefix := buf[:2]
  560. size := binary.BigEndian.Uint16(prefix)
  561. if size < uint16(plainSize) {
  562. return buf, fmt.Errorf("size underflow, need at least %d bytes", plainSize)
  563. }
  564. buf = append(buf, make([]byte, size-uint16(plainSize)+2)...)
  565. if _, err := io.ReadFull(r, buf[plainSize:]); err != nil {
  566. return buf, err
  567. }
  568. dec, err := key.Decrypt(buf[2:], nil, prefix)
  569. if err != nil {
  570. return buf, err
  571. }
  572. // Can't use rlp.DecodeBytes here because it rejects
  573. // trailing data (forward-compatibility).
  574. s := rlp.NewStream(bytes.NewReader(dec), 0)
  575. return buf, s.Decode(msg)
  576. }
  577. // importPublicKey unmarshals 512 bit public keys.
  578. func importPublicKey(pubKey []byte) (*ecies.PublicKey, error) {
  579. var pubKey65 []byte
  580. switch len(pubKey) {
  581. case 64:
  582. // add 'uncompressed key' flag
  583. pubKey65 = append([]byte{0x04}, pubKey...)
  584. case 65:
  585. pubKey65 = pubKey
  586. default:
  587. return nil, fmt.Errorf("invalid public key length %v (expect 64/65)", len(pubKey))
  588. }
  589. // TODO: fewer pointless conversions
  590. pub, err := crypto.UnmarshalPubkey(pubKey65)
  591. if err != nil {
  592. return nil, err
  593. }
  594. return ecies.ImportECDSAPublic(pub), nil
  595. }
  596. func exportPubkey(pub *ecies.PublicKey) []byte {
  597. if pub == nil {
  598. panic("nil pubkey")
  599. }
  600. return elliptic.Marshal(pub.Curve, pub.X, pub.Y)[1:]
  601. }
  602. func xor(one, other []byte) (xor []byte) {
  603. xor = make([]byte, len(one))
  604. for i := 0; i < len(one); i++ {
  605. xor[i] = one[i] ^ other[i]
  606. }
  607. return xor
  608. }