rlpx.go 21 KB

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