github.com/aerth/aquachain@v1.4.1/p2p/rlpx.go (about)

     1  // Copyright 2015 The aquachain Authors
     2  // This file is part of the aquachain library.
     3  //
     4  // The aquachain 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 aquachain 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 aquachain 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/aquanetwork/aquachain/crypto"
    39  	"github.com/aquanetwork/aquachain/crypto/ecies"
    40  	"github.com/aquanetwork/aquachain/crypto/secp256k1"
    41  	"github.com/aquanetwork/aquachain/crypto/sha3"
    42  	"github.com/aquanetwork/aquachain/p2p/discover"
    43  	"github.com/aquanetwork/aquachain/rlp"
    44  	"github.com/golang/snappy"
    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  // doEncHandshake runs the protocol handshake using authenticated
   125  // messages. the protocol handshake is the first authenticated message
   126  // and also verifies whether the encryption handshake 'worked' and the
   127  // remote side actually provided the right public key.
   128  func (t *rlpx) doProtoHandshake(our *protoHandshake) (their *protoHandshake, err error) {
   129  	// Writing our handshake happens concurrently, we prefer
   130  	// returning the handshake read error. If the remote side
   131  	// disconnects us early with a valid reason, we should return it
   132  	// as the error so it can be tracked elsewhere.
   133  	werr := make(chan error, 1)
   134  	go func() { werr <- Send(t.rw, handshakeMsg, our) }()
   135  	if their, err = readProtocolHandshake(t.rw, our); err != nil {
   136  		<-werr // make sure the write terminates too
   137  		return nil, err
   138  	}
   139  	if err := <-werr; err != nil {
   140  		return nil, fmt.Errorf("write error: %v", err)
   141  	}
   142  	// If the protocol version supports Snappy encoding, upgrade immediately
   143  	t.rw.snappy = their.Version >= snappyProtocolVersion
   144  
   145  	return their, nil
   146  }
   147  
   148  func readProtocolHandshake(rw MsgReader, our *protoHandshake) (*protoHandshake, error) {
   149  	msg, err := rw.ReadMsg()
   150  	if err != nil {
   151  		return nil, err
   152  	}
   153  	if msg.Size > baseProtocolMaxMsgSize {
   154  		return nil, fmt.Errorf("message too big")
   155  	}
   156  	if msg.Code == discMsg {
   157  		// Disconnect before protocol handshake is valid according to the
   158  		// spec and we send it ourself if the posthanshake checks fail.
   159  		// We can't return the reason directly, though, because it is echoed
   160  		// back otherwise. Wrap it in a string instead.
   161  		var reason [1]DiscReason
   162  		rlp.Decode(msg.Payload, &reason)
   163  		return nil, reason[0]
   164  	}
   165  	if msg.Code != handshakeMsg {
   166  		return nil, fmt.Errorf("expected handshake, got %x", msg.Code)
   167  	}
   168  	var hs protoHandshake
   169  	if err := msg.Decode(&hs); err != nil {
   170  		return nil, err
   171  	}
   172  	if (hs.ID == discover.NodeID{}) {
   173  		return nil, DiscInvalidIdentity
   174  	}
   175  	return &hs, nil
   176  }
   177  
   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, nil)
   185  	} else {
   186  		sec, err = initiatorEncHandshake(t.fd, prv, dial.ID, nil)
   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, token []byte) (s secrets, err error) {
   284  	h := &encHandshake{initiator: true, remoteID: remoteID}
   285  	authMsg, err := h.makeAuthMsg(prv, token)
   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, token []byte) (*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  // token is the token from a previous session with this node.
   356  func receiverEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, token []byte) (s secrets, err error) {
   357  	authMsg := new(authMsgV4)
   358  	authPacket, err := readHandshakeMsg(authMsg, encAuthMsgLen, prv, conn)
   359  	if err != nil {
   360  		return s, err
   361  	}
   362  	h := new(encHandshake)
   363  	if err := h.handleAuthMsg(authMsg, prv); err != nil {
   364  		return s, err
   365  	}
   366  
   367  	authRespMsg, err := h.makeAuthResp()
   368  	if err != nil {
   369  		return s, err
   370  	}
   371  	var authRespPacket []byte
   372  	if authMsg.gotPlain {
   373  		authRespPacket, err = authRespMsg.sealPlain(h)
   374  	} else {
   375  		authRespPacket, err = sealEIP8(authRespMsg, h)
   376  	}
   377  	if err != nil {
   378  		return s, err
   379  	}
   380  	if _, err = conn.Write(authRespPacket); err != nil {
   381  		return s, err
   382  	}
   383  	return h.secrets(authPacket, authRespPacket)
   384  }
   385  
   386  func (h *encHandshake) handleAuthMsg(msg *authMsgV4, prv *ecdsa.PrivateKey) error {
   387  	// Import the remote identity.
   388  	h.initNonce = msg.Nonce[:]
   389  	h.remoteID = msg.InitiatorPubkey
   390  	rpub, err := h.remoteID.Pubkey()
   391  	if err != nil {
   392  		return fmt.Errorf("bad remoteID: %#v", err)
   393  	}
   394  	h.remotePub = ecies.ImportECDSAPublic(rpub)
   395  
   396  	// Generate random keypair for ECDH.
   397  	// If a private key is already set, use it instead of generating one (for testing).
   398  	if h.randomPrivKey == nil {
   399  		h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
   400  		if err != nil {
   401  			return err
   402  		}
   403  	}
   404  
   405  	// Check the signature.
   406  	token, err := h.staticSharedSecret(prv)
   407  	if err != nil {
   408  		return err
   409  	}
   410  	signedMsg := xor(token, h.initNonce)
   411  	remoteRandomPub, err := secp256k1.RecoverPubkey(signedMsg, msg.Signature[:])
   412  	if err != nil {
   413  		return err
   414  	}
   415  	h.remoteRandomPub, _ = importPublicKey(remoteRandomPub)
   416  	return nil
   417  }
   418  
   419  func (h *encHandshake) makeAuthResp() (msg *authRespV4, err error) {
   420  	// Generate random nonce.
   421  	h.respNonce = make([]byte, shaLen)
   422  	if _, err = rand.Read(h.respNonce); err != nil {
   423  		return nil, err
   424  	}
   425  
   426  	msg = new(authRespV4)
   427  	copy(msg.Nonce[:], h.respNonce)
   428  	copy(msg.RandomPubkey[:], exportPubkey(&h.randomPrivKey.PublicKey))
   429  	msg.Version = 4
   430  	return msg, nil
   431  }
   432  
   433  func (msg *authMsgV4) sealPlain(h *encHandshake) ([]byte, error) {
   434  	buf := make([]byte, authMsgLen)
   435  	n := copy(buf, msg.Signature[:])
   436  	n += copy(buf[n:], crypto.Keccak256(exportPubkey(&h.randomPrivKey.PublicKey)))
   437  	n += copy(buf[n:], msg.InitiatorPubkey[:])
   438  	n += copy(buf[n:], msg.Nonce[:])
   439  	buf[n] = 0 // token-flag
   440  	return ecies.Encrypt(rand.Reader, h.remotePub, buf, nil, nil)
   441  }
   442  
   443  func (msg *authMsgV4) decodePlain(input []byte) {
   444  	n := copy(msg.Signature[:], input)
   445  	n += shaLen // skip sha3(initiator-ephemeral-pubk)
   446  	n += copy(msg.InitiatorPubkey[:], input[n:])
   447  	copy(msg.Nonce[:], input[n:])
   448  	msg.Version = 4
   449  	msg.gotPlain = true
   450  }
   451  
   452  func (msg *authRespV4) sealPlain(hs *encHandshake) ([]byte, error) {
   453  	buf := make([]byte, authRespLen)
   454  	n := copy(buf, msg.RandomPubkey[:])
   455  	copy(buf[n:], msg.Nonce[:])
   456  	return ecies.Encrypt(rand.Reader, hs.remotePub, buf, nil, nil)
   457  }
   458  
   459  func (msg *authRespV4) decodePlain(input []byte) {
   460  	n := copy(msg.RandomPubkey[:], input)
   461  	copy(msg.Nonce[:], input[n:])
   462  	msg.Version = 4
   463  }
   464  
   465  var padSpace = make([]byte, 300)
   466  
   467  func sealEIP8(msg interface{}, h *encHandshake) ([]byte, error) {
   468  	buf := new(bytes.Buffer)
   469  	if err := rlp.Encode(buf, msg); err != nil {
   470  		return nil, err
   471  	}
   472  	// pad with random amount of data. the amount needs to be at least 100 bytes to make
   473  	// the message distinguishable from pre-EIP-8 handshakes.
   474  	pad := padSpace[:mrand.Intn(len(padSpace)-100)+100]
   475  	buf.Write(pad)
   476  	prefix := make([]byte, 2)
   477  	binary.BigEndian.PutUint16(prefix, uint16(buf.Len()+eciesOverhead))
   478  
   479  	enc, err := ecies.Encrypt(rand.Reader, h.remotePub, buf.Bytes(), nil, prefix)
   480  	return append(prefix, enc...), err
   481  }
   482  
   483  type plainDecoder interface {
   484  	decodePlain([]byte)
   485  }
   486  
   487  func readHandshakeMsg(msg plainDecoder, plainSize int, prv *ecdsa.PrivateKey, r io.Reader) ([]byte, error) {
   488  	buf := make([]byte, plainSize)
   489  	if _, err := io.ReadFull(r, buf); err != nil {
   490  		return buf, err
   491  	}
   492  	// Attempt decoding pre-EIP-8 "plain" format.
   493  	key := ecies.ImportECDSA(prv)
   494  	if dec, err := key.Decrypt(buf, nil, nil); err == nil {
   495  		msg.decodePlain(dec)
   496  		return buf, nil
   497  	}
   498  	// Could be EIP-8 format, try that.
   499  	prefix := buf[:2]
   500  	size := binary.BigEndian.Uint16(prefix)
   501  	if size < uint16(plainSize) {
   502  		return buf, fmt.Errorf("size underflow, need at least %d bytes", plainSize)
   503  	}
   504  	buf = append(buf, make([]byte, size-uint16(plainSize)+2)...)
   505  	if _, err := io.ReadFull(r, buf[plainSize:]); err != nil {
   506  		return buf, err
   507  	}
   508  	dec, err := key.Decrypt(buf[2:], nil, prefix)
   509  	if err != nil {
   510  		return buf, err
   511  	}
   512  	// Can't use rlp.DecodeBytes here because it rejects
   513  	// trailing data (forward-compatibility).
   514  	s := rlp.NewStream(bytes.NewReader(dec), 0)
   515  	return buf, s.Decode(msg)
   516  }
   517  
   518  // importPublicKey unmarshals 512 bit public keys.
   519  func importPublicKey(pubKey []byte) (*ecies.PublicKey, error) {
   520  	var pubKey65 []byte
   521  	switch len(pubKey) {
   522  	case 64:
   523  		// add 'uncompressed key' flag
   524  		pubKey65 = append([]byte{0x04}, pubKey...)
   525  	case 65:
   526  		pubKey65 = pubKey
   527  	default:
   528  		return nil, fmt.Errorf("invalid public key length %v (expect 64/65)", len(pubKey))
   529  	}
   530  	// TODO: fewer pointless conversions
   531  	pub := crypto.ToECDSAPub(pubKey65)
   532  	if pub.X == nil {
   533  		return nil, fmt.Errorf("invalid public key")
   534  	}
   535  	return ecies.ImportECDSAPublic(pub), nil
   536  }
   537  
   538  func exportPubkey(pub *ecies.PublicKey) []byte {
   539  	if pub == nil {
   540  		panic("nil pubkey")
   541  	}
   542  	return elliptic.Marshal(pub.Curve, pub.X, pub.Y)[1:]
   543  }
   544  
   545  func xor(one, other []byte) (xor []byte) {
   546  	xor = make([]byte, len(one))
   547  	for i := 0; i < len(one); i++ {
   548  		xor[i] = one[i] ^ other[i]
   549  	}
   550  	return xor
   551  }
   552  
   553  var (
   554  	// this is used in place of actual frame header data.
   555  	// TODO: replace this when Msg contains the protocol type code.
   556  	zeroHeader = []byte{0xC2, 0x80, 0x80}
   557  	// sixteen zero bytes
   558  	zero16 = make([]byte, 16)
   559  )
   560  
   561  // rlpxFrameRW implements a simplified version of RLPx framing.
   562  // chunked messages are not supported and all headers are equal to
   563  // zeroHeader.
   564  //
   565  // rlpxFrameRW is not safe for concurrent use from multiple goroutines.
   566  type rlpxFrameRW struct {
   567  	conn io.ReadWriter
   568  	enc  cipher.Stream
   569  	dec  cipher.Stream
   570  
   571  	macCipher  cipher.Block
   572  	egressMAC  hash.Hash
   573  	ingressMAC hash.Hash
   574  
   575  	snappy bool
   576  }
   577  
   578  func newRLPXFrameRW(conn io.ReadWriter, s secrets) *rlpxFrameRW {
   579  	macc, err := aes.NewCipher(s.MAC)
   580  	if err != nil {
   581  		panic("invalid MAC secret: " + err.Error())
   582  	}
   583  	encc, err := aes.NewCipher(s.AES)
   584  	if err != nil {
   585  		panic("invalid AES secret: " + err.Error())
   586  	}
   587  	// we use an all-zeroes IV for AES because the key used
   588  	// for encryption is ephemeral.
   589  	iv := make([]byte, encc.BlockSize())
   590  	return &rlpxFrameRW{
   591  		conn:       conn,
   592  		enc:        cipher.NewCTR(encc, iv),
   593  		dec:        cipher.NewCTR(encc, iv),
   594  		macCipher:  macc,
   595  		egressMAC:  s.EgressMAC,
   596  		ingressMAC: s.IngressMAC,
   597  	}
   598  }
   599  
   600  func (rw *rlpxFrameRW) WriteMsg(msg Msg) error {
   601  	ptype, _ := rlp.EncodeToBytes(msg.Code)
   602  
   603  	// if snappy is enabled, compress message now
   604  	if rw.snappy {
   605  		if msg.Size > maxUint24 {
   606  			return errPlainMessageTooLarge
   607  		}
   608  		payload, _ := ioutil.ReadAll(msg.Payload)
   609  		payload = snappy.Encode(nil, payload)
   610  
   611  		msg.Payload = bytes.NewReader(payload)
   612  		msg.Size = uint32(len(payload))
   613  	}
   614  	// write header
   615  	headbuf := make([]byte, 32)
   616  	fsize := uint32(len(ptype)) + msg.Size
   617  	if fsize > maxUint24 {
   618  		return errors.New("message size overflows uint24")
   619  	}
   620  	putInt24(fsize, headbuf) // TODO: check overflow
   621  	copy(headbuf[3:], zeroHeader)
   622  	rw.enc.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now encrypted
   623  
   624  	// write header MAC
   625  	copy(headbuf[16:], updateMAC(rw.egressMAC, rw.macCipher, headbuf[:16]))
   626  	if _, err := rw.conn.Write(headbuf); err != nil {
   627  		return err
   628  	}
   629  
   630  	// write encrypted frame, updating the egress MAC hash with
   631  	// the data written to conn.
   632  	tee := cipher.StreamWriter{S: rw.enc, W: io.MultiWriter(rw.conn, rw.egressMAC)}
   633  	if _, err := tee.Write(ptype); err != nil {
   634  		return err
   635  	}
   636  	if _, err := io.Copy(tee, msg.Payload); err != nil {
   637  		return err
   638  	}
   639  	if padding := fsize % 16; padding > 0 {
   640  		if _, err := tee.Write(zero16[:16-padding]); err != nil {
   641  			return err
   642  		}
   643  	}
   644  
   645  	// write frame MAC. egress MAC hash is up to date because
   646  	// frame content was written to it as well.
   647  	fmacseed := rw.egressMAC.Sum(nil)
   648  	mac := updateMAC(rw.egressMAC, rw.macCipher, fmacseed)
   649  	_, err := rw.conn.Write(mac)
   650  	return err
   651  }
   652  
   653  func (rw *rlpxFrameRW) ReadMsg() (msg Msg, err error) {
   654  	// read the header
   655  	headbuf := make([]byte, 32)
   656  	if _, err := io.ReadFull(rw.conn, headbuf); err != nil {
   657  		return msg, err
   658  	}
   659  	// verify header mac
   660  	shouldMAC := updateMAC(rw.ingressMAC, rw.macCipher, headbuf[:16])
   661  	if !hmac.Equal(shouldMAC, headbuf[16:]) {
   662  		return msg, errors.New("bad header MAC")
   663  	}
   664  	rw.dec.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now decrypted
   665  	fsize := readInt24(headbuf)
   666  	// ignore protocol type for now
   667  
   668  	// read the frame content
   669  	var rsize = fsize // frame size rounded up to 16 byte boundary
   670  	if padding := fsize % 16; padding > 0 {
   671  		rsize += 16 - padding
   672  	}
   673  	framebuf := make([]byte, rsize)
   674  	if _, err := io.ReadFull(rw.conn, framebuf); err != nil {
   675  		return msg, err
   676  	}
   677  
   678  	// read and validate frame MAC. we can re-use headbuf for that.
   679  	rw.ingressMAC.Write(framebuf)
   680  	fmacseed := rw.ingressMAC.Sum(nil)
   681  	if _, err := io.ReadFull(rw.conn, headbuf[:16]); err != nil {
   682  		return msg, err
   683  	}
   684  	shouldMAC = updateMAC(rw.ingressMAC, rw.macCipher, fmacseed)
   685  	if !hmac.Equal(shouldMAC, headbuf[:16]) {
   686  		return msg, errors.New("bad frame MAC")
   687  	}
   688  
   689  	// decrypt frame content
   690  	rw.dec.XORKeyStream(framebuf, framebuf)
   691  
   692  	// decode message code
   693  	content := bytes.NewReader(framebuf[:fsize])
   694  	if err := rlp.Decode(content, &msg.Code); err != nil {
   695  		return msg, err
   696  	}
   697  	msg.Size = uint32(content.Len())
   698  	msg.Payload = content
   699  
   700  	// if snappy is enabled, verify and decompress message
   701  	if rw.snappy {
   702  		payload, err := ioutil.ReadAll(msg.Payload)
   703  		if err != nil {
   704  			return msg, err
   705  		}
   706  		size, err := snappy.DecodedLen(payload)
   707  		if err != nil {
   708  			return msg, err
   709  		}
   710  		if size > int(maxUint24) {
   711  			return msg, errPlainMessageTooLarge
   712  		}
   713  		payload, err = snappy.Decode(nil, payload)
   714  		if err != nil {
   715  			return msg, err
   716  		}
   717  		msg.Size, msg.Payload = uint32(size), bytes.NewReader(payload)
   718  	}
   719  	return msg, nil
   720  }
   721  
   722  // updateMAC reseeds the given hash with encrypted seed.
   723  // it returns the first 16 bytes of the hash sum after seeding.
   724  func updateMAC(mac hash.Hash, block cipher.Block, seed []byte) []byte {
   725  	aesbuf := make([]byte, aes.BlockSize)
   726  	block.Encrypt(aesbuf, mac.Sum(nil))
   727  	for i := range aesbuf {
   728  		aesbuf[i] ^= seed[i]
   729  	}
   730  	mac.Write(aesbuf)
   731  	return mac.Sum(nil)[:16]
   732  }
   733  
   734  func readInt24(b []byte) uint32 {
   735  	return uint32(b[2]) | uint32(b[1])<<8 | uint32(b[0])<<16
   736  }
   737  
   738  func putInt24(v uint32, b []byte) {
   739  	b[0] = byte(v >> 16)
   740  	b[1] = byte(v >> 8)
   741  	b[2] = byte(v)
   742  }