rlpx.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  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/crypto"
  36. "github.com/ethereum/go-ethereum/crypto/ecies"
  37. "github.com/ethereum/go-ethereum/crypto/secp256k1"
  38. "github.com/ethereum/go-ethereum/crypto/sha3"
  39. "github.com/ethereum/go-ethereum/p2p/discover"
  40. "github.com/ethereum/go-ethereum/rlp"
  41. "github.com/golang/snappy"
  42. )
  43. const (
  44. maxUint24 = ^uint32(0) >> 8
  45. sskLen = 16 // ecies.MaxSharedKeyLength(pubKey) / 2
  46. sigLen = 65 // 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, our); 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, our *protoHandshake) (*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 posthanshake 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 (hs.ID == discover.NodeID{}) {
  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 *discover.Node) (discover.NodeID, error) {
  158. var (
  159. sec secrets
  160. err error
  161. )
  162. if dial == nil {
  163. sec, err = receiverEncHandshake(t.fd, prv, nil)
  164. } else {
  165. sec, err = initiatorEncHandshake(t.fd, prv, dial.ID, nil)
  166. }
  167. if err != nil {
  168. return discover.NodeID{}, err
  169. }
  170. t.wmu.Lock()
  171. t.rw = newRLPXFrameRW(t.fd, sec)
  172. t.wmu.Unlock()
  173. return sec.RemoteID, nil
  174. }
  175. // encHandshake contains the state of the encryption handshake.
  176. type encHandshake struct {
  177. initiator bool
  178. remoteID discover.NodeID
  179. remotePub *ecies.PublicKey // remote-pubk
  180. initNonce, respNonce []byte // nonce
  181. randomPrivKey *ecies.PrivateKey // ecdhe-random
  182. remoteRandomPub *ecies.PublicKey // ecdhe-random-pubk
  183. }
  184. // secrets represents the connection secrets
  185. // which are negotiated during the encryption handshake.
  186. type secrets struct {
  187. RemoteID discover.NodeID
  188. AES, MAC []byte
  189. EgressMAC, IngressMAC hash.Hash
  190. Token []byte
  191. }
  192. // RLPx v4 handshake auth (defined in EIP-8).
  193. type authMsgV4 struct {
  194. gotPlain bool // whether read packet had plain format.
  195. Signature [sigLen]byte
  196. InitiatorPubkey [pubLen]byte
  197. Nonce [shaLen]byte
  198. Version uint
  199. // Ignore additional fields (forward-compatibility)
  200. Rest []rlp.RawValue `rlp:"tail"`
  201. }
  202. // RLPx v4 handshake response (defined in EIP-8).
  203. type authRespV4 struct {
  204. RandomPubkey [pubLen]byte
  205. Nonce [shaLen]byte
  206. Version uint
  207. // Ignore additional fields (forward-compatibility)
  208. Rest []rlp.RawValue `rlp:"tail"`
  209. }
  210. // secrets is called after the handshake is completed.
  211. // It extracts the connection secrets from the handshake values.
  212. func (h *encHandshake) secrets(auth, authResp []byte) (secrets, error) {
  213. ecdheSecret, err := h.randomPrivKey.GenerateShared(h.remoteRandomPub, sskLen, sskLen)
  214. if err != nil {
  215. return secrets{}, err
  216. }
  217. // derive base secrets from ephemeral key agreement
  218. sharedSecret := crypto.Keccak256(ecdheSecret, crypto.Keccak256(h.respNonce, h.initNonce))
  219. aesSecret := crypto.Keccak256(ecdheSecret, sharedSecret)
  220. s := secrets{
  221. RemoteID: h.remoteID,
  222. AES: aesSecret,
  223. MAC: crypto.Keccak256(ecdheSecret, aesSecret),
  224. }
  225. // setup sha3 instances for the MACs
  226. mac1 := sha3.NewKeccak256()
  227. mac1.Write(xor(s.MAC, h.respNonce))
  228. mac1.Write(auth)
  229. mac2 := sha3.NewKeccak256()
  230. mac2.Write(xor(s.MAC, h.initNonce))
  231. mac2.Write(authResp)
  232. if h.initiator {
  233. s.EgressMAC, s.IngressMAC = mac1, mac2
  234. } else {
  235. s.EgressMAC, s.IngressMAC = mac2, mac1
  236. }
  237. return s, nil
  238. }
  239. // staticSharedSecret returns the static shared secret, the result
  240. // of key agreement between the local and remote static node key.
  241. func (h *encHandshake) staticSharedSecret(prv *ecdsa.PrivateKey) ([]byte, error) {
  242. return ecies.ImportECDSA(prv).GenerateShared(h.remotePub, sskLen, sskLen)
  243. }
  244. // initiatorEncHandshake negotiates a session token on conn.
  245. // it should be called on the dialing side of the connection.
  246. //
  247. // prv is the local client's private key.
  248. func initiatorEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, remoteID discover.NodeID, token []byte) (s secrets, err error) {
  249. h := &encHandshake{initiator: true, remoteID: remoteID}
  250. authMsg, err := h.makeAuthMsg(prv, token)
  251. if err != nil {
  252. return s, err
  253. }
  254. authPacket, err := sealEIP8(authMsg, h)
  255. if err != nil {
  256. return s, err
  257. }
  258. if _, err = conn.Write(authPacket); err != nil {
  259. return s, err
  260. }
  261. authRespMsg := new(authRespV4)
  262. authRespPacket, err := readHandshakeMsg(authRespMsg, encAuthRespLen, prv, conn)
  263. if err != nil {
  264. return s, err
  265. }
  266. if err := h.handleAuthResp(authRespMsg); err != nil {
  267. return s, err
  268. }
  269. return h.secrets(authPacket, authRespPacket)
  270. }
  271. // makeAuthMsg creates the initiator handshake message.
  272. func (h *encHandshake) makeAuthMsg(prv *ecdsa.PrivateKey, token []byte) (*authMsgV4, error) {
  273. rpub, err := h.remoteID.Pubkey()
  274. if err != nil {
  275. return nil, fmt.Errorf("bad remoteID: %v", err)
  276. }
  277. h.remotePub = ecies.ImportECDSAPublic(rpub)
  278. // Generate random initiator nonce.
  279. h.initNonce = make([]byte, shaLen)
  280. if _, err := rand.Read(h.initNonce); err != nil {
  281. return nil, err
  282. }
  283. // Generate random keypair to for ECDH.
  284. h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
  285. if err != nil {
  286. return nil, err
  287. }
  288. // Sign known message: static-shared-secret ^ nonce
  289. token, err = h.staticSharedSecret(prv)
  290. if err != nil {
  291. return nil, err
  292. }
  293. signed := xor(token, h.initNonce)
  294. signature, err := crypto.Sign(signed, h.randomPrivKey.ExportECDSA())
  295. if err != nil {
  296. return nil, err
  297. }
  298. msg := new(authMsgV4)
  299. copy(msg.Signature[:], signature)
  300. copy(msg.InitiatorPubkey[:], crypto.FromECDSAPub(&prv.PublicKey)[1:])
  301. copy(msg.Nonce[:], h.initNonce)
  302. msg.Version = 4
  303. return msg, nil
  304. }
  305. func (h *encHandshake) handleAuthResp(msg *authRespV4) (err error) {
  306. h.respNonce = msg.Nonce[:]
  307. h.remoteRandomPub, err = importPublicKey(msg.RandomPubkey[:])
  308. return err
  309. }
  310. // receiverEncHandshake negotiates a session token on conn.
  311. // it should be called on the listening side of the connection.
  312. //
  313. // prv is the local client's private key.
  314. // token is the token from a previous session with this node.
  315. func receiverEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, token []byte) (s secrets, err error) {
  316. authMsg := new(authMsgV4)
  317. authPacket, err := readHandshakeMsg(authMsg, encAuthMsgLen, prv, conn)
  318. if err != nil {
  319. return s, err
  320. }
  321. h := new(encHandshake)
  322. if err := h.handleAuthMsg(authMsg, prv); err != nil {
  323. return s, err
  324. }
  325. authRespMsg, err := h.makeAuthResp()
  326. if err != nil {
  327. return s, err
  328. }
  329. var authRespPacket []byte
  330. if authMsg.gotPlain {
  331. authRespPacket, err = authRespMsg.sealPlain(h)
  332. } else {
  333. authRespPacket, err = sealEIP8(authRespMsg, h)
  334. }
  335. if err != nil {
  336. return s, err
  337. }
  338. if _, err = conn.Write(authRespPacket); err != nil {
  339. return s, err
  340. }
  341. return h.secrets(authPacket, authRespPacket)
  342. }
  343. func (h *encHandshake) handleAuthMsg(msg *authMsgV4, prv *ecdsa.PrivateKey) error {
  344. // Import the remote identity.
  345. h.initNonce = msg.Nonce[:]
  346. h.remoteID = msg.InitiatorPubkey
  347. rpub, err := h.remoteID.Pubkey()
  348. if err != nil {
  349. return fmt.Errorf("bad remoteID: %#v", err)
  350. }
  351. h.remotePub = ecies.ImportECDSAPublic(rpub)
  352. // Generate random keypair for ECDH.
  353. // If a private key is already set, use it instead of generating one (for testing).
  354. if h.randomPrivKey == nil {
  355. h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
  356. if err != nil {
  357. return err
  358. }
  359. }
  360. // Check the signature.
  361. token, err := h.staticSharedSecret(prv)
  362. if err != nil {
  363. return err
  364. }
  365. signedMsg := xor(token, h.initNonce)
  366. remoteRandomPub, err := secp256k1.RecoverPubkey(signedMsg, msg.Signature[:])
  367. if err != nil {
  368. return err
  369. }
  370. h.remoteRandomPub, _ = importPublicKey(remoteRandomPub)
  371. return nil
  372. }
  373. func (h *encHandshake) makeAuthResp() (msg *authRespV4, err error) {
  374. // Generate random nonce.
  375. h.respNonce = make([]byte, shaLen)
  376. if _, err = rand.Read(h.respNonce); err != nil {
  377. return nil, err
  378. }
  379. msg = new(authRespV4)
  380. copy(msg.Nonce[:], h.respNonce)
  381. copy(msg.RandomPubkey[:], exportPubkey(&h.randomPrivKey.PublicKey))
  382. msg.Version = 4
  383. return msg, nil
  384. }
  385. func (msg *authMsgV4) sealPlain(h *encHandshake) ([]byte, error) {
  386. buf := make([]byte, authMsgLen)
  387. n := copy(buf, msg.Signature[:])
  388. n += copy(buf[n:], crypto.Keccak256(exportPubkey(&h.randomPrivKey.PublicKey)))
  389. n += copy(buf[n:], msg.InitiatorPubkey[:])
  390. n += copy(buf[n:], msg.Nonce[:])
  391. buf[n] = 0 // token-flag
  392. return ecies.Encrypt(rand.Reader, h.remotePub, buf, nil, nil)
  393. }
  394. func (msg *authMsgV4) decodePlain(input []byte) {
  395. n := copy(msg.Signature[:], input)
  396. n += shaLen // skip sha3(initiator-ephemeral-pubk)
  397. n += copy(msg.InitiatorPubkey[:], input[n:])
  398. copy(msg.Nonce[:], input[n:])
  399. msg.Version = 4
  400. msg.gotPlain = true
  401. }
  402. func (msg *authRespV4) sealPlain(hs *encHandshake) ([]byte, error) {
  403. buf := make([]byte, authRespLen)
  404. n := copy(buf, msg.RandomPubkey[:])
  405. copy(buf[n:], msg.Nonce[:])
  406. return ecies.Encrypt(rand.Reader, hs.remotePub, buf, nil, nil)
  407. }
  408. func (msg *authRespV4) decodePlain(input []byte) {
  409. n := copy(msg.RandomPubkey[:], input)
  410. copy(msg.Nonce[:], input[n:])
  411. msg.Version = 4
  412. }
  413. var padSpace = make([]byte, 300)
  414. func sealEIP8(msg interface{}, h *encHandshake) ([]byte, error) {
  415. buf := new(bytes.Buffer)
  416. if err := rlp.Encode(buf, msg); err != nil {
  417. return nil, err
  418. }
  419. // pad with random amount of data. the amount needs to be at least 100 bytes to make
  420. // the message distinguishable from pre-EIP-8 handshakes.
  421. pad := padSpace[:mrand.Intn(len(padSpace)-100)+100]
  422. buf.Write(pad)
  423. prefix := make([]byte, 2)
  424. binary.BigEndian.PutUint16(prefix, uint16(buf.Len()+eciesOverhead))
  425. enc, err := ecies.Encrypt(rand.Reader, h.remotePub, buf.Bytes(), nil, prefix)
  426. return append(prefix, enc...), err
  427. }
  428. type plainDecoder interface {
  429. decodePlain([]byte)
  430. }
  431. func readHandshakeMsg(msg plainDecoder, plainSize int, prv *ecdsa.PrivateKey, r io.Reader) ([]byte, error) {
  432. buf := make([]byte, plainSize)
  433. if _, err := io.ReadFull(r, buf); err != nil {
  434. return buf, err
  435. }
  436. // Attempt decoding pre-EIP-8 "plain" format.
  437. key := ecies.ImportECDSA(prv)
  438. if dec, err := key.Decrypt(buf, nil, nil); err == nil {
  439. msg.decodePlain(dec)
  440. return buf, nil
  441. }
  442. // Could be EIP-8 format, try that.
  443. prefix := buf[:2]
  444. size := binary.BigEndian.Uint16(prefix)
  445. if size < uint16(plainSize) {
  446. return buf, fmt.Errorf("size underflow, need at least %d bytes", plainSize)
  447. }
  448. buf = append(buf, make([]byte, size-uint16(plainSize)+2)...)
  449. if _, err := io.ReadFull(r, buf[plainSize:]); err != nil {
  450. return buf, err
  451. }
  452. dec, err := key.Decrypt(buf[2:], nil, prefix)
  453. if err != nil {
  454. return buf, err
  455. }
  456. // Can't use rlp.DecodeBytes here because it rejects
  457. // trailing data (forward-compatibility).
  458. s := rlp.NewStream(bytes.NewReader(dec), 0)
  459. return buf, s.Decode(msg)
  460. }
  461. // importPublicKey unmarshals 512 bit public keys.
  462. func importPublicKey(pubKey []byte) (*ecies.PublicKey, error) {
  463. var pubKey65 []byte
  464. switch len(pubKey) {
  465. case 64:
  466. // add 'uncompressed key' flag
  467. pubKey65 = append([]byte{0x04}, pubKey...)
  468. case 65:
  469. pubKey65 = pubKey
  470. default:
  471. return nil, fmt.Errorf("invalid public key length %v (expect 64/65)", len(pubKey))
  472. }
  473. // TODO: fewer pointless conversions
  474. pub := crypto.ToECDSAPub(pubKey65)
  475. if pub.X == nil {
  476. return nil, fmt.Errorf("invalid public key")
  477. }
  478. return ecies.ImportECDSAPublic(pub), nil
  479. }
  480. func exportPubkey(pub *ecies.PublicKey) []byte {
  481. if pub == nil {
  482. panic("nil pubkey")
  483. }
  484. return elliptic.Marshal(pub.Curve, pub.X, pub.Y)[1:]
  485. }
  486. func xor(one, other []byte) (xor []byte) {
  487. xor = make([]byte, len(one))
  488. for i := 0; i < len(one); i++ {
  489. xor[i] = one[i] ^ other[i]
  490. }
  491. return xor
  492. }
  493. var (
  494. // this is used in place of actual frame header data.
  495. // TODO: replace this when Msg contains the protocol type code.
  496. zeroHeader = []byte{0xC2, 0x80, 0x80}
  497. // sixteen zero bytes
  498. zero16 = make([]byte, 16)
  499. )
  500. // rlpxFrameRW implements a simplified version of RLPx framing.
  501. // chunked messages are not supported and all headers are equal to
  502. // zeroHeader.
  503. //
  504. // rlpxFrameRW is not safe for concurrent use from multiple goroutines.
  505. type rlpxFrameRW struct {
  506. conn io.ReadWriter
  507. enc cipher.Stream
  508. dec cipher.Stream
  509. macCipher cipher.Block
  510. egressMAC hash.Hash
  511. ingressMAC hash.Hash
  512. snappy bool
  513. }
  514. func newRLPXFrameRW(conn io.ReadWriter, s secrets) *rlpxFrameRW {
  515. macc, err := aes.NewCipher(s.MAC)
  516. if err != nil {
  517. panic("invalid MAC secret: " + err.Error())
  518. }
  519. encc, err := aes.NewCipher(s.AES)
  520. if err != nil {
  521. panic("invalid AES secret: " + err.Error())
  522. }
  523. // we use an all-zeroes IV for AES because the key used
  524. // for encryption is ephemeral.
  525. iv := make([]byte, encc.BlockSize())
  526. return &rlpxFrameRW{
  527. conn: conn,
  528. enc: cipher.NewCTR(encc, iv),
  529. dec: cipher.NewCTR(encc, iv),
  530. macCipher: macc,
  531. egressMAC: s.EgressMAC,
  532. ingressMAC: s.IngressMAC,
  533. }
  534. }
  535. func (rw *rlpxFrameRW) WriteMsg(msg Msg) error {
  536. ptype, _ := rlp.EncodeToBytes(msg.Code)
  537. // if snappy is enabled, compress message now
  538. if rw.snappy {
  539. if msg.Size > maxUint24 {
  540. return errPlainMessageTooLarge
  541. }
  542. payload, _ := ioutil.ReadAll(msg.Payload)
  543. payload = snappy.Encode(nil, payload)
  544. msg.Payload = bytes.NewReader(payload)
  545. msg.Size = uint32(len(payload))
  546. }
  547. // write header
  548. headbuf := make([]byte, 32)
  549. fsize := uint32(len(ptype)) + msg.Size
  550. if fsize > maxUint24 {
  551. return errors.New("message size overflows uint24")
  552. }
  553. putInt24(fsize, headbuf) // TODO: check overflow
  554. copy(headbuf[3:], zeroHeader)
  555. rw.enc.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now encrypted
  556. // write header MAC
  557. copy(headbuf[16:], updateMAC(rw.egressMAC, rw.macCipher, headbuf[:16]))
  558. if _, err := rw.conn.Write(headbuf); err != nil {
  559. return err
  560. }
  561. // write encrypted frame, updating the egress MAC hash with
  562. // the data written to conn.
  563. tee := cipher.StreamWriter{S: rw.enc, W: io.MultiWriter(rw.conn, rw.egressMAC)}
  564. if _, err := tee.Write(ptype); err != nil {
  565. return err
  566. }
  567. if _, err := io.Copy(tee, msg.Payload); err != nil {
  568. return err
  569. }
  570. if padding := fsize % 16; padding > 0 {
  571. if _, err := tee.Write(zero16[:16-padding]); err != nil {
  572. return err
  573. }
  574. }
  575. // write frame MAC. egress MAC hash is up to date because
  576. // frame content was written to it as well.
  577. fmacseed := rw.egressMAC.Sum(nil)
  578. mac := updateMAC(rw.egressMAC, rw.macCipher, fmacseed)
  579. _, err := rw.conn.Write(mac)
  580. return err
  581. }
  582. func (rw *rlpxFrameRW) ReadMsg() (msg Msg, err error) {
  583. // read the header
  584. headbuf := make([]byte, 32)
  585. if _, err := io.ReadFull(rw.conn, headbuf); err != nil {
  586. return msg, err
  587. }
  588. // verify header mac
  589. shouldMAC := updateMAC(rw.ingressMAC, rw.macCipher, headbuf[:16])
  590. if !hmac.Equal(shouldMAC, headbuf[16:]) {
  591. return msg, errors.New("bad header MAC")
  592. }
  593. rw.dec.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now decrypted
  594. fsize := readInt24(headbuf)
  595. // ignore protocol type for now
  596. // read the frame content
  597. var rsize = fsize // frame size rounded up to 16 byte boundary
  598. if padding := fsize % 16; padding > 0 {
  599. rsize += 16 - padding
  600. }
  601. framebuf := make([]byte, rsize)
  602. if _, err := io.ReadFull(rw.conn, framebuf); err != nil {
  603. return msg, err
  604. }
  605. // read and validate frame MAC. we can re-use headbuf for that.
  606. rw.ingressMAC.Write(framebuf)
  607. fmacseed := rw.ingressMAC.Sum(nil)
  608. if _, err := io.ReadFull(rw.conn, headbuf[:16]); err != nil {
  609. return msg, err
  610. }
  611. shouldMAC = updateMAC(rw.ingressMAC, rw.macCipher, fmacseed)
  612. if !hmac.Equal(shouldMAC, headbuf[:16]) {
  613. return msg, errors.New("bad frame MAC")
  614. }
  615. // decrypt frame content
  616. rw.dec.XORKeyStream(framebuf, framebuf)
  617. // decode message code
  618. content := bytes.NewReader(framebuf[:fsize])
  619. if err := rlp.Decode(content, &msg.Code); err != nil {
  620. return msg, err
  621. }
  622. msg.Size = uint32(content.Len())
  623. msg.Payload = content
  624. // if snappy is enabled, verify and decompress message
  625. if rw.snappy {
  626. payload, err := ioutil.ReadAll(msg.Payload)
  627. if err != nil {
  628. return msg, err
  629. }
  630. size, err := snappy.DecodedLen(payload)
  631. if err != nil {
  632. return msg, err
  633. }
  634. if size > int(maxUint24) {
  635. return msg, errPlainMessageTooLarge
  636. }
  637. payload, err = snappy.Decode(nil, payload)
  638. if err != nil {
  639. return msg, err
  640. }
  641. msg.Size, msg.Payload = uint32(size), bytes.NewReader(payload)
  642. }
  643. return msg, nil
  644. }
  645. // updateMAC reseeds the given hash with encrypted seed.
  646. // it returns the first 16 bytes of the hash sum after seeding.
  647. func updateMAC(mac hash.Hash, block cipher.Block, seed []byte) []byte {
  648. aesbuf := make([]byte, aes.BlockSize)
  649. block.Encrypt(aesbuf, mac.Sum(nil))
  650. for i := range aesbuf {
  651. aesbuf[i] ^= seed[i]
  652. }
  653. mac.Write(aesbuf)
  654. return mac.Sum(nil)[:16]
  655. }
  656. func readInt24(b []byte) uint32 {
  657. return uint32(b[2]) | uint32(b[1])<<8 | uint32(b[0])<<16
  658. }
  659. func putInt24(v uint32, b []byte) {
  660. b[0] = byte(v >> 16)
  661. b[1] = byte(v >> 8)
  662. b[2] = byte(v)
  663. }