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