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