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