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