1// Copyright 2010 The Go Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style 3// license that can be found in the LICENSE file. 4 5// TLS low level connection and record layer 6 7package runner 8 9import ( 10 "bytes" 11 "crypto/cipher" 12 "crypto/ecdsa" 13 "crypto/subtle" 14 "crypto/x509" 15 "encoding/binary" 16 "errors" 17 "fmt" 18 "io" 19 "net" 20 "sync" 21 "time" 22) 23 24// A Conn represents a secured connection. 25// It implements the net.Conn interface. 26type Conn struct { 27 // constant 28 conn net.Conn 29 isDTLS bool 30 isClient bool 31 32 // constant after handshake; protected by handshakeMutex 33 handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex 34 handshakeErr error // error resulting from handshake 35 wireVersion uint16 // TLS wire version 36 vers uint16 // TLS version 37 haveVers bool // version has been negotiated 38 config *Config // configuration passed to constructor 39 handshakeComplete bool 40 skipEarlyData bool // On a server, indicates that the client is sending early data that must be skipped over. 41 didResume bool // whether this connection was a session resumption 42 extendedMasterSecret bool // whether this session used an extended master secret 43 cipherSuite *cipherSuite 44 ocspResponse []byte // stapled OCSP response 45 sctList []byte // signed certificate timestamp list 46 peerCertificates []*x509.Certificate 47 // verifiedChains contains the certificate chains that we built, as 48 // opposed to the ones presented by the server. 49 verifiedChains [][]*x509.Certificate 50 // serverName contains the server name indicated by the client, if any. 51 serverName string 52 // firstFinished contains the first Finished hash sent during the 53 // handshake. This is the "tls-unique" channel binding value. 54 firstFinished [12]byte 55 // peerSignatureAlgorithm contains the signature algorithm that was used 56 // by the peer in the handshake, or zero if not applicable. 57 peerSignatureAlgorithm signatureAlgorithm 58 // curveID contains the curve that was used in the handshake, or zero if 59 // not applicable. 60 curveID CurveID 61 // quicTransportParams contains the QUIC transport params received 62 // by the peer using codepoint 57. 63 quicTransportParams []byte 64 // quicTransportParams contains the QUIC transport params received 65 // by the peer using legacy codepoint 0xffa5. 66 quicTransportParamsLegacy []byte 67 68 clientRandom, serverRandom [32]byte 69 earlyExporterSecret []byte 70 exporterSecret []byte 71 resumptionSecret []byte 72 73 clientProtocol string 74 clientProtocolFallback bool 75 usedALPN bool 76 77 localApplicationSettings, peerApplicationSettings []byte 78 hasApplicationSettings bool 79 localApplicationSettingsOld, peerApplicationSettingsOld []byte 80 hasApplicationSettingsOld bool 81 82 // verify_data values for the renegotiation extension. 83 clientVerify []byte 84 serverVerify []byte 85 86 channelID *ecdsa.PublicKey 87 88 srtpProtectionProfile uint16 89 90 clientVersion uint16 91 92 // input/output 93 in, out halfConn // in.Mutex < out.Mutex 94 rawInput *block // raw input, right off the wire 95 input *block // application record waiting to be read 96 hand bytes.Buffer // handshake record waiting to be read 97 98 // pendingFlight, if PackHandshakeFlight is enabled, is the buffer of 99 // handshake data to be split into records at the end of the flight. 100 pendingFlight bytes.Buffer 101 102 // DTLS state 103 sendHandshakeSeq uint16 104 recvHandshakeSeq uint16 105 handMsg []byte // pending assembled handshake message 106 handMsgLen int // handshake message length, not including the header 107 pendingFragments [][]byte // pending outgoing handshake fragments. 108 pendingPacket []byte // pending outgoing packet. 109 110 keyUpdateSeen bool 111 keyUpdateRequested bool 112 seenOneByteRecord bool 113 114 expectTLS13ChangeCipherSpec bool 115 116 // seenHandshakePackEnd is whether the most recent handshake record was 117 // not full for ExpectPackedEncryptedHandshake. If true, no more 118 // handshake data may be received until the next flight or epoch change. 119 seenHandshakePackEnd bool 120 121 // echAccepted indicates whether ECH was accepted for this connection. 122 echAccepted bool 123 124 tmp [16]byte 125} 126 127func (c *Conn) init() { 128 c.in.isDTLS = c.isDTLS 129 c.out.isDTLS = c.isDTLS 130 c.in.config = c.config 131 c.out.config = c.config 132 133 c.out.updateOutSeq() 134} 135 136// Access to net.Conn methods. 137// Cannot just embed net.Conn because that would 138// export the struct field too. 139 140// LocalAddr returns the local network address. 141func (c *Conn) LocalAddr() net.Addr { 142 return c.conn.LocalAddr() 143} 144 145// RemoteAddr returns the remote network address. 146func (c *Conn) RemoteAddr() net.Addr { 147 return c.conn.RemoteAddr() 148} 149 150// SetDeadline sets the read and write deadlines associated with the connection. 151// A zero value for t means Read and Write will not time out. 152// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error. 153func (c *Conn) SetDeadline(t time.Time) error { 154 return c.conn.SetDeadline(t) 155} 156 157// SetReadDeadline sets the read deadline on the underlying connection. 158// A zero value for t means Read will not time out. 159func (c *Conn) SetReadDeadline(t time.Time) error { 160 return c.conn.SetReadDeadline(t) 161} 162 163// SetWriteDeadline sets the write deadline on the underlying conneciton. 164// A zero value for t means Write will not time out. 165// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error. 166func (c *Conn) SetWriteDeadline(t time.Time) error { 167 return c.conn.SetWriteDeadline(t) 168} 169 170// A halfConn represents one direction of the record layer 171// connection, either sending or receiving. 172type halfConn struct { 173 sync.Mutex 174 175 err error // first permanent error 176 version uint16 // protocol version 177 wireVersion uint16 // wire version 178 isDTLS bool 179 cipher any // cipher algorithm 180 mac macFunction 181 seq [8]byte // 64-bit sequence number 182 outSeq [8]byte // Mapped sequence number 183 bfree *block // list of free blocks 184 185 nextCipher any // next encryption state 186 nextMac macFunction // next MAC algorithm 187 nextSeq [6]byte // next epoch's starting sequence number in DTLS 188 189 // used to save allocating a new buffer for each MAC. 190 inDigestBuf, outDigestBuf []byte 191 192 trafficSecret []byte 193 194 config *Config 195} 196 197func (hc *halfConn) setErrorLocked(err error) error { 198 hc.err = err 199 return err 200} 201 202func (hc *halfConn) error() error { 203 // This should be locked, but I've removed it for the renegotiation 204 // tests since we don't concurrently read and write the same tls.Conn 205 // in any case during testing. 206 err := hc.err 207 return err 208} 209 210// prepareCipherSpec sets the encryption and MAC states 211// that a subsequent changeCipherSpec will use. 212func (hc *halfConn) prepareCipherSpec(version uint16, cipher any, mac macFunction) { 213 hc.wireVersion = version 214 protocolVersion, ok := wireToVersion(version, hc.isDTLS) 215 if !ok { 216 panic("TLS: unknown version") 217 } 218 hc.version = protocolVersion 219 hc.nextCipher = cipher 220 hc.nextMac = mac 221} 222 223// changeCipherSpec changes the encryption and MAC states 224// to the ones previously passed to prepareCipherSpec. 225func (hc *halfConn) changeCipherSpec(config *Config) error { 226 if hc.nextCipher == nil { 227 return alertInternalError 228 } 229 hc.cipher = hc.nextCipher 230 hc.mac = hc.nextMac 231 hc.nextCipher = nil 232 hc.nextMac = nil 233 hc.config = config 234 hc.incEpoch() 235 236 if config.Bugs.NullAllCiphers { 237 hc.cipher = nullCipher{} 238 hc.mac = nil 239 } 240 return nil 241} 242 243// useTrafficSecret sets the current cipher state for TLS 1.3. 244func (hc *halfConn) useTrafficSecret(version uint16, suite *cipherSuite, secret []byte, side trafficDirection) { 245 hc.wireVersion = version 246 protocolVersion, ok := wireToVersion(version, hc.isDTLS) 247 if !ok { 248 panic("TLS: unknown version") 249 } 250 hc.version = protocolVersion 251 hc.cipher = deriveTrafficAEAD(version, suite, secret, side) 252 if hc.config.Bugs.NullAllCiphers { 253 hc.cipher = nullCipher{} 254 } 255 hc.trafficSecret = secret 256 hc.incEpoch() 257} 258 259// resetCipher changes the cipher state back to no encryption to be able 260// to send an unencrypted ClientHello in response to HelloRetryRequest 261// after 0-RTT data was rejected. 262func (hc *halfConn) resetCipher() { 263 hc.cipher = nil 264 hc.incEpoch() 265} 266 267// incSeq increments the sequence number. 268func (hc *halfConn) incSeq(isOutgoing bool) { 269 limit := 0 270 increment := uint64(1) 271 if hc.isDTLS { 272 // Increment up to the epoch in DTLS. 273 limit = 2 274 } 275 for i := 7; i >= limit; i-- { 276 increment += uint64(hc.seq[i]) 277 hc.seq[i] = byte(increment) 278 increment >>= 8 279 } 280 281 // Not allowed to let sequence number wrap. 282 // Instead, must renegotiate before it does. 283 // Not likely enough to bother. 284 if increment != 0 { 285 panic("TLS: sequence number wraparound") 286 } 287 288 hc.updateOutSeq() 289} 290 291// incNextSeq increments the starting sequence number for the next epoch. 292func (hc *halfConn) incNextSeq() { 293 for i := len(hc.nextSeq) - 1; i >= 0; i-- { 294 hc.nextSeq[i]++ 295 if hc.nextSeq[i] != 0 { 296 return 297 } 298 } 299 panic("TLS: sequence number wraparound") 300} 301 302// incEpoch resets the sequence number. In DTLS, it also increments the epoch 303// half of the sequence number. 304func (hc *halfConn) incEpoch() { 305 if hc.isDTLS { 306 for i := 1; i >= 0; i-- { 307 hc.seq[i]++ 308 if hc.seq[i] != 0 { 309 break 310 } 311 if i == 0 { 312 panic("TLS: epoch number wraparound") 313 } 314 } 315 copy(hc.seq[2:], hc.nextSeq[:]) 316 for i := range hc.nextSeq { 317 hc.nextSeq[i] = 0 318 } 319 } else { 320 for i := range hc.seq { 321 hc.seq[i] = 0 322 } 323 } 324 325 hc.updateOutSeq() 326} 327 328func (hc *halfConn) updateOutSeq() { 329 if hc.config.Bugs.SequenceNumberMapping != nil { 330 seqU64 := binary.BigEndian.Uint64(hc.seq[:]) 331 seqU64 = hc.config.Bugs.SequenceNumberMapping(seqU64) 332 binary.BigEndian.PutUint64(hc.outSeq[:], seqU64) 333 334 // The DTLS epoch cannot be changed. 335 copy(hc.outSeq[:2], hc.seq[:2]) 336 return 337 } 338 339 copy(hc.outSeq[:], hc.seq[:]) 340} 341 342func (hc *halfConn) recordHeaderLen() int { 343 if hc.isDTLS { 344 return dtlsRecordHeaderLen 345 } 346 return tlsRecordHeaderLen 347} 348 349// removePadding returns an unpadded slice, in constant time, which is a prefix 350// of the input. It also returns a byte which is equal to 255 if the padding 351// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2 352func removePadding(payload []byte) ([]byte, byte) { 353 if len(payload) < 1 { 354 return payload, 0 355 } 356 357 paddingLen := payload[len(payload)-1] 358 t := uint(len(payload)-1) - uint(paddingLen) 359 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero 360 good := byte(int32(^t) >> 31) 361 362 toCheck := 255 // the maximum possible padding length 363 // The length of the padded data is public, so we can use an if here 364 if toCheck+1 > len(payload) { 365 toCheck = len(payload) - 1 366 } 367 368 for i := 0; i < toCheck; i++ { 369 t := uint(paddingLen) - uint(i) 370 // if i <= paddingLen then the MSB of t is zero 371 mask := byte(int32(^t) >> 31) 372 b := payload[len(payload)-1-i] 373 good &^= mask&paddingLen ^ mask&b 374 } 375 376 // We AND together the bits of good and replicate the result across 377 // all the bits. 378 good &= good << 4 379 good &= good << 2 380 good &= good << 1 381 good = uint8(int8(good) >> 7) 382 383 toRemove := good&paddingLen + 1 384 return payload[:len(payload)-int(toRemove)], good 385} 386 387func roundUp(a, b int) int { 388 return a + (b-a%b)%b 389} 390 391// cbcMode is an interface for block ciphers using cipher block chaining. 392type cbcMode interface { 393 cipher.BlockMode 394 SetIV([]byte) 395} 396 397// decrypt checks and strips the mac and decrypts the data in b. Returns a 398// success boolean, the number of bytes to skip from the start of the record in 399// order to get the application payload, the encrypted record type (or 0 400// if there is none), and an optional alert value. 401func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, contentType recordType, alertValue alert) { 402 recordHeaderLen := hc.recordHeaderLen() 403 404 // pull out payload 405 payload := b.data[recordHeaderLen:] 406 407 macSize := 0 408 if hc.mac != nil { 409 macSize = hc.mac.Size() 410 } 411 412 paddingGood := byte(255) 413 explicitIVLen := 0 414 415 seq := hc.seq[:] 416 if hc.isDTLS { 417 // DTLS sequence numbers are explicit. 418 seq = b.data[3:11] 419 } 420 421 // decrypt 422 if hc.cipher != nil { 423 switch c := hc.cipher.(type) { 424 case cipher.Stream: 425 c.XORKeyStream(payload, payload) 426 case *tlsAead: 427 nonce := seq 428 if c.explicitNonce { 429 explicitIVLen = 8 430 if len(payload) < explicitIVLen { 431 return false, 0, 0, alertBadRecordMAC 432 } 433 nonce = payload[:8] 434 payload = payload[8:] 435 } 436 437 var additionalData []byte 438 if hc.version < VersionTLS13 { 439 additionalData = make([]byte, 13) 440 copy(additionalData, seq) 441 copy(additionalData[8:], b.data[:3]) 442 n := len(payload) - c.Overhead() 443 additionalData[11] = byte(n >> 8) 444 additionalData[12] = byte(n) 445 } else { 446 additionalData = b.data[:recordHeaderLen] 447 } 448 var err error 449 payload, err = c.Open(payload[:0], nonce, payload, additionalData) 450 if err != nil { 451 return false, 0, 0, alertBadRecordMAC 452 } 453 b.resize(recordHeaderLen + explicitIVLen + len(payload)) 454 case cbcMode: 455 blockSize := c.BlockSize() 456 if hc.version >= VersionTLS11 || hc.isDTLS { 457 explicitIVLen = blockSize 458 } 459 460 if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) { 461 return false, 0, 0, alertBadRecordMAC 462 } 463 464 if explicitIVLen > 0 { 465 c.SetIV(payload[:explicitIVLen]) 466 payload = payload[explicitIVLen:] 467 } 468 c.CryptBlocks(payload, payload) 469 payload, paddingGood = removePadding(payload) 470 b.resize(recordHeaderLen + explicitIVLen + len(payload)) 471 472 // note that we still have a timing side-channel in the 473 // MAC check, below. An attacker can align the record 474 // so that a correct padding will cause one less hash 475 // block to be calculated. Then they can iteratively 476 // decrypt a record by breaking each byte. See 477 // "Password Interception in a SSL/TLS Channel", Brice 478 // Canvel et al. 479 // 480 // However, our behavior matches OpenSSL, so we leak 481 // only as much as they do. 482 case nullCipher: 483 break 484 default: 485 panic("unknown cipher type") 486 } 487 488 if hc.version >= VersionTLS13 { 489 i := len(payload) 490 for i > 0 && payload[i-1] == 0 { 491 i-- 492 } 493 payload = payload[:i] 494 if len(payload) == 0 { 495 return false, 0, 0, alertUnexpectedMessage 496 } 497 contentType = recordType(payload[len(payload)-1]) 498 payload = payload[:len(payload)-1] 499 b.resize(recordHeaderLen + len(payload)) 500 } 501 } 502 503 // check, strip mac 504 if hc.mac != nil { 505 if len(payload) < macSize { 506 return false, 0, 0, alertBadRecordMAC 507 } 508 509 // strip mac off payload, b.data 510 n := len(payload) - macSize 511 b.data[recordHeaderLen-2] = byte(n >> 8) 512 b.data[recordHeaderLen-1] = byte(n) 513 b.resize(recordHeaderLen + explicitIVLen + n) 514 remoteMAC := payload[n:] 515 localMAC := hc.mac.MAC(hc.inDigestBuf, seq, b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], payload[:n]) 516 517 if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 { 518 return false, 0, 0, alertBadRecordMAC 519 } 520 hc.inDigestBuf = localMAC 521 } 522 hc.incSeq(false) 523 524 return true, recordHeaderLen + explicitIVLen, contentType, 0 525} 526 527// padToBlockSize calculates the needed padding block, if any, for a payload. 528// On exit, prefix aliases payload and extends to the end of the last full 529// block of payload. finalBlock is a fresh slice which contains the contents of 530// any suffix of payload as well as the needed padding to make finalBlock a 531// full block. 532func padToBlockSize(payload []byte, blockSize int, config *Config) (prefix, finalBlock []byte) { 533 overrun := len(payload) % blockSize 534 prefix = payload[:len(payload)-overrun] 535 536 paddingLen := blockSize - overrun 537 finalSize := blockSize 538 if config.Bugs.MaxPadding { 539 for paddingLen+blockSize <= 256 { 540 paddingLen += blockSize 541 } 542 finalSize = 256 543 } 544 finalBlock = make([]byte, finalSize) 545 for i := range finalBlock { 546 finalBlock[i] = byte(paddingLen - 1) 547 } 548 if config.Bugs.PaddingFirstByteBad || config.Bugs.PaddingFirstByteBadIf255 && paddingLen == 256 { 549 finalBlock[overrun] ^= 0xff 550 } 551 copy(finalBlock, payload[len(payload)-overrun:]) 552 return 553} 554 555// encrypt encrypts and macs the data in b. 556func (hc *halfConn) encrypt(b *block, explicitIVLen int, typ recordType) (bool, alert) { 557 recordHeaderLen := hc.recordHeaderLen() 558 559 // mac 560 if hc.mac != nil { 561 mac := hc.mac.MAC(hc.outDigestBuf, hc.outSeq[0:], b.data[:3], b.data[recordHeaderLen-2:recordHeaderLen], b.data[recordHeaderLen+explicitIVLen:]) 562 563 n := len(b.data) 564 b.resize(n + len(mac)) 565 copy(b.data[n:], mac) 566 hc.outDigestBuf = mac 567 } 568 569 payload := b.data[recordHeaderLen:] 570 571 // encrypt 572 if hc.cipher != nil { 573 // Add TLS 1.3 padding. 574 if hc.version >= VersionTLS13 { 575 paddingLen := hc.config.Bugs.RecordPadding 576 if hc.config.Bugs.OmitRecordContents { 577 b.resize(recordHeaderLen + paddingLen) 578 } else { 579 b.resize(len(b.data) + 1 + paddingLen) 580 b.data[len(b.data)-paddingLen-1] = byte(typ) 581 } 582 for i := 0; i < paddingLen; i++ { 583 b.data[len(b.data)-paddingLen+i] = 0 584 } 585 } 586 587 switch c := hc.cipher.(type) { 588 case cipher.Stream: 589 c.XORKeyStream(payload, payload) 590 case *tlsAead: 591 payloadLen := len(b.data) - recordHeaderLen - explicitIVLen 592 b.resize(len(b.data) + c.Overhead()) 593 nonce := hc.outSeq[:] 594 if c.explicitNonce { 595 nonce = b.data[recordHeaderLen : recordHeaderLen+explicitIVLen] 596 } 597 payload := b.data[recordHeaderLen+explicitIVLen:] 598 payload = payload[:payloadLen] 599 600 var additionalData []byte 601 if hc.version < VersionTLS13 { 602 additionalData = make([]byte, 13) 603 copy(additionalData, hc.outSeq[:]) 604 copy(additionalData[8:], b.data[:3]) 605 additionalData[11] = byte(payloadLen >> 8) 606 additionalData[12] = byte(payloadLen) 607 } else { 608 additionalData = make([]byte, 5) 609 copy(additionalData, b.data[:3]) 610 n := len(b.data) - recordHeaderLen 611 additionalData[3] = byte(n >> 8) 612 additionalData[4] = byte(n) 613 } 614 615 c.Seal(payload[:0], nonce, payload, additionalData) 616 case cbcMode: 617 blockSize := c.BlockSize() 618 if explicitIVLen > 0 { 619 c.SetIV(payload[:explicitIVLen]) 620 payload = payload[explicitIVLen:] 621 } 622 prefix, finalBlock := padToBlockSize(payload, blockSize, hc.config) 623 b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock)) 624 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix) 625 c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock) 626 case nullCipher: 627 break 628 default: 629 panic("unknown cipher type") 630 } 631 } 632 633 // update length to include MAC and any block padding needed. 634 n := len(b.data) - recordHeaderLen 635 b.data[recordHeaderLen-2] = byte(n >> 8) 636 b.data[recordHeaderLen-1] = byte(n) 637 hc.incSeq(true) 638 639 return true, 0 640} 641 642// A block is a simple data buffer. 643type block struct { 644 data []byte 645 off int // index for Read 646 link *block 647} 648 649// resize resizes block to be n bytes, growing if necessary. 650func (b *block) resize(n int) { 651 if n > cap(b.data) { 652 b.reserve(n) 653 } 654 b.data = b.data[0:n] 655} 656 657// reserve makes sure that block contains a capacity of at least n bytes. 658func (b *block) reserve(n int) { 659 if cap(b.data) >= n { 660 return 661 } 662 m := cap(b.data) 663 if m == 0 { 664 m = 1024 665 } 666 for m < n { 667 m *= 2 668 } 669 data := make([]byte, len(b.data), m) 670 copy(data, b.data) 671 b.data = data 672} 673 674// readFromUntil reads from r into b until b contains at least n bytes 675// or else returns an error. 676func (b *block) readFromUntil(r io.Reader, n int) error { 677 // quick case 678 if len(b.data) >= n { 679 return nil 680 } 681 682 // read until have enough. 683 b.reserve(n) 684 for { 685 m, err := r.Read(b.data[len(b.data):cap(b.data)]) 686 b.data = b.data[0 : len(b.data)+m] 687 if len(b.data) >= n { 688 // TODO(bradfitz,agl): slightly suspicious 689 // that we're throwing away r.Read's err here. 690 break 691 } 692 if err != nil { 693 return err 694 } 695 } 696 return nil 697} 698 699func (b *block) Read(p []byte) (n int, err error) { 700 n = copy(p, b.data[b.off:]) 701 b.off += n 702 return 703} 704 705// newBlock allocates a new block, from hc's free list if possible. 706func (hc *halfConn) newBlock() *block { 707 b := hc.bfree 708 if b == nil { 709 return new(block) 710 } 711 hc.bfree = b.link 712 b.link = nil 713 b.resize(0) 714 return b 715} 716 717// freeBlock returns a block to hc's free list. 718// The protocol is such that each side only has a block or two on 719// its free list at a time, so there's no need to worry about 720// trimming the list, etc. 721func (hc *halfConn) freeBlock(b *block) { 722 b.link = hc.bfree 723 hc.bfree = b 724} 725 726// splitBlock splits a block after the first n bytes, 727// returning a block with those n bytes and a 728// block with the remainder. the latter may be nil. 729func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) { 730 if len(b.data) <= n { 731 return b, nil 732 } 733 bb := hc.newBlock() 734 bb.resize(len(b.data) - n) 735 copy(bb.data, b.data[n:]) 736 b.data = b.data[0:n] 737 return b, bb 738} 739 740func (c *Conn) useInTrafficSecret(level encryptionLevel, version uint16, suite *cipherSuite, secret []byte) error { 741 if c.hand.Len() != 0 { 742 return c.in.setErrorLocked(errors.New("tls: buffered handshake messages on cipher change")) 743 } 744 side := serverWrite 745 if !c.isClient { 746 side = clientWrite 747 } 748 if c.config.Bugs.MockQUICTransport != nil { 749 c.config.Bugs.MockQUICTransport.readLevel = level 750 c.config.Bugs.MockQUICTransport.readSecret = secret 751 c.config.Bugs.MockQUICTransport.readCipherSuite = suite.id 752 } 753 c.in.useTrafficSecret(version, suite, secret, side) 754 c.seenHandshakePackEnd = false 755 return nil 756} 757 758func (c *Conn) useOutTrafficSecret(level encryptionLevel, version uint16, suite *cipherSuite, secret []byte) { 759 side := serverWrite 760 if c.isClient { 761 side = clientWrite 762 } 763 if c.config.Bugs.MockQUICTransport != nil { 764 c.config.Bugs.MockQUICTransport.writeLevel = level 765 c.config.Bugs.MockQUICTransport.writeSecret = secret 766 c.config.Bugs.MockQUICTransport.writeCipherSuite = suite.id 767 } 768 c.out.useTrafficSecret(version, suite, secret, side) 769} 770 771func (c *Conn) setSkipEarlyData() { 772 if c.config.Bugs.MockQUICTransport != nil { 773 c.config.Bugs.MockQUICTransport.skipEarlyData = true 774 } else { 775 c.skipEarlyData = true 776 } 777} 778 779func (c *Conn) shouldSkipEarlyData() bool { 780 if c.config.Bugs.MockQUICTransport != nil { 781 return c.config.Bugs.MockQUICTransport.skipEarlyData 782 } 783 return c.skipEarlyData 784} 785 786func (c *Conn) doReadRecord(want recordType) (recordType, *block, error) { 787RestartReadRecord: 788 if c.isDTLS { 789 return c.dtlsDoReadRecord(want) 790 } 791 792 recordHeaderLen := c.in.recordHeaderLen() 793 794 if c.rawInput == nil { 795 c.rawInput = c.in.newBlock() 796 } 797 b := c.rawInput 798 799 // Read header, payload. 800 if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil { 801 // RFC suggests that EOF without an alertCloseNotify is 802 // an error, but popular web sites seem to do this, 803 // so we can't make it an error, outside of tests. 804 if err == io.EOF && c.config.Bugs.ExpectCloseNotify { 805 err = io.ErrUnexpectedEOF 806 } 807 if e, ok := err.(net.Error); !ok || !e.Temporary() { 808 c.in.setErrorLocked(err) 809 } 810 return 0, nil, err 811 } 812 813 typ := recordType(b.data[0]) 814 815 // No valid TLS record has a type of 0x80, however SSLv2 handshakes 816 // start with a uint16 length where the MSB is set and the first record 817 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests 818 // an SSLv2 client. 819 if want == recordTypeHandshake && typ == 0x80 { 820 c.sendAlert(alertProtocolVersion) 821 return 0, nil, c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received")) 822 } 823 824 vers := uint16(b.data[1])<<8 | uint16(b.data[2]) 825 n := int(b.data[3])<<8 | int(b.data[4]) 826 827 // Alerts sent near version negotiation do not have a well-defined 828 // record-layer version prior to TLS 1.3. (In TLS 1.3, the record-layer 829 // version is irrelevant.) 830 if typ != recordTypeAlert { 831 var expect uint16 832 if c.haveVers { 833 expect = c.vers 834 if c.vers >= VersionTLS13 { 835 expect = VersionTLS12 836 } 837 } else { 838 expect = c.config.Bugs.ExpectInitialRecordVersion 839 } 840 if expect != 0 && vers != expect { 841 c.sendAlert(alertProtocolVersion) 842 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, expect)) 843 } 844 } 845 if n > maxCiphertext { 846 c.sendAlert(alertRecordOverflow) 847 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n)) 848 } 849 if !c.haveVers { 850 // First message, be extra suspicious: 851 // this might not be a TLS client. 852 // Bail out before reading a full 'body', if possible. 853 // The current max version is 3.1. 854 // If the version is >= 16.0, it's probably not real. 855 // Similarly, a clientHello message encodes in 856 // well under a kilobyte. If the length is >= 12 kB, 857 // it's probably not real. 858 if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 { 859 c.sendAlert(alertUnexpectedMessage) 860 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake")) 861 } 862 } 863 if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil { 864 if err == io.EOF { 865 err = io.ErrUnexpectedEOF 866 } 867 if e, ok := err.(net.Error); !ok || !e.Temporary() { 868 c.in.setErrorLocked(err) 869 } 870 return 0, nil, err 871 } 872 873 // Process message. 874 b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n) 875 ok, off, encTyp, alertValue := c.in.decrypt(b) 876 877 // Handle skipping over early data. 878 if !ok && c.skipEarlyData { 879 goto RestartReadRecord 880 } 881 882 // If the server is expecting a second ClientHello (in response to 883 // a HelloRetryRequest) and the client sends early data, there 884 // won't be a decryption failure but it still needs to be skipped. 885 if c.in.cipher == nil && typ == recordTypeApplicationData && c.skipEarlyData { 886 goto RestartReadRecord 887 } 888 889 if !ok { 890 return 0, nil, c.in.setErrorLocked(c.sendAlert(alertValue)) 891 } 892 b.off = off 893 c.skipEarlyData = false 894 895 if c.vers >= VersionTLS13 && c.in.cipher != nil { 896 if typ != recordTypeApplicationData { 897 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: outer record type is not application data")) 898 } 899 typ = encTyp 900 } 901 902 length := len(b.data[b.off:]) 903 if c.config.Bugs.ExpectRecordSplitting && typ == recordTypeApplicationData && length != 1 && !c.seenOneByteRecord { 904 return 0, nil, c.in.setErrorLocked(fmt.Errorf("tls: application data records were not split")) 905 } 906 907 c.seenOneByteRecord = typ == recordTypeApplicationData && length == 1 908 return typ, b, nil 909} 910 911func (c *Conn) readTLS13ChangeCipherSpec() error { 912 if c.config.Bugs.MockQUICTransport != nil { 913 return nil 914 } 915 if !c.expectTLS13ChangeCipherSpec { 916 panic("c.expectTLS13ChangeCipherSpec not set") 917 } 918 919 // Read the ChangeCipherSpec. 920 if c.rawInput == nil { 921 c.rawInput = c.in.newBlock() 922 } 923 b := c.rawInput 924 if err := b.readFromUntil(c.conn, 1); err != nil { 925 return c.in.setErrorLocked(fmt.Errorf("tls: error reading TLS 1.3 ChangeCipherSpec: %s", err)) 926 } 927 if recordType(b.data[0]) == recordTypeAlert { 928 // If the client is sending an alert, allow the ChangeCipherSpec 929 // to be skipped. It may be rejecting a sufficiently malformed 930 // ServerHello that it can't parse out the version. 931 c.expectTLS13ChangeCipherSpec = false 932 return nil 933 } 934 if err := b.readFromUntil(c.conn, 6); err != nil { 935 return c.in.setErrorLocked(fmt.Errorf("tls: error reading TLS 1.3 ChangeCipherSpec: %s", err)) 936 } 937 938 // Check they match that we expect. 939 expected := [6]byte{byte(recordTypeChangeCipherSpec), 3, 1, 0, 1, 1} 940 if c.vers >= VersionTLS13 { 941 expected[2] = 3 942 } 943 if !bytes.Equal(b.data[:6], expected[:]) { 944 return c.in.setErrorLocked(fmt.Errorf("tls: error invalid TLS 1.3 ChangeCipherSpec: %x", b.data[:6])) 945 } 946 947 // Discard the data. 948 b, c.rawInput = c.in.splitBlock(b, 6) 949 c.in.freeBlock(b) 950 951 c.expectTLS13ChangeCipherSpec = false 952 return nil 953} 954 955// readRecord reads the next TLS record from the connection 956// and updates the record layer state. 957// c.in.Mutex <= L; c.input == nil. 958func (c *Conn) readRecord(want recordType) error { 959 // Caller must be in sync with connection: 960 // handshake data if handshake not yet completed, 961 // else application data. 962 switch want { 963 default: 964 c.sendAlert(alertInternalError) 965 return c.in.setErrorLocked(errors.New("tls: unknown record type requested")) 966 case recordTypeChangeCipherSpec: 967 if c.handshakeComplete { 968 c.sendAlert(alertInternalError) 969 return c.in.setErrorLocked(errors.New("tls: ChangeCipherSpec requested after handshake complete")) 970 } 971 case recordTypeApplicationData, recordTypeAlert, recordTypeHandshake: 972 break 973 } 974 975 if c.expectTLS13ChangeCipherSpec { 976 if err := c.readTLS13ChangeCipherSpec(); err != nil { 977 return err 978 } 979 } 980 981Again: 982 doReadRecord := c.doReadRecord 983 if c.config.Bugs.MockQUICTransport != nil { 984 doReadRecord = c.config.Bugs.MockQUICTransport.readRecord 985 } 986 typ, b, err := doReadRecord(want) 987 if err != nil { 988 return err 989 } 990 data := b.data[b.off:] 991 max := maxPlaintext 992 if c.config.Bugs.MaxReceivePlaintext != 0 { 993 max = c.config.Bugs.MaxReceivePlaintext 994 } 995 if len(data) > max { 996 err := c.sendAlert(alertRecordOverflow) 997 c.in.freeBlock(b) 998 return c.in.setErrorLocked(err) 999 } 1000 1001 if typ != recordTypeHandshake { 1002 c.seenHandshakePackEnd = false 1003 } else if c.seenHandshakePackEnd { 1004 c.in.freeBlock(b) 1005 return c.in.setErrorLocked(errors.New("tls: peer violated ExpectPackedEncryptedHandshake")) 1006 } 1007 1008 switch typ { 1009 default: 1010 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 1011 1012 case recordTypeAlert: 1013 if len(data) != 2 { 1014 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 1015 break 1016 } 1017 if alert(data[1]) == alertCloseNotify { 1018 c.in.setErrorLocked(io.EOF) 1019 break 1020 } 1021 switch data[0] { 1022 case alertLevelWarning: 1023 // drop on the floor 1024 c.in.freeBlock(b) 1025 goto Again 1026 case alertLevelError: 1027 c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])}) 1028 default: 1029 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 1030 } 1031 1032 case recordTypeChangeCipherSpec: 1033 if typ != want || len(data) != 1 || data[0] != 1 { 1034 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 1035 break 1036 } 1037 if c.hand.Len() != 0 { 1038 c.in.setErrorLocked(errors.New("tls: buffered handshake messages on cipher change")) 1039 break 1040 } 1041 if err := c.in.changeCipherSpec(c.config); err != nil { 1042 c.in.setErrorLocked(c.sendAlert(err.(alert))) 1043 } 1044 1045 case recordTypeApplicationData: 1046 if typ != want { 1047 c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 1048 break 1049 } 1050 c.input = b 1051 b = nil 1052 1053 case recordTypeHandshake: 1054 // Allow handshake data while reading application data to 1055 // trigger post-handshake messages. 1056 // TODO(rsc): Should at least pick off connection close. 1057 if typ != want && want != recordTypeApplicationData { 1058 return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation)) 1059 } 1060 c.hand.Write(data) 1061 if pack := c.config.Bugs.ExpectPackedEncryptedHandshake; pack > 0 && len(data) < pack && c.out.cipher != nil { 1062 c.seenHandshakePackEnd = true 1063 } 1064 } 1065 1066 if b != nil { 1067 c.in.freeBlock(b) 1068 } 1069 return c.in.err 1070} 1071 1072// sendAlert sends a TLS alert message. 1073// c.out.Mutex <= L. 1074func (c *Conn) sendAlertLocked(level byte, err alert) error { 1075 c.tmp[0] = level 1076 c.tmp[1] = byte(err) 1077 if c.config.Bugs.FragmentAlert { 1078 c.writeRecord(recordTypeAlert, c.tmp[0:1]) 1079 c.writeRecord(recordTypeAlert, c.tmp[1:2]) 1080 } else if c.config.Bugs.DoubleAlert { 1081 copy(c.tmp[2:4], c.tmp[0:2]) 1082 c.writeRecord(recordTypeAlert, c.tmp[0:4]) 1083 } else { 1084 c.writeRecord(recordTypeAlert, c.tmp[0:2]) 1085 } 1086 // Error alerts are fatal to the connection. 1087 if level == alertLevelError { 1088 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err}) 1089 } 1090 return nil 1091} 1092 1093// sendAlert sends a TLS alert message. 1094// L < c.out.Mutex. 1095func (c *Conn) sendAlert(err alert) error { 1096 level := byte(alertLevelError) 1097 if err == alertNoRenegotiation || err == alertCloseNotify { 1098 level = alertLevelWarning 1099 } 1100 return c.SendAlert(level, err) 1101} 1102 1103func (c *Conn) SendAlert(level byte, err alert) error { 1104 c.out.Lock() 1105 defer c.out.Unlock() 1106 return c.sendAlertLocked(level, err) 1107} 1108 1109// writeV2Record writes a record for a V2ClientHello. 1110func (c *Conn) writeV2Record(data []byte) (n int, err error) { 1111 record := make([]byte, 2+len(data)) 1112 record[0] = uint8(len(data)>>8) | 0x80 1113 record[1] = uint8(len(data)) 1114 copy(record[2:], data) 1115 return c.conn.Write(record) 1116} 1117 1118// writeRecord writes a TLS record with the given type and payload 1119// to the connection and updates the record layer state. 1120// c.out.Mutex <= L. 1121func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) { 1122 c.seenHandshakePackEnd = false 1123 if typ == recordTypeHandshake { 1124 msgType := data[0] 1125 if c.config.Bugs.SendWrongMessageType != 0 && msgType == c.config.Bugs.SendWrongMessageType { 1126 msgType += 42 1127 } 1128 if msgType != data[0] { 1129 data = append([]byte{msgType}, data[1:]...) 1130 } 1131 1132 if c.config.Bugs.SendTrailingMessageData != 0 && msgType == c.config.Bugs.SendTrailingMessageData { 1133 // Add a 0 to the body. 1134 newData := make([]byte, len(data)+1) 1135 copy(newData, data) 1136 1137 // Fix the header. 1138 newLen := len(newData) - 4 1139 newData[1] = byte(newLen >> 16) 1140 newData[2] = byte(newLen >> 8) 1141 newData[3] = byte(newLen) 1142 1143 data = newData 1144 } 1145 1146 if c.config.Bugs.TrailingDataWithFinished && msgType == typeFinished { 1147 // Add a 0 to the record. Note unused bytes in |data| may be owned by the 1148 // caller, so we force a new allocation. 1149 data = append(data[:len(data):len(data)], 0) 1150 } 1151 } 1152 1153 if c.isDTLS { 1154 return c.dtlsWriteRecord(typ, data) 1155 } 1156 if c.config.Bugs.MockQUICTransport != nil { 1157 return c.config.Bugs.MockQUICTransport.writeRecord(typ, data) 1158 } 1159 1160 if typ == recordTypeHandshake { 1161 if c.config.Bugs.SendHelloRequestBeforeEveryHandshakeMessage { 1162 newData := make([]byte, 0, 4+len(data)) 1163 newData = append(newData, typeHelloRequest, 0, 0, 0) 1164 newData = append(newData, data...) 1165 data = newData 1166 } 1167 1168 if c.config.Bugs.PackHandshakeFlight { 1169 c.pendingFlight.Write(data) 1170 return len(data), nil 1171 } 1172 } 1173 1174 // Flush buffered data before writing anything. 1175 if err := c.flushHandshake(); err != nil { 1176 return 0, err 1177 } 1178 1179 if typ == recordTypeApplicationData && c.config.Bugs.SendPostHandshakeChangeCipherSpec { 1180 if _, err := c.doWriteRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil { 1181 return 0, err 1182 } 1183 } 1184 1185 return c.doWriteRecord(typ, data) 1186} 1187 1188func (c *Conn) doWriteRecord(typ recordType, data []byte) (n int, err error) { 1189 recordHeaderLen := c.out.recordHeaderLen() 1190 b := c.out.newBlock() 1191 first := true 1192 isClientHello := typ == recordTypeHandshake && len(data) > 0 && data[0] == typeClientHello 1193 for len(data) > 0 || first { 1194 m := len(data) 1195 if m > maxPlaintext && !c.config.Bugs.SendLargeRecords { 1196 m = maxPlaintext 1197 } 1198 if typ == recordTypeHandshake && c.config.Bugs.MaxHandshakeRecordLength > 0 && m > c.config.Bugs.MaxHandshakeRecordLength { 1199 m = c.config.Bugs.MaxHandshakeRecordLength 1200 // By default, do not fragment the client_version or 1201 // server_version, which are located in the first 6 1202 // bytes. 1203 if first && isClientHello && !c.config.Bugs.FragmentClientVersion && m < 6 { 1204 m = 6 1205 } 1206 } 1207 explicitIVLen := 0 1208 explicitIVIsSeq := false 1209 first = false 1210 1211 var cbc cbcMode 1212 if c.out.version >= VersionTLS11 { 1213 var ok bool 1214 if cbc, ok = c.out.cipher.(cbcMode); ok { 1215 explicitIVLen = cbc.BlockSize() 1216 } 1217 } 1218 if explicitIVLen == 0 { 1219 if aead, ok := c.out.cipher.(*tlsAead); ok && aead.explicitNonce { 1220 explicitIVLen = 8 1221 // The AES-GCM construction in TLS has an 1222 // explicit nonce so that the nonce can be 1223 // random. However, the nonce is only 8 bytes 1224 // which is too small for a secure, random 1225 // nonce. Therefore we use the sequence number 1226 // as the nonce. 1227 explicitIVIsSeq = true 1228 } 1229 } 1230 b.resize(recordHeaderLen + explicitIVLen + m) 1231 b.data[0] = byte(typ) 1232 if c.vers >= VersionTLS13 && c.out.cipher != nil { 1233 b.data[0] = byte(recordTypeApplicationData) 1234 if outerType := c.config.Bugs.OuterRecordType; outerType != 0 { 1235 b.data[0] = byte(outerType) 1236 } 1237 } 1238 vers := c.vers 1239 if vers == 0 { 1240 // Some TLS servers fail if the record version is 1241 // greater than TLS 1.0 for the initial ClientHello. 1242 // 1243 // TLS 1.3 fixes the version number in the record 1244 // layer to {3, 1}. 1245 vers = VersionTLS10 1246 } 1247 if c.vers >= VersionTLS13 || c.out.version >= VersionTLS13 { 1248 vers = VersionTLS12 1249 } 1250 1251 if c.config.Bugs.SendRecordVersion != 0 { 1252 vers = c.config.Bugs.SendRecordVersion 1253 } 1254 if c.vers == 0 && c.config.Bugs.SendInitialRecordVersion != 0 { 1255 vers = c.config.Bugs.SendInitialRecordVersion 1256 } 1257 b.data[1] = byte(vers >> 8) 1258 b.data[2] = byte(vers) 1259 b.data[3] = byte(m >> 8) 1260 b.data[4] = byte(m) 1261 if explicitIVLen > 0 { 1262 explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen] 1263 if explicitIVIsSeq { 1264 copy(explicitIV, c.out.seq[:]) 1265 } else { 1266 if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil { 1267 break 1268 } 1269 } 1270 } 1271 copy(b.data[recordHeaderLen+explicitIVLen:], data) 1272 c.out.encrypt(b, explicitIVLen, typ) 1273 _, err = c.conn.Write(b.data) 1274 if err != nil { 1275 break 1276 } 1277 n += m 1278 data = data[m:] 1279 } 1280 c.out.freeBlock(b) 1281 1282 if typ == recordTypeChangeCipherSpec && c.vers < VersionTLS13 { 1283 err = c.out.changeCipherSpec(c.config) 1284 if err != nil { 1285 return n, c.sendAlertLocked(alertLevelError, err.(alert)) 1286 } 1287 } 1288 return 1289} 1290 1291func (c *Conn) flushHandshake() error { 1292 if c.isDTLS { 1293 return c.dtlsFlushHandshake() 1294 } 1295 1296 for c.pendingFlight.Len() > 0 { 1297 var buf [maxPlaintext]byte 1298 n, _ := c.pendingFlight.Read(buf[:]) 1299 if _, err := c.doWriteRecord(recordTypeHandshake, buf[:n]); err != nil { 1300 return err 1301 } 1302 } 1303 1304 c.pendingFlight.Reset() 1305 return nil 1306} 1307 1308func (c *Conn) doReadHandshake() ([]byte, error) { 1309 if c.isDTLS { 1310 return c.dtlsDoReadHandshake() 1311 } 1312 1313 for c.hand.Len() < 4 { 1314 if err := c.in.err; err != nil { 1315 return nil, err 1316 } 1317 if err := c.readRecord(recordTypeHandshake); err != nil { 1318 return nil, err 1319 } 1320 } 1321 1322 data := c.hand.Bytes() 1323 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3]) 1324 if n > maxHandshake { 1325 return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError)) 1326 } 1327 for c.hand.Len() < 4+n { 1328 if err := c.in.err; err != nil { 1329 return nil, err 1330 } 1331 if err := c.readRecord(recordTypeHandshake); err != nil { 1332 return nil, err 1333 } 1334 } 1335 return c.hand.Next(4 + n), nil 1336} 1337 1338// readHandshake reads the next handshake message from 1339// the record layer. 1340// c.in.Mutex < L; c.out.Mutex < L. 1341func (c *Conn) readHandshake() (any, error) { 1342 data, err := c.doReadHandshake() 1343 if err != nil { 1344 return nil, err 1345 } 1346 1347 var m handshakeMessage 1348 switch data[0] { 1349 case typeHelloRequest: 1350 m = new(helloRequestMsg) 1351 case typeClientHello: 1352 m = &clientHelloMsg{ 1353 isDTLS: c.isDTLS, 1354 } 1355 case typeServerHello: 1356 m = &serverHelloMsg{ 1357 isDTLS: c.isDTLS, 1358 } 1359 case typeNewSessionTicket: 1360 m = &newSessionTicketMsg{ 1361 vers: c.wireVersion, 1362 isDTLS: c.isDTLS, 1363 } 1364 case typeEncryptedExtensions: 1365 if c.isClient { 1366 m = new(encryptedExtensionsMsg) 1367 } else { 1368 m = new(clientEncryptedExtensionsMsg) 1369 } 1370 case typeCertificate: 1371 m = &certificateMsg{ 1372 hasRequestContext: c.vers >= VersionTLS13, 1373 } 1374 case typeCompressedCertificate: 1375 m = new(compressedCertificateMsg) 1376 case typeCertificateRequest: 1377 m = &certificateRequestMsg{ 1378 vers: c.wireVersion, 1379 hasSignatureAlgorithm: c.vers >= VersionTLS12, 1380 hasRequestContext: c.vers >= VersionTLS13, 1381 } 1382 case typeCertificateStatus: 1383 m = new(certificateStatusMsg) 1384 case typeServerKeyExchange: 1385 m = new(serverKeyExchangeMsg) 1386 case typeServerHelloDone: 1387 m = new(serverHelloDoneMsg) 1388 case typeClientKeyExchange: 1389 m = new(clientKeyExchangeMsg) 1390 case typeCertificateVerify: 1391 m = &certificateVerifyMsg{ 1392 hasSignatureAlgorithm: c.vers >= VersionTLS12, 1393 } 1394 case typeNextProtocol: 1395 m = new(nextProtoMsg) 1396 case typeFinished: 1397 m = new(finishedMsg) 1398 case typeHelloVerifyRequest: 1399 m = new(helloVerifyRequestMsg) 1400 case typeChannelID: 1401 m = new(channelIDMsg) 1402 case typeKeyUpdate: 1403 m = new(keyUpdateMsg) 1404 case typeEndOfEarlyData: 1405 m = new(endOfEarlyDataMsg) 1406 default: 1407 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 1408 } 1409 1410 // The handshake message unmarshallers 1411 // expect to be able to keep references to data, 1412 // so pass in a fresh copy that won't be overwritten. 1413 data = append([]byte(nil), data...) 1414 1415 if data[0] == typeServerHello && len(data) >= 38 { 1416 vers := uint16(data[4])<<8 | uint16(data[5]) 1417 if vers == VersionTLS12 && bytes.Equal(data[6:38], tls13HelloRetryRequest) { 1418 m = new(helloRetryRequestMsg) 1419 } 1420 } 1421 1422 if !m.unmarshal(data) { 1423 return nil, c.in.setErrorLocked(c.sendAlert(alertDecodeError)) 1424 } 1425 return m, nil 1426} 1427 1428// skipPacket processes all the DTLS records in packet. It updates 1429// sequence number expectations but otherwise ignores them. 1430func (c *Conn) skipPacket(packet []byte) error { 1431 for len(packet) > 0 { 1432 if len(packet) < 13 { 1433 return errors.New("tls: bad packet") 1434 } 1435 // Dropped packets are completely ignored save to update 1436 // expected sequence numbers for this and the next epoch. (We 1437 // don't assert on the contents of the packets both for 1438 // simplicity and because a previous test with one shorter 1439 // timeout schedule would have done so.) 1440 epoch := packet[3:5] 1441 seq := packet[5:11] 1442 length := uint16(packet[11])<<8 | uint16(packet[12]) 1443 if bytes.Equal(c.in.seq[:2], epoch) { 1444 if bytes.Compare(seq, c.in.seq[2:]) < 0 { 1445 return errors.New("tls: sequence mismatch") 1446 } 1447 copy(c.in.seq[2:], seq) 1448 c.in.incSeq(false) 1449 } else { 1450 if bytes.Compare(seq, c.in.nextSeq[:]) < 0 { 1451 return errors.New("tls: sequence mismatch") 1452 } 1453 copy(c.in.nextSeq[:], seq) 1454 c.in.incNextSeq() 1455 } 1456 if len(packet) < 13+int(length) { 1457 return errors.New("tls: bad packet") 1458 } 1459 packet = packet[13+length:] 1460 } 1461 return nil 1462} 1463 1464// simulatePacketLoss simulates the loss of a handshake leg from the 1465// peer based on the schedule in c.config.Bugs. If resendFunc is 1466// non-nil, it is called after each simulated timeout to retransmit 1467// handshake messages from the local end. This is used in cases where 1468// the peer retransmits on a stale Finished rather than a timeout. 1469func (c *Conn) simulatePacketLoss(resendFunc func()) error { 1470 if len(c.config.Bugs.TimeoutSchedule) == 0 { 1471 return nil 1472 } 1473 if !c.isDTLS { 1474 return errors.New("tls: TimeoutSchedule may only be set in DTLS") 1475 } 1476 if c.config.Bugs.PacketAdaptor == nil { 1477 return errors.New("tls: TimeoutSchedule set without PacketAdapter") 1478 } 1479 for _, timeout := range c.config.Bugs.TimeoutSchedule { 1480 // Simulate a timeout. 1481 packets, err := c.config.Bugs.PacketAdaptor.SendReadTimeout(timeout) 1482 if err != nil { 1483 return err 1484 } 1485 for _, packet := range packets { 1486 if err := c.skipPacket(packet); err != nil { 1487 return err 1488 } 1489 } 1490 if resendFunc != nil { 1491 resendFunc() 1492 } 1493 } 1494 return nil 1495} 1496 1497func (c *Conn) SendHalfHelloRequest() error { 1498 if err := c.Handshake(); err != nil { 1499 return err 1500 } 1501 1502 c.out.Lock() 1503 defer c.out.Unlock() 1504 1505 if _, err := c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0}); err != nil { 1506 return err 1507 } 1508 return c.flushHandshake() 1509} 1510 1511// Write writes data to the connection. 1512func (c *Conn) Write(b []byte) (int, error) { 1513 if err := c.Handshake(); err != nil { 1514 return 0, err 1515 } 1516 1517 c.out.Lock() 1518 defer c.out.Unlock() 1519 1520 if err := c.out.err; err != nil { 1521 return 0, err 1522 } 1523 1524 if !c.handshakeComplete { 1525 return 0, alertInternalError 1526 } 1527 1528 if c.keyUpdateRequested { 1529 if err := c.sendKeyUpdateLocked(keyUpdateNotRequested); err != nil { 1530 return 0, err 1531 } 1532 c.keyUpdateRequested = false 1533 } 1534 1535 if c.config.Bugs.SendSpuriousAlert != 0 { 1536 c.sendAlertLocked(alertLevelError, c.config.Bugs.SendSpuriousAlert) 1537 } 1538 1539 if c.config.Bugs.SendHelloRequestBeforeEveryAppDataRecord { 1540 c.writeRecord(recordTypeHandshake, []byte{typeHelloRequest, 0, 0, 0}) 1541 c.flushHandshake() 1542 } 1543 1544 // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext 1545 // attack when using block mode ciphers due to predictable IVs. 1546 // This can be prevented by splitting each Application Data 1547 // record into two records, effectively randomizing the IV. 1548 // 1549 // http://www.openssl.org/~bodo/tls-cbc.txt 1550 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814 1551 // http://www.imperialviolet.org/2012/01/15/beastfollowup.html 1552 1553 var m int 1554 if len(b) > 1 && c.vers <= VersionTLS10 && !c.isDTLS { 1555 if _, ok := c.out.cipher.(cipher.BlockMode); ok { 1556 n, err := c.writeRecord(recordTypeApplicationData, b[:1]) 1557 if err != nil { 1558 return n, c.out.setErrorLocked(err) 1559 } 1560 m, b = 1, b[1:] 1561 } 1562 } 1563 1564 n, err := c.writeRecord(recordTypeApplicationData, b) 1565 return n + m, c.out.setErrorLocked(err) 1566} 1567 1568func (c *Conn) processTLS13NewSessionTicket(newSessionTicket *newSessionTicketMsg, cipherSuite *cipherSuite) error { 1569 if c.config.Bugs.ExpectGREASE && !newSessionTicket.hasGREASEExtension { 1570 return errors.New("tls: no GREASE ticket extension found") 1571 } 1572 1573 if c.config.Bugs.ExpectTicketEarlyData && newSessionTicket.maxEarlyDataSize == 0 { 1574 return errors.New("tls: no early_data ticket extension found") 1575 } 1576 1577 if c.config.Bugs.ExpectNoNewSessionTicket { 1578 return errors.New("tls: received unexpected NewSessionTicket") 1579 } 1580 1581 if c.config.ClientSessionCache == nil || newSessionTicket.ticketLifetime == 0 { 1582 return nil 1583 } 1584 1585 session := &ClientSessionState{ 1586 sessionTicket: newSessionTicket.ticket, 1587 vers: c.vers, 1588 wireVersion: c.wireVersion, 1589 cipherSuite: cipherSuite, 1590 secret: deriveSessionPSK(cipherSuite, c.wireVersion, c.resumptionSecret, newSessionTicket.ticketNonce), 1591 serverCertificates: c.peerCertificates, 1592 sctList: c.sctList, 1593 ocspResponse: c.ocspResponse, 1594 ticketCreationTime: c.config.time(), 1595 ticketExpiration: c.config.time().Add(time.Duration(newSessionTicket.ticketLifetime) * time.Second), 1596 ticketAgeAdd: newSessionTicket.ticketAgeAdd, 1597 maxEarlyDataSize: newSessionTicket.maxEarlyDataSize, 1598 earlyALPN: c.clientProtocol, 1599 hasApplicationSettings: c.hasApplicationSettings, 1600 localApplicationSettings: c.localApplicationSettings, 1601 peerApplicationSettings: c.peerApplicationSettings, 1602 hasApplicationSettingsOld: c.hasApplicationSettingsOld, 1603 localApplicationSettingsOld: c.localApplicationSettingsOld, 1604 peerApplicationSettingsOld: c.peerApplicationSettingsOld, 1605 } 1606 1607 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config) 1608 _, ok := c.config.ClientSessionCache.Get(cacheKey) 1609 if !ok || !c.config.Bugs.UseFirstSessionTicket { 1610 c.config.ClientSessionCache.Put(cacheKey, session) 1611 } 1612 return nil 1613} 1614 1615func (c *Conn) handlePostHandshakeMessage() error { 1616 msg, err := c.readHandshake() 1617 if err != nil { 1618 return err 1619 } 1620 1621 if c.vers < VersionTLS13 { 1622 if !c.isClient { 1623 c.sendAlert(alertUnexpectedMessage) 1624 return errors.New("tls: unexpected post-handshake message") 1625 } 1626 1627 _, ok := msg.(*helloRequestMsg) 1628 if !ok { 1629 c.sendAlert(alertUnexpectedMessage) 1630 return alertUnexpectedMessage 1631 } 1632 1633 c.handshakeComplete = false 1634 return c.Handshake() 1635 } 1636 1637 if c.isClient { 1638 if newSessionTicket, ok := msg.(*newSessionTicketMsg); ok { 1639 return c.processTLS13NewSessionTicket(newSessionTicket, c.cipherSuite) 1640 } 1641 } 1642 1643 if keyUpdate, ok := msg.(*keyUpdateMsg); ok { 1644 c.keyUpdateSeen = true 1645 1646 if c.config.Bugs.RejectUnsolicitedKeyUpdate { 1647 return errors.New("tls: unexpected KeyUpdate message") 1648 } 1649 if err := c.useInTrafficSecret(encryptionApplication, c.in.wireVersion, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), c.wireVersion, c.in.trafficSecret)); err != nil { 1650 return err 1651 } 1652 if keyUpdate.keyUpdateRequest == keyUpdateRequested { 1653 c.keyUpdateRequested = true 1654 } 1655 return nil 1656 } 1657 1658 c.sendAlert(alertUnexpectedMessage) 1659 return errors.New("tls: unexpected post-handshake message") 1660} 1661 1662// Reads a KeyUpdate acknowledgment from the peer. There may not be any 1663// application data records before the message. 1664func (c *Conn) ReadKeyUpdateACK() error { 1665 c.in.Lock() 1666 defer c.in.Unlock() 1667 1668 msg, err := c.readHandshake() 1669 if err != nil { 1670 return err 1671 } 1672 1673 keyUpdate, ok := msg.(*keyUpdateMsg) 1674 if !ok { 1675 c.sendAlert(alertUnexpectedMessage) 1676 return fmt.Errorf("tls: unexpected message (%T) when reading KeyUpdate", msg) 1677 } 1678 1679 if keyUpdate.keyUpdateRequest != keyUpdateNotRequested { 1680 return errors.New("tls: received invalid KeyUpdate message") 1681 } 1682 1683 return c.useInTrafficSecret(encryptionApplication, c.in.wireVersion, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), c.wireVersion, c.in.trafficSecret)) 1684} 1685 1686func (c *Conn) Renegotiate() error { 1687 if !c.isClient { 1688 helloReq := new(helloRequestMsg).marshal() 1689 if c.config.Bugs.BadHelloRequest != nil { 1690 helloReq = c.config.Bugs.BadHelloRequest 1691 } 1692 c.writeRecord(recordTypeHandshake, helloReq) 1693 c.flushHandshake() 1694 } 1695 1696 c.handshakeComplete = false 1697 return c.Handshake() 1698} 1699 1700// Read can be made to time out and return a net.Error with Timeout() == true 1701// after a fixed time limit; see SetDeadline and SetReadDeadline. 1702func (c *Conn) Read(b []byte) (n int, err error) { 1703 if err = c.Handshake(); err != nil { 1704 return 1705 } 1706 1707 c.in.Lock() 1708 defer c.in.Unlock() 1709 1710 // Some OpenSSL servers send empty records in order to randomize the 1711 // CBC IV. So this loop ignores a limited number of empty records. 1712 const maxConsecutiveEmptyRecords = 100 1713 for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ { 1714 for c.input == nil && c.in.err == nil { 1715 if err := c.readRecord(recordTypeApplicationData); err != nil { 1716 // Soft error, like EAGAIN 1717 return 0, err 1718 } 1719 for c.hand.Len() > 0 { 1720 // We received handshake bytes, indicating a 1721 // post-handshake message. 1722 if err := c.handlePostHandshakeMessage(); err != nil { 1723 return 0, err 1724 } 1725 } 1726 } 1727 if err := c.in.err; err != nil { 1728 return 0, err 1729 } 1730 1731 n, err = c.input.Read(b) 1732 if c.input.off >= len(c.input.data) || c.isDTLS { 1733 c.in.freeBlock(c.input) 1734 c.input = nil 1735 } 1736 1737 // If a close-notify alert is waiting, read it so that 1738 // we can return (n, EOF) instead of (n, nil), to signal 1739 // to the HTTP response reading goroutine that the 1740 // connection is now closed. This eliminates a race 1741 // where the HTTP response reading goroutine would 1742 // otherwise not observe the EOF until its next read, 1743 // by which time a client goroutine might have already 1744 // tried to reuse the HTTP connection for a new 1745 // request. 1746 // See https://codereview.appspot.com/76400046 1747 // and http://golang.org/issue/3514 1748 if ri := c.rawInput; ri != nil && 1749 n != 0 && err == nil && 1750 c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert { 1751 if recErr := c.readRecord(recordTypeApplicationData); recErr != nil { 1752 err = recErr // will be io.EOF on closeNotify 1753 } 1754 } 1755 1756 if n != 0 || err != nil { 1757 return n, err 1758 } 1759 } 1760 1761 return 0, io.ErrNoProgress 1762} 1763 1764// Close closes the connection. 1765func (c *Conn) Close() error { 1766 var alertErr error 1767 1768 c.handshakeMutex.Lock() 1769 defer c.handshakeMutex.Unlock() 1770 if c.handshakeComplete && !c.config.Bugs.NoCloseNotify { 1771 alert := alertCloseNotify 1772 if c.config.Bugs.SendAlertOnShutdown != 0 { 1773 alert = c.config.Bugs.SendAlertOnShutdown 1774 } 1775 alertErr = c.sendAlert(alert) 1776 // Clear local alerts when sending alerts so we continue to wait 1777 // for the peer rather than closing the socket early. 1778 if opErr, ok := alertErr.(*net.OpError); ok && opErr.Op == "local error" { 1779 alertErr = nil 1780 } 1781 } 1782 1783 // Consume a close_notify from the peer if one hasn't been received 1784 // already. This avoids the peer from failing |SSL_shutdown| due to a 1785 // write failing. 1786 if c.handshakeComplete && alertErr == nil && c.config.Bugs.ExpectCloseNotify { 1787 for c.in.error() == nil { 1788 c.readRecord(recordTypeAlert) 1789 } 1790 if c.in.error() != io.EOF { 1791 alertErr = c.in.error() 1792 } 1793 } 1794 1795 if err := c.conn.Close(); err != nil { 1796 return err 1797 } 1798 return alertErr 1799} 1800 1801// Handshake runs the client or server handshake 1802// protocol if it has not yet been run. 1803// Most uses of this package need not call Handshake 1804// explicitly: the first Read or Write will call it automatically. 1805func (c *Conn) Handshake() error { 1806 c.handshakeMutex.Lock() 1807 defer c.handshakeMutex.Unlock() 1808 if err := c.handshakeErr; err != nil { 1809 return err 1810 } 1811 if c.handshakeComplete { 1812 return nil 1813 } 1814 1815 if c.isDTLS && c.config.Bugs.SendSplitAlert { 1816 c.conn.Write([]byte{ 1817 byte(recordTypeAlert), // type 1818 0xfe, 0xff, // version 1819 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, // sequence 1820 0x0, 0x2, // length 1821 }) 1822 c.conn.Write([]byte{alertLevelError, byte(alertInternalError)}) 1823 } 1824 if data := c.config.Bugs.AppDataBeforeHandshake; data != nil { 1825 c.writeRecord(recordTypeApplicationData, data) 1826 } 1827 if c.isClient { 1828 c.handshakeErr = c.clientHandshake() 1829 } else { 1830 c.handshakeErr = c.serverHandshake() 1831 } 1832 if c.handshakeErr == nil && c.config.Bugs.SendInvalidRecordType { 1833 c.writeRecord(recordType(42), []byte("invalid record")) 1834 } 1835 return c.handshakeErr 1836} 1837 1838// ConnectionState returns basic TLS details about the connection. 1839func (c *Conn) ConnectionState() ConnectionState { 1840 c.handshakeMutex.Lock() 1841 defer c.handshakeMutex.Unlock() 1842 1843 var state ConnectionState 1844 state.HandshakeComplete = c.handshakeComplete 1845 if c.handshakeComplete { 1846 state.Version = c.vers 1847 state.NegotiatedProtocol = c.clientProtocol 1848 state.DidResume = c.didResume 1849 state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback 1850 state.NegotiatedProtocolFromALPN = c.usedALPN 1851 state.CipherSuite = c.cipherSuite.id 1852 state.PeerCertificates = c.peerCertificates 1853 state.VerifiedChains = c.verifiedChains 1854 state.OCSPResponse = c.ocspResponse 1855 state.ServerName = c.serverName 1856 state.ChannelID = c.channelID 1857 state.SRTPProtectionProfile = c.srtpProtectionProfile 1858 state.TLSUnique = c.firstFinished[:] 1859 state.SCTList = c.sctList 1860 state.PeerSignatureAlgorithm = c.peerSignatureAlgorithm 1861 state.CurveID = c.curveID 1862 state.QUICTransportParams = c.quicTransportParams 1863 state.QUICTransportParamsLegacy = c.quicTransportParamsLegacy 1864 state.HasApplicationSettings = c.hasApplicationSettings 1865 state.PeerApplicationSettings = c.peerApplicationSettings 1866 state.HasApplicationSettingsOld = c.hasApplicationSettingsOld 1867 state.PeerApplicationSettingsOld = c.peerApplicationSettingsOld 1868 state.ECHAccepted = c.echAccepted 1869 } 1870 1871 return state 1872} 1873 1874// VerifyHostname checks that the peer certificate chain is valid for 1875// connecting to host. If so, it returns nil; if not, it returns an error 1876// describing the problem. 1877func (c *Conn) VerifyHostname(host string) error { 1878 c.handshakeMutex.Lock() 1879 defer c.handshakeMutex.Unlock() 1880 if !c.isClient { 1881 return errors.New("tls: VerifyHostname called on TLS server connection") 1882 } 1883 if !c.handshakeComplete { 1884 return errors.New("tls: handshake has not yet been performed") 1885 } 1886 return c.peerCertificates[0].VerifyHostname(host) 1887} 1888 1889func (c *Conn) exportKeyingMaterialTLS13(length int, secret, label, context []byte) []byte { 1890 hash := c.cipherSuite.hash() 1891 exporterKeyingLabel := []byte("exporter") 1892 contextHash := hash.New() 1893 contextHash.Write(context) 1894 exporterContext := hash.New().Sum(nil) 1895 derivedSecret := hkdfExpandLabel(c.cipherSuite.hash(), secret, label, exporterContext, hash.Size()) 1896 return hkdfExpandLabel(c.cipherSuite.hash(), derivedSecret, exporterKeyingLabel, contextHash.Sum(nil), length) 1897} 1898 1899// ExportKeyingMaterial exports keying material from the current connection 1900// state, as per RFC 5705. 1901func (c *Conn) ExportKeyingMaterial(length int, label, context []byte, useContext bool) ([]byte, error) { 1902 c.handshakeMutex.Lock() 1903 defer c.handshakeMutex.Unlock() 1904 if !c.handshakeComplete { 1905 return nil, errors.New("tls: handshake has not yet been performed") 1906 } 1907 1908 if c.vers >= VersionTLS13 { 1909 return c.exportKeyingMaterialTLS13(length, c.exporterSecret, label, context), nil 1910 } 1911 1912 seedLen := len(c.clientRandom) + len(c.serverRandom) 1913 if useContext { 1914 seedLen += 2 + len(context) 1915 } 1916 seed := make([]byte, 0, seedLen) 1917 seed = append(seed, c.clientRandom[:]...) 1918 seed = append(seed, c.serverRandom[:]...) 1919 if useContext { 1920 seed = append(seed, byte(len(context)>>8), byte(len(context))) 1921 seed = append(seed, context...) 1922 } 1923 result := make([]byte, length) 1924 prfForVersion(c.vers, c.cipherSuite)(result, c.exporterSecret, label, seed) 1925 return result, nil 1926} 1927 1928func (c *Conn) ExportEarlyKeyingMaterial(length int, label, context []byte) ([]byte, error) { 1929 if c.vers < VersionTLS13 { 1930 return nil, errors.New("tls: early exporters not defined before TLS 1.3") 1931 } 1932 1933 if c.earlyExporterSecret == nil { 1934 return nil, errors.New("tls: no early exporter secret") 1935 } 1936 1937 return c.exportKeyingMaterialTLS13(length, c.earlyExporterSecret, label, context), nil 1938} 1939 1940// noRenegotiationInfo returns true if the renegotiation info extension 1941// should be supported in the current handshake. 1942func (c *Conn) noRenegotiationInfo() bool { 1943 if c.config.Bugs.NoRenegotiationInfo { 1944 return true 1945 } 1946 if c.cipherSuite == nil && c.config.Bugs.NoRenegotiationInfoInInitial { 1947 return true 1948 } 1949 if c.cipherSuite != nil && c.config.Bugs.NoRenegotiationInfoAfterInitial { 1950 return true 1951 } 1952 return false 1953} 1954 1955func (c *Conn) SendNewSessionTicket(nonce []byte) error { 1956 if c.isClient || c.vers < VersionTLS13 { 1957 return errors.New("tls: cannot send post-handshake NewSessionTicket") 1958 } 1959 1960 var peerCertificatesRaw [][]byte 1961 for _, cert := range c.peerCertificates { 1962 peerCertificatesRaw = append(peerCertificatesRaw, cert.Raw) 1963 } 1964 1965 addBuffer := make([]byte, 4) 1966 _, err := io.ReadFull(c.config.rand(), addBuffer) 1967 if err != nil { 1968 c.sendAlert(alertInternalError) 1969 return errors.New("tls: short read from Rand: " + err.Error()) 1970 } 1971 ticketAgeAdd := uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0]) 1972 1973 // TODO(davidben): Allow configuring these values. 1974 m := &newSessionTicketMsg{ 1975 vers: c.wireVersion, 1976 isDTLS: c.isDTLS, 1977 ticketLifetime: uint32(24 * time.Hour / time.Second), 1978 duplicateEarlyDataExtension: c.config.Bugs.DuplicateTicketEarlyData, 1979 customExtension: c.config.Bugs.CustomTicketExtension, 1980 ticketAgeAdd: ticketAgeAdd, 1981 ticketNonce: nonce, 1982 maxEarlyDataSize: c.config.MaxEarlyDataSize, 1983 } 1984 if c.config.Bugs.MockQUICTransport != nil && m.maxEarlyDataSize > 0 { 1985 m.maxEarlyDataSize = 0xffffffff 1986 } 1987 1988 if c.config.Bugs.SendTicketLifetime != 0 { 1989 m.ticketLifetime = uint32(c.config.Bugs.SendTicketLifetime / time.Second) 1990 } 1991 1992 state := sessionState{ 1993 vers: c.vers, 1994 cipherSuite: c.cipherSuite.id, 1995 secret: deriveSessionPSK(c.cipherSuite, c.wireVersion, c.resumptionSecret, nonce), 1996 certificates: peerCertificatesRaw, 1997 ticketCreationTime: c.config.time(), 1998 ticketExpiration: c.config.time().Add(time.Duration(m.ticketLifetime) * time.Second), 1999 ticketAgeAdd: uint32(addBuffer[3])<<24 | uint32(addBuffer[2])<<16 | uint32(addBuffer[1])<<8 | uint32(addBuffer[0]), 2000 earlyALPN: []byte(c.clientProtocol), 2001 hasApplicationSettings: c.hasApplicationSettings, 2002 localApplicationSettings: c.localApplicationSettings, 2003 peerApplicationSettings: c.peerApplicationSettings, 2004 hasApplicationSettingsOld: c.hasApplicationSettingsOld, 2005 localApplicationSettingsOld: c.localApplicationSettingsOld, 2006 peerApplicationSettingsOld: c.peerApplicationSettingsOld, 2007 } 2008 2009 if !c.config.Bugs.SendEmptySessionTicket { 2010 var err error 2011 m.ticket, err = c.encryptTicket(&state) 2012 if err != nil { 2013 return err 2014 } 2015 } 2016 c.out.Lock() 2017 defer c.out.Unlock() 2018 _, err = c.writeRecord(recordTypeHandshake, m.marshal()) 2019 return err 2020} 2021 2022func (c *Conn) SendKeyUpdate(keyUpdateRequest byte) error { 2023 c.out.Lock() 2024 defer c.out.Unlock() 2025 return c.sendKeyUpdateLocked(keyUpdateRequest) 2026} 2027 2028func (c *Conn) sendKeyUpdateLocked(keyUpdateRequest byte) error { 2029 if c.vers < VersionTLS13 { 2030 return errors.New("tls: attempted to send KeyUpdate before TLS 1.3") 2031 } 2032 2033 m := keyUpdateMsg{ 2034 keyUpdateRequest: keyUpdateRequest, 2035 } 2036 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil { 2037 return err 2038 } 2039 if err := c.flushHandshake(); err != nil { 2040 return err 2041 } 2042 c.useOutTrafficSecret(encryptionApplication, c.out.wireVersion, c.cipherSuite, updateTrafficSecret(c.cipherSuite.hash(), c.wireVersion, c.out.trafficSecret)) 2043 return nil 2044} 2045 2046func (c *Conn) sendFakeEarlyData(len int) error { 2047 // Assemble a fake early data record. This does not use writeRecord 2048 // because the record layer may be using different keys at this point. 2049 payload := make([]byte, 5+len) 2050 payload[0] = byte(recordTypeApplicationData) 2051 payload[1] = 3 2052 payload[2] = 3 2053 payload[3] = byte(len >> 8) 2054 payload[4] = byte(len) 2055 _, err := c.conn.Write(payload) 2056 return err 2057} 2058