v5_encoding_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. // Copyright 2019 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package discover
  17. import (
  18. "bytes"
  19. "crypto/ecdsa"
  20. "encoding/hex"
  21. "fmt"
  22. "net"
  23. "reflect"
  24. "testing"
  25. "github.com/davecgh/go-spew/spew"
  26. "github.com/ethereum/go-ethereum/common/mclock"
  27. "github.com/ethereum/go-ethereum/crypto"
  28. "github.com/ethereum/go-ethereum/p2p/enode"
  29. )
  30. var (
  31. testKeyA, _ = crypto.HexToECDSA("eef77acb6c6a6eebc5b363a475ac583ec7eccdb42b6481424c60f59aa326547f")
  32. testKeyB, _ = crypto.HexToECDSA("66fb62bfbd66b9177a138c1e5cddbe4f7c30c343e94e68df8769459cb1cde628")
  33. testIDnonce = [32]byte{5, 6, 7, 8, 9, 10, 11, 12}
  34. )
  35. func TestDeriveKeysV5(t *testing.T) {
  36. t.Parallel()
  37. var (
  38. n1 = enode.ID{1}
  39. n2 = enode.ID{2}
  40. challenge = &whoareyouV5{}
  41. db, _ = enode.OpenDB("")
  42. ln = enode.NewLocalNode(db, testKeyA)
  43. c = newWireCodec(ln, testKeyA, mclock.System{})
  44. )
  45. defer db.Close()
  46. sec1 := c.deriveKeys(n1, n2, testKeyA, &testKeyB.PublicKey, challenge)
  47. sec2 := c.deriveKeys(n1, n2, testKeyB, &testKeyA.PublicKey, challenge)
  48. if sec1 == nil || sec2 == nil {
  49. t.Fatal("key agreement failed")
  50. }
  51. if !reflect.DeepEqual(sec1, sec2) {
  52. t.Fatalf("keys not equal:\n %+v\n %+v", sec1, sec2)
  53. }
  54. }
  55. // This test checks the basic handshake flow where A talks to B and A has no secrets.
  56. func TestHandshakeV5(t *testing.T) {
  57. t.Parallel()
  58. net := newHandshakeTest()
  59. defer net.close()
  60. // A -> B RANDOM PACKET
  61. packet, _ := net.nodeA.encode(t, net.nodeB, &findnodeV5{})
  62. resp := net.nodeB.expectDecode(t, p_unknownV5, packet)
  63. // A <- B WHOAREYOU
  64. challenge := &whoareyouV5{
  65. AuthTag: resp.(*unknownV5).AuthTag,
  66. IDNonce: testIDnonce,
  67. RecordSeq: 0,
  68. }
  69. whoareyou, _ := net.nodeB.encode(t, net.nodeA, challenge)
  70. net.nodeA.expectDecode(t, p_whoareyouV5, whoareyou)
  71. // A -> B FINDNODE
  72. findnode, _ := net.nodeA.encodeWithChallenge(t, net.nodeB, challenge, &findnodeV5{})
  73. net.nodeB.expectDecode(t, p_findnodeV5, findnode)
  74. if len(net.nodeB.c.sc.handshakes) > 0 {
  75. t.Fatalf("node B didn't remove handshake from challenge map")
  76. }
  77. // A <- B NODES
  78. nodes, _ := net.nodeB.encode(t, net.nodeA, &nodesV5{Total: 1})
  79. net.nodeA.expectDecode(t, p_nodesV5, nodes)
  80. }
  81. // This test checks that handshake attempts are removed within the timeout.
  82. func TestHandshakeV5_timeout(t *testing.T) {
  83. t.Parallel()
  84. net := newHandshakeTest()
  85. defer net.close()
  86. // A -> B RANDOM PACKET
  87. packet, _ := net.nodeA.encode(t, net.nodeB, &findnodeV5{})
  88. resp := net.nodeB.expectDecode(t, p_unknownV5, packet)
  89. // A <- B WHOAREYOU
  90. challenge := &whoareyouV5{
  91. AuthTag: resp.(*unknownV5).AuthTag,
  92. IDNonce: testIDnonce,
  93. RecordSeq: 0,
  94. }
  95. whoareyou, _ := net.nodeB.encode(t, net.nodeA, challenge)
  96. net.nodeA.expectDecode(t, p_whoareyouV5, whoareyou)
  97. // A -> B FINDNODE after timeout
  98. net.clock.Run(handshakeTimeout + 1)
  99. findnode, _ := net.nodeA.encodeWithChallenge(t, net.nodeB, challenge, &findnodeV5{})
  100. net.nodeB.expectDecodeErr(t, errUnexpectedHandshake, findnode)
  101. }
  102. // This test checks handshake behavior when no record is sent in the auth response.
  103. func TestHandshakeV5_norecord(t *testing.T) {
  104. t.Parallel()
  105. net := newHandshakeTest()
  106. defer net.close()
  107. // A -> B RANDOM PACKET
  108. packet, _ := net.nodeA.encode(t, net.nodeB, &findnodeV5{})
  109. resp := net.nodeB.expectDecode(t, p_unknownV5, packet)
  110. // A <- B WHOAREYOU
  111. nodeA := net.nodeA.n()
  112. if nodeA.Seq() == 0 {
  113. t.Fatal("need non-zero sequence number")
  114. }
  115. challenge := &whoareyouV5{
  116. AuthTag: resp.(*unknownV5).AuthTag,
  117. IDNonce: testIDnonce,
  118. RecordSeq: nodeA.Seq(),
  119. node: nodeA,
  120. }
  121. whoareyou, _ := net.nodeB.encode(t, net.nodeA, challenge)
  122. net.nodeA.expectDecode(t, p_whoareyouV5, whoareyou)
  123. // A -> B FINDNODE
  124. findnode, _ := net.nodeA.encodeWithChallenge(t, net.nodeB, challenge, &findnodeV5{})
  125. net.nodeB.expectDecode(t, p_findnodeV5, findnode)
  126. // A <- B NODES
  127. nodes, _ := net.nodeB.encode(t, net.nodeA, &nodesV5{Total: 1})
  128. net.nodeA.expectDecode(t, p_nodesV5, nodes)
  129. }
  130. // In this test, A tries to send FINDNODE with existing secrets but B doesn't know
  131. // anything about A.
  132. func TestHandshakeV5_rekey(t *testing.T) {
  133. t.Parallel()
  134. net := newHandshakeTest()
  135. defer net.close()
  136. initKeys := &handshakeSecrets{
  137. readKey: []byte("BBBBBBBBBBBBBBBB"),
  138. writeKey: []byte("AAAAAAAAAAAAAAAA"),
  139. }
  140. net.nodeA.c.sc.storeNewSession(net.nodeB.id(), net.nodeB.addr(), initKeys.readKey, initKeys.writeKey)
  141. // A -> B FINDNODE (encrypted with zero keys)
  142. findnode, authTag := net.nodeA.encode(t, net.nodeB, &findnodeV5{})
  143. net.nodeB.expectDecode(t, p_unknownV5, findnode)
  144. // A <- B WHOAREYOU
  145. challenge := &whoareyouV5{AuthTag: authTag, IDNonce: testIDnonce}
  146. whoareyou, _ := net.nodeB.encode(t, net.nodeA, challenge)
  147. net.nodeA.expectDecode(t, p_whoareyouV5, whoareyou)
  148. // Check that new keys haven't been stored yet.
  149. if s := net.nodeA.c.sc.session(net.nodeB.id(), net.nodeB.addr()); !bytes.Equal(s.writeKey, initKeys.writeKey) || !bytes.Equal(s.readKey, initKeys.readKey) {
  150. t.Fatal("node A stored keys too early")
  151. }
  152. if s := net.nodeB.c.sc.session(net.nodeA.id(), net.nodeA.addr()); s != nil {
  153. t.Fatal("node B stored keys too early")
  154. }
  155. // A -> B FINDNODE encrypted with new keys
  156. findnode, _ = net.nodeA.encodeWithChallenge(t, net.nodeB, challenge, &findnodeV5{})
  157. net.nodeB.expectDecode(t, p_findnodeV5, findnode)
  158. // A <- B NODES
  159. nodes, _ := net.nodeB.encode(t, net.nodeA, &nodesV5{Total: 1})
  160. net.nodeA.expectDecode(t, p_nodesV5, nodes)
  161. }
  162. // In this test A and B have different keys before the handshake.
  163. func TestHandshakeV5_rekey2(t *testing.T) {
  164. t.Parallel()
  165. net := newHandshakeTest()
  166. defer net.close()
  167. initKeysA := &handshakeSecrets{
  168. readKey: []byte("BBBBBBBBBBBBBBBB"),
  169. writeKey: []byte("AAAAAAAAAAAAAAAA"),
  170. }
  171. initKeysB := &handshakeSecrets{
  172. readKey: []byte("CCCCCCCCCCCCCCCC"),
  173. writeKey: []byte("DDDDDDDDDDDDDDDD"),
  174. }
  175. net.nodeA.c.sc.storeNewSession(net.nodeB.id(), net.nodeB.addr(), initKeysA.readKey, initKeysA.writeKey)
  176. net.nodeB.c.sc.storeNewSession(net.nodeA.id(), net.nodeA.addr(), initKeysB.readKey, initKeysA.writeKey)
  177. // A -> B FINDNODE encrypted with initKeysA
  178. findnode, authTag := net.nodeA.encode(t, net.nodeB, &findnodeV5{Distance: 3})
  179. net.nodeB.expectDecode(t, p_unknownV5, findnode)
  180. // A <- B WHOAREYOU
  181. challenge := &whoareyouV5{AuthTag: authTag, IDNonce: testIDnonce}
  182. whoareyou, _ := net.nodeB.encode(t, net.nodeA, challenge)
  183. net.nodeA.expectDecode(t, p_whoareyouV5, whoareyou)
  184. // A -> B FINDNODE encrypted with new keys
  185. findnode, _ = net.nodeA.encodeWithChallenge(t, net.nodeB, challenge, &findnodeV5{})
  186. net.nodeB.expectDecode(t, p_findnodeV5, findnode)
  187. // A <- B NODES
  188. nodes, _ := net.nodeB.encode(t, net.nodeA, &nodesV5{Total: 1})
  189. net.nodeA.expectDecode(t, p_nodesV5, nodes)
  190. }
  191. // This test checks some malformed packets.
  192. func TestDecodeErrorsV5(t *testing.T) {
  193. t.Parallel()
  194. net := newHandshakeTest()
  195. defer net.close()
  196. net.nodeA.expectDecodeErr(t, errTooShort, []byte{})
  197. // TODO some more tests would be nice :)
  198. }
  199. // This benchmark checks performance of authHeader decoding, verification and key derivation.
  200. func BenchmarkV5_DecodeAuthSecp256k1(b *testing.B) {
  201. net := newHandshakeTest()
  202. defer net.close()
  203. var (
  204. idA = net.nodeA.id()
  205. addrA = net.nodeA.addr()
  206. challenge = &whoareyouV5{AuthTag: []byte("authresp"), RecordSeq: 0, node: net.nodeB.n()}
  207. nonce = make([]byte, gcmNonceSize)
  208. )
  209. header, _, _ := net.nodeA.c.makeAuthHeader(nonce, challenge)
  210. challenge.node = nil // force ENR signature verification in decoder
  211. b.ResetTimer()
  212. for i := 0; i < b.N; i++ {
  213. _, _, err := net.nodeB.c.decodeAuthResp(idA, addrA, header, challenge)
  214. if err != nil {
  215. b.Fatal(err)
  216. }
  217. }
  218. }
  219. // This benchmark checks how long it takes to decode an encrypted ping packet.
  220. func BenchmarkV5_DecodePing(b *testing.B) {
  221. net := newHandshakeTest()
  222. defer net.close()
  223. r := []byte{233, 203, 93, 195, 86, 47, 177, 186, 227, 43, 2, 141, 244, 230, 120, 17}
  224. w := []byte{79, 145, 252, 171, 167, 216, 252, 161, 208, 190, 176, 106, 214, 39, 178, 134}
  225. net.nodeA.c.sc.storeNewSession(net.nodeB.id(), net.nodeB.addr(), r, w)
  226. net.nodeB.c.sc.storeNewSession(net.nodeA.id(), net.nodeA.addr(), w, r)
  227. addrB := net.nodeA.addr()
  228. ping := &pingV5{ReqID: []byte("reqid"), ENRSeq: 5}
  229. enc, _, err := net.nodeA.c.encode(net.nodeB.id(), addrB, ping, nil)
  230. if err != nil {
  231. b.Fatalf("can't encode: %v", err)
  232. }
  233. b.ResetTimer()
  234. for i := 0; i < b.N; i++ {
  235. _, _, p, _ := net.nodeB.c.decode(enc, addrB)
  236. if _, ok := p.(*pingV5); !ok {
  237. b.Fatalf("wrong packet type %T", p)
  238. }
  239. }
  240. }
  241. var pp = spew.NewDefaultConfig()
  242. type handshakeTest struct {
  243. nodeA, nodeB handshakeTestNode
  244. clock mclock.Simulated
  245. }
  246. type handshakeTestNode struct {
  247. ln *enode.LocalNode
  248. c *wireCodec
  249. }
  250. func newHandshakeTest() *handshakeTest {
  251. t := new(handshakeTest)
  252. t.nodeA.init(testKeyA, net.IP{127, 0, 0, 1}, &t.clock)
  253. t.nodeB.init(testKeyB, net.IP{127, 0, 0, 1}, &t.clock)
  254. return t
  255. }
  256. func (t *handshakeTest) close() {
  257. t.nodeA.ln.Database().Close()
  258. t.nodeB.ln.Database().Close()
  259. }
  260. func (n *handshakeTestNode) init(key *ecdsa.PrivateKey, ip net.IP, clock mclock.Clock) {
  261. db, _ := enode.OpenDB("")
  262. n.ln = enode.NewLocalNode(db, key)
  263. n.ln.SetStaticIP(ip)
  264. n.c = newWireCodec(n.ln, key, clock)
  265. }
  266. func (n *handshakeTestNode) encode(t testing.TB, to handshakeTestNode, p packetV5) ([]byte, []byte) {
  267. t.Helper()
  268. return n.encodeWithChallenge(t, to, nil, p)
  269. }
  270. func (n *handshakeTestNode) encodeWithChallenge(t testing.TB, to handshakeTestNode, c *whoareyouV5, p packetV5) ([]byte, []byte) {
  271. t.Helper()
  272. // Copy challenge and add destination node. This avoids sharing 'c' among the two codecs.
  273. var challenge *whoareyouV5
  274. if c != nil {
  275. challengeCopy := *c
  276. challenge = &challengeCopy
  277. challenge.node = to.n()
  278. }
  279. // Encode to destination.
  280. enc, authTag, err := n.c.encode(to.id(), to.addr(), p, challenge)
  281. if err != nil {
  282. t.Fatal(fmt.Errorf("(%s) %v", n.ln.ID().TerminalString(), err))
  283. }
  284. t.Logf("(%s) -> (%s) %s\n%s", n.ln.ID().TerminalString(), to.id().TerminalString(), p.name(), hex.Dump(enc))
  285. return enc, authTag
  286. }
  287. func (n *handshakeTestNode) expectDecode(t *testing.T, ptype byte, p []byte) packetV5 {
  288. t.Helper()
  289. dec, err := n.decode(p)
  290. if err != nil {
  291. t.Fatal(fmt.Errorf("(%s) %v", n.ln.ID().TerminalString(), err))
  292. }
  293. t.Logf("(%s) %#v", n.ln.ID().TerminalString(), pp.NewFormatter(dec))
  294. if dec.kind() != ptype {
  295. t.Fatalf("expected packet type %d, got %d", ptype, dec.kind())
  296. }
  297. return dec
  298. }
  299. func (n *handshakeTestNode) expectDecodeErr(t *testing.T, wantErr error, p []byte) {
  300. t.Helper()
  301. if _, err := n.decode(p); !reflect.DeepEqual(err, wantErr) {
  302. t.Fatal(fmt.Errorf("(%s) got err %q, want %q", n.ln.ID().TerminalString(), err, wantErr))
  303. }
  304. }
  305. func (n *handshakeTestNode) decode(input []byte) (packetV5, error) {
  306. _, _, p, err := n.c.decode(input, "127.0.0.1")
  307. return p, err
  308. }
  309. func (n *handshakeTestNode) n() *enode.Node {
  310. return n.ln.Node()
  311. }
  312. func (n *handshakeTestNode) addr() string {
  313. return n.ln.Node().IP().String()
  314. }
  315. func (n *handshakeTestNode) id() enode.ID {
  316. return n.ln.ID()
  317. }