2022-05-24 20:39:40 +02:00
|
|
|
// Copyright 2020 The go-ethereum Authors
|
2015-07-22 18:48:40 +02:00
|
|
|
// This file is part of the go-ethereum library.
|
2015-07-07 02:54:22 +02:00
|
|
|
//
|
2015-07-23 18:35:11 +02:00
|
|
|
// The go-ethereum library is free software: you can redistribute it and/or modify
|
2015-07-07 02:54:22 +02:00
|
|
|
// it under the terms of the GNU Lesser General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
//
|
2015-07-22 18:48:40 +02:00
|
|
|
// The go-ethereum library is distributed in the hope that it will be useful,
|
2015-07-07 02:54:22 +02:00
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
2015-07-22 18:48:40 +02:00
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
2015-07-07 02:54:22 +02:00
|
|
|
// GNU Lesser General Public License for more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU Lesser General Public License
|
2015-07-22 18:48:40 +02:00
|
|
|
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
2015-07-07 02:54:22 +02:00
|
|
|
|
2020-09-22 10:17:39 +02:00
|
|
|
// Package rlpx implements the RLPx transport protocol.
|
|
|
|
package rlpx
|
2015-02-26 22:30:34 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"crypto/aes"
|
|
|
|
"crypto/cipher"
|
2015-05-16 00:38:28 +02:00
|
|
|
"crypto/ecdsa"
|
2015-02-26 22:30:34 +00:00
|
|
|
"crypto/hmac"
|
2015-05-16 00:38:28 +02:00
|
|
|
"crypto/rand"
|
2015-12-23 01:48:55 +01:00
|
|
|
"encoding/binary"
|
2015-02-26 22:30:34 +00:00
|
|
|
"errors"
|
2015-05-16 00:38:28 +02:00
|
|
|
"fmt"
|
2015-02-26 22:30:34 +00:00
|
|
|
"hash"
|
|
|
|
"io"
|
2015-12-23 01:48:55 +01:00
|
|
|
mrand "math/rand"
|
2015-05-16 00:38:28 +02:00
|
|
|
"net"
|
|
|
|
"time"
|
2015-02-26 22:30:34 +00:00
|
|
|
|
2015-05-16 00:38:28 +02:00
|
|
|
"github.com/ethereum/go-ethereum/crypto"
|
|
|
|
"github.com/ethereum/go-ethereum/crypto/ecies"
|
2015-02-26 22:30:34 +00:00
|
|
|
"github.com/ethereum/go-ethereum/rlp"
|
2017-09-26 16:54:49 +03:00
|
|
|
"github.com/golang/snappy"
|
2019-01-03 16:15:26 -06:00
|
|
|
"golang.org/x/crypto/sha3"
|
2015-02-26 22:30:34 +00:00
|
|
|
)
|
|
|
|
|
2020-09-22 10:17:39 +02:00
|
|
|
// 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 {
|
2021-05-27 10:19:13 +02:00
|
|
|
dialDest *ecdsa.PublicKey
|
|
|
|
conn net.Conn
|
|
|
|
session *sessionState
|
|
|
|
|
|
|
|
// These are the buffers for snappy compression.
|
|
|
|
// Compression is enabled if they are non-nil.
|
|
|
|
snappyReadBuffer []byte
|
|
|
|
snappyWriteBuffer []byte
|
2020-09-22 10:17:39 +02:00
|
|
|
}
|
2015-05-16 00:38:28 +02:00
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
// sessionState contains the session keys.
|
|
|
|
type sessionState struct {
|
2020-09-22 10:17:39 +02:00
|
|
|
enc cipher.Stream
|
|
|
|
dec cipher.Stream
|
2015-05-16 00:38:28 +02:00
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
egressMAC hashMAC
|
|
|
|
ingressMAC hashMAC
|
|
|
|
rbuf readBuffer
|
|
|
|
wbuf writeBuffer
|
|
|
|
}
|
|
|
|
|
|
|
|
// hashMAC holds the state of the RLPx v4 MAC contraption.
|
|
|
|
type hashMAC struct {
|
|
|
|
cipher cipher.Block
|
|
|
|
hash hash.Hash
|
|
|
|
aesBuffer [16]byte
|
|
|
|
hashBuffer [32]byte
|
|
|
|
seedBuffer [32]byte
|
|
|
|
}
|
|
|
|
|
|
|
|
func newHashMAC(cipher cipher.Block, h hash.Hash) hashMAC {
|
|
|
|
m := hashMAC{cipher: cipher, hash: h}
|
|
|
|
if cipher.BlockSize() != len(m.aesBuffer) {
|
|
|
|
panic(fmt.Errorf("invalid MAC cipher block size %d", cipher.BlockSize()))
|
|
|
|
}
|
|
|
|
if h.Size() != len(m.hashBuffer) {
|
|
|
|
panic(fmt.Errorf("invalid MAC digest size %d", h.Size()))
|
|
|
|
}
|
|
|
|
return m
|
2020-09-22 10:17:39 +02:00
|
|
|
}
|
2017-09-26 16:54:49 +03:00
|
|
|
|
2020-09-22 10:17:39 +02:00
|
|
|
// 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,
|
|
|
|
}
|
|
|
|
}
|
2015-05-16 00:38:28 +02:00
|
|
|
|
2020-09-22 10:17:39 +02:00
|
|
|
// 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) {
|
2021-05-27 10:19:13 +02:00
|
|
|
if snappy {
|
|
|
|
c.snappyReadBuffer = []byte{}
|
|
|
|
c.snappyWriteBuffer = []byte{}
|
|
|
|
} else {
|
|
|
|
c.snappyReadBuffer = nil
|
|
|
|
c.snappyWriteBuffer = nil
|
|
|
|
}
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
|
|
|
|
2020-09-22 10:17:39 +02:00
|
|
|
// SetReadDeadline sets the deadline for all future read operations.
|
|
|
|
func (c *Conn) SetReadDeadline(time time.Time) error {
|
|
|
|
return c.conn.SetReadDeadline(time)
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
|
|
|
|
2020-09-22 10:17:39 +02:00
|
|
|
// SetWriteDeadline sets the deadline for all future write operations.
|
|
|
|
func (c *Conn) SetWriteDeadline(time time.Time) error {
|
|
|
|
return c.conn.SetWriteDeadline(time)
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
|
|
|
|
2020-09-22 10:17:39 +02:00
|
|
|
// SetDeadline sets the deadline for all future read and write operations.
|
|
|
|
func (c *Conn) SetDeadline(time time.Time) error {
|
|
|
|
return c.conn.SetDeadline(time)
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
|
|
|
|
2020-09-22 10:17:39 +02:00
|
|
|
// Read reads a message from the connection.
|
2021-05-27 10:19:13 +02:00
|
|
|
// The returned data buffer is valid until the next call to Read.
|
2020-09-22 10:17:39 +02:00
|
|
|
func (c *Conn) Read() (code uint64, data []byte, wireSize int, err error) {
|
2021-05-27 10:19:13 +02:00
|
|
|
if c.session == nil {
|
2020-09-22 10:17:39 +02:00
|
|
|
panic("can't ReadMsg before handshake")
|
|
|
|
}
|
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
frame, err := c.session.readFrame(c.conn)
|
2020-09-22 10:17:39 +02:00
|
|
|
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.
|
2021-05-27 10:19:13 +02:00
|
|
|
if c.snappyReadBuffer != nil {
|
2020-09-22 10:17:39 +02:00
|
|
|
var actualSize int
|
|
|
|
actualSize, err = snappy.DecodedLen(data)
|
|
|
|
if err != nil {
|
|
|
|
return code, nil, 0, err
|
|
|
|
}
|
|
|
|
if actualSize > maxUint24 {
|
|
|
|
return code, nil, 0, errPlainMessageTooLarge
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
2021-05-27 10:19:13 +02:00
|
|
|
c.snappyReadBuffer = growslice(c.snappyReadBuffer, actualSize)
|
|
|
|
data, err = snappy.Decode(c.snappyReadBuffer, data)
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
2020-09-22 10:17:39 +02:00
|
|
|
return code, data, wireSize, err
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
func (h *sessionState) readFrame(conn io.Reader) ([]byte, error) {
|
|
|
|
h.rbuf.reset()
|
|
|
|
|
|
|
|
// Read the frame header.
|
|
|
|
header, err := h.rbuf.read(conn, 32)
|
|
|
|
if err != nil {
|
2015-05-16 00:38:28 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
2020-09-22 10:17:39 +02:00
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
// Verify header MAC.
|
|
|
|
wantHeaderMAC := h.ingressMAC.computeHeader(header[:16])
|
|
|
|
if !hmac.Equal(wantHeaderMAC, header[16:]) {
|
2020-09-22 10:17:39 +02:00
|
|
|
return nil, errors.New("bad header MAC")
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
2017-09-26 16:54:49 +03:00
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
// Decrypt the frame header to get the frame size.
|
|
|
|
h.dec.XORKeyStream(header[:16], header[:16])
|
|
|
|
fsize := readUint24(header[:16])
|
|
|
|
// Frame size rounded up to 16 byte boundary for padding.
|
|
|
|
rsize := fsize
|
2020-09-22 10:17:39 +02:00
|
|
|
if padding := fsize % 16; padding > 0 {
|
|
|
|
rsize += 16 - padding
|
|
|
|
}
|
2021-05-27 10:19:13 +02:00
|
|
|
|
|
|
|
// Read the frame content.
|
|
|
|
frame, err := h.rbuf.read(conn, int(rsize))
|
|
|
|
if err != nil {
|
2020-09-22 10:17:39 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
2015-05-16 00:38:28 +02:00
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
// Validate frame MAC.
|
|
|
|
frameMAC, err := h.rbuf.read(conn, 16)
|
|
|
|
if err != nil {
|
2015-05-16 00:38:28 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
2021-05-27 10:19:13 +02:00
|
|
|
wantFrameMAC := h.ingressMAC.computeFrame(frame)
|
|
|
|
if !hmac.Equal(wantFrameMAC, frameMAC) {
|
2020-09-22 10:17:39 +02:00
|
|
|
return nil, errors.New("bad frame MAC")
|
|
|
|
}
|
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
// Decrypt the frame data.
|
|
|
|
h.dec.XORKeyStream(frame, frame)
|
|
|
|
return frame[:fsize], nil
|
2020-09-22 10:17:39 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// 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) {
|
2021-05-27 10:19:13 +02:00
|
|
|
if c.session == nil {
|
2020-09-22 10:17:39 +02:00
|
|
|
panic("can't WriteMsg before handshake")
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
2020-09-22 10:17:39 +02:00
|
|
|
if len(data) > maxUint24 {
|
|
|
|
return 0, errPlainMessageTooLarge
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
2021-05-27 10:19:13 +02:00
|
|
|
if c.snappyWriteBuffer != nil {
|
|
|
|
// Ensure the buffer has sufficient size.
|
|
|
|
// Package snappy will allocate its own buffer if the provided
|
|
|
|
// one is smaller than MaxEncodedLen.
|
|
|
|
c.snappyWriteBuffer = growslice(c.snappyWriteBuffer, snappy.MaxEncodedLen(len(data)))
|
|
|
|
data = snappy.Encode(c.snappyWriteBuffer, data)
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
2020-09-22 10:17:39 +02:00
|
|
|
|
|
|
|
wireSize := uint32(len(data))
|
2021-05-27 10:19:13 +02:00
|
|
|
err := c.session.writeFrame(c.conn, code, data)
|
2020-09-22 10:17:39 +02:00
|
|
|
return wireSize, err
|
|
|
|
}
|
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
func (h *sessionState) writeFrame(conn io.Writer, code uint64, data []byte) error {
|
|
|
|
h.wbuf.reset()
|
2020-09-22 10:17:39 +02:00
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
// Write header.
|
|
|
|
fsize := rlp.IntSize(code) + len(data)
|
2020-09-22 10:17:39 +02:00
|
|
|
if fsize > maxUint24 {
|
|
|
|
return errPlainMessageTooLarge
|
|
|
|
}
|
2021-05-27 10:19:13 +02:00
|
|
|
header := h.wbuf.appendZero(16)
|
|
|
|
putUint24(uint32(fsize), header)
|
|
|
|
copy(header[3:], zeroHeader)
|
|
|
|
h.enc.XORKeyStream(header, header)
|
2020-09-22 10:17:39 +02:00
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
// Write header MAC.
|
|
|
|
h.wbuf.Write(h.egressMAC.computeHeader(header))
|
2020-09-22 10:17:39 +02:00
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
// Encode and encrypt the frame data.
|
|
|
|
offset := len(h.wbuf.data)
|
|
|
|
h.wbuf.data = rlp.AppendUint64(h.wbuf.data, code)
|
|
|
|
h.wbuf.Write(data)
|
2020-09-22 10:17:39 +02:00
|
|
|
if padding := fsize % 16; padding > 0 {
|
2021-05-27 10:19:13 +02:00
|
|
|
h.wbuf.appendZero(16 - padding)
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
2021-05-27 10:19:13 +02:00
|
|
|
framedata := h.wbuf.data[offset:]
|
|
|
|
h.enc.XORKeyStream(framedata, framedata)
|
2020-09-22 10:17:39 +02:00
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
// Write frame MAC.
|
|
|
|
h.wbuf.Write(h.egressMAC.computeFrame(framedata))
|
|
|
|
|
|
|
|
_, err := conn.Write(h.wbuf.data)
|
2020-09-22 10:17:39 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
// computeHeader computes the MAC of a frame header.
|
|
|
|
func (m *hashMAC) computeHeader(header []byte) []byte {
|
|
|
|
sum1 := m.hash.Sum(m.hashBuffer[:0])
|
|
|
|
return m.compute(sum1, header)
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
// computeFrame computes the MAC of framedata.
|
|
|
|
func (m *hashMAC) computeFrame(framedata []byte) []byte {
|
|
|
|
m.hash.Write(framedata)
|
|
|
|
seed := m.hash.Sum(m.seedBuffer[:0])
|
|
|
|
return m.compute(seed, seed[:16])
|
2020-09-22 10:17:39 +02:00
|
|
|
}
|
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
// compute computes the MAC of a 16-byte 'seed'.
|
|
|
|
//
|
|
|
|
// To do this, it encrypts the current value of the hash state, then XORs the ciphertext
|
|
|
|
// with seed. The obtained value is written back into the hash state and hash output is
|
|
|
|
// taken again. The first 16 bytes of the resulting sum are the MAC value.
|
|
|
|
//
|
|
|
|
// This MAC construction is a horrible, legacy thing.
|
|
|
|
func (m *hashMAC) compute(sum1, seed []byte) []byte {
|
|
|
|
if len(seed) != len(m.aesBuffer) {
|
|
|
|
panic("invalid MAC seed")
|
|
|
|
}
|
|
|
|
|
|
|
|
m.cipher.Encrypt(m.aesBuffer[:], sum1)
|
|
|
|
for i := range m.aesBuffer {
|
|
|
|
m.aesBuffer[i] ^= seed[i]
|
2020-09-22 10:17:39 +02:00
|
|
|
}
|
2021-05-27 10:19:13 +02:00
|
|
|
m.hash.Write(m.aesBuffer[:])
|
|
|
|
sum2 := m.hash.Sum(m.hashBuffer[:0])
|
|
|
|
return sum2[:16]
|
2020-09-22 10:17:39 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// 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) {
|
2015-05-16 00:38:28 +02:00
|
|
|
var (
|
2020-09-22 10:17:39 +02:00
|
|
|
sec Secrets
|
2015-05-16 00:38:28 +02:00
|
|
|
err error
|
2021-05-27 10:19:13 +02:00
|
|
|
h handshakeState
|
2015-05-16 00:38:28 +02:00
|
|
|
)
|
2020-09-22 10:17:39 +02:00
|
|
|
if c.dialDest != nil {
|
2021-05-27 10:19:13 +02:00
|
|
|
sec, err = h.runInitiator(c.conn, prv, c.dialDest)
|
2015-05-16 00:38:28 +02:00
|
|
|
} else {
|
2021-05-27 10:19:13 +02:00
|
|
|
sec, err = h.runRecipient(c.conn, prv)
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
|
|
|
if err != nil {
|
all: new p2p node representation (#17643)
Package p2p/enode provides a generalized representation of p2p nodes
which can contain arbitrary information in key/value pairs. It is also
the new home for the node database. The "v4" identity scheme is also
moved here from p2p/enr to remove the dependency on Ethereum crypto from
that package.
Record signature handling is changed significantly. The identity scheme
registry is removed and acceptable schemes must be passed to any method
that needs identity. This means records must now be validated explicitly
after decoding.
The enode API is designed to make signature handling easy and safe: most
APIs around the codebase work with enode.Node, which is a wrapper around
a valid record. Going from enr.Record to enode.Node requires a valid
signature.
* p2p/discover: port to p2p/enode
This ports the discovery code to the new node representation in
p2p/enode. The wire protocol is unchanged, this can be considered a
refactoring change. The Kademlia table can now deal with nodes using an
arbitrary identity scheme. This requires a few incompatible API changes:
- Table.Lookup is not available anymore. It used to take a public key
as argument because v4 protocol requires one. Its replacement is
LookupRandom.
- Table.Resolve takes *enode.Node instead of NodeID. This is also for
v4 protocol compatibility because nodes cannot be looked up by ID
alone.
- Types Node and NodeID are gone. Further commits in the series will be
fixes all over the the codebase to deal with those removals.
* p2p: port to p2p/enode and discovery changes
This adapts package p2p to the changes in p2p/discover. All uses of
discover.Node and discover.NodeID are replaced by their equivalents from
p2p/enode.
New API is added to retrieve the enode.Node instance of a peer. The
behavior of Server.Self with discovery disabled is improved. It now
tries much harder to report a working IP address, falling back to
127.0.0.1 if no suitable address can be determined through other means.
These changes were needed for tests of other packages later in the
series.
* p2p/simulations, p2p/testing: port to p2p/enode
No surprises here, mostly replacements of discover.Node, discover.NodeID
with their new equivalents. The 'interesting' API changes are:
- testing.ProtocolSession tracks complete nodes, not just their IDs.
- adapters.NodeConfig has a new method to create a complete node.
These changes were needed to make swarm tests work.
Note that the NodeID change makes the code incompatible with old
simulation snapshots.
* whisper/whisperv5, whisper/whisperv6: port to p2p/enode
This port was easy because whisper uses []byte for node IDs and
URL strings in the API.
* eth: port to p2p/enode
Again, easy to port because eth uses strings for node IDs and doesn't
care about node information in any way.
* les: port to p2p/enode
Apart from replacing discover.NodeID with enode.ID, most changes are in
the server pool code. It now deals with complete nodes instead
of (Pubkey, IP, Port) triples. The database format is unchanged for now,
but we should probably change it to use the node database later.
* node: port to p2p/enode
This change simply replaces discover.Node and discover.NodeID with their
new equivalents.
* swarm/network: port to p2p/enode
Swarm has its own node address representation, BzzAddr, containing both
an overlay address (the hash of a secp256k1 public key) and an underlay
address (enode:// URL).
There are no changes to the BzzAddr format in this commit, but certain
operations such as creating a BzzAddr from a node ID are now impossible
because node IDs aren't public keys anymore.
Most swarm-related changes in the series remove uses of
NewAddrFromNodeID, replacing it with NewAddr which takes a complete node
as argument. ToOverlayAddr is removed because we can just use the node
ID directly.
2018-09-25 00:59:00 +02:00
|
|
|
return nil, err
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
2020-09-22 10:17:39 +02:00
|
|
|
c.InitWithSecrets(sec)
|
2021-05-27 10:19:13 +02:00
|
|
|
c.session.rbuf = h.rbuf
|
|
|
|
c.session.wbuf = h.wbuf
|
2020-09-22 10:17:39 +02:00
|
|
|
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) {
|
2021-05-27 10:19:13 +02:00
|
|
|
if c.session != nil {
|
2020-09-22 10:17:39 +02:00
|
|
|
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())
|
2021-05-27 10:19:13 +02:00
|
|
|
c.session = &sessionState{
|
2020-09-22 10:17:39 +02:00
|
|
|
enc: cipher.NewCTR(encc, iv),
|
|
|
|
dec: cipher.NewCTR(encc, iv),
|
2021-05-27 10:19:13 +02:00
|
|
|
egressMAC: newHashMAC(macc, sec.EgressMAC),
|
|
|
|
ingressMAC: newHashMAC(macc, sec.IngressMAC),
|
2020-09-22 10:17:39 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close closes the underlying network connection.
|
|
|
|
func (c *Conn) Close() error {
|
|
|
|
return c.conn.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Constants for the handshake.
|
|
|
|
const (
|
|
|
|
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)
|
|
|
|
|
|
|
|
eciesOverhead = 65 /* pubkey */ + 16 /* IV */ + 32 /* MAC */
|
|
|
|
)
|
|
|
|
|
|
|
|
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}
|
|
|
|
|
|
|
|
// 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
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
// handshakeState contains the state of the encryption handshake.
|
|
|
|
type handshakeState struct {
|
all: new p2p node representation (#17643)
Package p2p/enode provides a generalized representation of p2p nodes
which can contain arbitrary information in key/value pairs. It is also
the new home for the node database. The "v4" identity scheme is also
moved here from p2p/enr to remove the dependency on Ethereum crypto from
that package.
Record signature handling is changed significantly. The identity scheme
registry is removed and acceptable schemes must be passed to any method
that needs identity. This means records must now be validated explicitly
after decoding.
The enode API is designed to make signature handling easy and safe: most
APIs around the codebase work with enode.Node, which is a wrapper around
a valid record. Going from enr.Record to enode.Node requires a valid
signature.
* p2p/discover: port to p2p/enode
This ports the discovery code to the new node representation in
p2p/enode. The wire protocol is unchanged, this can be considered a
refactoring change. The Kademlia table can now deal with nodes using an
arbitrary identity scheme. This requires a few incompatible API changes:
- Table.Lookup is not available anymore. It used to take a public key
as argument because v4 protocol requires one. Its replacement is
LookupRandom.
- Table.Resolve takes *enode.Node instead of NodeID. This is also for
v4 protocol compatibility because nodes cannot be looked up by ID
alone.
- Types Node and NodeID are gone. Further commits in the series will be
fixes all over the the codebase to deal with those removals.
* p2p: port to p2p/enode and discovery changes
This adapts package p2p to the changes in p2p/discover. All uses of
discover.Node and discover.NodeID are replaced by their equivalents from
p2p/enode.
New API is added to retrieve the enode.Node instance of a peer. The
behavior of Server.Self with discovery disabled is improved. It now
tries much harder to report a working IP address, falling back to
127.0.0.1 if no suitable address can be determined through other means.
These changes were needed for tests of other packages later in the
series.
* p2p/simulations, p2p/testing: port to p2p/enode
No surprises here, mostly replacements of discover.Node, discover.NodeID
with their new equivalents. The 'interesting' API changes are:
- testing.ProtocolSession tracks complete nodes, not just their IDs.
- adapters.NodeConfig has a new method to create a complete node.
These changes were needed to make swarm tests work.
Note that the NodeID change makes the code incompatible with old
simulation snapshots.
* whisper/whisperv5, whisper/whisperv6: port to p2p/enode
This port was easy because whisper uses []byte for node IDs and
URL strings in the API.
* eth: port to p2p/enode
Again, easy to port because eth uses strings for node IDs and doesn't
care about node information in any way.
* les: port to p2p/enode
Apart from replacing discover.NodeID with enode.ID, most changes are in
the server pool code. It now deals with complete nodes instead
of (Pubkey, IP, Port) triples. The database format is unchanged for now,
but we should probably change it to use the node database later.
* node: port to p2p/enode
This change simply replaces discover.Node and discover.NodeID with their
new equivalents.
* swarm/network: port to p2p/enode
Swarm has its own node address representation, BzzAddr, containing both
an overlay address (the hash of a secp256k1 public key) and an underlay
address (enode:// URL).
There are no changes to the BzzAddr format in this commit, but certain
operations such as creating a BzzAddr from a node ID are now impossible
because node IDs aren't public keys anymore.
Most swarm-related changes in the series remove uses of
NewAddrFromNodeID, replacing it with NewAddr which takes a complete node
as argument. ToOverlayAddr is removed because we can just use the node
ID directly.
2018-09-25 00:59:00 +02:00
|
|
|
initiator bool
|
|
|
|
remote *ecies.PublicKey // remote-pubk
|
2015-05-16 00:38:28 +02:00
|
|
|
initNonce, respNonce []byte // nonce
|
|
|
|
randomPrivKey *ecies.PrivateKey // ecdhe-random
|
|
|
|
remoteRandomPub *ecies.PublicKey // ecdhe-random-pubk
|
2021-05-27 10:19:13 +02:00
|
|
|
|
|
|
|
rbuf readBuffer
|
|
|
|
wbuf writeBuffer
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
|
|
|
|
2015-12-23 01:48:55 +01:00
|
|
|
// RLPx v4 handshake auth (defined in EIP-8).
|
|
|
|
type authMsgV4 struct {
|
|
|
|
Signature [sigLen]byte
|
|
|
|
InitiatorPubkey [pubLen]byte
|
|
|
|
Nonce [shaLen]byte
|
|
|
|
Version uint
|
|
|
|
|
|
|
|
// Ignore additional fields (forward-compatibility)
|
|
|
|
Rest []rlp.RawValue `rlp:"tail"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// RLPx v4 handshake response (defined in EIP-8).
|
|
|
|
type authRespV4 struct {
|
|
|
|
RandomPubkey [pubLen]byte
|
|
|
|
Nonce [shaLen]byte
|
|
|
|
Version uint
|
|
|
|
|
|
|
|
// Ignore additional fields (forward-compatibility)
|
|
|
|
Rest []rlp.RawValue `rlp:"tail"`
|
|
|
|
}
|
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
// runRecipient negotiates a session token on conn.
|
2020-09-22 10:17:39 +02:00
|
|
|
// it should be called on the listening side of the connection.
|
|
|
|
//
|
|
|
|
// prv is the local client's private key.
|
2021-05-27 10:19:13 +02:00
|
|
|
func (h *handshakeState) runRecipient(conn io.ReadWriter, prv *ecdsa.PrivateKey) (s Secrets, err error) {
|
2020-09-22 10:17:39 +02:00
|
|
|
authMsg := new(authMsgV4)
|
2021-05-27 10:19:13 +02:00
|
|
|
authPacket, err := h.readMsg(authMsg, prv, conn)
|
2020-09-22 10:17:39 +02:00
|
|
|
if err != nil {
|
|
|
|
return s, err
|
|
|
|
}
|
|
|
|
if err := h.handleAuthMsg(authMsg, prv); err != nil {
|
|
|
|
return s, err
|
|
|
|
}
|
|
|
|
|
|
|
|
authRespMsg, err := h.makeAuthResp()
|
|
|
|
if err != nil {
|
|
|
|
return s, err
|
|
|
|
}
|
2021-05-27 10:19:13 +02:00
|
|
|
authRespPacket, err := h.sealEIP8(authRespMsg)
|
2020-09-22 10:17:39 +02:00
|
|
|
if err != nil {
|
|
|
|
return s, err
|
|
|
|
}
|
|
|
|
if _, err = conn.Write(authRespPacket); err != nil {
|
|
|
|
return s, err
|
|
|
|
}
|
2021-05-27 10:19:13 +02:00
|
|
|
|
2020-09-22 10:17:39 +02:00
|
|
|
return h.secrets(authPacket, authRespPacket)
|
|
|
|
}
|
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
func (h *handshakeState) handleAuthMsg(msg *authMsgV4, prv *ecdsa.PrivateKey) error {
|
2020-09-22 10:17:39 +02:00
|
|
|
// 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
|
|
|
|
}
|
|
|
|
|
2015-05-16 00:38:28 +02:00
|
|
|
// secrets is called after the handshake is completed.
|
|
|
|
// It extracts the connection secrets from the handshake values.
|
2021-05-27 10:19:13 +02:00
|
|
|
func (h *handshakeState) secrets(auth, authResp []byte) (Secrets, error) {
|
2015-05-16 00:38:28 +02:00
|
|
|
ecdheSecret, err := h.randomPrivKey.GenerateShared(h.remoteRandomPub, sskLen, sskLen)
|
|
|
|
if err != nil {
|
2020-09-22 10:17:39 +02:00
|
|
|
return Secrets{}, err
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// derive base secrets from ephemeral key agreement
|
2016-02-21 18:40:27 +00:00
|
|
|
sharedSecret := crypto.Keccak256(ecdheSecret, crypto.Keccak256(h.respNonce, h.initNonce))
|
|
|
|
aesSecret := crypto.Keccak256(ecdheSecret, sharedSecret)
|
2020-09-22 10:17:39 +02:00
|
|
|
s := Secrets{
|
|
|
|
remote: h.remote.ExportECDSA(),
|
all: new p2p node representation (#17643)
Package p2p/enode provides a generalized representation of p2p nodes
which can contain arbitrary information in key/value pairs. It is also
the new home for the node database. The "v4" identity scheme is also
moved here from p2p/enr to remove the dependency on Ethereum crypto from
that package.
Record signature handling is changed significantly. The identity scheme
registry is removed and acceptable schemes must be passed to any method
that needs identity. This means records must now be validated explicitly
after decoding.
The enode API is designed to make signature handling easy and safe: most
APIs around the codebase work with enode.Node, which is a wrapper around
a valid record. Going from enr.Record to enode.Node requires a valid
signature.
* p2p/discover: port to p2p/enode
This ports the discovery code to the new node representation in
p2p/enode. The wire protocol is unchanged, this can be considered a
refactoring change. The Kademlia table can now deal with nodes using an
arbitrary identity scheme. This requires a few incompatible API changes:
- Table.Lookup is not available anymore. It used to take a public key
as argument because v4 protocol requires one. Its replacement is
LookupRandom.
- Table.Resolve takes *enode.Node instead of NodeID. This is also for
v4 protocol compatibility because nodes cannot be looked up by ID
alone.
- Types Node and NodeID are gone. Further commits in the series will be
fixes all over the the codebase to deal with those removals.
* p2p: port to p2p/enode and discovery changes
This adapts package p2p to the changes in p2p/discover. All uses of
discover.Node and discover.NodeID are replaced by their equivalents from
p2p/enode.
New API is added to retrieve the enode.Node instance of a peer. The
behavior of Server.Self with discovery disabled is improved. It now
tries much harder to report a working IP address, falling back to
127.0.0.1 if no suitable address can be determined through other means.
These changes were needed for tests of other packages later in the
series.
* p2p/simulations, p2p/testing: port to p2p/enode
No surprises here, mostly replacements of discover.Node, discover.NodeID
with their new equivalents. The 'interesting' API changes are:
- testing.ProtocolSession tracks complete nodes, not just their IDs.
- adapters.NodeConfig has a new method to create a complete node.
These changes were needed to make swarm tests work.
Note that the NodeID change makes the code incompatible with old
simulation snapshots.
* whisper/whisperv5, whisper/whisperv6: port to p2p/enode
This port was easy because whisper uses []byte for node IDs and
URL strings in the API.
* eth: port to p2p/enode
Again, easy to port because eth uses strings for node IDs and doesn't
care about node information in any way.
* les: port to p2p/enode
Apart from replacing discover.NodeID with enode.ID, most changes are in
the server pool code. It now deals with complete nodes instead
of (Pubkey, IP, Port) triples. The database format is unchanged for now,
but we should probably change it to use the node database later.
* node: port to p2p/enode
This change simply replaces discover.Node and discover.NodeID with their
new equivalents.
* swarm/network: port to p2p/enode
Swarm has its own node address representation, BzzAddr, containing both
an overlay address (the hash of a secp256k1 public key) and an underlay
address (enode:// URL).
There are no changes to the BzzAddr format in this commit, but certain
operations such as creating a BzzAddr from a node ID are now impossible
because node IDs aren't public keys anymore.
Most swarm-related changes in the series remove uses of
NewAddrFromNodeID, replacing it with NewAddr which takes a complete node
as argument. ToOverlayAddr is removed because we can just use the node
ID directly.
2018-09-25 00:59:00 +02:00
|
|
|
AES: aesSecret,
|
|
|
|
MAC: crypto.Keccak256(ecdheSecret, aesSecret),
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// setup sha3 instances for the MACs
|
2019-01-03 16:15:26 -06:00
|
|
|
mac1 := sha3.NewLegacyKeccak256()
|
2015-05-16 00:38:28 +02:00
|
|
|
mac1.Write(xor(s.MAC, h.respNonce))
|
|
|
|
mac1.Write(auth)
|
2019-01-03 16:15:26 -06:00
|
|
|
mac2 := sha3.NewLegacyKeccak256()
|
2015-05-16 00:38:28 +02:00
|
|
|
mac2.Write(xor(s.MAC, h.initNonce))
|
|
|
|
mac2.Write(authResp)
|
|
|
|
if h.initiator {
|
|
|
|
s.EgressMAC, s.IngressMAC = mac1, mac2
|
|
|
|
} else {
|
|
|
|
s.EgressMAC, s.IngressMAC = mac2, mac1
|
|
|
|
}
|
|
|
|
|
|
|
|
return s, nil
|
|
|
|
}
|
|
|
|
|
2015-12-23 01:48:55 +01:00
|
|
|
// staticSharedSecret returns the static shared secret, the result
|
|
|
|
// of key agreement between the local and remote static node key.
|
2021-05-27 10:19:13 +02:00
|
|
|
func (h *handshakeState) staticSharedSecret(prv *ecdsa.PrivateKey) ([]byte, error) {
|
all: new p2p node representation (#17643)
Package p2p/enode provides a generalized representation of p2p nodes
which can contain arbitrary information in key/value pairs. It is also
the new home for the node database. The "v4" identity scheme is also
moved here from p2p/enr to remove the dependency on Ethereum crypto from
that package.
Record signature handling is changed significantly. The identity scheme
registry is removed and acceptable schemes must be passed to any method
that needs identity. This means records must now be validated explicitly
after decoding.
The enode API is designed to make signature handling easy and safe: most
APIs around the codebase work with enode.Node, which is a wrapper around
a valid record. Going from enr.Record to enode.Node requires a valid
signature.
* p2p/discover: port to p2p/enode
This ports the discovery code to the new node representation in
p2p/enode. The wire protocol is unchanged, this can be considered a
refactoring change. The Kademlia table can now deal with nodes using an
arbitrary identity scheme. This requires a few incompatible API changes:
- Table.Lookup is not available anymore. It used to take a public key
as argument because v4 protocol requires one. Its replacement is
LookupRandom.
- Table.Resolve takes *enode.Node instead of NodeID. This is also for
v4 protocol compatibility because nodes cannot be looked up by ID
alone.
- Types Node and NodeID are gone. Further commits in the series will be
fixes all over the the codebase to deal with those removals.
* p2p: port to p2p/enode and discovery changes
This adapts package p2p to the changes in p2p/discover. All uses of
discover.Node and discover.NodeID are replaced by their equivalents from
p2p/enode.
New API is added to retrieve the enode.Node instance of a peer. The
behavior of Server.Self with discovery disabled is improved. It now
tries much harder to report a working IP address, falling back to
127.0.0.1 if no suitable address can be determined through other means.
These changes were needed for tests of other packages later in the
series.
* p2p/simulations, p2p/testing: port to p2p/enode
No surprises here, mostly replacements of discover.Node, discover.NodeID
with their new equivalents. The 'interesting' API changes are:
- testing.ProtocolSession tracks complete nodes, not just their IDs.
- adapters.NodeConfig has a new method to create a complete node.
These changes were needed to make swarm tests work.
Note that the NodeID change makes the code incompatible with old
simulation snapshots.
* whisper/whisperv5, whisper/whisperv6: port to p2p/enode
This port was easy because whisper uses []byte for node IDs and
URL strings in the API.
* eth: port to p2p/enode
Again, easy to port because eth uses strings for node IDs and doesn't
care about node information in any way.
* les: port to p2p/enode
Apart from replacing discover.NodeID with enode.ID, most changes are in
the server pool code. It now deals with complete nodes instead
of (Pubkey, IP, Port) triples. The database format is unchanged for now,
but we should probably change it to use the node database later.
* node: port to p2p/enode
This change simply replaces discover.Node and discover.NodeID with their
new equivalents.
* swarm/network: port to p2p/enode
Swarm has its own node address representation, BzzAddr, containing both
an overlay address (the hash of a secp256k1 public key) and an underlay
address (enode:// URL).
There are no changes to the BzzAddr format in this commit, but certain
operations such as creating a BzzAddr from a node ID are now impossible
because node IDs aren't public keys anymore.
Most swarm-related changes in the series remove uses of
NewAddrFromNodeID, replacing it with NewAddr which takes a complete node
as argument. ToOverlayAddr is removed because we can just use the node
ID directly.
2018-09-25 00:59:00 +02:00
|
|
|
return ecies.ImportECDSA(prv).GenerateShared(h.remote, sskLen, sskLen)
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
// runInitiator negotiates a session token on conn.
|
2015-05-16 00:38:28 +02:00
|
|
|
// it should be called on the dialing side of the connection.
|
|
|
|
//
|
|
|
|
// prv is the local client's private key.
|
2021-05-27 10:19:13 +02:00
|
|
|
func (h *handshakeState) runInitiator(conn io.ReadWriter, prv *ecdsa.PrivateKey, remote *ecdsa.PublicKey) (s Secrets, err error) {
|
|
|
|
h.initiator = true
|
|
|
|
h.remote = ecies.ImportECDSAPublic(remote)
|
|
|
|
|
2018-07-23 23:36:08 +08:00
|
|
|
authMsg, err := h.makeAuthMsg(prv)
|
2015-05-16 00:38:28 +02:00
|
|
|
if err != nil {
|
|
|
|
return s, err
|
|
|
|
}
|
2021-05-27 10:19:13 +02:00
|
|
|
authPacket, err := h.sealEIP8(authMsg)
|
2015-05-16 00:38:28 +02:00
|
|
|
if err != nil {
|
|
|
|
return s, err
|
|
|
|
}
|
2020-09-22 10:17:39 +02:00
|
|
|
|
2015-12-23 01:48:55 +01:00
|
|
|
if _, err = conn.Write(authPacket); err != nil {
|
2015-05-16 00:38:28 +02:00
|
|
|
return s, err
|
|
|
|
}
|
|
|
|
|
2015-12-23 01:48:55 +01:00
|
|
|
authRespMsg := new(authRespV4)
|
2021-05-27 10:19:13 +02:00
|
|
|
authRespPacket, err := h.readMsg(authRespMsg, prv, conn)
|
2015-12-23 01:48:55 +01:00
|
|
|
if err != nil {
|
2015-05-16 00:38:28 +02:00
|
|
|
return s, err
|
|
|
|
}
|
2015-12-23 01:48:55 +01:00
|
|
|
if err := h.handleAuthResp(authRespMsg); err != nil {
|
2015-05-16 00:38:28 +02:00
|
|
|
return s, err
|
|
|
|
}
|
2021-05-27 10:19:13 +02:00
|
|
|
|
2015-12-23 01:48:55 +01:00
|
|
|
return h.secrets(authPacket, authRespPacket)
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
|
|
|
|
2015-12-23 01:48:55 +01:00
|
|
|
// makeAuthMsg creates the initiator handshake message.
|
2021-05-27 10:19:13 +02:00
|
|
|
func (h *handshakeState) makeAuthMsg(prv *ecdsa.PrivateKey) (*authMsgV4, error) {
|
2015-12-23 01:48:55 +01:00
|
|
|
// Generate random initiator nonce.
|
|
|
|
h.initNonce = make([]byte, shaLen)
|
all: new p2p node representation (#17643)
Package p2p/enode provides a generalized representation of p2p nodes
which can contain arbitrary information in key/value pairs. It is also
the new home for the node database. The "v4" identity scheme is also
moved here from p2p/enr to remove the dependency on Ethereum crypto from
that package.
Record signature handling is changed significantly. The identity scheme
registry is removed and acceptable schemes must be passed to any method
that needs identity. This means records must now be validated explicitly
after decoding.
The enode API is designed to make signature handling easy and safe: most
APIs around the codebase work with enode.Node, which is a wrapper around
a valid record. Going from enr.Record to enode.Node requires a valid
signature.
* p2p/discover: port to p2p/enode
This ports the discovery code to the new node representation in
p2p/enode. The wire protocol is unchanged, this can be considered a
refactoring change. The Kademlia table can now deal with nodes using an
arbitrary identity scheme. This requires a few incompatible API changes:
- Table.Lookup is not available anymore. It used to take a public key
as argument because v4 protocol requires one. Its replacement is
LookupRandom.
- Table.Resolve takes *enode.Node instead of NodeID. This is also for
v4 protocol compatibility because nodes cannot be looked up by ID
alone.
- Types Node and NodeID are gone. Further commits in the series will be
fixes all over the the codebase to deal with those removals.
* p2p: port to p2p/enode and discovery changes
This adapts package p2p to the changes in p2p/discover. All uses of
discover.Node and discover.NodeID are replaced by their equivalents from
p2p/enode.
New API is added to retrieve the enode.Node instance of a peer. The
behavior of Server.Self with discovery disabled is improved. It now
tries much harder to report a working IP address, falling back to
127.0.0.1 if no suitable address can be determined through other means.
These changes were needed for tests of other packages later in the
series.
* p2p/simulations, p2p/testing: port to p2p/enode
No surprises here, mostly replacements of discover.Node, discover.NodeID
with their new equivalents. The 'interesting' API changes are:
- testing.ProtocolSession tracks complete nodes, not just their IDs.
- adapters.NodeConfig has a new method to create a complete node.
These changes were needed to make swarm tests work.
Note that the NodeID change makes the code incompatible with old
simulation snapshots.
* whisper/whisperv5, whisper/whisperv6: port to p2p/enode
This port was easy because whisper uses []byte for node IDs and
URL strings in the API.
* eth: port to p2p/enode
Again, easy to port because eth uses strings for node IDs and doesn't
care about node information in any way.
* les: port to p2p/enode
Apart from replacing discover.NodeID with enode.ID, most changes are in
the server pool code. It now deals with complete nodes instead
of (Pubkey, IP, Port) triples. The database format is unchanged for now,
but we should probably change it to use the node database later.
* node: port to p2p/enode
This change simply replaces discover.Node and discover.NodeID with their
new equivalents.
* swarm/network: port to p2p/enode
Swarm has its own node address representation, BzzAddr, containing both
an overlay address (the hash of a secp256k1 public key) and an underlay
address (enode:// URL).
There are no changes to the BzzAddr format in this commit, but certain
operations such as creating a BzzAddr from a node ID are now impossible
because node IDs aren't public keys anymore.
Most swarm-related changes in the series remove uses of
NewAddrFromNodeID, replacing it with NewAddr which takes a complete node
as argument. ToOverlayAddr is removed because we can just use the node
ID directly.
2018-09-25 00:59:00 +02:00
|
|
|
_, err := rand.Read(h.initNonce)
|
|
|
|
if err != nil {
|
2015-05-16 00:38:28 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
2015-12-23 01:48:55 +01:00
|
|
|
// Generate random keypair to for ECDH.
|
2017-02-18 09:24:12 +01:00
|
|
|
h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
|
2015-05-16 00:38:28 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2015-12-23 01:48:55 +01:00
|
|
|
// Sign known message: static-shared-secret ^ nonce
|
2018-07-23 23:36:08 +08:00
|
|
|
token, err := h.staticSharedSecret(prv)
|
2015-12-23 01:48:55 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
|
|
|
signed := xor(token, h.initNonce)
|
|
|
|
signature, err := crypto.Sign(signed, h.randomPrivKey.ExportECDSA())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2015-12-23 01:48:55 +01:00
|
|
|
msg := new(authMsgV4)
|
|
|
|
copy(msg.Signature[:], signature)
|
|
|
|
copy(msg.InitiatorPubkey[:], crypto.FromECDSAPub(&prv.PublicKey)[1:])
|
|
|
|
copy(msg.Nonce[:], h.initNonce)
|
|
|
|
msg.Version = 4
|
|
|
|
return msg, nil
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
func (h *handshakeState) handleAuthResp(msg *authRespV4) (err error) {
|
2015-12-23 01:48:55 +01:00
|
|
|
h.respNonce = msg.Nonce[:]
|
|
|
|
h.remoteRandomPub, err = importPublicKey(msg.RandomPubkey[:])
|
|
|
|
return err
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
func (h *handshakeState) makeAuthResp() (msg *authRespV4, err error) {
|
2015-12-23 01:48:55 +01:00
|
|
|
// Generate random nonce.
|
|
|
|
h.respNonce = make([]byte, shaLen)
|
|
|
|
if _, err = rand.Read(h.respNonce); err != nil {
|
2015-05-16 00:38:28 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
2015-07-14 02:21:02 +00:00
|
|
|
|
2015-12-23 01:48:55 +01:00
|
|
|
msg = new(authRespV4)
|
|
|
|
copy(msg.Nonce[:], h.respNonce)
|
|
|
|
copy(msg.RandomPubkey[:], exportPubkey(&h.randomPrivKey.PublicKey))
|
|
|
|
msg.Version = 4
|
|
|
|
return msg, nil
|
|
|
|
}
|
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
// readMsg reads an encrypted handshake message, decoding it into msg.
|
|
|
|
func (h *handshakeState) readMsg(msg interface{}, prv *ecdsa.PrivateKey, r io.Reader) ([]byte, error) {
|
|
|
|
h.rbuf.reset()
|
|
|
|
h.rbuf.grow(512)
|
2015-12-23 01:48:55 +01:00
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
// Read the size prefix.
|
|
|
|
prefix, err := h.rbuf.read(r, 2)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
size := binary.BigEndian.Uint16(prefix)
|
2015-12-23 01:48:55 +01:00
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
// Read the handshake packet.
|
|
|
|
packet, err := h.rbuf.read(r, int(size))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
dec, err := ecies.ImportECDSA(prv).Decrypt(packet, nil, prefix)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
// Can't use rlp.DecodeBytes here because it rejects
|
|
|
|
// trailing data (forward-compatibility).
|
|
|
|
s := rlp.NewStream(bytes.NewReader(dec), 0)
|
|
|
|
err = s.Decode(msg)
|
|
|
|
return h.rbuf.data[:len(prefix)+len(packet)], err
|
2015-12-23 01:48:55 +01:00
|
|
|
}
|
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
// sealEIP8 encrypts a handshake message.
|
|
|
|
func (h *handshakeState) sealEIP8(msg interface{}) ([]byte, error) {
|
|
|
|
h.wbuf.reset()
|
2015-12-23 01:48:55 +01:00
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
// Write the message plaintext.
|
|
|
|
if err := rlp.Encode(&h.wbuf, msg); err != nil {
|
2015-12-23 01:48:55 +01:00
|
|
|
return nil, err
|
2015-07-14 02:21:02 +00:00
|
|
|
}
|
2021-05-27 10:19:13 +02:00
|
|
|
// Pad with random amount of data. the amount needs to be at least 100 bytes to make
|
2015-12-23 01:48:55 +01:00
|
|
|
// the message distinguishable from pre-EIP-8 handshakes.
|
2021-05-27 10:19:13 +02:00
|
|
|
h.wbuf.appendZero(mrand.Intn(100) + 100)
|
|
|
|
|
2015-12-23 01:48:55 +01:00
|
|
|
prefix := make([]byte, 2)
|
2021-05-27 10:19:13 +02:00
|
|
|
binary.BigEndian.PutUint16(prefix, uint16(len(h.wbuf.data)+eciesOverhead))
|
2015-07-14 02:21:02 +00:00
|
|
|
|
2021-05-27 10:19:13 +02:00
|
|
|
enc, err := ecies.Encrypt(rand.Reader, h.remote, h.wbuf.data, nil, prefix)
|
2015-12-23 01:48:55 +01:00
|
|
|
return append(prefix, enc...), err
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// importPublicKey unmarshals 512 bit public keys.
|
|
|
|
func importPublicKey(pubKey []byte) (*ecies.PublicKey, error) {
|
|
|
|
var pubKey65 []byte
|
|
|
|
switch len(pubKey) {
|
|
|
|
case 64:
|
|
|
|
// add 'uncompressed key' flag
|
|
|
|
pubKey65 = append([]byte{0x04}, pubKey...)
|
|
|
|
case 65:
|
|
|
|
pubKey65 = pubKey
|
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf("invalid public key length %v (expect 64/65)", len(pubKey))
|
|
|
|
}
|
|
|
|
// TODO: fewer pointless conversions
|
2018-06-12 15:26:08 +02:00
|
|
|
pub, err := crypto.UnmarshalPubkey(pubKey65)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2015-12-23 01:48:55 +01:00
|
|
|
}
|
|
|
|
return ecies.ImportECDSAPublic(pub), nil
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func exportPubkey(pub *ecies.PublicKey) []byte {
|
|
|
|
if pub == nil {
|
|
|
|
panic("nil pubkey")
|
|
|
|
}
|
2024-03-18 17:36:50 +01:00
|
|
|
if curve, ok := pub.Curve.(crypto.EllipticCurve); ok {
|
|
|
|
return curve.Marshal(pub.X, pub.Y)[1:]
|
|
|
|
}
|
|
|
|
return []byte{}
|
2015-05-16 00:38:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func xor(one, other []byte) (xor []byte) {
|
|
|
|
xor = make([]byte, len(one))
|
|
|
|
for i := 0; i < len(one); i++ {
|
|
|
|
xor[i] = one[i] ^ other[i]
|
|
|
|
}
|
|
|
|
return xor
|
|
|
|
}
|