@@ -5,12 +5,14 @@ import (
55 "crypto/rand"
66 "errors"
77 "fmt"
8+ "hash"
89 "io"
910 "net"
1011
1112 "github.com/ethereum/go-ethereum/crypto"
1213 "github.com/ethereum/go-ethereum/crypto/ecies"
1314 "github.com/ethereum/go-ethereum/crypto/secp256k1"
15+ "github.com/ethereum/go-ethereum/crypto/sha3"
1416 "github.com/ethereum/go-ethereum/p2p/discover"
1517 "github.com/ethereum/go-ethereum/rlp"
1618)
@@ -38,13 +40,23 @@ func newConn(fd net.Conn, hs *protoHandshake) *conn {
3840 return & conn {newFrameRW (fd , msgWriteTimeout ), hs }
3941}
4042
41- // encHandshake represents information about the remote end
42- // of a connection that is negotiated during the encryption handshake.
43+ // encHandshake contains the state of the encryption handshake.
4344type encHandshake struct {
44- ID discover.NodeID
45- IngressMAC []byte
46- EgressMAC []byte
47- Token []byte
45+ remoteID discover.NodeID
46+ initiator bool
47+ initNonce , respNonce []byte
48+ dhSharedSecret []byte
49+ randomPrivKey * ecdsa.PrivateKey
50+ remoteRandomPub * ecdsa.PublicKey
51+ }
52+
53+ // secrets represents the connection secrets
54+ // which are negotiated during the encryption handshake.
55+ type secrets struct {
56+ RemoteID discover.NodeID
57+ AES , MAC []byte
58+ EgressMAC , IngressMAC hash.Hash
59+ Token []byte
4860}
4961
5062// protoHandshake is the RLP structure of the protocol handshake.
@@ -56,6 +68,34 @@ type protoHandshake struct {
5668 ID discover.NodeID
5769}
5870
71+ // secrets is called after the handshake is completed.
72+ // It extracts the connection secrets from the handshake values.
73+ func (h * encHandshake ) secrets (auth , authResp []byte ) secrets {
74+ sharedSecret := crypto .Sha3 (h .dhSharedSecret , crypto .Sha3 (h .respNonce , h .initNonce ))
75+ aesSecret := crypto .Sha3 (h .dhSharedSecret , sharedSecret )
76+ s := secrets {
77+ RemoteID : h .remoteID ,
78+ AES : aesSecret ,
79+ MAC : crypto .Sha3 (h .dhSharedSecret , aesSecret ),
80+ Token : crypto .Sha3 (sharedSecret ),
81+ }
82+
83+ // setup sha3 instances for the MACs
84+ mac1 := sha3 .NewKeccak256 ()
85+ mac1 .Write (xor (s .MAC , h .respNonce ))
86+ mac1 .Write (auth )
87+ mac2 := sha3 .NewKeccak256 ()
88+ mac2 .Write (xor (s .MAC , h .initNonce ))
89+ mac2 .Write (authResp )
90+ if h .initiator {
91+ s .EgressMAC , s .IngressMAC = mac1 , mac2
92+ } else {
93+ s .EgressMAC , s .IngressMAC = mac2 , mac1
94+ }
95+
96+ return s
97+ }
98+
5999// setupConn starts a protocol session on the given connection.
60100// It runs the encryption handshake and the protocol handshake.
61101// If dial is non-nil, the connection the local node is the initiator.
@@ -68,36 +108,47 @@ func setupConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *di
68108}
69109
70110func setupInboundConn (fd net.Conn , prv * ecdsa.PrivateKey , our * protoHandshake ) (* conn , error ) {
71- // var remotePubkey []byte
72- // sessionToken, remotePubkey, err = inboundEncHandshake(fd, prv, nil)
73- // copy(remoteID[:], remotePubkey)
111+ secrets , err := inboundEncHandshake (fd , prv , nil )
112+ if err != nil {
113+ return nil , fmt .Errorf ("encryption handshake failed: %v" , err )
114+ }
74115
75- rw := newFrameRW (fd , msgWriteTimeout )
76- rhs , err := readProtocolHandshake (rw , our )
116+ // Run the protocol handshake using authenticated messages.
117+ // TODO: move buffering setup here (out of newFrameRW)
118+ phsrw := newRlpxFrameRW (fd , secrets )
119+ rhs , err := readProtocolHandshake (phsrw , our )
77120 if err != nil {
78121 return nil , err
79122 }
80- if err := writeProtocolHandshake (rw , our ); err != nil {
123+ if err := writeProtocolHandshake (phsrw , our ); err != nil {
81124 return nil , fmt .Errorf ("protocol write error: %v" , err )
82125 }
126+
127+ rw := newFrameRW (fd , msgWriteTimeout )
83128 return & conn {rw , rhs }, nil
84129}
85130
86131func setupOutboundConn (fd net.Conn , prv * ecdsa.PrivateKey , our * protoHandshake , dial * discover.Node ) (* conn , error ) {
87- // remoteID = dial.ID
88- // sessionToken, err = outboundEncHandshake(fd, prv, remoteID[:], nil)
132+ secrets , err := outboundEncHandshake (fd , prv , dial .ID [:], nil )
133+ if err != nil {
134+ return nil , fmt .Errorf ("encryption handshake failed: %v" , err )
135+ }
89136
90- rw := newFrameRW (fd , msgWriteTimeout )
91- if err := writeProtocolHandshake (rw , our ); err != nil {
137+ // Run the protocol handshake using authenticated messages.
138+ // TODO: move buffering setup here (out of newFrameRW)
139+ phsrw := newRlpxFrameRW (fd , secrets )
140+ if err := writeProtocolHandshake (phsrw , our ); err != nil {
92141 return nil , fmt .Errorf ("protocol write error: %v" , err )
93142 }
94- rhs , err := readProtocolHandshake (rw , our )
143+ rhs , err := readProtocolHandshake (phsrw , our )
95144 if err != nil {
96145 return nil , fmt .Errorf ("protocol handshake read error: %v" , err )
97146 }
98147 if rhs .ID != dial .ID {
99148 return nil , errors .New ("dialed node id mismatch" )
100149 }
150+
151+ rw := newFrameRW (fd , msgWriteTimeout )
101152 return & conn {rw , rhs }, nil
102153}
103154
@@ -107,58 +158,62 @@ func setupOutboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake,
107158// privateKey is the local client's private key
108159// remotePublicKey is the remote peer's node ID
109160// sessionToken is the token from a previous session with this node.
110- func outboundEncHandshake (conn io.ReadWriter , prvKey * ecdsa.PrivateKey , remotePublicKey []byte , sessionToken []byte ) (
111- newSessionToken []byte ,
112- err error ,
113- ) {
161+ func outboundEncHandshake (conn io.ReadWriter , prvKey * ecdsa.PrivateKey , remotePublicKey []byte , sessionToken []byte ) (s secrets , err error ) {
114162 auth , initNonce , randomPrivKey , err := authMsg (prvKey , remotePublicKey , sessionToken )
115163 if err != nil {
116- return nil , err
164+ return s , err
117165 }
118166 if _ , err = conn .Write (auth ); err != nil {
119- return nil , err
167+ return s , err
120168 }
121169
122170 response := make ([]byte , rHSLen )
123171 if _ , err = io .ReadFull (conn , response ); err != nil {
124- return nil , err
172+ return s , err
125173 }
126174 recNonce , remoteRandomPubKey , _ , err := completeHandshake (response , prvKey )
127175 if err != nil {
128- return nil , err
176+ return s , err
129177 }
130178
131- return newSession (initNonce , recNonce , randomPrivKey , remoteRandomPubKey )
179+ h := & encHandshake {
180+ initiator : true ,
181+ initNonce : initNonce ,
182+ respNonce : recNonce ,
183+ randomPrivKey : randomPrivKey ,
184+ remoteRandomPub : remoteRandomPubKey ,
185+ }
186+ copy (h .remoteID [:], remotePublicKey )
187+ return h .secrets (auth , response ), nil
132188}
133189
134190// authMsg creates the initiator handshake.
191+ // TODO: change all the names
135192func authMsg (prvKey * ecdsa.PrivateKey , remotePubKeyS , sessionToken []byte ) (
136193 auth , initNonce []byte ,
137194 randomPrvKey * ecdsa.PrivateKey ,
138195 err error ,
139196) {
140- // session init, common to both parties
141197 remotePubKey , err := importPublicKey (remotePubKeyS )
142198 if err != nil {
143199 return
144200 }
145201
146- var tokenFlag byte // = 0x00
202+ var tokenFlag byte
147203 if sessionToken == nil {
148204 // no session token found means we need to generate shared secret.
149205 // ecies shared secret is used as initial session token for new peers
150206 // generate shared key from prv and remote pubkey
151207 if sessionToken , err = ecies .ImportECDSA (prvKey ).GenerateShared (ecies .ImportECDSAPublic (remotePubKey ), sskLen , sskLen ); err != nil {
152208 return
153209 }
154- // tokenFlag = 0x00 // redundant
155210 } else {
156211 // for known peers, we use stored token from the previous session
157212 tokenFlag = 0x01
158213 }
159214
160- //E(remote-pubk, S(ecdhe-random, ecdh-shared-secret^nonce) || H(ecdhe-random-pubk) || pubk || nonce || 0x0)
161- // E(remote-pubk, S(ecdhe-random, token^nonce) || H(ecdhe-random-pubk) || pubk || nonce || 0x1)
215+ //E(remote-pubk, S(ecdhe-random, sha3( ecdh-shared-secret^nonce) ) || H(ecdhe-random-pubk) || pubk || nonce || 0x0)
216+ // E(remote-pubk, S(ecdhe-random, sha3( token^nonce) ) || H(ecdhe-random-pubk) || pubk || nonce || 0x1)
162217 // allocate msgLen long message,
163218 var msg []byte = make ([]byte , authMsgLen )
164219 initNonce = msg [authMsgLen - shaLen - 1 : authMsgLen - 1 ]
@@ -242,27 +297,32 @@ func completeHandshake(auth []byte, prvKey *ecdsa.PrivateKey) (
242297//
243298// privateKey is the local client's private key
244299// sessionToken is the token from a previous session with this node.
245- func inboundEncHandshake (conn io.ReadWriter , prvKey * ecdsa.PrivateKey , sessionToken []byte ) (
246- token , remotePubKey []byte ,
247- err error ,
248- ) {
300+ func inboundEncHandshake (conn io.ReadWriter , prvKey * ecdsa.PrivateKey , sessionToken []byte ) (s secrets , err error ) {
249301 // we are listening connection. we are responders in the
250302 // handshake. Extract info from the authentication. The initiator
251303 // starts by sending us a handshake that we need to respond to. so
252304 // we read auth message first, then respond.
253305 auth := make ([]byte , iHSLen )
254306 if _ , err := io .ReadFull (conn , auth ); err != nil {
255- return nil , nil , err
307+ return s , err
256308 }
257309 response , recNonce , initNonce , remotePubKey , randomPrivKey , remoteRandomPubKey , err := authResp (auth , sessionToken , prvKey )
258310 if err != nil {
259- return nil , nil , err
311+ return s , err
260312 }
261313 if _ , err = conn .Write (response ); err != nil {
262- return nil , nil , err
314+ return s , err
263315 }
264- token , err = newSession (initNonce , recNonce , randomPrivKey , remoteRandomPubKey )
265- return token , remotePubKey , err
316+
317+ h := & encHandshake {
318+ initiator : false ,
319+ initNonce : initNonce ,
320+ respNonce : recNonce ,
321+ randomPrivKey : randomPrivKey ,
322+ remoteRandomPub : remoteRandomPubKey ,
323+ }
324+ copy (h .remoteID [:], remotePubKey )
325+ return h .secrets (auth , response ), err
266326}
267327
268328// authResp is called by peer if it accepted (but not
@@ -349,23 +409,6 @@ func authResp(auth, sessionToken []byte, prvKey *ecdsa.PrivateKey) (
349409 return
350410}
351411
352- // newSession is called after the handshake is completed. The
353- // arguments are values negotiated in the handshake. The return value
354- // is a new session Token to be remembered for the next time we
355- // connect with this peer.
356- func newSession (initNonce , respNonce []byte , privKey * ecdsa.PrivateKey , remoteRandomPubKey * ecdsa.PublicKey ) ([]byte , error ) {
357- // 3) Now we can trust ecdhe-random-pubk to derive new keys
358- //ecdhe-shared-secret = ecdh.agree(ecdhe-random, remote-ecdhe-random-pubk)
359- pubKey := ecies .ImportECDSAPublic (remoteRandomPubKey )
360- dhSharedSecret , err := ecies .ImportECDSA (privKey ).GenerateShared (pubKey , sskLen , sskLen )
361- if err != nil {
362- return nil , err
363- }
364- sharedSecret := crypto .Sha3 (dhSharedSecret , crypto .Sha3 (respNonce , initNonce ))
365- sessionToken := crypto .Sha3 (sharedSecret )
366- return sessionToken , nil
367- }
368-
369412// importPublicKey unmarshals 512 bit public keys.
370413func importPublicKey (pubKey []byte ) (pubKeyEC * ecdsa.PublicKey , err error ) {
371414 var pubKey65 []byte
0 commit comments