handshake.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. package p2p
  2. import (
  3. "crypto/ecdsa"
  4. "crypto/elliptic"
  5. "crypto/rand"
  6. "errors"
  7. "fmt"
  8. "hash"
  9. "io"
  10. "net"
  11. "github.com/ethereum/go-ethereum/crypto"
  12. "github.com/ethereum/go-ethereum/crypto/ecies"
  13. "github.com/ethereum/go-ethereum/crypto/secp256k1"
  14. "github.com/ethereum/go-ethereum/crypto/sha3"
  15. "github.com/ethereum/go-ethereum/p2p/discover"
  16. "github.com/ethereum/go-ethereum/rlp"
  17. )
  18. const (
  19. sskLen = 16 // ecies.MaxSharedKeyLength(pubKey) / 2
  20. sigLen = 65 // elliptic S256
  21. pubLen = 64 // 512 bit pubkey in uncompressed representation without format byte
  22. shaLen = 32 // hash length (for nonce etc)
  23. authMsgLen = sigLen + shaLen + pubLen + shaLen + 1
  24. authRespLen = pubLen + shaLen + 1
  25. eciesBytes = 65 + 16 + 32
  26. encAuthMsgLen = authMsgLen + eciesBytes // size of the final ECIES payload sent as initiator's handshake
  27. encAuthRespLen = authRespLen + eciesBytes // size of the final ECIES payload sent as receiver's handshake
  28. )
  29. // conn represents a remote connection after encryption handshake
  30. // and protocol handshake have completed.
  31. //
  32. // The MsgReadWriter is usually layered as follows:
  33. //
  34. // netWrapper (I/O timeouts, thread-safe ReadMsg, WriteMsg)
  35. // rlpxFrameRW (message encoding, encryption, authentication)
  36. // bufio.ReadWriter (buffering)
  37. // net.Conn (network I/O)
  38. //
  39. type conn struct {
  40. MsgReadWriter
  41. *protoHandshake
  42. }
  43. // secrets represents the connection secrets
  44. // which are negotiated during the encryption handshake.
  45. type secrets struct {
  46. RemoteID discover.NodeID
  47. AES, MAC []byte
  48. EgressMAC, IngressMAC hash.Hash
  49. Token []byte
  50. }
  51. // protoHandshake is the RLP structure of the protocol handshake.
  52. type protoHandshake struct {
  53. Version uint64
  54. Name string
  55. Caps []Cap
  56. ListenPort uint64
  57. ID discover.NodeID
  58. }
  59. // setupConn starts a protocol session on the given connection.
  60. // It runs the encryption handshake and the protocol handshake.
  61. // If dial is non-nil, the connection the local node is the initiator.
  62. func setupConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node) (*conn, error) {
  63. if dial == nil {
  64. return setupInboundConn(fd, prv, our)
  65. } else {
  66. return setupOutboundConn(fd, prv, our, dial)
  67. }
  68. }
  69. func setupInboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake) (*conn, error) {
  70. secrets, err := receiverEncHandshake(fd, prv, nil)
  71. if err != nil {
  72. return nil, fmt.Errorf("encryption handshake failed: %v", err)
  73. }
  74. // Run the protocol handshake using authenticated messages.
  75. rw := newRlpxFrameRW(fd, secrets)
  76. rhs, err := readProtocolHandshake(rw, our)
  77. if err != nil {
  78. return nil, err
  79. }
  80. if rhs.ID != secrets.RemoteID {
  81. return nil, errors.New("node ID in protocol handshake does not match encryption handshake")
  82. }
  83. // TODO: validate that handshake node ID matches
  84. if err := writeProtocolHandshake(rw, our); err != nil {
  85. return nil, fmt.Errorf("protocol write error: %v", err)
  86. }
  87. return &conn{rw, rhs}, nil
  88. }
  89. func setupOutboundConn(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node) (*conn, error) {
  90. secrets, err := initiatorEncHandshake(fd, prv, dial.ID, nil)
  91. if err != nil {
  92. return nil, fmt.Errorf("encryption handshake failed: %v", err)
  93. }
  94. // Run the protocol handshake using authenticated messages.
  95. rw := newRlpxFrameRW(fd, secrets)
  96. if err := writeProtocolHandshake(rw, our); err != nil {
  97. return nil, fmt.Errorf("protocol write error: %v", err)
  98. }
  99. rhs, err := readProtocolHandshake(rw, our)
  100. if err != nil {
  101. return nil, fmt.Errorf("protocol handshake read error: %v", err)
  102. }
  103. if rhs.ID != dial.ID {
  104. return nil, errors.New("dialed node id mismatch")
  105. }
  106. return &conn{rw, rhs}, nil
  107. }
  108. // encHandshake contains the state of the encryption handshake.
  109. type encHandshake struct {
  110. initiator bool
  111. remoteID discover.NodeID
  112. remotePub *ecies.PublicKey // remote-pubk
  113. initNonce, respNonce []byte // nonce
  114. randomPrivKey *ecies.PrivateKey // ecdhe-random
  115. remoteRandomPub *ecies.PublicKey // ecdhe-random-pubk
  116. }
  117. // secrets is called after the handshake is completed.
  118. // It extracts the connection secrets from the handshake values.
  119. func (h *encHandshake) secrets(auth, authResp []byte) (secrets, error) {
  120. ecdheSecret, err := h.randomPrivKey.GenerateShared(h.remoteRandomPub, sskLen, sskLen)
  121. if err != nil {
  122. return secrets{}, err
  123. }
  124. // derive base secrets from ephemeral key agreement
  125. sharedSecret := crypto.Sha3(ecdheSecret, crypto.Sha3(h.respNonce, h.initNonce))
  126. aesSecret := crypto.Sha3(ecdheSecret, sharedSecret)
  127. s := secrets{
  128. RemoteID: h.remoteID,
  129. AES: aesSecret,
  130. MAC: crypto.Sha3(ecdheSecret, aesSecret),
  131. Token: crypto.Sha3(sharedSecret),
  132. }
  133. // setup sha3 instances for the MACs
  134. mac1 := sha3.NewKeccak256()
  135. mac1.Write(xor(s.MAC, h.respNonce))
  136. mac1.Write(auth)
  137. mac2 := sha3.NewKeccak256()
  138. mac2.Write(xor(s.MAC, h.initNonce))
  139. mac2.Write(authResp)
  140. if h.initiator {
  141. s.EgressMAC, s.IngressMAC = mac1, mac2
  142. } else {
  143. s.EgressMAC, s.IngressMAC = mac2, mac1
  144. }
  145. return s, nil
  146. }
  147. func (h *encHandshake) ecdhShared(prv *ecdsa.PrivateKey) ([]byte, error) {
  148. return ecies.ImportECDSA(prv).GenerateShared(h.remotePub, sskLen, sskLen)
  149. }
  150. // initiatorEncHandshake negotiates a session token on conn.
  151. // it should be called on the dialing side of the connection.
  152. //
  153. // prv is the local client's private key.
  154. // token is the token from a previous session with this node.
  155. func initiatorEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, remoteID discover.NodeID, token []byte) (s secrets, err error) {
  156. h, err := newInitiatorHandshake(remoteID)
  157. if err != nil {
  158. return s, err
  159. }
  160. auth, err := h.authMsg(prv, token)
  161. if err != nil {
  162. return s, err
  163. }
  164. if _, err = conn.Write(auth); err != nil {
  165. return s, err
  166. }
  167. response := make([]byte, encAuthRespLen)
  168. if _, err = io.ReadFull(conn, response); err != nil {
  169. return s, err
  170. }
  171. if err := h.decodeAuthResp(response, prv); err != nil {
  172. return s, err
  173. }
  174. return h.secrets(auth, response)
  175. }
  176. func newInitiatorHandshake(remoteID discover.NodeID) (*encHandshake, error) {
  177. // generate random initiator nonce
  178. n := make([]byte, shaLen)
  179. if _, err := rand.Read(n); err != nil {
  180. return nil, err
  181. }
  182. // generate random keypair to use for signing
  183. randpriv, err := ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
  184. if err != nil {
  185. return nil, err
  186. }
  187. rpub, err := remoteID.Pubkey()
  188. if err != nil {
  189. return nil, fmt.Errorf("bad remoteID: %v", err)
  190. }
  191. h := &encHandshake{
  192. initiator: true,
  193. remoteID: remoteID,
  194. remotePub: ecies.ImportECDSAPublic(rpub),
  195. initNonce: n,
  196. randomPrivKey: randpriv,
  197. }
  198. return h, nil
  199. }
  200. // authMsg creates an encrypted initiator handshake message.
  201. func (h *encHandshake) authMsg(prv *ecdsa.PrivateKey, token []byte) ([]byte, error) {
  202. var tokenFlag byte
  203. if token == nil {
  204. // no session token found means we need to generate shared secret.
  205. // ecies shared secret is used as initial session token for new peers
  206. // generate shared key from prv and remote pubkey
  207. var err error
  208. if token, err = h.ecdhShared(prv); err != nil {
  209. return nil, err
  210. }
  211. } else {
  212. // for known peers, we use stored token from the previous session
  213. tokenFlag = 0x01
  214. }
  215. // sign known message:
  216. // ecdh-shared-secret^nonce for new peers
  217. // token^nonce for old peers
  218. signed := xor(token, h.initNonce)
  219. signature, err := crypto.Sign(signed, h.randomPrivKey.ExportECDSA())
  220. if err != nil {
  221. return nil, err
  222. }
  223. // encode auth message
  224. // signature || sha3(ecdhe-random-pubk) || pubk || nonce || token-flag
  225. msg := make([]byte, authMsgLen)
  226. n := copy(msg, signature)
  227. n += copy(msg[n:], crypto.Sha3(exportPubkey(&h.randomPrivKey.PublicKey)))
  228. n += copy(msg[n:], crypto.FromECDSAPub(&prv.PublicKey)[1:])
  229. n += copy(msg[n:], h.initNonce)
  230. msg[n] = tokenFlag
  231. // encrypt auth message using remote-pubk
  232. return ecies.Encrypt(rand.Reader, h.remotePub, msg, nil, nil)
  233. }
  234. // decodeAuthResp decode an encrypted authentication response message.
  235. func (h *encHandshake) decodeAuthResp(auth []byte, prv *ecdsa.PrivateKey) error {
  236. msg, err := crypto.Decrypt(prv, auth)
  237. if err != nil {
  238. return fmt.Errorf("could not decrypt auth response (%v)", err)
  239. }
  240. h.respNonce = msg[pubLen : pubLen+shaLen]
  241. h.remoteRandomPub, err = importPublicKey(msg[:pubLen])
  242. if err != nil {
  243. return err
  244. }
  245. // ignore token flag for now
  246. return nil
  247. }
  248. // receiverEncHandshake negotiates a session token on conn.
  249. // it should be called on the listening side of the connection.
  250. //
  251. // prv is the local client's private key.
  252. // token is the token from a previous session with this node.
  253. func receiverEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, token []byte) (s secrets, err error) {
  254. // read remote auth sent by initiator.
  255. auth := make([]byte, encAuthMsgLen)
  256. if _, err := io.ReadFull(conn, auth); err != nil {
  257. return s, err
  258. }
  259. h, err := decodeAuthMsg(prv, token, auth)
  260. if err != nil {
  261. return s, err
  262. }
  263. // send auth response
  264. resp, err := h.authResp(prv, token)
  265. if err != nil {
  266. return s, err
  267. }
  268. if _, err = conn.Write(resp); err != nil {
  269. return s, err
  270. }
  271. return h.secrets(auth, resp)
  272. }
  273. func decodeAuthMsg(prv *ecdsa.PrivateKey, token []byte, auth []byte) (*encHandshake, error) {
  274. var err error
  275. h := new(encHandshake)
  276. // generate random keypair for session
  277. h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil)
  278. if err != nil {
  279. return nil, err
  280. }
  281. // generate random nonce
  282. h.respNonce = make([]byte, shaLen)
  283. if _, err = rand.Read(h.respNonce); err != nil {
  284. return nil, err
  285. }
  286. msg, err := crypto.Decrypt(prv, auth)
  287. if err != nil {
  288. return nil, fmt.Errorf("could not decrypt auth message (%v)", err)
  289. }
  290. // decode message parameters
  291. // signature || sha3(ecdhe-random-pubk) || pubk || nonce || token-flag
  292. h.initNonce = msg[authMsgLen-shaLen-1 : authMsgLen-1]
  293. copy(h.remoteID[:], msg[sigLen+shaLen:sigLen+shaLen+pubLen])
  294. rpub, err := h.remoteID.Pubkey()
  295. if err != nil {
  296. return nil, fmt.Errorf("bad remoteID: %#v", err)
  297. }
  298. h.remotePub = ecies.ImportECDSAPublic(rpub)
  299. // recover remote random pubkey from signed message.
  300. if token == nil {
  301. // TODO: it is an error if the initiator has a token and we don't. check that.
  302. // no session token means we need to generate shared secret.
  303. // ecies shared secret is used as initial session token for new peers.
  304. // generate shared key from prv and remote pubkey.
  305. if token, err = h.ecdhShared(prv); err != nil {
  306. return nil, err
  307. }
  308. }
  309. signedMsg := xor(token, h.initNonce)
  310. remoteRandomPub, err := secp256k1.RecoverPubkey(signedMsg, msg[:sigLen])
  311. if err != nil {
  312. return nil, err
  313. }
  314. h.remoteRandomPub, _ = importPublicKey(remoteRandomPub)
  315. return h, nil
  316. }
  317. // authResp generates the encrypted authentication response message.
  318. func (h *encHandshake) authResp(prv *ecdsa.PrivateKey, token []byte) ([]byte, error) {
  319. // responder auth message
  320. // E(remote-pubk, ecdhe-random-pubk || nonce || 0x0)
  321. resp := make([]byte, authRespLen)
  322. n := copy(resp, exportPubkey(&h.randomPrivKey.PublicKey))
  323. n += copy(resp[n:], h.respNonce)
  324. if token == nil {
  325. resp[n] = 0
  326. } else {
  327. resp[n] = 1
  328. }
  329. // encrypt using remote-pubk
  330. return ecies.Encrypt(rand.Reader, h.remotePub, resp, nil, nil)
  331. }
  332. // importPublicKey unmarshals 512 bit public keys.
  333. func importPublicKey(pubKey []byte) (*ecies.PublicKey, error) {
  334. var pubKey65 []byte
  335. switch len(pubKey) {
  336. case 64:
  337. // add 'uncompressed key' flag
  338. pubKey65 = append([]byte{0x04}, pubKey...)
  339. case 65:
  340. pubKey65 = pubKey
  341. default:
  342. return nil, fmt.Errorf("invalid public key length %v (expect 64/65)", len(pubKey))
  343. }
  344. // TODO: fewer pointless conversions
  345. return ecies.ImportECDSAPublic(crypto.ToECDSAPub(pubKey65)), nil
  346. }
  347. func exportPubkey(pub *ecies.PublicKey) []byte {
  348. if pub == nil {
  349. panic("nil pubkey")
  350. }
  351. return elliptic.Marshal(pub.Curve, pub.X, pub.Y)[1:]
  352. }
  353. func xor(one, other []byte) (xor []byte) {
  354. xor = make([]byte, len(one))
  355. for i := 0; i < len(one); i++ {
  356. xor[i] = one[i] ^ other[i]
  357. }
  358. return xor
  359. }
  360. func writeProtocolHandshake(w MsgWriter, our *protoHandshake) error {
  361. return EncodeMsg(w, handshakeMsg, our.Version, our.Name, our.Caps, our.ListenPort, our.ID[:])
  362. }
  363. func readProtocolHandshake(r MsgReader, our *protoHandshake) (*protoHandshake, error) {
  364. // read and handle remote handshake
  365. msg, err := r.ReadMsg()
  366. if err != nil {
  367. return nil, err
  368. }
  369. if msg.Code == discMsg {
  370. // disconnect before protocol handshake is valid according to the
  371. // spec and we send it ourself if Server.addPeer fails.
  372. var reason DiscReason
  373. rlp.Decode(msg.Payload, &reason)
  374. return nil, discRequestedError(reason)
  375. }
  376. if msg.Code != handshakeMsg {
  377. return nil, fmt.Errorf("expected handshake, got %x", msg.Code)
  378. }
  379. if msg.Size > baseProtocolMaxMsgSize {
  380. return nil, fmt.Errorf("message too big (%d > %d)", msg.Size, baseProtocolMaxMsgSize)
  381. }
  382. var hs protoHandshake
  383. if err := msg.Decode(&hs); err != nil {
  384. return nil, err
  385. }
  386. // validate handshake info
  387. if hs.Version != our.Version {
  388. return nil, newPeerError(errP2PVersionMismatch, "required version %d, received %d\n", baseProtocolVersion, hs.Version)
  389. }
  390. if (hs.ID == discover.NodeID{}) {
  391. return nil, newPeerError(errPubkeyInvalid, "missing")
  392. }
  393. return &hs, nil
  394. }