github.com/wzbox/go-ethereum@v1.9.2/p2p/rlpx.go (about)

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