|
|
@@ -14,7 +14,8 @@
|
|
|
// You should have received a copy of the GNU Lesser General Public License
|
|
|
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
|
-package p2p
|
|
|
+// Package rlpx implements the RLPx transport protocol.
|
|
|
+package rlpx
|
|
|
|
|
|
import (
|
|
|
"bytes"
|
|
|
@@ -29,169 +30,312 @@ import (
|
|
|
"fmt"
|
|
|
"hash"
|
|
|
"io"
|
|
|
- "io/ioutil"
|
|
|
mrand "math/rand"
|
|
|
"net"
|
|
|
- "sync"
|
|
|
"time"
|
|
|
|
|
|
- "github.com/ethereum/go-ethereum/common/bitutil"
|
|
|
"github.com/ethereum/go-ethereum/crypto"
|
|
|
"github.com/ethereum/go-ethereum/crypto/ecies"
|
|
|
- "github.com/ethereum/go-ethereum/metrics"
|
|
|
"github.com/ethereum/go-ethereum/rlp"
|
|
|
"github.com/golang/snappy"
|
|
|
"golang.org/x/crypto/sha3"
|
|
|
)
|
|
|
|
|
|
-const (
|
|
|
- maxUint24 = ^uint32(0) >> 8
|
|
|
-
|
|
|
- sskLen = 16 // ecies.MaxSharedKeyLength(pubKey) / 2
|
|
|
- sigLen = crypto.SignatureLength // elliptic S256
|
|
|
- pubLen = 64 // 512 bit pubkey in uncompressed representation without format byte
|
|
|
- shaLen = 32 // hash length (for nonce etc)
|
|
|
-
|
|
|
- authMsgLen = sigLen + shaLen + pubLen + shaLen + 1
|
|
|
- authRespLen = pubLen + shaLen + 1
|
|
|
-
|
|
|
- eciesOverhead = 65 /* pubkey */ + 16 /* IV */ + 32 /* MAC */
|
|
|
-
|
|
|
- encAuthMsgLen = authMsgLen + eciesOverhead // size of encrypted pre-EIP-8 initiator handshake
|
|
|
- encAuthRespLen = authRespLen + eciesOverhead // size of encrypted pre-EIP-8 handshake reply
|
|
|
+// Conn is an RLPx network connection. It wraps a low-level network connection. The
|
|
|
+// underlying connection should not be used for other activity when it is wrapped by Conn.
|
|
|
+//
|
|
|
+// Before sending messages, a handshake must be performed by calling the Handshake method.
|
|
|
+// This type is not generally safe for concurrent use, but reading and writing of messages
|
|
|
+// may happen concurrently after the handshake.
|
|
|
+type Conn struct {
|
|
|
+ dialDest *ecdsa.PublicKey
|
|
|
+ conn net.Conn
|
|
|
+ handshake *handshakeState
|
|
|
+ snappy bool
|
|
|
+}
|
|
|
|
|
|
- // total timeout for encryption handshake and protocol
|
|
|
- // handshake in both directions.
|
|
|
- handshakeTimeout = 5 * time.Second
|
|
|
+type handshakeState struct {
|
|
|
+ enc cipher.Stream
|
|
|
+ dec cipher.Stream
|
|
|
|
|
|
- // This is the timeout for sending the disconnect reason.
|
|
|
- // This is shorter than the usual timeout because we don't want
|
|
|
- // to wait if the connection is known to be bad anyway.
|
|
|
- discWriteTimeout = 1 * time.Second
|
|
|
-)
|
|
|
-
|
|
|
-// errPlainMessageTooLarge is returned if a decompressed message length exceeds
|
|
|
-// the allowed 24 bits (i.e. length >= 16MB).
|
|
|
-var errPlainMessageTooLarge = errors.New("message length >= 16MB")
|
|
|
+ macCipher cipher.Block
|
|
|
+ egressMAC hash.Hash
|
|
|
+ ingressMAC hash.Hash
|
|
|
+}
|
|
|
|
|
|
-// rlpx is the transport protocol used by actual (non-test) connections.
|
|
|
-// It wraps the frame encoder with locks and read/write deadlines.
|
|
|
-type rlpx struct {
|
|
|
- fd net.Conn
|
|
|
+// NewConn wraps the given network connection. If dialDest is non-nil, the connection
|
|
|
+// behaves as the initiator during the handshake.
|
|
|
+func NewConn(conn net.Conn, dialDest *ecdsa.PublicKey) *Conn {
|
|
|
+ return &Conn{
|
|
|
+ dialDest: dialDest,
|
|
|
+ conn: conn,
|
|
|
+ }
|
|
|
+}
|
|
|
|
|
|
- rmu, wmu sync.Mutex
|
|
|
- rw *rlpxFrameRW
|
|
|
+// SetSnappy enables or disables snappy compression of messages. This is usually called
|
|
|
+// after the devp2p Hello message exchange when the negotiated version indicates that
|
|
|
+// compression is available on both ends of the connection.
|
|
|
+func (c *Conn) SetSnappy(snappy bool) {
|
|
|
+ c.snappy = snappy
|
|
|
}
|
|
|
|
|
|
-func newRLPX(fd net.Conn) transport {
|
|
|
- fd.SetDeadline(time.Now().Add(handshakeTimeout))
|
|
|
- return &rlpx{fd: fd}
|
|
|
+// SetReadDeadline sets the deadline for all future read operations.
|
|
|
+func (c *Conn) SetReadDeadline(time time.Time) error {
|
|
|
+ return c.conn.SetReadDeadline(time)
|
|
|
}
|
|
|
|
|
|
-func (t *rlpx) ReadMsg() (Msg, error) {
|
|
|
- t.rmu.Lock()
|
|
|
- defer t.rmu.Unlock()
|
|
|
- t.fd.SetReadDeadline(time.Now().Add(frameReadTimeout))
|
|
|
- return t.rw.ReadMsg()
|
|
|
+// SetWriteDeadline sets the deadline for all future write operations.
|
|
|
+func (c *Conn) SetWriteDeadline(time time.Time) error {
|
|
|
+ return c.conn.SetWriteDeadline(time)
|
|
|
}
|
|
|
|
|
|
-func (t *rlpx) WriteMsg(msg Msg) error {
|
|
|
- t.wmu.Lock()
|
|
|
- defer t.wmu.Unlock()
|
|
|
- t.fd.SetWriteDeadline(time.Now().Add(frameWriteTimeout))
|
|
|
- return t.rw.WriteMsg(msg)
|
|
|
+// SetDeadline sets the deadline for all future read and write operations.
|
|
|
+func (c *Conn) SetDeadline(time time.Time) error {
|
|
|
+ return c.conn.SetDeadline(time)
|
|
|
}
|
|
|
|
|
|
-func (t *rlpx) close(err error) {
|
|
|
- t.wmu.Lock()
|
|
|
- defer t.wmu.Unlock()
|
|
|
- // Tell the remote end why we're disconnecting if possible.
|
|
|
- if t.rw != nil {
|
|
|
- if r, ok := err.(DiscReason); ok && r != DiscNetworkError {
|
|
|
- // rlpx tries to send DiscReason to disconnected peer
|
|
|
- // if the connection is net.Pipe (in-memory simulation)
|
|
|
- // it hangs forever, since net.Pipe does not implement
|
|
|
- // a write deadline. Because of this only try to send
|
|
|
- // the disconnect reason message if there is no error.
|
|
|
- if err := t.fd.SetWriteDeadline(time.Now().Add(discWriteTimeout)); err == nil {
|
|
|
- SendItems(t.rw, discMsg, r)
|
|
|
- }
|
|
|
+// Read reads a message from the connection.
|
|
|
+func (c *Conn) Read() (code uint64, data []byte, wireSize int, err error) {
|
|
|
+ if c.handshake == nil {
|
|
|
+ panic("can't ReadMsg before handshake")
|
|
|
+ }
|
|
|
+
|
|
|
+ frame, err := c.handshake.readFrame(c.conn)
|
|
|
+ if err != nil {
|
|
|
+ return 0, nil, 0, err
|
|
|
+ }
|
|
|
+ code, data, err = rlp.SplitUint64(frame)
|
|
|
+ if err != nil {
|
|
|
+ return 0, nil, 0, fmt.Errorf("invalid message code: %v", err)
|
|
|
+ }
|
|
|
+ wireSize = len(data)
|
|
|
+
|
|
|
+ // If snappy is enabled, verify and decompress message.
|
|
|
+ if c.snappy {
|
|
|
+ var actualSize int
|
|
|
+ actualSize, err = snappy.DecodedLen(data)
|
|
|
+ if err != nil {
|
|
|
+ return code, nil, 0, err
|
|
|
+ }
|
|
|
+ if actualSize > maxUint24 {
|
|
|
+ return code, nil, 0, errPlainMessageTooLarge
|
|
|
}
|
|
|
+ data, err = snappy.Decode(nil, data)
|
|
|
}
|
|
|
- t.fd.Close()
|
|
|
+ return code, data, wireSize, err
|
|
|
}
|
|
|
|
|
|
-func (t *rlpx) doProtoHandshake(our *protoHandshake) (their *protoHandshake, err error) {
|
|
|
- // Writing our handshake happens concurrently, we prefer
|
|
|
- // returning the handshake read error. If the remote side
|
|
|
- // disconnects us early with a valid reason, we should return it
|
|
|
- // as the error so it can be tracked elsewhere.
|
|
|
- werr := make(chan error, 1)
|
|
|
- go func() { werr <- Send(t.rw, handshakeMsg, our) }()
|
|
|
- if their, err = readProtocolHandshake(t.rw); err != nil {
|
|
|
- <-werr // make sure the write terminates too
|
|
|
+func (h *handshakeState) readFrame(conn io.Reader) ([]byte, error) {
|
|
|
+ // read the header
|
|
|
+ headbuf := make([]byte, 32)
|
|
|
+ if _, err := io.ReadFull(conn, headbuf); err != nil {
|
|
|
return nil, err
|
|
|
}
|
|
|
- if err := <-werr; err != nil {
|
|
|
- return nil, fmt.Errorf("write error: %v", err)
|
|
|
+
|
|
|
+ // verify header mac
|
|
|
+ shouldMAC := updateMAC(h.ingressMAC, h.macCipher, headbuf[:16])
|
|
|
+ if !hmac.Equal(shouldMAC, headbuf[16:]) {
|
|
|
+ return nil, errors.New("bad header MAC")
|
|
|
}
|
|
|
- // If the protocol version supports Snappy encoding, upgrade immediately
|
|
|
- t.rw.snappy = their.Version >= snappyProtocolVersion
|
|
|
+ h.dec.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now decrypted
|
|
|
+ fsize := readInt24(headbuf)
|
|
|
+ // ignore protocol type for now
|
|
|
|
|
|
- return their, nil
|
|
|
-}
|
|
|
+ // read the frame content
|
|
|
+ var rsize = fsize // frame size rounded up to 16 byte boundary
|
|
|
+ if padding := fsize % 16; padding > 0 {
|
|
|
+ rsize += 16 - padding
|
|
|
+ }
|
|
|
+ framebuf := make([]byte, rsize)
|
|
|
+ if _, err := io.ReadFull(conn, framebuf); err != nil {
|
|
|
+ return nil, err
|
|
|
+ }
|
|
|
|
|
|
-func readProtocolHandshake(rw MsgReader) (*protoHandshake, error) {
|
|
|
- msg, err := rw.ReadMsg()
|
|
|
- if err != nil {
|
|
|
+ // read and validate frame MAC. we can re-use headbuf for that.
|
|
|
+ h.ingressMAC.Write(framebuf)
|
|
|
+ fmacseed := h.ingressMAC.Sum(nil)
|
|
|
+ if _, err := io.ReadFull(conn, headbuf[:16]); err != nil {
|
|
|
return nil, err
|
|
|
}
|
|
|
- if msg.Size > baseProtocolMaxMsgSize {
|
|
|
- return nil, fmt.Errorf("message too big")
|
|
|
+ shouldMAC = updateMAC(h.ingressMAC, h.macCipher, fmacseed)
|
|
|
+ if !hmac.Equal(shouldMAC, headbuf[:16]) {
|
|
|
+ return nil, errors.New("bad frame MAC")
|
|
|
+ }
|
|
|
+
|
|
|
+ // decrypt frame content
|
|
|
+ h.dec.XORKeyStream(framebuf, framebuf)
|
|
|
+ return framebuf[:fsize], nil
|
|
|
+}
|
|
|
+
|
|
|
+// Write writes a message to the connection.
|
|
|
+//
|
|
|
+// Write returns the written size of the message data. This may be less than or equal to
|
|
|
+// len(data) depending on whether snappy compression is enabled.
|
|
|
+func (c *Conn) Write(code uint64, data []byte) (uint32, error) {
|
|
|
+ if c.handshake == nil {
|
|
|
+ panic("can't WriteMsg before handshake")
|
|
|
}
|
|
|
- if msg.Code == discMsg {
|
|
|
- // Disconnect before protocol handshake is valid according to the
|
|
|
- // spec and we send it ourself if the post-handshake checks fail.
|
|
|
- // We can't return the reason directly, though, because it is echoed
|
|
|
- // back otherwise. Wrap it in a string instead.
|
|
|
- var reason [1]DiscReason
|
|
|
- rlp.Decode(msg.Payload, &reason)
|
|
|
- return nil, reason[0]
|
|
|
+ if len(data) > maxUint24 {
|
|
|
+ return 0, errPlainMessageTooLarge
|
|
|
}
|
|
|
- if msg.Code != handshakeMsg {
|
|
|
- return nil, fmt.Errorf("expected handshake, got %x", msg.Code)
|
|
|
+ if c.snappy {
|
|
|
+ data = snappy.Encode(nil, data)
|
|
|
}
|
|
|
- var hs protoHandshake
|
|
|
- if err := msg.Decode(&hs); err != nil {
|
|
|
- return nil, err
|
|
|
+
|
|
|
+ wireSize := uint32(len(data))
|
|
|
+ err := c.handshake.writeFrame(c.conn, code, data)
|
|
|
+ return wireSize, err
|
|
|
+}
|
|
|
+
|
|
|
+func (h *handshakeState) writeFrame(conn io.Writer, code uint64, data []byte) error {
|
|
|
+ ptype, _ := rlp.EncodeToBytes(code)
|
|
|
+
|
|
|
+ // write header
|
|
|
+ headbuf := make([]byte, 32)
|
|
|
+ fsize := len(ptype) + len(data)
|
|
|
+ if fsize > maxUint24 {
|
|
|
+ return errPlainMessageTooLarge
|
|
|
+ }
|
|
|
+ putInt24(uint32(fsize), headbuf)
|
|
|
+ copy(headbuf[3:], zeroHeader)
|
|
|
+ h.enc.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now encrypted
|
|
|
+
|
|
|
+ // write header MAC
|
|
|
+ copy(headbuf[16:], updateMAC(h.egressMAC, h.macCipher, headbuf[:16]))
|
|
|
+ if _, err := conn.Write(headbuf); err != nil {
|
|
|
+ return err
|
|
|
+ }
|
|
|
+
|
|
|
+ // write encrypted frame, updating the egress MAC hash with
|
|
|
+ // the data written to conn.
|
|
|
+ tee := cipher.StreamWriter{S: h.enc, W: io.MultiWriter(conn, h.egressMAC)}
|
|
|
+ if _, err := tee.Write(ptype); err != nil {
|
|
|
+ return err
|
|
|
+ }
|
|
|
+ if _, err := tee.Write(data); err != nil {
|
|
|
+ return err
|
|
|
}
|
|
|
- if len(hs.ID) != 64 || !bitutil.TestBytes(hs.ID) {
|
|
|
- return nil, DiscInvalidIdentity
|
|
|
+ if padding := fsize % 16; padding > 0 {
|
|
|
+ if _, err := tee.Write(zero16[:16-padding]); err != nil {
|
|
|
+ return err
|
|
|
+ }
|
|
|
}
|
|
|
- return &hs, nil
|
|
|
+
|
|
|
+ // write frame MAC. egress MAC hash is up to date because
|
|
|
+ // frame content was written to it as well.
|
|
|
+ fmacseed := h.egressMAC.Sum(nil)
|
|
|
+ mac := updateMAC(h.egressMAC, h.macCipher, fmacseed)
|
|
|
+ _, err := conn.Write(mac)
|
|
|
+ return err
|
|
|
+}
|
|
|
+
|
|
|
+func readInt24(b []byte) uint32 {
|
|
|
+ return uint32(b[2]) | uint32(b[1])<<8 | uint32(b[0])<<16
|
|
|
}
|
|
|
|
|
|
-// doEncHandshake runs the protocol handshake using authenticated
|
|
|
-// messages. the protocol handshake is the first authenticated message
|
|
|
-// and also verifies whether the encryption handshake 'worked' and the
|
|
|
-// remote side actually provided the right public key.
|
|
|
-func (t *rlpx) doEncHandshake(prv *ecdsa.PrivateKey, dial *ecdsa.PublicKey) (*ecdsa.PublicKey, error) {
|
|
|
+func putInt24(v uint32, b []byte) {
|
|
|
+ b[0] = byte(v >> 16)
|
|
|
+ b[1] = byte(v >> 8)
|
|
|
+ b[2] = byte(v)
|
|
|
+}
|
|
|
+
|
|
|
+// updateMAC reseeds the given hash with encrypted seed.
|
|
|
+// it returns the first 16 bytes of the hash sum after seeding.
|
|
|
+func updateMAC(mac hash.Hash, block cipher.Block, seed []byte) []byte {
|
|
|
+ aesbuf := make([]byte, aes.BlockSize)
|
|
|
+ block.Encrypt(aesbuf, mac.Sum(nil))
|
|
|
+ for i := range aesbuf {
|
|
|
+ aesbuf[i] ^= seed[i]
|
|
|
+ }
|
|
|
+ mac.Write(aesbuf)
|
|
|
+ return mac.Sum(nil)[:16]
|
|
|
+}
|
|
|
+
|
|
|
+// Handshake performs the handshake. This must be called before any data is written
|
|
|
+// or read from the connection.
|
|
|
+func (c *Conn) Handshake(prv *ecdsa.PrivateKey) (*ecdsa.PublicKey, error) {
|
|
|
var (
|
|
|
- sec secrets
|
|
|
+ sec Secrets
|
|
|
err error
|
|
|
)
|
|
|
- if dial == nil {
|
|
|
- sec, err = receiverEncHandshake(t.fd, prv)
|
|
|
+ if c.dialDest != nil {
|
|
|
+ sec, err = initiatorEncHandshake(c.conn, prv, c.dialDest)
|
|
|
} else {
|
|
|
- sec, err = initiatorEncHandshake(t.fd, prv, dial)
|
|
|
+ sec, err = receiverEncHandshake(c.conn, prv)
|
|
|
}
|
|
|
if err != nil {
|
|
|
return nil, err
|
|
|
}
|
|
|
- t.wmu.Lock()
|
|
|
- t.rw = newRLPXFrameRW(t.fd, sec)
|
|
|
- t.wmu.Unlock()
|
|
|
- return sec.Remote.ExportECDSA(), nil
|
|
|
+ c.InitWithSecrets(sec)
|
|
|
+ return sec.remote, err
|
|
|
+}
|
|
|
+
|
|
|
+// InitWithSecrets injects connection secrets as if a handshake had
|
|
|
+// been performed. This cannot be called after the handshake.
|
|
|
+func (c *Conn) InitWithSecrets(sec Secrets) {
|
|
|
+ if c.handshake != nil {
|
|
|
+ panic("can't handshake twice")
|
|
|
+ }
|
|
|
+ macc, err := aes.NewCipher(sec.MAC)
|
|
|
+ if err != nil {
|
|
|
+ panic("invalid MAC secret: " + err.Error())
|
|
|
+ }
|
|
|
+ encc, err := aes.NewCipher(sec.AES)
|
|
|
+ if err != nil {
|
|
|
+ panic("invalid AES secret: " + err.Error())
|
|
|
+ }
|
|
|
+ // we use an all-zeroes IV for AES because the key used
|
|
|
+ // for encryption is ephemeral.
|
|
|
+ iv := make([]byte, encc.BlockSize())
|
|
|
+ c.handshake = &handshakeState{
|
|
|
+ enc: cipher.NewCTR(encc, iv),
|
|
|
+ dec: cipher.NewCTR(encc, iv),
|
|
|
+ macCipher: macc,
|
|
|
+ egressMAC: sec.EgressMAC,
|
|
|
+ ingressMAC: sec.IngressMAC,
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+// Close closes the underlying network connection.
|
|
|
+func (c *Conn) Close() error {
|
|
|
+ return c.conn.Close()
|
|
|
+}
|
|
|
+
|
|
|
+// Constants for the handshake.
|
|
|
+const (
|
|
|
+ maxUint24 = int(^uint32(0) >> 8)
|
|
|
+
|
|
|
+ sskLen = 16 // ecies.MaxSharedKeyLength(pubKey) / 2
|
|
|
+ sigLen = crypto.SignatureLength // elliptic S256
|
|
|
+ pubLen = 64 // 512 bit pubkey in uncompressed representation without format byte
|
|
|
+ shaLen = 32 // hash length (for nonce etc)
|
|
|
+
|
|
|
+ authMsgLen = sigLen + shaLen + pubLen + shaLen + 1
|
|
|
+ authRespLen = pubLen + shaLen + 1
|
|
|
+
|
|
|
+ eciesOverhead = 65 /* pubkey */ + 16 /* IV */ + 32 /* MAC */
|
|
|
+
|
|
|
+ encAuthMsgLen = authMsgLen + eciesOverhead // size of encrypted pre-EIP-8 initiator handshake
|
|
|
+ encAuthRespLen = authRespLen + eciesOverhead // size of encrypted pre-EIP-8 handshake reply
|
|
|
+)
|
|
|
+
|
|
|
+var (
|
|
|
+ // this is used in place of actual frame header data.
|
|
|
+ // TODO: replace this when Msg contains the protocol type code.
|
|
|
+ zeroHeader = []byte{0xC2, 0x80, 0x80}
|
|
|
+ // sixteen zero bytes
|
|
|
+ zero16 = make([]byte, 16)
|
|
|
+
|
|
|
+ // errPlainMessageTooLarge is returned if a decompressed message length exceeds
|
|
|
+ // the allowed 24 bits (i.e. length >= 16MB).
|
|
|
+ errPlainMessageTooLarge = errors.New("message length >= 16MB")
|
|
|
+)
|
|
|
+
|
|
|
+// Secrets represents the connection secrets which are negotiated during the handshake.
|
|
|
+type Secrets struct {
|
|
|
+ AES, MAC []byte
|
|
|
+ EgressMAC, IngressMAC hash.Hash
|
|
|
+ remote *ecdsa.PublicKey
|
|
|
}
|
|
|
|
|
|
// encHandshake contains the state of the encryption handshake.
|
|
|
@@ -203,15 +347,6 @@ type encHandshake struct {
|
|
|
remoteRandomPub *ecies.PublicKey // ecdhe-random-pubk
|
|
|
}
|
|
|
|
|
|
-// secrets represents the connection secrets
|
|
|
-// which are negotiated during the encryption handshake.
|
|
|
-type secrets struct {
|
|
|
- Remote *ecies.PublicKey
|
|
|
- AES, MAC []byte
|
|
|
- EgressMAC, IngressMAC hash.Hash
|
|
|
- Token []byte
|
|
|
-}
|
|
|
-
|
|
|
// RLPx v4 handshake auth (defined in EIP-8).
|
|
|
type authMsgV4 struct {
|
|
|
gotPlain bool // whether read packet had plain format.
|
|
|
@@ -235,19 +370,85 @@ type authRespV4 struct {
|
|
|
Rest []rlp.RawValue `rlp:"tail"`
|
|
|
}
|
|
|
|
|
|
+// receiverEncHandshake negotiates a session token on conn.
|
|
|
+// it should be called on the listening side of the connection.
|
|
|
+//
|
|
|
+// prv is the local client's private key.
|
|
|
+func receiverEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey) (s Secrets, err error) {
|
|
|
+ authMsg := new(authMsgV4)
|
|
|
+ authPacket, err := readHandshakeMsg(authMsg, encAuthMsgLen, prv, conn)
|
|
|
+ if err != nil {
|
|
|
+ return s, err
|
|
|
+ }
|
|
|
+ h := new(encHandshake)
|
|
|
+ if err := h.handleAuthMsg(authMsg, prv); err != nil {
|
|
|
+ return s, err
|
|
|
+ }
|
|
|
+
|
|
|
+ authRespMsg, err := h.makeAuthResp()
|
|
|
+ if err != nil {
|
|
|
+ return s, err
|
|
|
+ }
|
|
|
+ var authRespPacket []byte
|
|
|
+ if authMsg.gotPlain {
|
|
|
+ authRespPacket, err = authRespMsg.sealPlain(h)
|
|
|
+ } else {
|
|
|
+ authRespPacket, err = sealEIP8(authRespMsg, h)
|
|
|
+ }
|
|
|
+ if err != nil {
|
|
|
+ return s, err
|
|
|
+ }
|
|
|
+ if _, err = conn.Write(authRespPacket); err != nil {
|
|
|
+ return s, err
|
|
|
+ }
|
|
|
+ return h.secrets(authPacket, authRespPacket)
|
|
|
+}
|
|
|
+
|
|
|
+func (h *encHandshake) handleAuthMsg(msg *authMsgV4, prv *ecdsa.PrivateKey) error {
|
|
|
+ // Import the remote identity.
|
|
|
+ rpub, err := importPublicKey(msg.InitiatorPubkey[:])
|
|
|
+ if err != nil {
|
|
|
+ return err
|
|
|
+ }
|
|
|
+ h.initNonce = msg.Nonce[:]
|
|
|
+ h.remote = rpub
|
|
|
+
|
|
|
+ // Generate random keypair for ECDH.
|
|
|
+ // If a private key is already set, use it instead of generating one (for testing).
|
|
|
+ if h.randomPrivKey == nil {
|
|
|
+ h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
|
|
|
+ if err != nil {
|
|
|
+ return err
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // Check the signature.
|
|
|
+ token, err := h.staticSharedSecret(prv)
|
|
|
+ if err != nil {
|
|
|
+ return err
|
|
|
+ }
|
|
|
+ signedMsg := xor(token, h.initNonce)
|
|
|
+ remoteRandomPub, err := crypto.Ecrecover(signedMsg, msg.Signature[:])
|
|
|
+ if err != nil {
|
|
|
+ return err
|
|
|
+ }
|
|
|
+ h.remoteRandomPub, _ = importPublicKey(remoteRandomPub)
|
|
|
+ return nil
|
|
|
+}
|
|
|
+
|
|
|
// secrets is called after the handshake is completed.
|
|
|
// It extracts the connection secrets from the handshake values.
|
|
|
-func (h *encHandshake) secrets(auth, authResp []byte) (secrets, error) {
|
|
|
+func (h *encHandshake) secrets(auth, authResp []byte) (Secrets, error) {
|
|
|
ecdheSecret, err := h.randomPrivKey.GenerateShared(h.remoteRandomPub, sskLen, sskLen)
|
|
|
if err != nil {
|
|
|
- return secrets{}, err
|
|
|
+ return Secrets{}, err
|
|
|
}
|
|
|
|
|
|
// derive base secrets from ephemeral key agreement
|
|
|
sharedSecret := crypto.Keccak256(ecdheSecret, crypto.Keccak256(h.respNonce, h.initNonce))
|
|
|
aesSecret := crypto.Keccak256(ecdheSecret, sharedSecret)
|
|
|
- s := secrets{
|
|
|
- Remote: h.remote,
|
|
|
+ s := Secrets{
|
|
|
+ remote: h.remote.ExportECDSA(),
|
|
|
AES: aesSecret,
|
|
|
MAC: crypto.Keccak256(ecdheSecret, aesSecret),
|
|
|
}
|
|
|
@@ -278,7 +479,7 @@ func (h *encHandshake) staticSharedSecret(prv *ecdsa.PrivateKey) ([]byte, error)
|
|
|
// it should be called on the dialing side of the connection.
|
|
|
//
|
|
|
// prv is the local client's private key.
|
|
|
-func initiatorEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, remote *ecdsa.PublicKey) (s secrets, err error) {
|
|
|
+func initiatorEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, remote *ecdsa.PublicKey) (s Secrets, err error) {
|
|
|
h := &encHandshake{initiator: true, remote: ecies.ImportECDSAPublic(remote)}
|
|
|
authMsg, err := h.makeAuthMsg(prv)
|
|
|
if err != nil {
|
|
|
@@ -288,6 +489,7 @@ func initiatorEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, remote *ec
|
|
|
if err != nil {
|
|
|
return s, err
|
|
|
}
|
|
|
+
|
|
|
if _, err = conn.Write(authPacket); err != nil {
|
|
|
return s, err
|
|
|
}
|
|
|
@@ -342,72 +544,6 @@ func (h *encHandshake) handleAuthResp(msg *authRespV4) (err error) {
|
|
|
return err
|
|
|
}
|
|
|
|
|
|
-// receiverEncHandshake negotiates a session token on conn.
|
|
|
-// it should be called on the listening side of the connection.
|
|
|
-//
|
|
|
-// prv is the local client's private key.
|
|
|
-func receiverEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey) (s secrets, err error) {
|
|
|
- authMsg := new(authMsgV4)
|
|
|
- authPacket, err := readHandshakeMsg(authMsg, encAuthMsgLen, prv, conn)
|
|
|
- if err != nil {
|
|
|
- return s, err
|
|
|
- }
|
|
|
- h := new(encHandshake)
|
|
|
- if err := h.handleAuthMsg(authMsg, prv); err != nil {
|
|
|
- return s, err
|
|
|
- }
|
|
|
-
|
|
|
- authRespMsg, err := h.makeAuthResp()
|
|
|
- if err != nil {
|
|
|
- return s, err
|
|
|
- }
|
|
|
- var authRespPacket []byte
|
|
|
- if authMsg.gotPlain {
|
|
|
- authRespPacket, err = authRespMsg.sealPlain(h)
|
|
|
- } else {
|
|
|
- authRespPacket, err = sealEIP8(authRespMsg, h)
|
|
|
- }
|
|
|
- if err != nil {
|
|
|
- return s, err
|
|
|
- }
|
|
|
- if _, err = conn.Write(authRespPacket); err != nil {
|
|
|
- return s, err
|
|
|
- }
|
|
|
- return h.secrets(authPacket, authRespPacket)
|
|
|
-}
|
|
|
-
|
|
|
-func (h *encHandshake) handleAuthMsg(msg *authMsgV4, prv *ecdsa.PrivateKey) error {
|
|
|
- // Import the remote identity.
|
|
|
- rpub, err := importPublicKey(msg.InitiatorPubkey[:])
|
|
|
- if err != nil {
|
|
|
- return err
|
|
|
- }
|
|
|
- h.initNonce = msg.Nonce[:]
|
|
|
- h.remote = rpub
|
|
|
-
|
|
|
- // Generate random keypair for ECDH.
|
|
|
- // If a private key is already set, use it instead of generating one (for testing).
|
|
|
- if h.randomPrivKey == nil {
|
|
|
- h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
|
|
|
- if err != nil {
|
|
|
- return err
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- // Check the signature.
|
|
|
- token, err := h.staticSharedSecret(prv)
|
|
|
- if err != nil {
|
|
|
- return err
|
|
|
- }
|
|
|
- signedMsg := xor(token, h.initNonce)
|
|
|
- remoteRandomPub, err := crypto.Ecrecover(signedMsg, msg.Signature[:])
|
|
|
- if err != nil {
|
|
|
- return err
|
|
|
- }
|
|
|
- h.remoteRandomPub, _ = importPublicKey(remoteRandomPub)
|
|
|
- return nil
|
|
|
-}
|
|
|
-
|
|
|
func (h *encHandshake) makeAuthResp() (msg *authRespV4, err error) {
|
|
|
// Generate random nonce.
|
|
|
h.respNonce = make([]byte, shaLen)
|
|
|
@@ -531,201 +667,3 @@ func xor(one, other []byte) (xor []byte) {
|
|
|
}
|
|
|
return xor
|
|
|
}
|
|
|
-
|
|
|
-var (
|
|
|
- // this is used in place of actual frame header data.
|
|
|
- // TODO: replace this when Msg contains the protocol type code.
|
|
|
- zeroHeader = []byte{0xC2, 0x80, 0x80}
|
|
|
- // sixteen zero bytes
|
|
|
- zero16 = make([]byte, 16)
|
|
|
-)
|
|
|
-
|
|
|
-// rlpxFrameRW implements a simplified version of RLPx framing.
|
|
|
-// chunked messages are not supported and all headers are equal to
|
|
|
-// zeroHeader.
|
|
|
-//
|
|
|
-// rlpxFrameRW is not safe for concurrent use from multiple goroutines.
|
|
|
-type rlpxFrameRW struct {
|
|
|
- conn io.ReadWriter
|
|
|
- enc cipher.Stream
|
|
|
- dec cipher.Stream
|
|
|
-
|
|
|
- macCipher cipher.Block
|
|
|
- egressMAC hash.Hash
|
|
|
- ingressMAC hash.Hash
|
|
|
-
|
|
|
- snappy bool
|
|
|
-}
|
|
|
-
|
|
|
-func newRLPXFrameRW(conn io.ReadWriter, s secrets) *rlpxFrameRW {
|
|
|
- macc, err := aes.NewCipher(s.MAC)
|
|
|
- if err != nil {
|
|
|
- panic("invalid MAC secret: " + err.Error())
|
|
|
- }
|
|
|
- encc, err := aes.NewCipher(s.AES)
|
|
|
- if err != nil {
|
|
|
- panic("invalid AES secret: " + err.Error())
|
|
|
- }
|
|
|
- // we use an all-zeroes IV for AES because the key used
|
|
|
- // for encryption is ephemeral.
|
|
|
- iv := make([]byte, encc.BlockSize())
|
|
|
- return &rlpxFrameRW{
|
|
|
- conn: conn,
|
|
|
- enc: cipher.NewCTR(encc, iv),
|
|
|
- dec: cipher.NewCTR(encc, iv),
|
|
|
- macCipher: macc,
|
|
|
- egressMAC: s.EgressMAC,
|
|
|
- ingressMAC: s.IngressMAC,
|
|
|
- }
|
|
|
-}
|
|
|
-
|
|
|
-func (rw *rlpxFrameRW) WriteMsg(msg Msg) error {
|
|
|
- ptype, _ := rlp.EncodeToBytes(msg.Code)
|
|
|
-
|
|
|
- // if snappy is enabled, compress message now
|
|
|
- if rw.snappy {
|
|
|
- if msg.Size > maxUint24 {
|
|
|
- return errPlainMessageTooLarge
|
|
|
- }
|
|
|
- payload, _ := ioutil.ReadAll(msg.Payload)
|
|
|
- payload = snappy.Encode(nil, payload)
|
|
|
-
|
|
|
- msg.Payload = bytes.NewReader(payload)
|
|
|
- msg.Size = uint32(len(payload))
|
|
|
- }
|
|
|
- msg.meterSize = msg.Size
|
|
|
- if metrics.Enabled && msg.meterCap.Name != "" { // don't meter non-subprotocol messages
|
|
|
- m := fmt.Sprintf("%s/%s/%d/%#02x", egressMeterName, msg.meterCap.Name, msg.meterCap.Version, msg.meterCode)
|
|
|
- metrics.GetOrRegisterMeter(m, nil).Mark(int64(msg.meterSize))
|
|
|
- metrics.GetOrRegisterMeter(m+"/packets", nil).Mark(1)
|
|
|
- }
|
|
|
- // write header
|
|
|
- headbuf := make([]byte, 32)
|
|
|
- fsize := uint32(len(ptype)) + msg.Size
|
|
|
- if fsize > maxUint24 {
|
|
|
- return errors.New("message size overflows uint24")
|
|
|
- }
|
|
|
- putInt24(fsize, headbuf) // TODO: check overflow
|
|
|
- copy(headbuf[3:], zeroHeader)
|
|
|
- rw.enc.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now encrypted
|
|
|
-
|
|
|
- // write header MAC
|
|
|
- copy(headbuf[16:], updateMAC(rw.egressMAC, rw.macCipher, headbuf[:16]))
|
|
|
- if _, err := rw.conn.Write(headbuf); err != nil {
|
|
|
- return err
|
|
|
- }
|
|
|
-
|
|
|
- // write encrypted frame, updating the egress MAC hash with
|
|
|
- // the data written to conn.
|
|
|
- tee := cipher.StreamWriter{S: rw.enc, W: io.MultiWriter(rw.conn, rw.egressMAC)}
|
|
|
- if _, err := tee.Write(ptype); err != nil {
|
|
|
- return err
|
|
|
- }
|
|
|
- if _, err := io.Copy(tee, msg.Payload); err != nil {
|
|
|
- return err
|
|
|
- }
|
|
|
- if padding := fsize % 16; padding > 0 {
|
|
|
- if _, err := tee.Write(zero16[:16-padding]); err != nil {
|
|
|
- return err
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
- // write frame MAC. egress MAC hash is up to date because
|
|
|
- // frame content was written to it as well.
|
|
|
- fmacseed := rw.egressMAC.Sum(nil)
|
|
|
- mac := updateMAC(rw.egressMAC, rw.macCipher, fmacseed)
|
|
|
- _, err := rw.conn.Write(mac)
|
|
|
- return err
|
|
|
-}
|
|
|
-
|
|
|
-func (rw *rlpxFrameRW) ReadMsg() (msg Msg, err error) {
|
|
|
- // read the header
|
|
|
- headbuf := make([]byte, 32)
|
|
|
- if _, err := io.ReadFull(rw.conn, headbuf); err != nil {
|
|
|
- return msg, err
|
|
|
- }
|
|
|
- // verify header mac
|
|
|
- shouldMAC := updateMAC(rw.ingressMAC, rw.macCipher, headbuf[:16])
|
|
|
- if !hmac.Equal(shouldMAC, headbuf[16:]) {
|
|
|
- return msg, errors.New("bad header MAC")
|
|
|
- }
|
|
|
- rw.dec.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now decrypted
|
|
|
- fsize := readInt24(headbuf)
|
|
|
- // ignore protocol type for now
|
|
|
-
|
|
|
- // read the frame content
|
|
|
- var rsize = fsize // frame size rounded up to 16 byte boundary
|
|
|
- if padding := fsize % 16; padding > 0 {
|
|
|
- rsize += 16 - padding
|
|
|
- }
|
|
|
- framebuf := make([]byte, rsize)
|
|
|
- if _, err := io.ReadFull(rw.conn, framebuf); err != nil {
|
|
|
- return msg, err
|
|
|
- }
|
|
|
-
|
|
|
- // read and validate frame MAC. we can re-use headbuf for that.
|
|
|
- rw.ingressMAC.Write(framebuf)
|
|
|
- fmacseed := rw.ingressMAC.Sum(nil)
|
|
|
- if _, err := io.ReadFull(rw.conn, headbuf[:16]); err != nil {
|
|
|
- return msg, err
|
|
|
- }
|
|
|
- shouldMAC = updateMAC(rw.ingressMAC, rw.macCipher, fmacseed)
|
|
|
- if !hmac.Equal(shouldMAC, headbuf[:16]) {
|
|
|
- return msg, errors.New("bad frame MAC")
|
|
|
- }
|
|
|
-
|
|
|
- // decrypt frame content
|
|
|
- rw.dec.XORKeyStream(framebuf, framebuf)
|
|
|
-
|
|
|
- // decode message code
|
|
|
- content := bytes.NewReader(framebuf[:fsize])
|
|
|
- if err := rlp.Decode(content, &msg.Code); err != nil {
|
|
|
- return msg, err
|
|
|
- }
|
|
|
- msg.Size = uint32(content.Len())
|
|
|
- msg.meterSize = msg.Size
|
|
|
- msg.Payload = content
|
|
|
-
|
|
|
- // if snappy is enabled, verify and decompress message
|
|
|
- if rw.snappy {
|
|
|
- payload, err := ioutil.ReadAll(msg.Payload)
|
|
|
- if err != nil {
|
|
|
- return msg, err
|
|
|
- }
|
|
|
- size, err := snappy.DecodedLen(payload)
|
|
|
- if err != nil {
|
|
|
- return msg, err
|
|
|
- }
|
|
|
- if size > int(maxUint24) {
|
|
|
- return msg, errPlainMessageTooLarge
|
|
|
- }
|
|
|
- payload, err = snappy.Decode(nil, payload)
|
|
|
- if err != nil {
|
|
|
- return msg, err
|
|
|
- }
|
|
|
- msg.Size, msg.Payload = uint32(size), bytes.NewReader(payload)
|
|
|
- }
|
|
|
- return msg, nil
|
|
|
-}
|
|
|
-
|
|
|
-// updateMAC reseeds the given hash with encrypted seed.
|
|
|
-// it returns the first 16 bytes of the hash sum after seeding.
|
|
|
-func updateMAC(mac hash.Hash, block cipher.Block, seed []byte) []byte {
|
|
|
- aesbuf := make([]byte, aes.BlockSize)
|
|
|
- block.Encrypt(aesbuf, mac.Sum(nil))
|
|
|
- for i := range aesbuf {
|
|
|
- aesbuf[i] ^= seed[i]
|
|
|
- }
|
|
|
- mac.Write(aesbuf)
|
|
|
- return mac.Sum(nil)[:16]
|
|
|
-}
|
|
|
-
|
|
|
-func readInt24(b []byte) uint32 {
|
|
|
- return uint32(b[2]) | uint32(b[1])<<8 | uint32(b[0])<<16
|
|
|
-}
|
|
|
-
|
|
|
-func putInt24(v uint32, b []byte) {
|
|
|
- b[0] = byte(v >> 16)
|
|
|
- b[1] = byte(v >> 8)
|
|
|
- b[2] = byte(v)
|
|
|
-}
|