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