encoding.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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 v5wire
  17. import (
  18. "bytes"
  19. "crypto/aes"
  20. "crypto/cipher"
  21. "crypto/ecdsa"
  22. crand "crypto/rand"
  23. "crypto/sha256"
  24. "encoding/binary"
  25. "errors"
  26. "fmt"
  27. "hash"
  28. "github.com/ethereum/go-ethereum/common/mclock"
  29. "github.com/ethereum/go-ethereum/p2p/enode"
  30. "github.com/ethereum/go-ethereum/p2p/enr"
  31. "github.com/ethereum/go-ethereum/rlp"
  32. )
  33. // TODO concurrent WHOAREYOU tie-breaker
  34. // TODO rehandshake after X packets
  35. // Header represents a packet header.
  36. type Header struct {
  37. IV [sizeofMaskingIV]byte
  38. StaticHeader
  39. AuthData []byte
  40. src enode.ID // used by decoder
  41. }
  42. // StaticHeader contains the static fields of a packet header.
  43. type StaticHeader struct {
  44. ProtocolID [6]byte
  45. Version uint16
  46. Flag byte
  47. Nonce Nonce
  48. AuthSize uint16
  49. }
  50. // Authdata layouts.
  51. type (
  52. whoareyouAuthData struct {
  53. IDNonce [16]byte // ID proof data
  54. RecordSeq uint64 // highest known ENR sequence of requester
  55. }
  56. handshakeAuthData struct {
  57. h struct {
  58. SrcID enode.ID
  59. SigSize byte // ignature data
  60. PubkeySize byte // offset of
  61. }
  62. // Trailing variable-size data.
  63. signature, pubkey, record []byte
  64. }
  65. messageAuthData struct {
  66. SrcID enode.ID
  67. }
  68. )
  69. // Packet header flag values.
  70. const (
  71. flagMessage = iota
  72. flagWhoareyou
  73. flagHandshake
  74. )
  75. // Protocol constants.
  76. const (
  77. version = 1
  78. minVersion = 1
  79. sizeofMaskingIV = 16
  80. minMessageSize = 48 // this refers to data after static headers
  81. randomPacketMsgSize = 20
  82. )
  83. var protocolID = [6]byte{'d', 'i', 's', 'c', 'v', '5'}
  84. // Errors.
  85. var (
  86. errTooShort = errors.New("packet too short")
  87. errInvalidHeader = errors.New("invalid packet header")
  88. errInvalidFlag = errors.New("invalid flag value in header")
  89. errMinVersion = errors.New("version of packet header below minimum")
  90. errMsgTooShort = errors.New("message/handshake packet below minimum size")
  91. errAuthSize = errors.New("declared auth size is beyond packet length")
  92. errUnexpectedHandshake = errors.New("unexpected auth response, not in handshake")
  93. errInvalidAuthKey = errors.New("invalid ephemeral pubkey")
  94. errNoRecord = errors.New("expected ENR in handshake but none sent")
  95. errInvalidNonceSig = errors.New("invalid ID nonce signature")
  96. errMessageTooShort = errors.New("message contains no data")
  97. errMessageDecrypt = errors.New("cannot decrypt message")
  98. )
  99. // Public errors.
  100. var (
  101. ErrInvalidReqID = errors.New("request ID larger than 8 bytes")
  102. )
  103. // Packet sizes.
  104. var (
  105. sizeofStaticHeader = binary.Size(StaticHeader{})
  106. sizeofWhoareyouAuthData = binary.Size(whoareyouAuthData{})
  107. sizeofHandshakeAuthData = binary.Size(handshakeAuthData{}.h)
  108. sizeofMessageAuthData = binary.Size(messageAuthData{})
  109. sizeofStaticPacketData = sizeofMaskingIV + sizeofStaticHeader
  110. )
  111. // Codec encodes and decodes Discovery v5 packets.
  112. // This type is not safe for concurrent use.
  113. type Codec struct {
  114. sha256 hash.Hash
  115. localnode *enode.LocalNode
  116. privkey *ecdsa.PrivateKey
  117. sc *SessionCache
  118. // encoder buffers
  119. buf bytes.Buffer // whole packet
  120. headbuf bytes.Buffer // packet header
  121. msgbuf bytes.Buffer // message RLP plaintext
  122. msgctbuf []byte // message data ciphertext
  123. // decoder buffer
  124. reader bytes.Reader
  125. }
  126. // NewCodec creates a wire codec.
  127. func NewCodec(ln *enode.LocalNode, key *ecdsa.PrivateKey, clock mclock.Clock) *Codec {
  128. c := &Codec{
  129. sha256: sha256.New(),
  130. localnode: ln,
  131. privkey: key,
  132. sc: NewSessionCache(1024, clock),
  133. }
  134. return c
  135. }
  136. // Encode encodes a packet to a node. 'id' and 'addr' specify the destination node. The
  137. // 'challenge' parameter should be the most recently received WHOAREYOU packet from that
  138. // node.
  139. func (c *Codec) Encode(id enode.ID, addr string, packet Packet, challenge *Whoareyou) ([]byte, Nonce, error) {
  140. // Create the packet header.
  141. var (
  142. head Header
  143. session *session
  144. msgData []byte
  145. err error
  146. )
  147. switch {
  148. case packet.Kind() == WhoareyouPacket:
  149. head, err = c.encodeWhoareyou(id, packet.(*Whoareyou))
  150. case challenge != nil:
  151. // We have an unanswered challenge, send handshake.
  152. head, session, err = c.encodeHandshakeHeader(id, addr, challenge)
  153. default:
  154. session = c.sc.session(id, addr)
  155. if session != nil {
  156. // There is a session, use it.
  157. head, err = c.encodeMessageHeader(id, session)
  158. } else {
  159. // No keys, send random data to kick off the handshake.
  160. head, msgData, err = c.encodeRandom(id)
  161. }
  162. }
  163. if err != nil {
  164. return nil, Nonce{}, err
  165. }
  166. // Generate masking IV.
  167. if err := c.sc.maskingIVGen(head.IV[:]); err != nil {
  168. return nil, Nonce{}, fmt.Errorf("can't generate masking IV: %v", err)
  169. }
  170. // Encode header data.
  171. c.writeHeaders(&head)
  172. // Store sent WHOAREYOU challenges.
  173. if challenge, ok := packet.(*Whoareyou); ok {
  174. challenge.ChallengeData = bytesCopy(&c.buf)
  175. c.sc.storeSentHandshake(id, addr, challenge)
  176. } else if msgData == nil {
  177. headerData := c.buf.Bytes()
  178. msgData, err = c.encryptMessage(session, packet, &head, headerData)
  179. if err != nil {
  180. return nil, Nonce{}, err
  181. }
  182. }
  183. enc, err := c.EncodeRaw(id, head, msgData)
  184. return enc, head.Nonce, err
  185. }
  186. // EncodeRaw encodes a packet with the given header.
  187. func (c *Codec) EncodeRaw(id enode.ID, head Header, msgdata []byte) ([]byte, error) {
  188. c.writeHeaders(&head)
  189. // Apply masking.
  190. masked := c.buf.Bytes()[sizeofMaskingIV:]
  191. mask := head.mask(id)
  192. mask.XORKeyStream(masked[:], masked[:])
  193. // Write message data.
  194. c.buf.Write(msgdata)
  195. return c.buf.Bytes(), nil
  196. }
  197. func (c *Codec) writeHeaders(head *Header) {
  198. c.buf.Reset()
  199. c.buf.Write(head.IV[:])
  200. binary.Write(&c.buf, binary.BigEndian, &head.StaticHeader)
  201. c.buf.Write(head.AuthData)
  202. }
  203. // makeHeader creates a packet header.
  204. func (c *Codec) makeHeader(toID enode.ID, flag byte, authsizeExtra int) Header {
  205. var authsize int
  206. switch flag {
  207. case flagMessage:
  208. authsize = sizeofMessageAuthData
  209. case flagWhoareyou:
  210. authsize = sizeofWhoareyouAuthData
  211. case flagHandshake:
  212. authsize = sizeofHandshakeAuthData
  213. default:
  214. panic(fmt.Errorf("BUG: invalid packet header flag %x", flag))
  215. }
  216. authsize += authsizeExtra
  217. if authsize > int(^uint16(0)) {
  218. panic(fmt.Errorf("BUG: auth size %d overflows uint16", authsize))
  219. }
  220. return Header{
  221. StaticHeader: StaticHeader{
  222. ProtocolID: protocolID,
  223. Version: version,
  224. Flag: flag,
  225. AuthSize: uint16(authsize),
  226. },
  227. }
  228. }
  229. // encodeRandom encodes a packet with random content.
  230. func (c *Codec) encodeRandom(toID enode.ID) (Header, []byte, error) {
  231. head := c.makeHeader(toID, flagMessage, 0)
  232. // Encode auth data.
  233. auth := messageAuthData{SrcID: c.localnode.ID()}
  234. if _, err := crand.Read(head.Nonce[:]); err != nil {
  235. return head, nil, fmt.Errorf("can't get random data: %v", err)
  236. }
  237. c.headbuf.Reset()
  238. binary.Write(&c.headbuf, binary.BigEndian, auth)
  239. head.AuthData = c.headbuf.Bytes()
  240. // Fill message ciphertext buffer with random bytes.
  241. c.msgctbuf = append(c.msgctbuf[:0], make([]byte, randomPacketMsgSize)...)
  242. crand.Read(c.msgctbuf)
  243. return head, c.msgctbuf, nil
  244. }
  245. // encodeWhoareyou encodes a WHOAREYOU packet.
  246. func (c *Codec) encodeWhoareyou(toID enode.ID, packet *Whoareyou) (Header, error) {
  247. // Sanity check node field to catch misbehaving callers.
  248. if packet.RecordSeq > 0 && packet.Node == nil {
  249. panic("BUG: missing node in whoareyou with non-zero seq")
  250. }
  251. // Create header.
  252. head := c.makeHeader(toID, flagWhoareyou, 0)
  253. head.AuthData = bytesCopy(&c.buf)
  254. head.Nonce = packet.Nonce
  255. // Encode auth data.
  256. auth := &whoareyouAuthData{
  257. IDNonce: packet.IDNonce,
  258. RecordSeq: packet.RecordSeq,
  259. }
  260. c.headbuf.Reset()
  261. binary.Write(&c.headbuf, binary.BigEndian, auth)
  262. head.AuthData = c.headbuf.Bytes()
  263. return head, nil
  264. }
  265. // encodeHandshakeMessage encodes the handshake message packet header.
  266. func (c *Codec) encodeHandshakeHeader(toID enode.ID, addr string, challenge *Whoareyou) (Header, *session, error) {
  267. // Ensure calling code sets challenge.node.
  268. if challenge.Node == nil {
  269. panic("BUG: missing challenge.Node in encode")
  270. }
  271. // Generate new secrets.
  272. auth, session, err := c.makeHandshakeAuth(toID, addr, challenge)
  273. if err != nil {
  274. return Header{}, nil, err
  275. }
  276. // Generate nonce for message.
  277. nonce, err := c.sc.nextNonce(session)
  278. if err != nil {
  279. return Header{}, nil, fmt.Errorf("can't generate nonce: %v", err)
  280. }
  281. // TODO: this should happen when the first authenticated message is received
  282. c.sc.storeNewSession(toID, addr, session)
  283. // Encode the auth header.
  284. var (
  285. authsizeExtra = len(auth.pubkey) + len(auth.signature) + len(auth.record)
  286. head = c.makeHeader(toID, flagHandshake, authsizeExtra)
  287. )
  288. c.headbuf.Reset()
  289. binary.Write(&c.headbuf, binary.BigEndian, &auth.h)
  290. c.headbuf.Write(auth.signature)
  291. c.headbuf.Write(auth.pubkey)
  292. c.headbuf.Write(auth.record)
  293. head.AuthData = c.headbuf.Bytes()
  294. head.Nonce = nonce
  295. return head, session, err
  296. }
  297. // encodeAuthHeader creates the auth header on a request packet following WHOAREYOU.
  298. func (c *Codec) makeHandshakeAuth(toID enode.ID, addr string, challenge *Whoareyou) (*handshakeAuthData, *session, error) {
  299. auth := new(handshakeAuthData)
  300. auth.h.SrcID = c.localnode.ID()
  301. // Create the ephemeral key. This needs to be first because the
  302. // key is part of the ID nonce signature.
  303. var remotePubkey = new(ecdsa.PublicKey)
  304. if err := challenge.Node.Load((*enode.Secp256k1)(remotePubkey)); err != nil {
  305. return nil, nil, fmt.Errorf("can't find secp256k1 key for recipient")
  306. }
  307. ephkey, err := c.sc.ephemeralKeyGen()
  308. if err != nil {
  309. return nil, nil, fmt.Errorf("can't generate ephemeral key")
  310. }
  311. ephpubkey := EncodePubkey(&ephkey.PublicKey)
  312. auth.pubkey = ephpubkey[:]
  313. auth.h.PubkeySize = byte(len(auth.pubkey))
  314. // Add ID nonce signature to response.
  315. cdata := challenge.ChallengeData
  316. idsig, err := makeIDSignature(c.sha256, c.privkey, cdata, ephpubkey[:], toID)
  317. if err != nil {
  318. return nil, nil, fmt.Errorf("can't sign: %v", err)
  319. }
  320. auth.signature = idsig
  321. auth.h.SigSize = byte(len(auth.signature))
  322. // Add our record to response if it's newer than what remote side has.
  323. ln := c.localnode.Node()
  324. if challenge.RecordSeq < ln.Seq() {
  325. auth.record, _ = rlp.EncodeToBytes(ln.Record())
  326. }
  327. // Create session keys.
  328. sec := deriveKeys(sha256.New, ephkey, remotePubkey, c.localnode.ID(), challenge.Node.ID(), cdata)
  329. if sec == nil {
  330. return nil, nil, fmt.Errorf("key derivation failed")
  331. }
  332. return auth, sec, err
  333. }
  334. // encodeMessage encodes an encrypted message packet.
  335. func (c *Codec) encodeMessageHeader(toID enode.ID, s *session) (Header, error) {
  336. head := c.makeHeader(toID, flagMessage, 0)
  337. // Create the header.
  338. nonce, err := c.sc.nextNonce(s)
  339. if err != nil {
  340. return Header{}, fmt.Errorf("can't generate nonce: %v", err)
  341. }
  342. auth := messageAuthData{SrcID: c.localnode.ID()}
  343. c.buf.Reset()
  344. binary.Write(&c.buf, binary.BigEndian, &auth)
  345. head.AuthData = bytesCopy(&c.buf)
  346. head.Nonce = nonce
  347. return head, err
  348. }
  349. func (c *Codec) encryptMessage(s *session, p Packet, head *Header, headerData []byte) ([]byte, error) {
  350. // Encode message plaintext.
  351. c.msgbuf.Reset()
  352. c.msgbuf.WriteByte(p.Kind())
  353. if err := rlp.Encode(&c.msgbuf, p); err != nil {
  354. return nil, err
  355. }
  356. messagePT := c.msgbuf.Bytes()
  357. // Encrypt into message ciphertext buffer.
  358. messageCT, err := encryptGCM(c.msgctbuf[:0], s.writeKey, head.Nonce[:], messagePT, headerData)
  359. if err == nil {
  360. c.msgctbuf = messageCT
  361. }
  362. return messageCT, err
  363. }
  364. // Decode decodes a discovery packet.
  365. func (c *Codec) Decode(input []byte, addr string) (src enode.ID, n *enode.Node, p Packet, err error) {
  366. // Unmask the static header.
  367. if len(input) < sizeofStaticPacketData {
  368. return enode.ID{}, nil, nil, errTooShort
  369. }
  370. var head Header
  371. copy(head.IV[:], input[:sizeofMaskingIV])
  372. mask := head.mask(c.localnode.ID())
  373. staticHeader := input[sizeofMaskingIV:sizeofStaticPacketData]
  374. mask.XORKeyStream(staticHeader, staticHeader)
  375. // Decode and verify the static header.
  376. c.reader.Reset(staticHeader)
  377. binary.Read(&c.reader, binary.BigEndian, &head.StaticHeader)
  378. remainingInput := len(input) - sizeofStaticPacketData
  379. if err := head.checkValid(remainingInput); err != nil {
  380. return enode.ID{}, nil, nil, err
  381. }
  382. // Unmask auth data.
  383. authDataEnd := sizeofStaticPacketData + int(head.AuthSize)
  384. authData := input[sizeofStaticPacketData:authDataEnd]
  385. mask.XORKeyStream(authData, authData)
  386. head.AuthData = authData
  387. // Delete timed-out handshakes. This must happen before decoding to avoid
  388. // processing the same handshake twice.
  389. c.sc.handshakeGC()
  390. // Decode auth part and message.
  391. headerData := input[:authDataEnd]
  392. msgData := input[authDataEnd:]
  393. switch head.Flag {
  394. case flagWhoareyou:
  395. p, err = c.decodeWhoareyou(&head, headerData)
  396. case flagHandshake:
  397. n, p, err = c.decodeHandshakeMessage(addr, &head, headerData, msgData)
  398. case flagMessage:
  399. p, err = c.decodeMessage(addr, &head, headerData, msgData)
  400. default:
  401. err = errInvalidFlag
  402. }
  403. return head.src, n, p, err
  404. }
  405. // decodeWhoareyou reads packet data after the header as a WHOAREYOU packet.
  406. func (c *Codec) decodeWhoareyou(head *Header, headerData []byte) (Packet, error) {
  407. if len(head.AuthData) != sizeofWhoareyouAuthData {
  408. return nil, fmt.Errorf("invalid auth size %d for WHOAREYOU", len(head.AuthData))
  409. }
  410. var auth whoareyouAuthData
  411. c.reader.Reset(head.AuthData)
  412. binary.Read(&c.reader, binary.BigEndian, &auth)
  413. p := &Whoareyou{
  414. Nonce: head.Nonce,
  415. IDNonce: auth.IDNonce,
  416. RecordSeq: auth.RecordSeq,
  417. ChallengeData: make([]byte, len(headerData)),
  418. }
  419. copy(p.ChallengeData, headerData)
  420. return p, nil
  421. }
  422. func (c *Codec) decodeHandshakeMessage(fromAddr string, head *Header, headerData, msgData []byte) (n *enode.Node, p Packet, err error) {
  423. node, auth, session, err := c.decodeHandshake(fromAddr, head)
  424. if err != nil {
  425. c.sc.deleteHandshake(auth.h.SrcID, fromAddr)
  426. return nil, nil, err
  427. }
  428. // Decrypt the message using the new session keys.
  429. msg, err := c.decryptMessage(msgData, head.Nonce[:], headerData, session.readKey)
  430. if err != nil {
  431. c.sc.deleteHandshake(auth.h.SrcID, fromAddr)
  432. return node, msg, err
  433. }
  434. // Handshake OK, drop the challenge and store the new session keys.
  435. c.sc.storeNewSession(auth.h.SrcID, fromAddr, session)
  436. c.sc.deleteHandshake(auth.h.SrcID, fromAddr)
  437. return node, msg, nil
  438. }
  439. func (c *Codec) decodeHandshake(fromAddr string, head *Header) (n *enode.Node, auth handshakeAuthData, s *session, err error) {
  440. if auth, err = c.decodeHandshakeAuthData(head); err != nil {
  441. return nil, auth, nil, err
  442. }
  443. // Verify against our last WHOAREYOU.
  444. challenge := c.sc.getHandshake(auth.h.SrcID, fromAddr)
  445. if challenge == nil {
  446. return nil, auth, nil, errUnexpectedHandshake
  447. }
  448. // Get node record.
  449. n, err = c.decodeHandshakeRecord(challenge.Node, auth.h.SrcID, auth.record)
  450. if err != nil {
  451. return nil, auth, nil, err
  452. }
  453. // Verify ID nonce signature.
  454. sig := auth.signature
  455. cdata := challenge.ChallengeData
  456. err = verifyIDSignature(c.sha256, sig, n, cdata, auth.pubkey, c.localnode.ID())
  457. if err != nil {
  458. return nil, auth, nil, err
  459. }
  460. // Verify ephemeral key is on curve.
  461. ephkey, err := DecodePubkey(c.privkey.Curve, auth.pubkey)
  462. if err != nil {
  463. return nil, auth, nil, errInvalidAuthKey
  464. }
  465. // Derive sesssion keys.
  466. session := deriveKeys(sha256.New, c.privkey, ephkey, auth.h.SrcID, c.localnode.ID(), cdata)
  467. session = session.keysFlipped()
  468. return n, auth, session, nil
  469. }
  470. // decodeHandshakeAuthData reads the authdata section of a handshake packet.
  471. func (c *Codec) decodeHandshakeAuthData(head *Header) (auth handshakeAuthData, err error) {
  472. // Decode fixed size part.
  473. if len(head.AuthData) < sizeofHandshakeAuthData {
  474. return auth, fmt.Errorf("header authsize %d too low for handshake", head.AuthSize)
  475. }
  476. c.reader.Reset(head.AuthData)
  477. binary.Read(&c.reader, binary.BigEndian, &auth.h)
  478. head.src = auth.h.SrcID
  479. // Decode variable-size part.
  480. var (
  481. vardata = head.AuthData[sizeofHandshakeAuthData:]
  482. sigAndKeySize = int(auth.h.SigSize) + int(auth.h.PubkeySize)
  483. keyOffset = int(auth.h.SigSize)
  484. recOffset = keyOffset + int(auth.h.PubkeySize)
  485. )
  486. if len(vardata) < sigAndKeySize {
  487. return auth, errTooShort
  488. }
  489. auth.signature = vardata[:keyOffset]
  490. auth.pubkey = vardata[keyOffset:recOffset]
  491. auth.record = vardata[recOffset:]
  492. return auth, nil
  493. }
  494. // decodeHandshakeRecord verifies the node record contained in a handshake packet. The
  495. // remote node should include the record if we don't have one or if ours is older than the
  496. // latest sequence number.
  497. func (c *Codec) decodeHandshakeRecord(local *enode.Node, wantID enode.ID, remote []byte) (*enode.Node, error) {
  498. node := local
  499. if len(remote) > 0 {
  500. var record enr.Record
  501. if err := rlp.DecodeBytes(remote, &record); err != nil {
  502. return nil, err
  503. }
  504. if local == nil || local.Seq() < record.Seq() {
  505. n, err := enode.New(enode.ValidSchemes, &record)
  506. if err != nil {
  507. return nil, fmt.Errorf("invalid node record: %v", err)
  508. }
  509. if n.ID() != wantID {
  510. return nil, fmt.Errorf("record in handshake has wrong ID: %v", n.ID())
  511. }
  512. node = n
  513. }
  514. }
  515. if node == nil {
  516. return nil, errNoRecord
  517. }
  518. return node, nil
  519. }
  520. // decodeMessage reads packet data following the header as an ordinary message packet.
  521. func (c *Codec) decodeMessage(fromAddr string, head *Header, headerData, msgData []byte) (Packet, error) {
  522. if len(head.AuthData) != sizeofMessageAuthData {
  523. return nil, fmt.Errorf("invalid auth size %d for message packet", len(head.AuthData))
  524. }
  525. var auth messageAuthData
  526. c.reader.Reset(head.AuthData)
  527. binary.Read(&c.reader, binary.BigEndian, &auth)
  528. head.src = auth.SrcID
  529. // Try decrypting the message.
  530. key := c.sc.readKey(auth.SrcID, fromAddr)
  531. msg, err := c.decryptMessage(msgData, head.Nonce[:], headerData, key)
  532. if err == errMessageDecrypt {
  533. // It didn't work. Start the handshake since this is an ordinary message packet.
  534. return &Unknown{Nonce: head.Nonce}, nil
  535. }
  536. return msg, err
  537. }
  538. func (c *Codec) decryptMessage(input, nonce, headerData, readKey []byte) (Packet, error) {
  539. msgdata, err := decryptGCM(readKey, nonce, input, headerData)
  540. if err != nil {
  541. return nil, errMessageDecrypt
  542. }
  543. if len(msgdata) == 0 {
  544. return nil, errMessageTooShort
  545. }
  546. return DecodeMessage(msgdata[0], msgdata[1:])
  547. }
  548. // checkValid performs some basic validity checks on the header.
  549. // The packetLen here is the length remaining after the static header.
  550. func (h *StaticHeader) checkValid(packetLen int) error {
  551. if h.ProtocolID != protocolID {
  552. return errInvalidHeader
  553. }
  554. if h.Version < minVersion {
  555. return errMinVersion
  556. }
  557. if h.Flag != flagWhoareyou && packetLen < minMessageSize {
  558. return errMsgTooShort
  559. }
  560. if int(h.AuthSize) > packetLen {
  561. return errAuthSize
  562. }
  563. return nil
  564. }
  565. // headerMask returns a cipher for 'masking' / 'unmasking' packet headers.
  566. func (h *Header) mask(destID enode.ID) cipher.Stream {
  567. block, err := aes.NewCipher(destID[:16])
  568. if err != nil {
  569. panic("can't create cipher")
  570. }
  571. return cipher.NewCTR(block, h.IV[:])
  572. }
  573. func bytesCopy(r *bytes.Buffer) []byte {
  574. b := make([]byte, r.Len())
  575. copy(b, r.Bytes())
  576. return b
  577. }