rlpx.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  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 p2p
  17. import (
  18. "bytes"
  19. "crypto/aes"
  20. "crypto/cipher"
  21. "crypto/ecdsa"
  22. "crypto/elliptic"
  23. "crypto/hmac"
  24. "crypto/rand"
  25. "encoding/binary"
  26. "errors"
  27. "fmt"
  28. "hash"
  29. "io"
  30. "io/ioutil"
  31. mrand "math/rand"
  32. "net"
  33. "sync"
  34. "time"
  35. "github.com/ethereum/go-ethereum/common/bitutil"
  36. "github.com/ethereum/go-ethereum/crypto"
  37. "github.com/ethereum/go-ethereum/crypto/ecies"
  38. "github.com/ethereum/go-ethereum/rlp"
  39. "github.com/golang/snappy"
  40. "golang.org/x/crypto/sha3"
  41. )
  42. const (
  43. maxUint24 = ^uint32(0) >> 8
  44. sskLen = 16 // ecies.MaxSharedKeyLength(pubKey) / 2
  45. sigLen = 65 // elliptic S256
  46. pubLen = 64 // 512 bit pubkey in uncompressed representation without format byte
  47. shaLen = 32 // hash length (for nonce etc)
  48. authMsgLen = sigLen + shaLen + pubLen + shaLen + 1
  49. authRespLen = pubLen + shaLen + 1
  50. eciesOverhead = 65 /* pubkey */ + 16 /* IV */ + 32 /* MAC */
  51. encAuthMsgLen = authMsgLen + eciesOverhead // size of encrypted pre-EIP-8 initiator handshake
  52. encAuthRespLen = authRespLen + eciesOverhead // size of encrypted pre-EIP-8 handshake reply
  53. // total timeout for encryption handshake and protocol
  54. // handshake in both directions.
  55. handshakeTimeout = 5 * time.Second
  56. // This is the timeout for sending the disconnect reason.
  57. // This is shorter than the usual timeout because we don't want
  58. // to wait if the connection is known to be bad anyway.
  59. discWriteTimeout = 1 * time.Second
  60. )
  61. // errPlainMessageTooLarge is returned if a decompressed message length exceeds
  62. // the allowed 24 bits (i.e. length >= 16MB).
  63. var errPlainMessageTooLarge = errors.New("message length >= 16MB")
  64. // rlpx is the transport protocol used by actual (non-test) connections.
  65. // It wraps the frame encoder with locks and read/write deadlines.
  66. type rlpx struct {
  67. fd net.Conn
  68. rmu, wmu sync.Mutex
  69. rw *rlpxFrameRW
  70. }
  71. func newRLPX(fd net.Conn) transport {
  72. fd.SetDeadline(time.Now().Add(handshakeTimeout))
  73. return &rlpx{fd: fd}
  74. }
  75. func (t *rlpx) ReadMsg() (Msg, error) {
  76. t.rmu.Lock()
  77. defer t.rmu.Unlock()
  78. t.fd.SetReadDeadline(time.Now().Add(frameReadTimeout))
  79. return t.rw.ReadMsg()
  80. }
  81. func (t *rlpx) WriteMsg(msg Msg) error {
  82. t.wmu.Lock()
  83. defer t.wmu.Unlock()
  84. t.fd.SetWriteDeadline(time.Now().Add(frameWriteTimeout))
  85. return t.rw.WriteMsg(msg)
  86. }
  87. func (t *rlpx) close(err error) {
  88. t.wmu.Lock()
  89. defer t.wmu.Unlock()
  90. // Tell the remote end why we're disconnecting if possible.
  91. if t.rw != nil {
  92. if r, ok := err.(DiscReason); ok && r != DiscNetworkError {
  93. // rlpx tries to send DiscReason to disconnected peer
  94. // if the connection is net.Pipe (in-memory simulation)
  95. // it hangs forever, since net.Pipe does not implement
  96. // a write deadline. Because of this only try to send
  97. // the disconnect reason message if there is no error.
  98. if err := t.fd.SetWriteDeadline(time.Now().Add(discWriteTimeout)); err == nil {
  99. SendItems(t.rw, discMsg, r)
  100. }
  101. }
  102. }
  103. t.fd.Close()
  104. }
  105. func (t *rlpx) doProtoHandshake(our *protoHandshake) (their *protoHandshake, err error) {
  106. // Writing our handshake happens concurrently, we prefer
  107. // returning the handshake read error. If the remote side
  108. // disconnects us early with a valid reason, we should return it
  109. // as the error so it can be tracked elsewhere.
  110. werr := make(chan error, 1)
  111. go func() { werr <- Send(t.rw, handshakeMsg, our) }()
  112. if their, err = readProtocolHandshake(t.rw); err != nil {
  113. <-werr // make sure the write terminates too
  114. return nil, err
  115. }
  116. if err := <-werr; err != nil {
  117. return nil, fmt.Errorf("write error: %v", err)
  118. }
  119. // If the protocol version supports Snappy encoding, upgrade immediately
  120. t.rw.snappy = their.Version >= snappyProtocolVersion
  121. return their, nil
  122. }
  123. func readProtocolHandshake(rw MsgReader) (*protoHandshake, error) {
  124. msg, err := rw.ReadMsg()
  125. if err != nil {
  126. return nil, err
  127. }
  128. if msg.Size > baseProtocolMaxMsgSize {
  129. return nil, fmt.Errorf("message too big")
  130. }
  131. if msg.Code == discMsg {
  132. // Disconnect before protocol handshake is valid according to the
  133. // spec and we send it ourself if the post-handshake checks fail.
  134. // We can't return the reason directly, though, because it is echoed
  135. // back otherwise. Wrap it in a string instead.
  136. var reason [1]DiscReason
  137. rlp.Decode(msg.Payload, &reason)
  138. return nil, reason[0]
  139. }
  140. if msg.Code != handshakeMsg {
  141. return nil, fmt.Errorf("expected handshake, got %x", msg.Code)
  142. }
  143. var hs protoHandshake
  144. if err := msg.Decode(&hs); err != nil {
  145. return nil, err
  146. }
  147. if len(hs.ID) != 64 || !bitutil.TestBytes(hs.ID) {
  148. return nil, DiscInvalidIdentity
  149. }
  150. return &hs, nil
  151. }
  152. // doEncHandshake runs the protocol handshake using authenticated
  153. // messages. the protocol handshake is the first authenticated message
  154. // and also verifies whether the encryption handshake 'worked' and the
  155. // remote side actually provided the right public key.
  156. func (t *rlpx) doEncHandshake(prv *ecdsa.PrivateKey, dial *ecdsa.PublicKey) (*ecdsa.PublicKey, error) {
  157. var (
  158. sec secrets
  159. err error
  160. )
  161. if dial == nil {
  162. sec, err = receiverEncHandshake(t.fd, prv)
  163. } else {
  164. sec, err = initiatorEncHandshake(t.fd, prv, dial)
  165. }
  166. if err != nil {
  167. return nil, err
  168. }
  169. t.wmu.Lock()
  170. t.rw = newRLPXFrameRW(t.fd, sec)
  171. t.wmu.Unlock()
  172. return sec.Remote.ExportECDSA(), nil
  173. }
  174. // encHandshake contains the state of the encryption handshake.
  175. type encHandshake struct {
  176. initiator bool
  177. remote *ecies.PublicKey // remote-pubk
  178. initNonce, respNonce []byte // nonce
  179. randomPrivKey *ecies.PrivateKey // ecdhe-random
  180. remoteRandomPub *ecies.PublicKey // ecdhe-random-pubk
  181. }
  182. // secrets represents the connection secrets
  183. // which are negotiated during the encryption handshake.
  184. type secrets struct {
  185. Remote *ecies.PublicKey
  186. AES, MAC []byte
  187. EgressMAC, IngressMAC hash.Hash
  188. Token []byte
  189. }
  190. // RLPx v4 handshake auth (defined in EIP-8).
  191. type authMsgV4 struct {
  192. gotPlain bool // whether read packet had plain format.
  193. Signature [sigLen]byte
  194. InitiatorPubkey [pubLen]byte
  195. Nonce [shaLen]byte
  196. Version uint
  197. // Ignore additional fields (forward-compatibility)
  198. Rest []rlp.RawValue `rlp:"tail"`
  199. }
  200. // RLPx v4 handshake response (defined in EIP-8).
  201. type authRespV4 struct {
  202. RandomPubkey [pubLen]byte
  203. Nonce [shaLen]byte
  204. Version uint
  205. // Ignore additional fields (forward-compatibility)
  206. Rest []rlp.RawValue `rlp:"tail"`
  207. }
  208. // secrets is called after the handshake is completed.
  209. // It extracts the connection secrets from the handshake values.
  210. func (h *encHandshake) secrets(auth, authResp []byte) (secrets, error) {
  211. ecdheSecret, err := h.randomPrivKey.GenerateShared(h.remoteRandomPub, sskLen, sskLen)
  212. if err != nil {
  213. return secrets{}, err
  214. }
  215. // derive base secrets from ephemeral key agreement
  216. sharedSecret := crypto.Keccak256(ecdheSecret, crypto.Keccak256(h.respNonce, h.initNonce))
  217. aesSecret := crypto.Keccak256(ecdheSecret, sharedSecret)
  218. s := secrets{
  219. Remote: h.remote,
  220. AES: aesSecret,
  221. MAC: crypto.Keccak256(ecdheSecret, aesSecret),
  222. }
  223. // setup sha3 instances for the MACs
  224. mac1 := sha3.NewLegacyKeccak256()
  225. mac1.Write(xor(s.MAC, h.respNonce))
  226. mac1.Write(auth)
  227. mac2 := sha3.NewLegacyKeccak256()
  228. mac2.Write(xor(s.MAC, h.initNonce))
  229. mac2.Write(authResp)
  230. if h.initiator {
  231. s.EgressMAC, s.IngressMAC = mac1, mac2
  232. } else {
  233. s.EgressMAC, s.IngressMAC = mac2, mac1
  234. }
  235. return s, nil
  236. }
  237. // staticSharedSecret returns the static shared secret, the result
  238. // of key agreement between the local and remote static node key.
  239. func (h *encHandshake) staticSharedSecret(prv *ecdsa.PrivateKey) ([]byte, error) {
  240. return ecies.ImportECDSA(prv).GenerateShared(h.remote, sskLen, sskLen)
  241. }
  242. // initiatorEncHandshake negotiates a session token on conn.
  243. // it should be called on the dialing side of the connection.
  244. //
  245. // prv is the local client's private key.
  246. func initiatorEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, remote *ecdsa.PublicKey) (s secrets, err error) {
  247. h := &encHandshake{initiator: true, remote: ecies.ImportECDSAPublic(remote)}
  248. authMsg, err := h.makeAuthMsg(prv)
  249. if err != nil {
  250. return s, err
  251. }
  252. authPacket, err := sealEIP8(authMsg, h)
  253. if err != nil {
  254. return s, err
  255. }
  256. if _, err = conn.Write(authPacket); err != nil {
  257. return s, err
  258. }
  259. authRespMsg := new(authRespV4)
  260. authRespPacket, err := readHandshakeMsg(authRespMsg, encAuthRespLen, prv, conn)
  261. if err != nil {
  262. return s, err
  263. }
  264. if err := h.handleAuthResp(authRespMsg); err != nil {
  265. return s, err
  266. }
  267. return h.secrets(authPacket, authRespPacket)
  268. }
  269. // makeAuthMsg creates the initiator handshake message.
  270. func (h *encHandshake) makeAuthMsg(prv *ecdsa.PrivateKey) (*authMsgV4, error) {
  271. // Generate random initiator nonce.
  272. h.initNonce = make([]byte, shaLen)
  273. _, err := rand.Read(h.initNonce)
  274. if err != nil {
  275. return nil, err
  276. }
  277. // Generate random keypair to for ECDH.
  278. h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
  279. if err != nil {
  280. return nil, err
  281. }
  282. // Sign known message: static-shared-secret ^ nonce
  283. token, err := h.staticSharedSecret(prv)
  284. if err != nil {
  285. return nil, err
  286. }
  287. signed := xor(token, h.initNonce)
  288. signature, err := crypto.Sign(signed, h.randomPrivKey.ExportECDSA())
  289. if err != nil {
  290. return nil, err
  291. }
  292. msg := new(authMsgV4)
  293. copy(msg.Signature[:], signature)
  294. copy(msg.InitiatorPubkey[:], crypto.FromECDSAPub(&prv.PublicKey)[1:])
  295. copy(msg.Nonce[:], h.initNonce)
  296. msg.Version = 4
  297. return msg, nil
  298. }
  299. func (h *encHandshake) handleAuthResp(msg *authRespV4) (err error) {
  300. h.respNonce = msg.Nonce[:]
  301. h.remoteRandomPub, err = importPublicKey(msg.RandomPubkey[:])
  302. return err
  303. }
  304. // receiverEncHandshake negotiates a session token on conn.
  305. // it should be called on the listening side of the connection.
  306. //
  307. // prv is the local client's private key.
  308. func receiverEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey) (s secrets, err error) {
  309. authMsg := new(authMsgV4)
  310. authPacket, err := readHandshakeMsg(authMsg, encAuthMsgLen, prv, conn)
  311. if err != nil {
  312. return s, err
  313. }
  314. h := new(encHandshake)
  315. if err := h.handleAuthMsg(authMsg, prv); err != nil {
  316. return s, err
  317. }
  318. authRespMsg, err := h.makeAuthResp()
  319. if err != nil {
  320. return s, err
  321. }
  322. var authRespPacket []byte
  323. if authMsg.gotPlain {
  324. authRespPacket, err = authRespMsg.sealPlain(h)
  325. } else {
  326. authRespPacket, err = sealEIP8(authRespMsg, h)
  327. }
  328. if err != nil {
  329. return s, err
  330. }
  331. if _, err = conn.Write(authRespPacket); err != nil {
  332. return s, err
  333. }
  334. return h.secrets(authPacket, authRespPacket)
  335. }
  336. func (h *encHandshake) handleAuthMsg(msg *authMsgV4, prv *ecdsa.PrivateKey) error {
  337. // Import the remote identity.
  338. rpub, err := importPublicKey(msg.InitiatorPubkey[:])
  339. if err != nil {
  340. return err
  341. }
  342. h.initNonce = msg.Nonce[:]
  343. h.remote = rpub
  344. // Generate random keypair for ECDH.
  345. // If a private key is already set, use it instead of generating one (for testing).
  346. if h.randomPrivKey == nil {
  347. h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
  348. if err != nil {
  349. return err
  350. }
  351. }
  352. // Check the signature.
  353. token, err := h.staticSharedSecret(prv)
  354. if err != nil {
  355. return err
  356. }
  357. signedMsg := xor(token, h.initNonce)
  358. remoteRandomPub, err := crypto.Ecrecover(signedMsg, msg.Signature[:])
  359. if err != nil {
  360. return err
  361. }
  362. h.remoteRandomPub, _ = importPublicKey(remoteRandomPub)
  363. return nil
  364. }
  365. func (h *encHandshake) makeAuthResp() (msg *authRespV4, err error) {
  366. // Generate random nonce.
  367. h.respNonce = make([]byte, shaLen)
  368. if _, err = rand.Read(h.respNonce); err != nil {
  369. return nil, err
  370. }
  371. msg = new(authRespV4)
  372. copy(msg.Nonce[:], h.respNonce)
  373. copy(msg.RandomPubkey[:], exportPubkey(&h.randomPrivKey.PublicKey))
  374. msg.Version = 4
  375. return msg, nil
  376. }
  377. func (msg *authMsgV4) sealPlain(h *encHandshake) ([]byte, error) {
  378. buf := make([]byte, authMsgLen)
  379. n := copy(buf, msg.Signature[:])
  380. n += copy(buf[n:], crypto.Keccak256(exportPubkey(&h.randomPrivKey.PublicKey)))
  381. n += copy(buf[n:], msg.InitiatorPubkey[:])
  382. n += copy(buf[n:], msg.Nonce[:])
  383. buf[n] = 0 // token-flag
  384. return ecies.Encrypt(rand.Reader, h.remote, buf, nil, nil)
  385. }
  386. func (msg *authMsgV4) decodePlain(input []byte) {
  387. n := copy(msg.Signature[:], input)
  388. n += shaLen // skip sha3(initiator-ephemeral-pubk)
  389. n += copy(msg.InitiatorPubkey[:], input[n:])
  390. copy(msg.Nonce[:], input[n:])
  391. msg.Version = 4
  392. msg.gotPlain = true
  393. }
  394. func (msg *authRespV4) sealPlain(hs *encHandshake) ([]byte, error) {
  395. buf := make([]byte, authRespLen)
  396. n := copy(buf, msg.RandomPubkey[:])
  397. copy(buf[n:], msg.Nonce[:])
  398. return ecies.Encrypt(rand.Reader, hs.remote, buf, nil, nil)
  399. }
  400. func (msg *authRespV4) decodePlain(input []byte) {
  401. n := copy(msg.RandomPubkey[:], input)
  402. copy(msg.Nonce[:], input[n:])
  403. msg.Version = 4
  404. }
  405. var padSpace = make([]byte, 300)
  406. func sealEIP8(msg interface{}, h *encHandshake) ([]byte, error) {
  407. buf := new(bytes.Buffer)
  408. if err := rlp.Encode(buf, msg); err != nil {
  409. return nil, err
  410. }
  411. // pad with random amount of data. the amount needs to be at least 100 bytes to make
  412. // the message distinguishable from pre-EIP-8 handshakes.
  413. pad := padSpace[:mrand.Intn(len(padSpace)-100)+100]
  414. buf.Write(pad)
  415. prefix := make([]byte, 2)
  416. binary.BigEndian.PutUint16(prefix, uint16(buf.Len()+eciesOverhead))
  417. enc, err := ecies.Encrypt(rand.Reader, h.remote, buf.Bytes(), nil, prefix)
  418. return append(prefix, enc...), err
  419. }
  420. type plainDecoder interface {
  421. decodePlain([]byte)
  422. }
  423. func readHandshakeMsg(msg plainDecoder, plainSize int, prv *ecdsa.PrivateKey, r io.Reader) ([]byte, error) {
  424. buf := make([]byte, plainSize)
  425. if _, err := io.ReadFull(r, buf); err != nil {
  426. return buf, err
  427. }
  428. // Attempt decoding pre-EIP-8 "plain" format.
  429. key := ecies.ImportECDSA(prv)
  430. if dec, err := key.Decrypt(buf, nil, nil); err == nil {
  431. msg.decodePlain(dec)
  432. return buf, nil
  433. }
  434. // Could be EIP-8 format, try that.
  435. prefix := buf[:2]
  436. size := binary.BigEndian.Uint16(prefix)
  437. if size < uint16(plainSize) {
  438. return buf, fmt.Errorf("size underflow, need at least %d bytes", plainSize)
  439. }
  440. buf = append(buf, make([]byte, size-uint16(plainSize)+2)...)
  441. if _, err := io.ReadFull(r, buf[plainSize:]); err != nil {
  442. return buf, err
  443. }
  444. dec, err := key.Decrypt(buf[2:], nil, prefix)
  445. if err != nil {
  446. return buf, err
  447. }
  448. // Can't use rlp.DecodeBytes here because it rejects
  449. // trailing data (forward-compatibility).
  450. s := rlp.NewStream(bytes.NewReader(dec), 0)
  451. return buf, s.Decode(msg)
  452. }
  453. // importPublicKey unmarshals 512 bit public keys.
  454. func importPublicKey(pubKey []byte) (*ecies.PublicKey, error) {
  455. var pubKey65 []byte
  456. switch len(pubKey) {
  457. case 64:
  458. // add 'uncompressed key' flag
  459. pubKey65 = append([]byte{0x04}, pubKey...)
  460. case 65:
  461. pubKey65 = pubKey
  462. default:
  463. return nil, fmt.Errorf("invalid public key length %v (expect 64/65)", len(pubKey))
  464. }
  465. // TODO: fewer pointless conversions
  466. pub, err := crypto.UnmarshalPubkey(pubKey65)
  467. if err != nil {
  468. return nil, err
  469. }
  470. return ecies.ImportECDSAPublic(pub), nil
  471. }
  472. func exportPubkey(pub *ecies.PublicKey) []byte {
  473. if pub == nil {
  474. panic("nil pubkey")
  475. }
  476. return elliptic.Marshal(pub.Curve, pub.X, pub.Y)[1:]
  477. }
  478. func xor(one, other []byte) (xor []byte) {
  479. xor = make([]byte, len(one))
  480. for i := 0; i < len(one); i++ {
  481. xor[i] = one[i] ^ other[i]
  482. }
  483. return xor
  484. }
  485. var (
  486. // this is used in place of actual frame header data.
  487. // TODO: replace this when Msg contains the protocol type code.
  488. zeroHeader = []byte{0xC2, 0x80, 0x80}
  489. // sixteen zero bytes
  490. zero16 = make([]byte, 16)
  491. )
  492. // rlpxFrameRW implements a simplified version of RLPx framing.
  493. // chunked messages are not supported and all headers are equal to
  494. // zeroHeader.
  495. //
  496. // rlpxFrameRW is not safe for concurrent use from multiple goroutines.
  497. type rlpxFrameRW struct {
  498. conn io.ReadWriter
  499. enc cipher.Stream
  500. dec cipher.Stream
  501. macCipher cipher.Block
  502. egressMAC hash.Hash
  503. ingressMAC hash.Hash
  504. snappy bool
  505. }
  506. func newRLPXFrameRW(conn io.ReadWriter, s secrets) *rlpxFrameRW {
  507. macc, err := aes.NewCipher(s.MAC)
  508. if err != nil {
  509. panic("invalid MAC secret: " + err.Error())
  510. }
  511. encc, err := aes.NewCipher(s.AES)
  512. if err != nil {
  513. panic("invalid AES secret: " + err.Error())
  514. }
  515. // we use an all-zeroes IV for AES because the key used
  516. // for encryption is ephemeral.
  517. iv := make([]byte, encc.BlockSize())
  518. return &rlpxFrameRW{
  519. conn: conn,
  520. enc: cipher.NewCTR(encc, iv),
  521. dec: cipher.NewCTR(encc, iv),
  522. macCipher: macc,
  523. egressMAC: s.EgressMAC,
  524. ingressMAC: s.IngressMAC,
  525. }
  526. }
  527. func (rw *rlpxFrameRW) WriteMsg(msg Msg) error {
  528. ptype, _ := rlp.EncodeToBytes(msg.Code)
  529. // if snappy is enabled, compress message now
  530. if rw.snappy {
  531. if msg.Size > maxUint24 {
  532. return errPlainMessageTooLarge
  533. }
  534. payload, _ := ioutil.ReadAll(msg.Payload)
  535. payload = snappy.Encode(nil, payload)
  536. msg.Payload = bytes.NewReader(payload)
  537. msg.Size = uint32(len(payload))
  538. }
  539. // write header
  540. headbuf := make([]byte, 32)
  541. fsize := uint32(len(ptype)) + msg.Size
  542. if fsize > maxUint24 {
  543. return errors.New("message size overflows uint24")
  544. }
  545. putInt24(fsize, headbuf) // TODO: check overflow
  546. copy(headbuf[3:], zeroHeader)
  547. rw.enc.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now encrypted
  548. // write header MAC
  549. copy(headbuf[16:], updateMAC(rw.egressMAC, rw.macCipher, headbuf[:16]))
  550. if _, err := rw.conn.Write(headbuf); err != nil {
  551. return err
  552. }
  553. // write encrypted frame, updating the egress MAC hash with
  554. // the data written to conn.
  555. tee := cipher.StreamWriter{S: rw.enc, W: io.MultiWriter(rw.conn, rw.egressMAC)}
  556. if _, err := tee.Write(ptype); err != nil {
  557. return err
  558. }
  559. if _, err := io.Copy(tee, msg.Payload); err != nil {
  560. return err
  561. }
  562. if padding := fsize % 16; padding > 0 {
  563. if _, err := tee.Write(zero16[:16-padding]); err != nil {
  564. return err
  565. }
  566. }
  567. // write frame MAC. egress MAC hash is up to date because
  568. // frame content was written to it as well.
  569. fmacseed := rw.egressMAC.Sum(nil)
  570. mac := updateMAC(rw.egressMAC, rw.macCipher, fmacseed)
  571. _, err := rw.conn.Write(mac)
  572. return err
  573. }
  574. func (rw *rlpxFrameRW) ReadMsg() (msg Msg, err error) {
  575. // read the header
  576. headbuf := make([]byte, 32)
  577. if _, err := io.ReadFull(rw.conn, headbuf); err != nil {
  578. return msg, err
  579. }
  580. // verify header mac
  581. shouldMAC := updateMAC(rw.ingressMAC, rw.macCipher, headbuf[:16])
  582. if !hmac.Equal(shouldMAC, headbuf[16:]) {
  583. return msg, errors.New("bad header MAC")
  584. }
  585. rw.dec.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now decrypted
  586. fsize := readInt24(headbuf)
  587. // ignore protocol type for now
  588. // read the frame content
  589. var rsize = fsize // frame size rounded up to 16 byte boundary
  590. if padding := fsize % 16; padding > 0 {
  591. rsize += 16 - padding
  592. }
  593. framebuf := make([]byte, rsize)
  594. if _, err := io.ReadFull(rw.conn, framebuf); err != nil {
  595. return msg, err
  596. }
  597. // read and validate frame MAC. we can re-use headbuf for that.
  598. rw.ingressMAC.Write(framebuf)
  599. fmacseed := rw.ingressMAC.Sum(nil)
  600. if _, err := io.ReadFull(rw.conn, headbuf[:16]); err != nil {
  601. return msg, err
  602. }
  603. shouldMAC = updateMAC(rw.ingressMAC, rw.macCipher, fmacseed)
  604. if !hmac.Equal(shouldMAC, headbuf[:16]) {
  605. return msg, errors.New("bad frame MAC")
  606. }
  607. // decrypt frame content
  608. rw.dec.XORKeyStream(framebuf, framebuf)
  609. // decode message code
  610. content := bytes.NewReader(framebuf[:fsize])
  611. if err := rlp.Decode(content, &msg.Code); err != nil {
  612. return msg, err
  613. }
  614. msg.Size = uint32(content.Len())
  615. msg.Payload = content
  616. // if snappy is enabled, verify and decompress message
  617. if rw.snappy {
  618. payload, err := ioutil.ReadAll(msg.Payload)
  619. if err != nil {
  620. return msg, err
  621. }
  622. size, err := snappy.DecodedLen(payload)
  623. if err != nil {
  624. return msg, err
  625. }
  626. if size > int(maxUint24) {
  627. return msg, errPlainMessageTooLarge
  628. }
  629. payload, err = snappy.Decode(nil, payload)
  630. if err != nil {
  631. return msg, err
  632. }
  633. msg.Size, msg.Payload = uint32(size), bytes.NewReader(payload)
  634. }
  635. return msg, nil
  636. }
  637. // updateMAC reseeds the given hash with encrypted seed.
  638. // it returns the first 16 bytes of the hash sum after seeding.
  639. func updateMAC(mac hash.Hash, block cipher.Block, seed []byte) []byte {
  640. aesbuf := make([]byte, aes.BlockSize)
  641. block.Encrypt(aesbuf, mac.Sum(nil))
  642. for i := range aesbuf {
  643. aesbuf[i] ^= seed[i]
  644. }
  645. mac.Write(aesbuf)
  646. return mac.Sum(nil)[:16]
  647. }
  648. func readInt24(b []byte) uint32 {
  649. return uint32(b[2]) | uint32(b[1])<<8 | uint32(b[0])<<16
  650. }
  651. func putInt24(v uint32, b []byte) {
  652. b[0] = byte(v >> 16)
  653. b[1] = byte(v >> 8)
  654. b[2] = byte(v)
  655. }