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