rlpx.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  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)
  164. } else {
  165. sec, err = initiatorEncHandshake(t.fd, prv, dial.ID)
  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) (s secrets, err error) {
  249. h := &encHandshake{initiator: true, remoteID: remoteID}
  250. authMsg, err := h.makeAuthMsg(prv)
  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) (*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. func receiverEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey) (s secrets, err error) {
  315. authMsg := new(authMsgV4)
  316. authPacket, err := readHandshakeMsg(authMsg, encAuthMsgLen, prv, conn)
  317. if err != nil {
  318. return s, err
  319. }
  320. h := new(encHandshake)
  321. if err := h.handleAuthMsg(authMsg, prv); err != nil {
  322. return s, err
  323. }
  324. authRespMsg, err := h.makeAuthResp()
  325. if err != nil {
  326. return s, err
  327. }
  328. var authRespPacket []byte
  329. if authMsg.gotPlain {
  330. authRespPacket, err = authRespMsg.sealPlain(h)
  331. } else {
  332. authRespPacket, err = sealEIP8(authRespMsg, h)
  333. }
  334. if err != nil {
  335. return s, err
  336. }
  337. if _, err = conn.Write(authRespPacket); err != nil {
  338. return s, err
  339. }
  340. return h.secrets(authPacket, authRespPacket)
  341. }
  342. func (h *encHandshake) handleAuthMsg(msg *authMsgV4, prv *ecdsa.PrivateKey) error {
  343. // Import the remote identity.
  344. h.initNonce = msg.Nonce[:]
  345. h.remoteID = msg.InitiatorPubkey
  346. rpub, err := h.remoteID.Pubkey()
  347. if err != nil {
  348. return fmt.Errorf("bad remoteID: %#v", err)
  349. }
  350. h.remotePub = ecies.ImportECDSAPublic(rpub)
  351. // Generate random keypair for ECDH.
  352. // If a private key is already set, use it instead of generating one (for testing).
  353. if h.randomPrivKey == nil {
  354. h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
  355. if err != nil {
  356. return err
  357. }
  358. }
  359. // Check the signature.
  360. token, err := h.staticSharedSecret(prv)
  361. if err != nil {
  362. return err
  363. }
  364. signedMsg := xor(token, h.initNonce)
  365. remoteRandomPub, err := secp256k1.RecoverPubkey(signedMsg, msg.Signature[:])
  366. if err != nil {
  367. return err
  368. }
  369. h.remoteRandomPub, _ = importPublicKey(remoteRandomPub)
  370. return nil
  371. }
  372. func (h *encHandshake) makeAuthResp() (msg *authRespV4, err error) {
  373. // Generate random nonce.
  374. h.respNonce = make([]byte, shaLen)
  375. if _, err = rand.Read(h.respNonce); err != nil {
  376. return nil, err
  377. }
  378. msg = new(authRespV4)
  379. copy(msg.Nonce[:], h.respNonce)
  380. copy(msg.RandomPubkey[:], exportPubkey(&h.randomPrivKey.PublicKey))
  381. msg.Version = 4
  382. return msg, nil
  383. }
  384. func (msg *authMsgV4) sealPlain(h *encHandshake) ([]byte, error) {
  385. buf := make([]byte, authMsgLen)
  386. n := copy(buf, msg.Signature[:])
  387. n += copy(buf[n:], crypto.Keccak256(exportPubkey(&h.randomPrivKey.PublicKey)))
  388. n += copy(buf[n:], msg.InitiatorPubkey[:])
  389. n += copy(buf[n:], msg.Nonce[:])
  390. buf[n] = 0 // token-flag
  391. return ecies.Encrypt(rand.Reader, h.remotePub, buf, nil, nil)
  392. }
  393. func (msg *authMsgV4) decodePlain(input []byte) {
  394. n := copy(msg.Signature[:], input)
  395. n += shaLen // skip sha3(initiator-ephemeral-pubk)
  396. n += copy(msg.InitiatorPubkey[:], input[n:])
  397. copy(msg.Nonce[:], input[n:])
  398. msg.Version = 4
  399. msg.gotPlain = true
  400. }
  401. func (msg *authRespV4) sealPlain(hs *encHandshake) ([]byte, error) {
  402. buf := make([]byte, authRespLen)
  403. n := copy(buf, msg.RandomPubkey[:])
  404. copy(buf[n:], msg.Nonce[:])
  405. return ecies.Encrypt(rand.Reader, hs.remotePub, buf, nil, nil)
  406. }
  407. func (msg *authRespV4) decodePlain(input []byte) {
  408. n := copy(msg.RandomPubkey[:], input)
  409. copy(msg.Nonce[:], input[n:])
  410. msg.Version = 4
  411. }
  412. var padSpace = make([]byte, 300)
  413. func sealEIP8(msg interface{}, h *encHandshake) ([]byte, error) {
  414. buf := new(bytes.Buffer)
  415. if err := rlp.Encode(buf, msg); err != nil {
  416. return nil, err
  417. }
  418. // pad with random amount of data. the amount needs to be at least 100 bytes to make
  419. // the message distinguishable from pre-EIP-8 handshakes.
  420. pad := padSpace[:mrand.Intn(len(padSpace)-100)+100]
  421. buf.Write(pad)
  422. prefix := make([]byte, 2)
  423. binary.BigEndian.PutUint16(prefix, uint16(buf.Len()+eciesOverhead))
  424. enc, err := ecies.Encrypt(rand.Reader, h.remotePub, buf.Bytes(), nil, prefix)
  425. return append(prefix, enc...), err
  426. }
  427. type plainDecoder interface {
  428. decodePlain([]byte)
  429. }
  430. func readHandshakeMsg(msg plainDecoder, plainSize int, prv *ecdsa.PrivateKey, r io.Reader) ([]byte, error) {
  431. buf := make([]byte, plainSize)
  432. if _, err := io.ReadFull(r, buf); err != nil {
  433. return buf, err
  434. }
  435. // Attempt decoding pre-EIP-8 "plain" format.
  436. key := ecies.ImportECDSA(prv)
  437. if dec, err := key.Decrypt(buf, nil, nil); err == nil {
  438. msg.decodePlain(dec)
  439. return buf, nil
  440. }
  441. // Could be EIP-8 format, try that.
  442. prefix := buf[:2]
  443. size := binary.BigEndian.Uint16(prefix)
  444. if size < uint16(plainSize) {
  445. return buf, fmt.Errorf("size underflow, need at least %d bytes", plainSize)
  446. }
  447. buf = append(buf, make([]byte, size-uint16(plainSize)+2)...)
  448. if _, err := io.ReadFull(r, buf[plainSize:]); err != nil {
  449. return buf, err
  450. }
  451. dec, err := key.Decrypt(buf[2:], nil, prefix)
  452. if err != nil {
  453. return buf, err
  454. }
  455. // Can't use rlp.DecodeBytes here because it rejects
  456. // trailing data (forward-compatibility).
  457. s := rlp.NewStream(bytes.NewReader(dec), 0)
  458. return buf, s.Decode(msg)
  459. }
  460. // importPublicKey unmarshals 512 bit public keys.
  461. func importPublicKey(pubKey []byte) (*ecies.PublicKey, error) {
  462. var pubKey65 []byte
  463. switch len(pubKey) {
  464. case 64:
  465. // add 'uncompressed key' flag
  466. pubKey65 = append([]byte{0x04}, pubKey...)
  467. case 65:
  468. pubKey65 = pubKey
  469. default:
  470. return nil, fmt.Errorf("invalid public key length %v (expect 64/65)", len(pubKey))
  471. }
  472. // TODO: fewer pointless conversions
  473. pub, err := crypto.UnmarshalPubkey(pubKey65)
  474. if err != nil {
  475. return nil, err
  476. }
  477. return ecies.ImportECDSAPublic(pub), nil
  478. }
  479. func exportPubkey(pub *ecies.PublicKey) []byte {
  480. if pub == nil {
  481. panic("nil pubkey")
  482. }
  483. return elliptic.Marshal(pub.Curve, pub.X, pub.Y)[1:]
  484. }
  485. func xor(one, other []byte) (xor []byte) {
  486. xor = make([]byte, len(one))
  487. for i := 0; i < len(one); i++ {
  488. xor[i] = one[i] ^ other[i]
  489. }
  490. return xor
  491. }
  492. var (
  493. // this is used in place of actual frame header data.
  494. // TODO: replace this when Msg contains the protocol type code.
  495. zeroHeader = []byte{0xC2, 0x80, 0x80}
  496. // sixteen zero bytes
  497. zero16 = make([]byte, 16)
  498. )
  499. // rlpxFrameRW implements a simplified version of RLPx framing.
  500. // chunked messages are not supported and all headers are equal to
  501. // zeroHeader.
  502. //
  503. // rlpxFrameRW is not safe for concurrent use from multiple goroutines.
  504. type rlpxFrameRW struct {
  505. conn io.ReadWriter
  506. enc cipher.Stream
  507. dec cipher.Stream
  508. macCipher cipher.Block
  509. egressMAC hash.Hash
  510. ingressMAC hash.Hash
  511. snappy bool
  512. }
  513. func newRLPXFrameRW(conn io.ReadWriter, s secrets) *rlpxFrameRW {
  514. macc, err := aes.NewCipher(s.MAC)
  515. if err != nil {
  516. panic("invalid MAC secret: " + err.Error())
  517. }
  518. encc, err := aes.NewCipher(s.AES)
  519. if err != nil {
  520. panic("invalid AES secret: " + err.Error())
  521. }
  522. // we use an all-zeroes IV for AES because the key used
  523. // for encryption is ephemeral.
  524. iv := make([]byte, encc.BlockSize())
  525. return &rlpxFrameRW{
  526. conn: conn,
  527. enc: cipher.NewCTR(encc, iv),
  528. dec: cipher.NewCTR(encc, iv),
  529. macCipher: macc,
  530. egressMAC: s.EgressMAC,
  531. ingressMAC: s.IngressMAC,
  532. }
  533. }
  534. func (rw *rlpxFrameRW) WriteMsg(msg Msg) error {
  535. ptype, _ := rlp.EncodeToBytes(msg.Code)
  536. // if snappy is enabled, compress message now
  537. if rw.snappy {
  538. if msg.Size > maxUint24 {
  539. return errPlainMessageTooLarge
  540. }
  541. payload, _ := ioutil.ReadAll(msg.Payload)
  542. payload = snappy.Encode(nil, payload)
  543. msg.Payload = bytes.NewReader(payload)
  544. msg.Size = uint32(len(payload))
  545. }
  546. // write header
  547. headbuf := make([]byte, 32)
  548. fsize := uint32(len(ptype)) + msg.Size
  549. if fsize > maxUint24 {
  550. return errors.New("message size overflows uint24")
  551. }
  552. putInt24(fsize, headbuf) // TODO: check overflow
  553. copy(headbuf[3:], zeroHeader)
  554. rw.enc.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now encrypted
  555. // write header MAC
  556. copy(headbuf[16:], updateMAC(rw.egressMAC, rw.macCipher, headbuf[:16]))
  557. if _, err := rw.conn.Write(headbuf); err != nil {
  558. return err
  559. }
  560. // write encrypted frame, updating the egress MAC hash with
  561. // the data written to conn.
  562. tee := cipher.StreamWriter{S: rw.enc, W: io.MultiWriter(rw.conn, rw.egressMAC)}
  563. if _, err := tee.Write(ptype); err != nil {
  564. return err
  565. }
  566. if _, err := io.Copy(tee, msg.Payload); err != nil {
  567. return err
  568. }
  569. if padding := fsize % 16; padding > 0 {
  570. if _, err := tee.Write(zero16[:16-padding]); err != nil {
  571. return err
  572. }
  573. }
  574. // write frame MAC. egress MAC hash is up to date because
  575. // frame content was written to it as well.
  576. fmacseed := rw.egressMAC.Sum(nil)
  577. mac := updateMAC(rw.egressMAC, rw.macCipher, fmacseed)
  578. _, err := rw.conn.Write(mac)
  579. return err
  580. }
  581. func (rw *rlpxFrameRW) ReadMsg() (msg Msg, err error) {
  582. // read the header
  583. headbuf := make([]byte, 32)
  584. if _, err := io.ReadFull(rw.conn, headbuf); err != nil {
  585. return msg, err
  586. }
  587. // verify header mac
  588. shouldMAC := updateMAC(rw.ingressMAC, rw.macCipher, headbuf[:16])
  589. if !hmac.Equal(shouldMAC, headbuf[16:]) {
  590. return msg, errors.New("bad header MAC")
  591. }
  592. rw.dec.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now decrypted
  593. fsize := readInt24(headbuf)
  594. // ignore protocol type for now
  595. // read the frame content
  596. var rsize = fsize // frame size rounded up to 16 byte boundary
  597. if padding := fsize % 16; padding > 0 {
  598. rsize += 16 - padding
  599. }
  600. framebuf := make([]byte, rsize)
  601. if _, err := io.ReadFull(rw.conn, framebuf); err != nil {
  602. return msg, err
  603. }
  604. // read and validate frame MAC. we can re-use headbuf for that.
  605. rw.ingressMAC.Write(framebuf)
  606. fmacseed := rw.ingressMAC.Sum(nil)
  607. if _, err := io.ReadFull(rw.conn, headbuf[:16]); err != nil {
  608. return msg, err
  609. }
  610. shouldMAC = updateMAC(rw.ingressMAC, rw.macCipher, fmacseed)
  611. if !hmac.Equal(shouldMAC, headbuf[:16]) {
  612. return msg, errors.New("bad frame MAC")
  613. }
  614. // decrypt frame content
  615. rw.dec.XORKeyStream(framebuf, framebuf)
  616. // decode message code
  617. content := bytes.NewReader(framebuf[:fsize])
  618. if err := rlp.Decode(content, &msg.Code); err != nil {
  619. return msg, err
  620. }
  621. msg.Size = uint32(content.Len())
  622. msg.Payload = content
  623. // if snappy is enabled, verify and decompress message
  624. if rw.snappy {
  625. payload, err := ioutil.ReadAll(msg.Payload)
  626. if err != nil {
  627. return msg, err
  628. }
  629. size, err := snappy.DecodedLen(payload)
  630. if err != nil {
  631. return msg, err
  632. }
  633. if size > int(maxUint24) {
  634. return msg, errPlainMessageTooLarge
  635. }
  636. payload, err = snappy.Decode(nil, payload)
  637. if err != nil {
  638. return msg, err
  639. }
  640. msg.Size, msg.Payload = uint32(size), bytes.NewReader(payload)
  641. }
  642. return msg, nil
  643. }
  644. // updateMAC reseeds the given hash with encrypted seed.
  645. // it returns the first 16 bytes of the hash sum after seeding.
  646. func updateMAC(mac hash.Hash, block cipher.Block, seed []byte) []byte {
  647. aesbuf := make([]byte, aes.BlockSize)
  648. block.Encrypt(aesbuf, mac.Sum(nil))
  649. for i := range aesbuf {
  650. aesbuf[i] ^= seed[i]
  651. }
  652. mac.Write(aesbuf)
  653. return mac.Sum(nil)[:16]
  654. }
  655. func readInt24(b []byte) uint32 {
  656. return uint32(b[2]) | uint32(b[1])<<8 | uint32(b[0])<<16
  657. }
  658. func putInt24(v uint32, b []byte) {
  659. b[0] = byte(v >> 16)
  660. b[1] = byte(v >> 8)
  661. b[2] = byte(v)
  662. }