github.com/gochain/gochain/v3@v3.4.9/p2p/rlpx.go (about) 1 // Copyright 2015 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 17 package p2p 18 19 import ( 20 "bytes" 21 "crypto/aes" 22 "crypto/cipher" 23 "crypto/ecdsa" 24 "crypto/elliptic" 25 "crypto/hmac" 26 "crypto/rand" 27 "encoding/binary" 28 "errors" 29 "fmt" 30 "hash" 31 "io" 32 "io/ioutil" 33 mrand "math/rand" 34 "net" 35 "sync" 36 "time" 37 38 "github.com/golang/snappy" 39 "golang.org/x/crypto/sha3" 40 41 "github.com/gochain/gochain/v3/crypto" 42 "github.com/gochain/gochain/v3/crypto/ecies" 43 "github.com/gochain/gochain/v3/crypto/secp256k1" 44 "github.com/gochain/gochain/v3/p2p/discover" 45 "github.com/gochain/gochain/v3/rlp" 46 ) 47 48 const ( 49 maxUint24 = ^uint32(0) >> 8 50 51 sskLen = 16 // ecies.MaxSharedKeyLength(pubKey) / 2 52 sigLen = 65 // elliptic S256 53 pubLen = 64 // 512 bit pubkey in uncompressed representation without format byte 54 shaLen = 32 // hash length (for nonce etc) 55 56 authMsgLen = sigLen + shaLen + pubLen + shaLen + 1 57 authRespLen = pubLen + shaLen + 1 58 59 eciesOverhead = 65 /* pubkey */ + 16 /* IV */ + 32 /* MAC */ 60 61 encAuthMsgLen = authMsgLen + eciesOverhead // size of encrypted pre-EIP-8 initiator handshake 62 encAuthRespLen = authRespLen + eciesOverhead // size of encrypted pre-EIP-8 handshake reply 63 64 // total timeout for encryption handshake and protocol 65 // handshake in both directions. 66 handshakeTimeout = 5 * time.Second 67 68 // This is the timeout for sending the disconnect reason. 69 // This is shorter than the usual timeout because we don't want 70 // to wait if the connection is known to be bad anyway. 71 discWriteTimeout = 1 * time.Second 72 ) 73 74 // errPlainMessageTooLarge is returned if a decompressed message length exceeds 75 // the allowed 24 bits (i.e. length >= 16MB). 76 var errPlainMessageTooLarge = errors.New("message length >= 16MB") 77 78 // rlpx is the transport protocol used by actual (non-test) connections. 79 // It wraps the frame encoder with locks and read/write deadlines. 80 type rlpx struct { 81 fd net.Conn 82 83 rmu, wmu sync.Mutex 84 rw *rlpxFrameRW 85 } 86 87 func newRLPX(fd net.Conn) transport { 88 fd.SetDeadline(time.Now().Add(handshakeTimeout)) 89 return &rlpx{fd: fd} 90 } 91 92 func (t *rlpx) ReadMsg() (Msg, error) { 93 t.rmu.Lock() 94 defer t.rmu.Unlock() 95 t.fd.SetReadDeadline(time.Now().Add(frameReadTimeout)) 96 return t.rw.ReadMsg() 97 } 98 99 func (t *rlpx) WriteMsg(msg Msg) error { 100 t.wmu.Lock() 101 defer t.wmu.Unlock() 102 t.fd.SetWriteDeadline(time.Now().Add(frameWriteTimeout)) 103 return t.rw.WriteMsg(msg) 104 } 105 106 func (t *rlpx) close(err error) { 107 t.wmu.Lock() 108 defer t.wmu.Unlock() 109 // Tell the remote end why we're disconnecting if possible. 110 if t.rw != nil { 111 if r, ok := err.(DiscReason); ok && r != DiscNetworkError { 112 // rlpx tries to send DiscReason to disconnected peer 113 // if the connection is net.Pipe (in-memory simulation) 114 // it hangs forever, since net.Pipe does not implement 115 // a write deadline. Because of this only try to send 116 // the disconnect reason message if there is no error. 117 if err := t.fd.SetWriteDeadline(time.Now().Add(discWriteTimeout)); err == nil { 118 SendItems(t.rw, discMsg, r) 119 } 120 } 121 } 122 t.fd.Close() 123 } 124 125 // doEncHandshake runs the protocol handshake using authenticated 126 // messages. the protocol handshake is the first authenticated message 127 // and also verifies whether the encryption handshake 'worked' and the 128 // remote side actually provided the right public key. 129 func (t *rlpx) doProtoHandshake(our *protoHandshake) (their *protoHandshake, err error) { 130 // Writing our handshake happens concurrently, we prefer 131 // returning the handshake read error. If the remote side 132 // disconnects us early with a valid reason, we should return it 133 // as the error so it can be tracked elsewhere. 134 werr := make(chan error, 1) 135 go func() { werr <- Send(t.rw, handshakeMsg, our) }() 136 if their, err = readProtocolHandshake(t.rw, our); err != nil { 137 <-werr // make sure the write terminates too 138 return nil, err 139 } 140 if err := <-werr; err != nil { 141 return nil, fmt.Errorf("write error: %v", err) 142 } 143 // If the protocol version supports Snappy encoding, upgrade immediately 144 t.rw.snappy = their.Version >= snappyProtocolVersion 145 146 return their, nil 147 } 148 149 func readProtocolHandshake(rw MsgReader, our *protoHandshake) (*protoHandshake, error) { 150 msg, err := rw.ReadMsg() 151 if err != nil { 152 return nil, err 153 } 154 if msg.Size > baseProtocolMaxMsgSize { 155 return nil, fmt.Errorf("message too big") 156 } 157 if msg.Code == discMsg { 158 // Disconnect before protocol handshake is valid according to the 159 // spec and we send it ourself if the post-handshake checks fail. 160 // We can't return the reason directly, though, because it is echoed 161 // back otherwise. Wrap it in a string instead. 162 var reason [1]DiscReason 163 rlp.Decode(msg.Payload, &reason) 164 return nil, reason[0] 165 } 166 if msg.Code != handshakeMsg { 167 return nil, fmt.Errorf("expected handshake, got %x", msg.Code) 168 } 169 var hs protoHandshake 170 if err := msg.Decode(&hs); err != nil { 171 return nil, err 172 } 173 if (hs.ID == discover.NodeID{}) { 174 return nil, DiscInvalidIdentity 175 } 176 return &hs, nil 177 } 178 179 func (t *rlpx) doEncHandshake(prv *ecdsa.PrivateKey, dial *discover.Node) (discover.NodeID, error) { 180 var ( 181 sec secrets 182 err error 183 ) 184 if dial == nil { 185 sec, err = receiverEncHandshake(t.fd, prv, nil) 186 } else { 187 sec, err = initiatorEncHandshake(t.fd, prv, dial.ID, nil) 188 } 189 if err != nil { 190 return discover.NodeID{}, err 191 } 192 t.wmu.Lock() 193 t.rw = newRLPXFrameRW(t.fd, sec) 194 t.wmu.Unlock() 195 return sec.RemoteID, nil 196 } 197 198 // encHandshake contains the state of the encryption handshake. 199 type encHandshake struct { 200 initiator bool 201 remoteID discover.NodeID 202 203 remotePub *ecies.PublicKey // remote-pubk 204 initNonce, respNonce []byte // nonce 205 randomPrivKey *ecies.PrivateKey // ecdhe-random 206 remoteRandomPub *ecies.PublicKey // ecdhe-random-pubk 207 } 208 209 // secrets represents the connection secrets 210 // which are negotiated during the encryption handshake. 211 type secrets struct { 212 RemoteID discover.NodeID 213 AES, MAC []byte 214 EgressMAC, IngressMAC hash.Hash 215 Token []byte 216 } 217 218 // RLPx v4 handshake auth (defined in EIP-8). 219 type authMsgV4 struct { 220 gotPlain bool // whether read packet had plain format. 221 222 Signature [sigLen]byte 223 InitiatorPubkey [pubLen]byte 224 Nonce [shaLen]byte 225 Version uint 226 227 // Ignore additional fields (forward-compatibility) 228 Rest []rlp.RawValue `rlp:"tail"` 229 } 230 231 // RLPx v4 handshake response (defined in EIP-8). 232 type authRespV4 struct { 233 RandomPubkey [pubLen]byte 234 Nonce [shaLen]byte 235 Version uint 236 237 // Ignore additional fields (forward-compatibility) 238 Rest []rlp.RawValue `rlp:"tail"` 239 } 240 241 // secrets is called after the handshake is completed. 242 // It extracts the connection secrets from the handshake values. 243 func (h *encHandshake) secrets(auth, authResp []byte) (secrets, error) { 244 ecdheSecret, err := h.randomPrivKey.GenerateShared(h.remoteRandomPub, sskLen, sskLen) 245 if err != nil { 246 return secrets{}, err 247 } 248 249 // derive base secrets from ephemeral key agreement 250 sharedSecret := crypto.Keccak256(ecdheSecret, crypto.Keccak256(h.respNonce, h.initNonce)) 251 aesSecret := crypto.Keccak256(ecdheSecret, sharedSecret) 252 s := secrets{ 253 RemoteID: h.remoteID, 254 AES: aesSecret, 255 MAC: crypto.Keccak256(ecdheSecret, aesSecret), 256 } 257 258 // setup sha3 instances for the MACs 259 mac1 := sha3.NewLegacyKeccak256() 260 mac1.Write(xor(s.MAC, h.respNonce)) 261 mac1.Write(auth) 262 mac2 := sha3.NewLegacyKeccak256() 263 mac2.Write(xor(s.MAC, h.initNonce)) 264 mac2.Write(authResp) 265 if h.initiator { 266 s.EgressMAC, s.IngressMAC = mac1, mac2 267 } else { 268 s.EgressMAC, s.IngressMAC = mac2, mac1 269 } 270 271 return s, nil 272 } 273 274 // staticSharedSecret returns the static shared secret, the result 275 // of key agreement between the local and remote static node key. 276 func (h *encHandshake) staticSharedSecret(prv *ecdsa.PrivateKey) ([]byte, error) { 277 return ecies.ImportECDSA(prv).GenerateShared(h.remotePub, sskLen, sskLen) 278 } 279 280 // initiatorEncHandshake negotiates a session token on conn. 281 // it should be called on the dialing side of the connection. 282 // 283 // prv is the local client's private key. 284 func initiatorEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, remoteID discover.NodeID, token []byte) (s secrets, err error) { 285 h := &encHandshake{initiator: true, remoteID: remoteID} 286 authMsg, err := h.makeAuthMsg(prv, token) 287 if err != nil { 288 return s, err 289 } 290 authPacket, err := sealEIP8(authMsg, h) 291 if err != nil { 292 return s, err 293 } 294 if _, err = conn.Write(authPacket); err != nil { 295 return s, err 296 } 297 298 authRespMsg := new(authRespV4) 299 authRespPacket, err := readHandshakeMsg(authRespMsg, encAuthRespLen, prv, conn) 300 if err != nil { 301 return s, err 302 } 303 if err := h.handleAuthResp(authRespMsg); err != nil { 304 return s, err 305 } 306 return h.secrets(authPacket, authRespPacket) 307 } 308 309 // makeAuthMsg creates the initiator handshake message. 310 func (h *encHandshake) makeAuthMsg(prv *ecdsa.PrivateKey, token []byte) (*authMsgV4, error) { 311 rpub, err := h.remoteID.Pubkey() 312 if err != nil { 313 return nil, fmt.Errorf("bad remoteID: %v", err) 314 } 315 h.remotePub = ecies.ImportECDSAPublic(rpub) 316 // Generate random initiator nonce. 317 h.initNonce = make([]byte, shaLen) 318 if _, err := rand.Read(h.initNonce); err != nil { 319 return nil, err 320 } 321 // Generate random keypair to for ECDH. 322 h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil) 323 if err != nil { 324 return nil, err 325 } 326 327 // Sign known message: static-shared-secret ^ nonce 328 token, err = h.staticSharedSecret(prv) 329 if err != nil { 330 return nil, err 331 } 332 signed := xor(token, h.initNonce) 333 signature, err := crypto.Sign(signed, h.randomPrivKey.ExportECDSA()) 334 if err != nil { 335 return nil, err 336 } 337 338 msg := new(authMsgV4) 339 copy(msg.Signature[:], signature) 340 copy(msg.InitiatorPubkey[:], crypto.FromECDSAPub(&prv.PublicKey)[1:]) 341 copy(msg.Nonce[:], h.initNonce) 342 msg.Version = 4 343 return msg, nil 344 } 345 346 func (h *encHandshake) handleAuthResp(msg *authRespV4) (err error) { 347 h.respNonce = msg.Nonce[:] 348 h.remoteRandomPub, err = importPublicKey(msg.RandomPubkey[:]) 349 return err 350 } 351 352 // receiverEncHandshake negotiates a session token on conn. 353 // it should be called on the listening side of the connection. 354 // 355 // prv is the local client's private key. 356 // token is the token from a previous session with this node. 357 func receiverEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, token []byte) (s secrets, err error) { 358 authMsg := new(authMsgV4) 359 authPacket, err := readHandshakeMsg(authMsg, encAuthMsgLen, prv, conn) 360 if err != nil { 361 return s, err 362 } 363 h := new(encHandshake) 364 if err := h.handleAuthMsg(authMsg, prv); err != nil { 365 return s, err 366 } 367 368 authRespMsg, err := h.makeAuthResp() 369 if err != nil { 370 return s, err 371 } 372 var authRespPacket []byte 373 if authMsg.gotPlain { 374 authRespPacket, err = authRespMsg.sealPlain(h) 375 } else { 376 authRespPacket, err = sealEIP8(authRespMsg, h) 377 } 378 if err != nil { 379 return s, err 380 } 381 if _, err = conn.Write(authRespPacket); err != nil { 382 return s, err 383 } 384 return h.secrets(authPacket, authRespPacket) 385 } 386 387 func (h *encHandshake) handleAuthMsg(msg *authMsgV4, prv *ecdsa.PrivateKey) error { 388 // Import the remote identity. 389 h.initNonce = msg.Nonce[:] 390 h.remoteID = msg.InitiatorPubkey 391 rpub, err := h.remoteID.Pubkey() 392 if err != nil { 393 return fmt.Errorf("bad remoteID: %#v", err) 394 } 395 h.remotePub = ecies.ImportECDSAPublic(rpub) 396 397 // Generate random keypair for ECDH. 398 // If a private key is already set, use it instead of generating one (for testing). 399 if h.randomPrivKey == nil { 400 h.randomPrivKey, err = ecies.GenerateKey(rand.Reader, crypto.S256(), nil) 401 if err != nil { 402 return err 403 } 404 } 405 406 // Check the signature. 407 token, err := h.staticSharedSecret(prv) 408 if err != nil { 409 return err 410 } 411 signedMsg := xor(token, h.initNonce) 412 remoteRandomPub, err := secp256k1.RecoverPubkey(signedMsg, msg.Signature[:]) 413 if err != nil { 414 return err 415 } 416 h.remoteRandomPub, _ = importPublicKey(remoteRandomPub) 417 return nil 418 } 419 420 func (h *encHandshake) makeAuthResp() (msg *authRespV4, err error) { 421 // Generate random nonce. 422 h.respNonce = make([]byte, shaLen) 423 if _, err = rand.Read(h.respNonce); err != nil { 424 return nil, err 425 } 426 427 msg = new(authRespV4) 428 copy(msg.Nonce[:], h.respNonce) 429 copy(msg.RandomPubkey[:], exportPubkey(&h.randomPrivKey.PublicKey)) 430 msg.Version = 4 431 return msg, nil 432 } 433 434 func (msg *authMsgV4) sealPlain(h *encHandshake) ([]byte, error) { 435 buf := make([]byte, authMsgLen) 436 n := copy(buf, msg.Signature[:]) 437 n += copy(buf[n:], crypto.Keccak256(exportPubkey(&h.randomPrivKey.PublicKey))) 438 n += copy(buf[n:], msg.InitiatorPubkey[:]) 439 n += copy(buf[n:], msg.Nonce[:]) 440 buf[n] = 0 // token-flag 441 return ecies.Encrypt(rand.Reader, h.remotePub, buf, nil, nil) 442 } 443 444 func (msg *authMsgV4) decodePlain(input []byte) { 445 n := copy(msg.Signature[:], input) 446 n += shaLen // skip sha3(initiator-ephemeral-pubk) 447 n += copy(msg.InitiatorPubkey[:], input[n:]) 448 copy(msg.Nonce[:], input[n:]) 449 msg.Version = 4 450 msg.gotPlain = true 451 } 452 453 func (msg *authRespV4) sealPlain(hs *encHandshake) ([]byte, error) { 454 buf := make([]byte, authRespLen) 455 n := copy(buf, msg.RandomPubkey[:]) 456 copy(buf[n:], msg.Nonce[:]) 457 return ecies.Encrypt(rand.Reader, hs.remotePub, buf, nil, nil) 458 } 459 460 func (msg *authRespV4) decodePlain(input []byte) { 461 n := copy(msg.RandomPubkey[:], input) 462 copy(msg.Nonce[:], input[n:]) 463 msg.Version = 4 464 } 465 466 var padSpace = make([]byte, 300) 467 468 func sealEIP8(msg interface{}, h *encHandshake) ([]byte, error) { 469 buf := new(bytes.Buffer) 470 if err := rlp.Encode(buf, msg); err != nil { 471 return nil, err 472 } 473 // pad with random amount of data. the amount needs to be at least 100 bytes to make 474 // the message distinguishable from pre-EIP-8 handshakes. 475 pad := padSpace[:mrand.Intn(len(padSpace)-100)+100] 476 buf.Write(pad) 477 prefix := make([]byte, 2) 478 binary.BigEndian.PutUint16(prefix, uint16(buf.Len()+eciesOverhead)) 479 480 enc, err := ecies.Encrypt(rand.Reader, h.remotePub, buf.Bytes(), nil, prefix) 481 return append(prefix, enc...), err 482 } 483 484 type plainDecoder interface { 485 decodePlain([]byte) 486 } 487 488 func readHandshakeMsg(msg plainDecoder, plainSize int, prv *ecdsa.PrivateKey, r io.Reader) ([]byte, error) { 489 buf := make([]byte, plainSize) 490 if _, err := io.ReadFull(r, buf); err != nil { 491 return buf, err 492 } 493 // Attempt decoding pre-EIP-8 "plain" format. 494 key := ecies.ImportECDSA(prv) 495 if dec, err := key.Decrypt(buf, nil, nil); err == nil { 496 msg.decodePlain(dec) 497 return buf, nil 498 } 499 // Could be EIP-8 format, try that. 500 prefix := buf[:2] 501 size := binary.BigEndian.Uint16(prefix) 502 if size < uint16(plainSize) { 503 return buf, fmt.Errorf("size underflow, need at least %d bytes", plainSize) 504 } 505 buf = append(buf, make([]byte, size-uint16(plainSize)+2)...) 506 if _, err := io.ReadFull(r, buf[plainSize:]); err != nil { 507 return buf, err 508 } 509 dec, err := key.Decrypt(buf[2:], nil, prefix) 510 if err != nil { 511 return buf, err 512 } 513 // Can't use rlp.DecodeBytes here because it rejects 514 // trailing data (forward-compatibility). 515 s := rlp.NewStream(bytes.NewReader(dec), 0) 516 return buf, s.Decode(msg) 517 } 518 519 // importPublicKey unmarshals 512 bit public keys. 520 func importPublicKey(pubKey []byte) (*ecies.PublicKey, error) { 521 var pubKey65 []byte 522 switch len(pubKey) { 523 case 64: 524 // add 'uncompressed key' flag 525 pubKey65 = append([]byte{0x04}, pubKey...) 526 case 65: 527 pubKey65 = pubKey 528 default: 529 return nil, fmt.Errorf("invalid public key length %v (expect 64/65)", len(pubKey)) 530 } 531 // TODO: fewer pointless conversions 532 pub, err := crypto.UnmarshalPubkey(pubKey65) 533 if err != nil { 534 return nil, err 535 } 536 return ecies.ImportECDSAPublic(pub), nil 537 } 538 539 func exportPubkey(pub *ecies.PublicKey) []byte { 540 if pub == nil { 541 panic("nil pubkey") 542 } 543 return elliptic.Marshal(pub.Curve, pub.X, pub.Y)[1:] 544 } 545 546 func xor(one, other []byte) (xor []byte) { 547 xor = make([]byte, len(one)) 548 for i := 0; i < len(one); i++ { 549 xor[i] = one[i] ^ other[i] 550 } 551 return xor 552 } 553 554 var ( 555 // this is used in place of actual frame header data. 556 // TODO: replace this when Msg contains the protocol type code. 557 zeroHeader = []byte{0xC2, 0x80, 0x80} 558 // sixteen zero bytes 559 zero16 = make([]byte, 16) 560 ) 561 562 // rlpxFrameRW implements a simplified version of RLPx framing. 563 // chunked messages are not supported and all headers are equal to 564 // zeroHeader. 565 // 566 // rlpxFrameRW is not safe for concurrent use from multiple goroutines. 567 type rlpxFrameRW struct { 568 conn io.ReadWriter 569 enc cipher.Stream 570 dec cipher.Stream 571 572 macCipher cipher.Block 573 egressMAC hash.Hash 574 ingressMAC hash.Hash 575 576 snappy bool 577 } 578 579 func newRLPXFrameRW(conn io.ReadWriter, s secrets) *rlpxFrameRW { 580 macc, err := aes.NewCipher(s.MAC) 581 if err != nil { 582 panic("invalid MAC secret: " + err.Error()) 583 } 584 encc, err := aes.NewCipher(s.AES) 585 if err != nil { 586 panic("invalid AES secret: " + err.Error()) 587 } 588 // we use an all-zeroes IV for AES because the key used 589 // for encryption is ephemeral. 590 iv := make([]byte, encc.BlockSize()) 591 return &rlpxFrameRW{ 592 conn: conn, 593 enc: cipher.NewCTR(encc, iv), 594 dec: cipher.NewCTR(encc, iv), 595 macCipher: macc, 596 egressMAC: s.EgressMAC, 597 ingressMAC: s.IngressMAC, 598 } 599 } 600 601 func (rw *rlpxFrameRW) WriteMsg(msg Msg) error { 602 ptype, _ := rlp.EncodeToBytes(msg.Code) 603 604 // if snappy is enabled, compress message now 605 if rw.snappy { 606 if msg.Size > maxUint24 { 607 return errPlainMessageTooLarge 608 } 609 payload, _ := ioutil.ReadAll(msg.Payload) 610 payload = snappy.Encode(nil, payload) 611 612 msg.Payload = bytes.NewReader(payload) 613 msg.Size = uint32(len(payload)) 614 } 615 // write header 616 headbuf := make([]byte, 32) 617 fsize := uint32(len(ptype)) + msg.Size 618 if fsize > maxUint24 { 619 return errors.New("message size overflows uint24") 620 } 621 putInt24(fsize, headbuf) // TODO: check overflow 622 copy(headbuf[3:], zeroHeader) 623 rw.enc.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now encrypted 624 625 // write header MAC 626 copy(headbuf[16:], updateMAC(rw.egressMAC, rw.macCipher, headbuf[:16])) 627 if _, err := rw.conn.Write(headbuf); err != nil { 628 return err 629 } 630 631 // write encrypted frame, updating the egress MAC hash with 632 // the data written to conn. 633 tee := cipher.StreamWriter{S: rw.enc, W: io.MultiWriter(rw.conn, rw.egressMAC)} 634 if _, err := tee.Write(ptype); err != nil { 635 return err 636 } 637 if _, err := io.Copy(tee, msg.Payload); err != nil { 638 return err 639 } 640 if padding := fsize % 16; padding > 0 { 641 if _, err := tee.Write(zero16[:16-padding]); err != nil { 642 return err 643 } 644 } 645 646 // write frame MAC. egress MAC hash is up to date because 647 // frame content was written to it as well. 648 fmacseed := rw.egressMAC.Sum(nil) 649 mac := updateMAC(rw.egressMAC, rw.macCipher, fmacseed) 650 _, err := rw.conn.Write(mac) 651 return err 652 } 653 654 func (rw *rlpxFrameRW) ReadMsg() (msg Msg, err error) { 655 // read the header 656 headbuf := make([]byte, 32) 657 if _, err := io.ReadFull(rw.conn, headbuf); err != nil { 658 return msg, err 659 } 660 // verify header mac 661 shouldMAC := updateMAC(rw.ingressMAC, rw.macCipher, headbuf[:16]) 662 if !hmac.Equal(shouldMAC, headbuf[16:]) { 663 return msg, errors.New("bad header MAC") 664 } 665 rw.dec.XORKeyStream(headbuf[:16], headbuf[:16]) // first half is now decrypted 666 fsize := readInt24(headbuf) 667 // ignore protocol type for now 668 669 // read the frame content 670 var rsize = fsize // frame size rounded up to 16 byte boundary 671 if padding := fsize % 16; padding > 0 { 672 rsize += 16 - padding 673 } 674 framebuf := make([]byte, rsize) 675 if _, err := io.ReadFull(rw.conn, framebuf); err != nil { 676 return msg, err 677 } 678 679 // read and validate frame MAC. we can re-use headbuf for that. 680 rw.ingressMAC.Write(framebuf) 681 fmacseed := rw.ingressMAC.Sum(nil) 682 if _, err := io.ReadFull(rw.conn, headbuf[:16]); err != nil { 683 return msg, err 684 } 685 shouldMAC = updateMAC(rw.ingressMAC, rw.macCipher, fmacseed) 686 if !hmac.Equal(shouldMAC, headbuf[:16]) { 687 return msg, errors.New("bad frame MAC") 688 } 689 690 // decrypt frame content 691 rw.dec.XORKeyStream(framebuf, framebuf) 692 693 // decode message code 694 content := bytes.NewReader(framebuf[:fsize]) 695 if err := rlp.Decode(content, &msg.Code); err != nil { 696 return msg, err 697 } 698 msg.Size = uint32(content.Len()) 699 msg.Payload = content 700 701 // if snappy is enabled, verify and decompress message 702 if rw.snappy { 703 payload, err := ioutil.ReadAll(msg.Payload) 704 if err != nil { 705 return msg, err 706 } 707 size, err := snappy.DecodedLen(payload) 708 if err != nil { 709 return msg, err 710 } 711 if size > int(maxUint24) { 712 return msg, errPlainMessageTooLarge 713 } 714 payload, err = snappy.Decode(nil, payload) 715 if err != nil { 716 return msg, err 717 } 718 msg.Size, msg.Payload = uint32(size), bytes.NewReader(payload) 719 } 720 return msg, nil 721 } 722 723 // updateMAC reseeds the given hash with encrypted seed. 724 // it returns the first 16 bytes of the hash sum after seeding. 725 func updateMAC(mac hash.Hash, block cipher.Block, seed []byte) []byte { 726 aesbuf := make([]byte, aes.BlockSize) 727 block.Encrypt(aesbuf, mac.Sum(nil)) 728 for i := range aesbuf { 729 aesbuf[i] ^= seed[i] 730 } 731 mac.Write(aesbuf) 732 return mac.Sum(nil)[:16] 733 } 734 735 func readInt24(b []byte) uint32 { 736 return uint32(b[2]) | uint32(b[1])<<8 | uint32(b[0])<<16 737 } 738 739 func putInt24(v uint32, b []byte) { 740 b[0] = byte(v >> 16) 741 b[1] = byte(v >> 8) 742 b[2] = byte(v) 743 }