rlpx.go 21 KB

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