v4_udp.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  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. "container/list"
  20. "context"
  21. "crypto/ecdsa"
  22. crand "crypto/rand"
  23. "errors"
  24. "fmt"
  25. "io"
  26. "net"
  27. "sync"
  28. "time"
  29. "github.com/ethereum/go-ethereum/crypto"
  30. "github.com/ethereum/go-ethereum/log"
  31. "github.com/ethereum/go-ethereum/p2p/discover/v4wire"
  32. "github.com/ethereum/go-ethereum/p2p/enode"
  33. "github.com/ethereum/go-ethereum/p2p/netutil"
  34. "github.com/ethereum/go-ethereum/rlp"
  35. )
  36. // Errors
  37. var (
  38. errExpired = errors.New("expired")
  39. errUnsolicitedReply = errors.New("unsolicited reply")
  40. errUnknownNode = errors.New("unknown node")
  41. errTimeout = errors.New("RPC timeout")
  42. errClockWarp = errors.New("reply deadline too far in the future")
  43. errClosed = errors.New("socket closed")
  44. errLowPort = errors.New("low port")
  45. )
  46. const (
  47. respTimeout = 500 * time.Millisecond
  48. expiration = 20 * time.Second
  49. bondExpiration = 24 * time.Hour
  50. maxFindnodeFailures = 5 // nodes exceeding this limit are dropped
  51. ntpFailureThreshold = 32 // Continuous timeouts after which to check NTP
  52. ntpWarningCooldown = 10 * time.Minute // Minimum amount of time to pass before repeating NTP warning
  53. driftThreshold = 10 * time.Second // Allowed clock drift before warning user
  54. // Discovery packets are defined to be no larger than 1280 bytes.
  55. // Packets larger than this size will be cut at the end and treated
  56. // as invalid because their hash won't match.
  57. maxPacketSize = 1280
  58. )
  59. // UDPv4 implements the v4 wire protocol.
  60. type UDPv4 struct {
  61. conn UDPConn
  62. log log.Logger
  63. netrestrict *netutil.Netlist
  64. priv *ecdsa.PrivateKey
  65. localNode *enode.LocalNode
  66. db *enode.DB
  67. tab *Table
  68. closeOnce sync.Once
  69. wg sync.WaitGroup
  70. addReplyMatcher chan *replyMatcher
  71. gotreply chan reply
  72. closeCtx context.Context
  73. cancelCloseCtx context.CancelFunc
  74. }
  75. // replyMatcher represents a pending reply.
  76. //
  77. // Some implementations of the protocol wish to send more than one
  78. // reply packet to findnode. In general, any neighbors packet cannot
  79. // be matched up with a specific findnode packet.
  80. //
  81. // Our implementation handles this by storing a callback function for
  82. // each pending reply. Incoming packets from a node are dispatched
  83. // to all callback functions for that node.
  84. type replyMatcher struct {
  85. // these fields must match in the reply.
  86. from enode.ID
  87. ip net.IP
  88. ptype byte
  89. // time when the request must complete
  90. deadline time.Time
  91. // callback is called when a matching reply arrives. If it returns matched == true, the
  92. // reply was acceptable. The second return value indicates whether the callback should
  93. // be removed from the pending reply queue. If it returns false, the reply is considered
  94. // incomplete and the callback will be invoked again for the next matching reply.
  95. callback replyMatchFunc
  96. // errc receives nil when the callback indicates completion or an
  97. // error if no further reply is received within the timeout.
  98. errc chan error
  99. // reply contains the most recent reply. This field is safe for reading after errc has
  100. // received a value.
  101. reply v4wire.Packet
  102. }
  103. type replyMatchFunc func(v4wire.Packet) (matched bool, requestDone bool)
  104. // reply is a reply packet from a certain node.
  105. type reply struct {
  106. from enode.ID
  107. ip net.IP
  108. data v4wire.Packet
  109. // loop indicates whether there was
  110. // a matching request by sending on this channel.
  111. matched chan<- bool
  112. }
  113. func ListenV4(c UDPConn, ln *enode.LocalNode, cfg Config) (*UDPv4, error) {
  114. cfg = cfg.withDefaults()
  115. closeCtx, cancel := context.WithCancel(context.Background())
  116. t := &UDPv4{
  117. conn: c,
  118. priv: cfg.PrivateKey,
  119. netrestrict: cfg.NetRestrict,
  120. localNode: ln,
  121. db: ln.Database(),
  122. gotreply: make(chan reply),
  123. addReplyMatcher: make(chan *replyMatcher),
  124. closeCtx: closeCtx,
  125. cancelCloseCtx: cancel,
  126. log: cfg.Log,
  127. }
  128. tab, err := newTable(t, ln.Database(), cfg.Bootnodes, t.log)
  129. if err != nil {
  130. return nil, err
  131. }
  132. t.tab = tab
  133. go tab.loop()
  134. t.wg.Add(2)
  135. go t.loop()
  136. go t.readLoop(cfg.Unhandled)
  137. return t, nil
  138. }
  139. // Self returns the local node.
  140. func (t *UDPv4) Self() *enode.Node {
  141. return t.localNode.Node()
  142. }
  143. // Close shuts down the socket and aborts any running queries.
  144. func (t *UDPv4) Close() {
  145. t.closeOnce.Do(func() {
  146. t.cancelCloseCtx()
  147. t.conn.Close()
  148. t.wg.Wait()
  149. t.tab.close()
  150. })
  151. }
  152. // Resolve searches for a specific node with the given ID and tries to get the most recent
  153. // version of the node record for it. It returns n if the node could not be resolved.
  154. func (t *UDPv4) Resolve(n *enode.Node) *enode.Node {
  155. // Try asking directly. This works if the node is still responding on the endpoint we have.
  156. if rn, err := t.RequestENR(n); err == nil {
  157. return rn
  158. }
  159. // Check table for the ID, we might have a newer version there.
  160. if intable := t.tab.getNode(n.ID()); intable != nil && intable.Seq() > n.Seq() {
  161. n = intable
  162. if rn, err := t.RequestENR(n); err == nil {
  163. return rn
  164. }
  165. }
  166. // Otherwise perform a network lookup.
  167. var key enode.Secp256k1
  168. if n.Load(&key) != nil {
  169. return n // no secp256k1 key
  170. }
  171. result := t.LookupPubkey((*ecdsa.PublicKey)(&key))
  172. for _, rn := range result {
  173. if rn.ID() == n.ID() {
  174. if rn, err := t.RequestENR(rn); err == nil {
  175. return rn
  176. }
  177. }
  178. }
  179. return n
  180. }
  181. func (t *UDPv4) ourEndpoint() v4wire.Endpoint {
  182. n := t.Self()
  183. a := &net.UDPAddr{IP: n.IP(), Port: n.UDP()}
  184. return v4wire.NewEndpoint(a, uint16(n.TCP()))
  185. }
  186. // Ping sends a ping message to the given node.
  187. func (t *UDPv4) Ping(n *enode.Node) error {
  188. _, err := t.ping(n)
  189. return err
  190. }
  191. // ping sends a ping message to the given node and waits for a reply.
  192. func (t *UDPv4) ping(n *enode.Node) (seq uint64, err error) {
  193. rm := t.sendPing(n.ID(), &net.UDPAddr{IP: n.IP(), Port: n.UDP()}, nil)
  194. if err = <-rm.errc; err == nil {
  195. seq = rm.reply.(*v4wire.Pong).ENRSeq()
  196. }
  197. return seq, err
  198. }
  199. // sendPing sends a ping message to the given node and invokes the callback
  200. // when the reply arrives.
  201. func (t *UDPv4) sendPing(toid enode.ID, toaddr *net.UDPAddr, callback func()) *replyMatcher {
  202. req := t.makePing(toaddr)
  203. packet, hash, err := v4wire.Encode(t.priv, req)
  204. if err != nil {
  205. errc := make(chan error, 1)
  206. errc <- err
  207. return &replyMatcher{errc: errc}
  208. }
  209. // Add a matcher for the reply to the pending reply queue. Pongs are matched if they
  210. // reference the ping we're about to send.
  211. rm := t.pending(toid, toaddr.IP, v4wire.PongPacket, func(p v4wire.Packet) (matched bool, requestDone bool) {
  212. matched = bytes.Equal(p.(*v4wire.Pong).ReplyTok, hash)
  213. if matched && callback != nil {
  214. callback()
  215. }
  216. return matched, matched
  217. })
  218. // Send the packet.
  219. t.localNode.UDPContact(toaddr)
  220. t.write(toaddr, toid, req.Name(), packet)
  221. return rm
  222. }
  223. func (t *UDPv4) makePing(toaddr *net.UDPAddr) *v4wire.Ping {
  224. seq, _ := rlp.EncodeToBytes(t.localNode.Node().Seq())
  225. return &v4wire.Ping{
  226. Version: 4,
  227. From: t.ourEndpoint(),
  228. To: v4wire.NewEndpoint(toaddr, 0),
  229. Expiration: uint64(time.Now().Add(expiration).Unix()),
  230. Rest: []rlp.RawValue{seq},
  231. }
  232. }
  233. // LookupPubkey finds the closest nodes to the given public key.
  234. func (t *UDPv4) LookupPubkey(key *ecdsa.PublicKey) []*enode.Node {
  235. if t.tab.len() == 0 {
  236. // All nodes were dropped, refresh. The very first query will hit this
  237. // case and run the bootstrapping logic.
  238. <-t.tab.refresh()
  239. }
  240. return t.newLookup(t.closeCtx, encodePubkey(key)).run()
  241. }
  242. // RandomNodes is an iterator yielding nodes from a random walk of the DHT.
  243. func (t *UDPv4) RandomNodes() enode.Iterator {
  244. return newLookupIterator(t.closeCtx, t.newRandomLookup)
  245. }
  246. // lookupRandom implements transport.
  247. func (t *UDPv4) lookupRandom() []*enode.Node {
  248. return t.newRandomLookup(t.closeCtx).run()
  249. }
  250. // lookupSelf implements transport.
  251. func (t *UDPv4) lookupSelf() []*enode.Node {
  252. return t.newLookup(t.closeCtx, encodePubkey(&t.priv.PublicKey)).run()
  253. }
  254. func (t *UDPv4) newRandomLookup(ctx context.Context) *lookup {
  255. var target encPubkey
  256. crand.Read(target[:])
  257. return t.newLookup(ctx, target)
  258. }
  259. func (t *UDPv4) newLookup(ctx context.Context, targetKey encPubkey) *lookup {
  260. target := enode.ID(crypto.Keccak256Hash(targetKey[:]))
  261. ekey := v4wire.Pubkey(targetKey)
  262. it := newLookup(ctx, t.tab, target, func(n *node) ([]*node, error) {
  263. return t.findnode(n.ID(), n.addr(), ekey)
  264. })
  265. return it
  266. }
  267. // findnode sends a findnode request to the given node and waits until
  268. // the node has sent up to k neighbors.
  269. func (t *UDPv4) findnode(toid enode.ID, toaddr *net.UDPAddr, target v4wire.Pubkey) ([]*node, error) {
  270. t.ensureBond(toid, toaddr)
  271. // Add a matcher for 'neighbours' replies to the pending reply queue. The matcher is
  272. // active until enough nodes have been received.
  273. nodes := make([]*node, 0, bucketSize)
  274. nreceived := 0
  275. rm := t.pending(toid, toaddr.IP, v4wire.NeighborsPacket, func(r v4wire.Packet) (matched bool, requestDone bool) {
  276. reply := r.(*v4wire.Neighbors)
  277. for _, rn := range reply.Nodes {
  278. nreceived++
  279. n, err := t.nodeFromRPC(toaddr, rn)
  280. if err != nil {
  281. t.log.Trace("Invalid neighbor node received", "ip", rn.IP, "addr", toaddr, "err", err)
  282. continue
  283. }
  284. nodes = append(nodes, n)
  285. }
  286. return true, nreceived >= bucketSize
  287. })
  288. t.send(toaddr, toid, &v4wire.Findnode{
  289. Target: target,
  290. Expiration: uint64(time.Now().Add(expiration).Unix()),
  291. })
  292. // Ensure that callers don't see a timeout if the node actually responded. Since
  293. // findnode can receive more than one neighbors response, the reply matcher will be
  294. // active until the remote node sends enough nodes. If the remote end doesn't have
  295. // enough nodes the reply matcher will time out waiting for the second reply, but
  296. // there's no need for an error in that case.
  297. err := <-rm.errc
  298. if err == errTimeout && rm.reply != nil {
  299. err = nil
  300. }
  301. return nodes, err
  302. }
  303. // RequestENR sends enrRequest to the given node and waits for a response.
  304. func (t *UDPv4) RequestENR(n *enode.Node) (*enode.Node, error) {
  305. addr := &net.UDPAddr{IP: n.IP(), Port: n.UDP()}
  306. t.ensureBond(n.ID(), addr)
  307. req := &v4wire.ENRRequest{
  308. Expiration: uint64(time.Now().Add(expiration).Unix()),
  309. }
  310. packet, hash, err := v4wire.Encode(t.priv, req)
  311. if err != nil {
  312. return nil, err
  313. }
  314. // Add a matcher for the reply to the pending reply queue. Responses are matched if
  315. // they reference the request we're about to send.
  316. rm := t.pending(n.ID(), addr.IP, v4wire.ENRResponsePacket, func(r v4wire.Packet) (matched bool, requestDone bool) {
  317. matched = bytes.Equal(r.(*v4wire.ENRResponse).ReplyTok, hash)
  318. return matched, matched
  319. })
  320. // Send the packet and wait for the reply.
  321. t.write(addr, n.ID(), req.Name(), packet)
  322. if err := <-rm.errc; err != nil {
  323. return nil, err
  324. }
  325. // Verify the response record.
  326. respN, err := enode.New(enode.ValidSchemes, &rm.reply.(*v4wire.ENRResponse).Record)
  327. if err != nil {
  328. return nil, err
  329. }
  330. if respN.ID() != n.ID() {
  331. return nil, fmt.Errorf("invalid ID in response record")
  332. }
  333. if respN.Seq() < n.Seq() {
  334. return n, nil // response record is older
  335. }
  336. if err := netutil.CheckRelayIP(addr.IP, respN.IP()); err != nil {
  337. return nil, fmt.Errorf("invalid IP in response record: %v", err)
  338. }
  339. return respN, nil
  340. }
  341. // pending adds a reply matcher to the pending reply queue.
  342. // see the documentation of type replyMatcher for a detailed explanation.
  343. func (t *UDPv4) pending(id enode.ID, ip net.IP, ptype byte, callback replyMatchFunc) *replyMatcher {
  344. ch := make(chan error, 1)
  345. p := &replyMatcher{from: id, ip: ip, ptype: ptype, callback: callback, errc: ch}
  346. select {
  347. case t.addReplyMatcher <- p:
  348. // loop will handle it
  349. case <-t.closeCtx.Done():
  350. ch <- errClosed
  351. }
  352. return p
  353. }
  354. // handleReply dispatches a reply packet, invoking reply matchers. It returns
  355. // whether any matcher considered the packet acceptable.
  356. func (t *UDPv4) handleReply(from enode.ID, fromIP net.IP, req v4wire.Packet) bool {
  357. matched := make(chan bool, 1)
  358. select {
  359. case t.gotreply <- reply{from, fromIP, req, matched}:
  360. // loop will handle it
  361. return <-matched
  362. case <-t.closeCtx.Done():
  363. return false
  364. }
  365. }
  366. // loop runs in its own goroutine. it keeps track of
  367. // the refresh timer and the pending reply queue.
  368. func (t *UDPv4) loop() {
  369. defer t.wg.Done()
  370. var (
  371. plist = list.New()
  372. timeout = time.NewTimer(0)
  373. nextTimeout *replyMatcher // head of plist when timeout was last reset
  374. contTimeouts = 0 // number of continuous timeouts to do NTP checks
  375. ntpWarnTime = time.Unix(0, 0)
  376. )
  377. <-timeout.C // ignore first timeout
  378. defer timeout.Stop()
  379. resetTimeout := func() {
  380. if plist.Front() == nil || nextTimeout == plist.Front().Value {
  381. return
  382. }
  383. // Start the timer so it fires when the next pending reply has expired.
  384. now := time.Now()
  385. for el := plist.Front(); el != nil; el = el.Next() {
  386. nextTimeout = el.Value.(*replyMatcher)
  387. if dist := nextTimeout.deadline.Sub(now); dist < 2*respTimeout {
  388. timeout.Reset(dist)
  389. return
  390. }
  391. // Remove pending replies whose deadline is too far in the
  392. // future. These can occur if the system clock jumped
  393. // backwards after the deadline was assigned.
  394. nextTimeout.errc <- errClockWarp
  395. plist.Remove(el)
  396. }
  397. nextTimeout = nil
  398. timeout.Stop()
  399. }
  400. for {
  401. resetTimeout()
  402. select {
  403. case <-t.closeCtx.Done():
  404. for el := plist.Front(); el != nil; el = el.Next() {
  405. el.Value.(*replyMatcher).errc <- errClosed
  406. }
  407. return
  408. case p := <-t.addReplyMatcher:
  409. p.deadline = time.Now().Add(respTimeout)
  410. plist.PushBack(p)
  411. case r := <-t.gotreply:
  412. var matched bool // whether any replyMatcher considered the reply acceptable.
  413. for el := plist.Front(); el != nil; el = el.Next() {
  414. p := el.Value.(*replyMatcher)
  415. if p.from == r.from && p.ptype == r.data.Kind() && p.ip.Equal(r.ip) {
  416. ok, requestDone := p.callback(r.data)
  417. matched = matched || ok
  418. p.reply = r.data
  419. // Remove the matcher if callback indicates that all replies have been received.
  420. if requestDone {
  421. p.errc <- nil
  422. plist.Remove(el)
  423. }
  424. // Reset the continuous timeout counter (time drift detection)
  425. contTimeouts = 0
  426. }
  427. }
  428. r.matched <- matched
  429. case now := <-timeout.C:
  430. nextTimeout = nil
  431. // Notify and remove callbacks whose deadline is in the past.
  432. for el := plist.Front(); el != nil; el = el.Next() {
  433. p := el.Value.(*replyMatcher)
  434. if now.After(p.deadline) || now.Equal(p.deadline) {
  435. p.errc <- errTimeout
  436. plist.Remove(el)
  437. contTimeouts++
  438. }
  439. }
  440. // If we've accumulated too many timeouts, do an NTP time sync check
  441. if contTimeouts > ntpFailureThreshold {
  442. if time.Since(ntpWarnTime) >= ntpWarningCooldown {
  443. ntpWarnTime = time.Now()
  444. go checkClockDrift()
  445. }
  446. contTimeouts = 0
  447. }
  448. }
  449. }
  450. }
  451. func (t *UDPv4) send(toaddr *net.UDPAddr, toid enode.ID, req v4wire.Packet) ([]byte, error) {
  452. packet, hash, err := v4wire.Encode(t.priv, req)
  453. if err != nil {
  454. return hash, err
  455. }
  456. return hash, t.write(toaddr, toid, req.Name(), packet)
  457. }
  458. func (t *UDPv4) write(toaddr *net.UDPAddr, toid enode.ID, what string, packet []byte) error {
  459. _, err := t.conn.WriteToUDP(packet, toaddr)
  460. t.log.Trace(">> "+what, "id", toid, "addr", toaddr, "err", err)
  461. return err
  462. }
  463. // readLoop runs in its own goroutine. it handles incoming UDP packets.
  464. func (t *UDPv4) readLoop(unhandled chan<- ReadPacket) {
  465. defer t.wg.Done()
  466. if unhandled != nil {
  467. defer close(unhandled)
  468. }
  469. buf := make([]byte, maxPacketSize)
  470. for {
  471. nbytes, from, err := t.conn.ReadFromUDP(buf)
  472. if netutil.IsTemporaryError(err) {
  473. // Ignore temporary read errors.
  474. t.log.Debug("Temporary UDP read error", "err", err)
  475. continue
  476. } else if err != nil {
  477. // Shut down the loop for permament errors.
  478. if err != io.EOF {
  479. t.log.Debug("UDP read error", "err", err)
  480. }
  481. return
  482. }
  483. if t.handlePacket(from, buf[:nbytes]) != nil && unhandled != nil {
  484. select {
  485. case unhandled <- ReadPacket{buf[:nbytes], from}:
  486. default:
  487. }
  488. }
  489. }
  490. }
  491. func (t *UDPv4) handlePacket(from *net.UDPAddr, buf []byte) error {
  492. rawpacket, fromKey, hash, err := v4wire.Decode(buf)
  493. if err != nil {
  494. t.log.Debug("Bad discv4 packet", "addr", from, "err", err)
  495. return err
  496. }
  497. packet := t.wrapPacket(rawpacket)
  498. fromID := fromKey.ID()
  499. if err == nil && packet.preverify != nil {
  500. err = packet.preverify(packet, from, fromID, fromKey)
  501. }
  502. t.log.Trace("<< "+packet.Name(), "id", fromID, "addr", from, "err", err)
  503. if err == nil && packet.handle != nil {
  504. packet.handle(packet, from, fromID, hash)
  505. }
  506. return err
  507. }
  508. // checkBond checks if the given node has a recent enough endpoint proof.
  509. func (t *UDPv4) checkBond(id enode.ID, ip net.IP) bool {
  510. return time.Since(t.db.LastPongReceived(id, ip)) < bondExpiration
  511. }
  512. // ensureBond solicits a ping from a node if we haven't seen a ping from it for a while.
  513. // This ensures there is a valid endpoint proof on the remote end.
  514. func (t *UDPv4) ensureBond(toid enode.ID, toaddr *net.UDPAddr) {
  515. tooOld := time.Since(t.db.LastPingReceived(toid, toaddr.IP)) > bondExpiration
  516. if tooOld || t.db.FindFails(toid, toaddr.IP) > maxFindnodeFailures {
  517. rm := t.sendPing(toid, toaddr, nil)
  518. <-rm.errc
  519. // Wait for them to ping back and process our pong.
  520. time.Sleep(respTimeout)
  521. }
  522. }
  523. func (t *UDPv4) nodeFromRPC(sender *net.UDPAddr, rn v4wire.Node) (*node, error) {
  524. if rn.UDP <= 1024 {
  525. return nil, errLowPort
  526. }
  527. if err := netutil.CheckRelayIP(sender.IP, rn.IP); err != nil {
  528. return nil, err
  529. }
  530. if t.netrestrict != nil && !t.netrestrict.Contains(rn.IP) {
  531. return nil, errors.New("not contained in netrestrict whitelist")
  532. }
  533. key, err := v4wire.DecodePubkey(crypto.S256(), rn.ID)
  534. if err != nil {
  535. return nil, err
  536. }
  537. n := wrapNode(enode.NewV4(key, rn.IP, int(rn.TCP), int(rn.UDP)))
  538. err = n.ValidateComplete()
  539. return n, err
  540. }
  541. func nodeToRPC(n *node) v4wire.Node {
  542. var key ecdsa.PublicKey
  543. var ekey v4wire.Pubkey
  544. if err := n.Load((*enode.Secp256k1)(&key)); err == nil {
  545. ekey = v4wire.EncodePubkey(&key)
  546. }
  547. return v4wire.Node{ID: ekey, IP: n.IP(), UDP: uint16(n.UDP()), TCP: uint16(n.TCP())}
  548. }
  549. // wrapPacket returns the handler functions applicable to a packet.
  550. func (t *UDPv4) wrapPacket(p v4wire.Packet) *packetHandlerV4 {
  551. var h packetHandlerV4
  552. h.Packet = p
  553. switch p.(type) {
  554. case *v4wire.Ping:
  555. h.preverify = t.verifyPing
  556. h.handle = t.handlePing
  557. case *v4wire.Pong:
  558. h.preverify = t.verifyPong
  559. case *v4wire.Findnode:
  560. h.preverify = t.verifyFindnode
  561. h.handle = t.handleFindnode
  562. case *v4wire.Neighbors:
  563. h.preverify = t.verifyNeighbors
  564. case *v4wire.ENRRequest:
  565. h.preverify = t.verifyENRRequest
  566. h.handle = t.handleENRRequest
  567. case *v4wire.ENRResponse:
  568. h.preverify = t.verifyENRResponse
  569. }
  570. return &h
  571. }
  572. // packetHandlerV4 wraps a packet with handler functions.
  573. type packetHandlerV4 struct {
  574. v4wire.Packet
  575. senderKey *ecdsa.PublicKey // used for ping
  576. // preverify checks whether the packet is valid and should be handled at all.
  577. preverify func(p *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, fromKey v4wire.Pubkey) error
  578. // handle handles the packet.
  579. handle func(req *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, mac []byte)
  580. }
  581. // PING/v4
  582. func (t *UDPv4) verifyPing(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, fromKey v4wire.Pubkey) error {
  583. req := h.Packet.(*v4wire.Ping)
  584. senderKey, err := v4wire.DecodePubkey(crypto.S256(), fromKey)
  585. if err != nil {
  586. return err
  587. }
  588. if v4wire.Expired(req.Expiration) {
  589. return errExpired
  590. }
  591. h.senderKey = senderKey
  592. return nil
  593. }
  594. func (t *UDPv4) handlePing(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
  595. req := h.Packet.(*v4wire.Ping)
  596. // Reply.
  597. seq, _ := rlp.EncodeToBytes(t.localNode.Node().Seq())
  598. t.send(from, fromID, &v4wire.Pong{
  599. To: v4wire.NewEndpoint(from, req.From.TCP),
  600. ReplyTok: mac,
  601. Expiration: uint64(time.Now().Add(expiration).Unix()),
  602. Rest: []rlp.RawValue{seq},
  603. })
  604. // Ping back if our last pong on file is too far in the past.
  605. n := wrapNode(enode.NewV4(h.senderKey, from.IP, int(req.From.TCP), from.Port))
  606. if time.Since(t.db.LastPongReceived(n.ID(), from.IP)) > bondExpiration {
  607. t.sendPing(fromID, from, func() {
  608. t.tab.addVerifiedNode(n)
  609. })
  610. } else {
  611. t.tab.addVerifiedNode(n)
  612. }
  613. // Update node database and endpoint predictor.
  614. t.db.UpdateLastPingReceived(n.ID(), from.IP, time.Now())
  615. t.localNode.UDPEndpointStatement(from, &net.UDPAddr{IP: req.To.IP, Port: int(req.To.UDP)})
  616. }
  617. // PONG/v4
  618. func (t *UDPv4) verifyPong(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, fromKey v4wire.Pubkey) error {
  619. req := h.Packet.(*v4wire.Pong)
  620. if v4wire.Expired(req.Expiration) {
  621. return errExpired
  622. }
  623. if !t.handleReply(fromID, from.IP, req) {
  624. return errUnsolicitedReply
  625. }
  626. t.localNode.UDPEndpointStatement(from, &net.UDPAddr{IP: req.To.IP, Port: int(req.To.UDP)})
  627. t.db.UpdateLastPongReceived(fromID, from.IP, time.Now())
  628. return nil
  629. }
  630. // FINDNODE/v4
  631. func (t *UDPv4) verifyFindnode(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, fromKey v4wire.Pubkey) error {
  632. req := h.Packet.(*v4wire.Findnode)
  633. if v4wire.Expired(req.Expiration) {
  634. return errExpired
  635. }
  636. if !t.checkBond(fromID, from.IP) {
  637. // No endpoint proof pong exists, we don't process the packet. This prevents an
  638. // attack vector where the discovery protocol could be used to amplify traffic in a
  639. // DDOS attack. A malicious actor would send a findnode request with the IP address
  640. // and UDP port of the target as the source address. The recipient of the findnode
  641. // packet would then send a neighbors packet (which is a much bigger packet than
  642. // findnode) to the victim.
  643. return errUnknownNode
  644. }
  645. return nil
  646. }
  647. func (t *UDPv4) handleFindnode(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
  648. req := h.Packet.(*v4wire.Findnode)
  649. // Determine closest nodes.
  650. target := enode.ID(crypto.Keccak256Hash(req.Target[:]))
  651. closest := t.tab.findnodeByID(target, bucketSize, true).entries
  652. // Send neighbors in chunks with at most maxNeighbors per packet
  653. // to stay below the packet size limit.
  654. p := v4wire.Neighbors{Expiration: uint64(time.Now().Add(expiration).Unix())}
  655. var sent bool
  656. for _, n := range closest {
  657. if netutil.CheckRelayIP(from.IP, n.IP()) == nil {
  658. p.Nodes = append(p.Nodes, nodeToRPC(n))
  659. }
  660. if len(p.Nodes) == v4wire.MaxNeighbors {
  661. t.send(from, fromID, &p)
  662. p.Nodes = p.Nodes[:0]
  663. sent = true
  664. }
  665. }
  666. if len(p.Nodes) > 0 || !sent {
  667. t.send(from, fromID, &p)
  668. }
  669. }
  670. // NEIGHBORS/v4
  671. func (t *UDPv4) verifyNeighbors(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, fromKey v4wire.Pubkey) error {
  672. req := h.Packet.(*v4wire.Neighbors)
  673. if v4wire.Expired(req.Expiration) {
  674. return errExpired
  675. }
  676. if !t.handleReply(fromID, from.IP, h.Packet) {
  677. return errUnsolicitedReply
  678. }
  679. return nil
  680. }
  681. // ENRREQUEST/v4
  682. func (t *UDPv4) verifyENRRequest(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, fromKey v4wire.Pubkey) error {
  683. req := h.Packet.(*v4wire.ENRRequest)
  684. if v4wire.Expired(req.Expiration) {
  685. return errExpired
  686. }
  687. if !t.checkBond(fromID, from.IP) {
  688. return errUnknownNode
  689. }
  690. return nil
  691. }
  692. func (t *UDPv4) handleENRRequest(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, mac []byte) {
  693. t.send(from, fromID, &v4wire.ENRResponse{
  694. ReplyTok: mac,
  695. Record: *t.localNode.Node().Record(),
  696. })
  697. }
  698. // ENRRESPONSE/v4
  699. func (t *UDPv4) verifyENRResponse(h *packetHandlerV4, from *net.UDPAddr, fromID enode.ID, fromKey v4wire.Pubkey) error {
  700. if !t.handleReply(fromID, from.IP, h.Packet) {
  701. return errUnsolicitedReply
  702. }
  703. return nil
  704. }