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