rlpx.go 20 KB

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