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