github.com/twelsh-aw/go/src@v0.0.0-20230516233729-a56fe86a7c81/crypto/tls/conn.go (about) 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 7 package tls 8 9 import ( 10 "bytes" 11 "context" 12 "crypto/cipher" 13 "crypto/subtle" 14 "crypto/x509" 15 "errors" 16 "fmt" 17 "hash" 18 "io" 19 "net" 20 "sync" 21 "sync/atomic" 22 "time" 23 ) 24 25 // A Conn represents a secured connection. 26 // It implements the net.Conn interface. 27 type Conn struct { 28 // constant 29 conn net.Conn 30 isClient bool 31 handshakeFn func(context.Context) error // (*Conn).clientHandshake or serverHandshake 32 33 // isHandshakeComplete is true if the connection is currently transferring 34 // application data (i.e. is not currently processing a handshake). 35 // isHandshakeComplete is true implies handshakeErr == nil. 36 isHandshakeComplete atomic.Bool 37 // constant after handshake; protected by handshakeMutex 38 handshakeMutex sync.Mutex 39 handshakeErr error // error resulting from handshake 40 vers uint16 // TLS version 41 haveVers bool // version has been negotiated 42 config *Config // configuration passed to constructor 43 // handshakes counts the number of handshakes performed on the 44 // connection so far. If renegotiation is disabled then this is either 45 // zero or one. 46 handshakes int 47 didResume bool // whether this connection was a session resumption 48 cipherSuite uint16 49 ocspResponse []byte // stapled OCSP response 50 scts [][]byte // signed certificate timestamps from server 51 peerCertificates []*x509.Certificate 52 // activeCertHandles contains the cache handles to certificates in 53 // peerCertificates that are used to track active references. 54 activeCertHandles []*activeCert 55 // verifiedChains contains the certificate chains that we built, as 56 // opposed to the ones presented by the server. 57 verifiedChains [][]*x509.Certificate 58 // serverName contains the server name indicated by the client, if any. 59 serverName string 60 // secureRenegotiation is true if the server echoed the secure 61 // renegotiation extension. (This is meaningless as a server because 62 // renegotiation is not supported in that case.) 63 secureRenegotiation bool 64 // ekm is a closure for exporting keying material. 65 ekm func(label string, context []byte, length int) ([]byte, error) 66 // resumptionSecret is the resumption_master_secret for handling 67 // NewSessionTicket messages. nil if config.SessionTicketsDisabled. 68 resumptionSecret []byte 69 70 // ticketKeys is the set of active session ticket keys for this 71 // connection. The first one is used to encrypt new tickets and 72 // all are tried to decrypt tickets. 73 ticketKeys []ticketKey 74 75 // clientFinishedIsFirst is true if the client sent the first Finished 76 // message during the most recent handshake. This is recorded because 77 // the first transmitted Finished message is the tls-unique 78 // channel-binding value. 79 clientFinishedIsFirst bool 80 81 // closeNotifyErr is any error from sending the alertCloseNotify record. 82 closeNotifyErr error 83 // closeNotifySent is true if the Conn attempted to send an 84 // alertCloseNotify record. 85 closeNotifySent bool 86 87 // clientFinished and serverFinished contain the Finished message sent 88 // by the client or server in the most recent handshake. This is 89 // retained to support the renegotiation extension and tls-unique 90 // channel-binding. 91 clientFinished [12]byte 92 serverFinished [12]byte 93 94 // clientProtocol is the negotiated ALPN protocol. 95 clientProtocol string 96 97 // input/output 98 in, out halfConn 99 rawInput bytes.Buffer // raw input, starting with a record header 100 input bytes.Reader // application data waiting to be read, from rawInput.Next 101 hand bytes.Buffer // handshake data waiting to be read 102 buffering bool // whether records are buffered in sendBuf 103 sendBuf []byte // a buffer of records waiting to be sent 104 105 // bytesSent counts the bytes of application data sent. 106 // packetsSent counts packets. 107 bytesSent int64 108 packetsSent int64 109 110 // retryCount counts the number of consecutive non-advancing records 111 // received by Conn.readRecord. That is, records that neither advance the 112 // handshake, nor deliver application data. Protected by in.Mutex. 113 retryCount int 114 115 // activeCall indicates whether Close has been call in the low bit. 116 // the rest of the bits are the number of goroutines in Conn.Write. 117 activeCall atomic.Int32 118 119 tmp [16]byte 120 } 121 122 // Access to net.Conn methods. 123 // Cannot just embed net.Conn because that would 124 // export the struct field too. 125 126 // LocalAddr returns the local network address. 127 func (c *Conn) LocalAddr() net.Addr { 128 return c.conn.LocalAddr() 129 } 130 131 // RemoteAddr returns the remote network address. 132 func (c *Conn) RemoteAddr() net.Addr { 133 return c.conn.RemoteAddr() 134 } 135 136 // SetDeadline sets the read and write deadlines associated with the connection. 137 // A zero value for t means Read and Write will not time out. 138 // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error. 139 func (c *Conn) SetDeadline(t time.Time) error { 140 return c.conn.SetDeadline(t) 141 } 142 143 // SetReadDeadline sets the read deadline on the underlying connection. 144 // A zero value for t means Read will not time out. 145 func (c *Conn) SetReadDeadline(t time.Time) error { 146 return c.conn.SetReadDeadline(t) 147 } 148 149 // SetWriteDeadline sets the write deadline on the underlying connection. 150 // A zero value for t means Write will not time out. 151 // After a Write has timed out, the TLS state is corrupt and all future writes will return the same error. 152 func (c *Conn) SetWriteDeadline(t time.Time) error { 153 return c.conn.SetWriteDeadline(t) 154 } 155 156 // NetConn returns the underlying connection that is wrapped by c. 157 // Note that writing to or reading from this connection directly will corrupt the 158 // TLS session. 159 func (c *Conn) NetConn() net.Conn { 160 return c.conn 161 } 162 163 // A halfConn represents one direction of the record layer 164 // connection, either sending or receiving. 165 type halfConn struct { 166 sync.Mutex 167 168 err error // first permanent error 169 version uint16 // protocol version 170 cipher any // cipher algorithm 171 mac hash.Hash 172 seq [8]byte // 64-bit sequence number 173 174 scratchBuf [13]byte // to avoid allocs; interface method args escape 175 176 nextCipher any // next encryption state 177 nextMac hash.Hash // next MAC algorithm 178 179 trafficSecret []byte // current TLS 1.3 traffic secret 180 } 181 182 type permanentError struct { 183 err net.Error 184 } 185 186 func (e *permanentError) Error() string { return e.err.Error() } 187 func (e *permanentError) Unwrap() error { return e.err } 188 func (e *permanentError) Timeout() bool { return e.err.Timeout() } 189 func (e *permanentError) Temporary() bool { return false } 190 191 func (hc *halfConn) setErrorLocked(err error) error { 192 if e, ok := err.(net.Error); ok { 193 hc.err = &permanentError{err: e} 194 } else { 195 hc.err = err 196 } 197 return hc.err 198 } 199 200 // prepareCipherSpec sets the encryption and MAC states 201 // that a subsequent changeCipherSpec will use. 202 func (hc *halfConn) prepareCipherSpec(version uint16, cipher any, mac hash.Hash) { 203 hc.version = version 204 hc.nextCipher = cipher 205 hc.nextMac = mac 206 } 207 208 // changeCipherSpec changes the encryption and MAC states 209 // to the ones previously passed to prepareCipherSpec. 210 func (hc *halfConn) changeCipherSpec() error { 211 if hc.nextCipher == nil || hc.version == VersionTLS13 { 212 return alertInternalError 213 } 214 hc.cipher = hc.nextCipher 215 hc.mac = hc.nextMac 216 hc.nextCipher = nil 217 hc.nextMac = nil 218 for i := range hc.seq { 219 hc.seq[i] = 0 220 } 221 return nil 222 } 223 224 func (hc *halfConn) setTrafficSecret(suite *cipherSuiteTLS13, secret []byte) { 225 hc.trafficSecret = secret 226 key, iv := suite.trafficKey(secret) 227 hc.cipher = suite.aead(key, iv) 228 for i := range hc.seq { 229 hc.seq[i] = 0 230 } 231 } 232 233 // incSeq increments the sequence number. 234 func (hc *halfConn) incSeq() { 235 for i := 7; i >= 0; i-- { 236 hc.seq[i]++ 237 if hc.seq[i] != 0 { 238 return 239 } 240 } 241 242 // Not allowed to let sequence number wrap. 243 // Instead, must renegotiate before it does. 244 // Not likely enough to bother. 245 panic("TLS: sequence number wraparound") 246 } 247 248 // explicitNonceLen returns the number of bytes of explicit nonce or IV included 249 // in each record. Explicit nonces are present only in CBC modes after TLS 1.0 250 // and in certain AEAD modes in TLS 1.2. 251 func (hc *halfConn) explicitNonceLen() int { 252 if hc.cipher == nil { 253 return 0 254 } 255 256 switch c := hc.cipher.(type) { 257 case cipher.Stream: 258 return 0 259 case aead: 260 return c.explicitNonceLen() 261 case cbcMode: 262 // TLS 1.1 introduced a per-record explicit IV to fix the BEAST attack. 263 if hc.version >= VersionTLS11 { 264 return c.BlockSize() 265 } 266 return 0 267 default: 268 panic("unknown cipher type") 269 } 270 } 271 272 // extractPadding returns, in constant time, the length of the padding to remove 273 // from the end of payload. It also returns a byte which is equal to 255 if the 274 // padding was valid and 0 otherwise. See RFC 2246, Section 6.2.3.2. 275 func extractPadding(payload []byte) (toRemove int, good byte) { 276 if len(payload) < 1 { 277 return 0, 0 278 } 279 280 paddingLen := payload[len(payload)-1] 281 t := uint(len(payload)-1) - uint(paddingLen) 282 // if len(payload) >= (paddingLen - 1) then the MSB of t is zero 283 good = byte(int32(^t) >> 31) 284 285 // The maximum possible padding length plus the actual length field 286 toCheck := 256 287 // The length of the padded data is public, so we can use an if here 288 if toCheck > len(payload) { 289 toCheck = len(payload) 290 } 291 292 for i := 0; i < toCheck; i++ { 293 t := uint(paddingLen) - uint(i) 294 // if i <= paddingLen then the MSB of t is zero 295 mask := byte(int32(^t) >> 31) 296 b := payload[len(payload)-1-i] 297 good &^= mask&paddingLen ^ mask&b 298 } 299 300 // We AND together the bits of good and replicate the result across 301 // all the bits. 302 good &= good << 4 303 good &= good << 2 304 good &= good << 1 305 good = uint8(int8(good) >> 7) 306 307 // Zero the padding length on error. This ensures any unchecked bytes 308 // are included in the MAC. Otherwise, an attacker that could 309 // distinguish MAC failures from padding failures could mount an attack 310 // similar to POODLE in SSL 3.0: given a good ciphertext that uses a 311 // full block's worth of padding, replace the final block with another 312 // block. If the MAC check passed but the padding check failed, the 313 // last byte of that block decrypted to the block size. 314 // 315 // See also macAndPaddingGood logic below. 316 paddingLen &= good 317 318 toRemove = int(paddingLen) + 1 319 return 320 } 321 322 func roundUp(a, b int) int { 323 return a + (b-a%b)%b 324 } 325 326 // cbcMode is an interface for block ciphers using cipher block chaining. 327 type cbcMode interface { 328 cipher.BlockMode 329 SetIV([]byte) 330 } 331 332 // decrypt authenticates and decrypts the record if protection is active at 333 // this stage. The returned plaintext might overlap with the input. 334 func (hc *halfConn) decrypt(record []byte) ([]byte, recordType, error) { 335 var plaintext []byte 336 typ := recordType(record[0]) 337 payload := record[recordHeaderLen:] 338 339 // In TLS 1.3, change_cipher_spec messages are to be ignored without being 340 // decrypted. See RFC 8446, Appendix D.4. 341 if hc.version == VersionTLS13 && typ == recordTypeChangeCipherSpec { 342 return payload, typ, nil 343 } 344 345 paddingGood := byte(255) 346 paddingLen := 0 347 348 explicitNonceLen := hc.explicitNonceLen() 349 350 if hc.cipher != nil { 351 switch c := hc.cipher.(type) { 352 case cipher.Stream: 353 c.XORKeyStream(payload, payload) 354 case aead: 355 if len(payload) < explicitNonceLen { 356 return nil, 0, alertBadRecordMAC 357 } 358 nonce := payload[:explicitNonceLen] 359 if len(nonce) == 0 { 360 nonce = hc.seq[:] 361 } 362 payload = payload[explicitNonceLen:] 363 364 var additionalData []byte 365 if hc.version == VersionTLS13 { 366 additionalData = record[:recordHeaderLen] 367 } else { 368 additionalData = append(hc.scratchBuf[:0], hc.seq[:]...) 369 additionalData = append(additionalData, record[:3]...) 370 n := len(payload) - c.Overhead() 371 additionalData = append(additionalData, byte(n>>8), byte(n)) 372 } 373 374 var err error 375 plaintext, err = c.Open(payload[:0], nonce, payload, additionalData) 376 if err != nil { 377 return nil, 0, alertBadRecordMAC 378 } 379 case cbcMode: 380 blockSize := c.BlockSize() 381 minPayload := explicitNonceLen + roundUp(hc.mac.Size()+1, blockSize) 382 if len(payload)%blockSize != 0 || len(payload) < minPayload { 383 return nil, 0, alertBadRecordMAC 384 } 385 386 if explicitNonceLen > 0 { 387 c.SetIV(payload[:explicitNonceLen]) 388 payload = payload[explicitNonceLen:] 389 } 390 c.CryptBlocks(payload, payload) 391 392 // In a limited attempt to protect against CBC padding oracles like 393 // Lucky13, the data past paddingLen (which is secret) is passed to 394 // the MAC function as extra data, to be fed into the HMAC after 395 // computing the digest. This makes the MAC roughly constant time as 396 // long as the digest computation is constant time and does not 397 // affect the subsequent write, modulo cache effects. 398 paddingLen, paddingGood = extractPadding(payload) 399 default: 400 panic("unknown cipher type") 401 } 402 403 if hc.version == VersionTLS13 { 404 if typ != recordTypeApplicationData { 405 return nil, 0, alertUnexpectedMessage 406 } 407 if len(plaintext) > maxPlaintext+1 { 408 return nil, 0, alertRecordOverflow 409 } 410 // Remove padding and find the ContentType scanning from the end. 411 for i := len(plaintext) - 1; i >= 0; i-- { 412 if plaintext[i] != 0 { 413 typ = recordType(plaintext[i]) 414 plaintext = plaintext[:i] 415 break 416 } 417 if i == 0 { 418 return nil, 0, alertUnexpectedMessage 419 } 420 } 421 } 422 } else { 423 plaintext = payload 424 } 425 426 if hc.mac != nil { 427 macSize := hc.mac.Size() 428 if len(payload) < macSize { 429 return nil, 0, alertBadRecordMAC 430 } 431 432 n := len(payload) - macSize - paddingLen 433 n = subtle.ConstantTimeSelect(int(uint32(n)>>31), 0, n) // if n < 0 { n = 0 } 434 record[3] = byte(n >> 8) 435 record[4] = byte(n) 436 remoteMAC := payload[n : n+macSize] 437 localMAC := tls10MAC(hc.mac, hc.scratchBuf[:0], hc.seq[:], record[:recordHeaderLen], payload[:n], payload[n+macSize:]) 438 439 // This is equivalent to checking the MACs and paddingGood 440 // separately, but in constant-time to prevent distinguishing 441 // padding failures from MAC failures. Depending on what value 442 // of paddingLen was returned on bad padding, distinguishing 443 // bad MAC from bad padding can lead to an attack. 444 // 445 // See also the logic at the end of extractPadding. 446 macAndPaddingGood := subtle.ConstantTimeCompare(localMAC, remoteMAC) & int(paddingGood) 447 if macAndPaddingGood != 1 { 448 return nil, 0, alertBadRecordMAC 449 } 450 451 plaintext = payload[:n] 452 } 453 454 hc.incSeq() 455 return plaintext, typ, nil 456 } 457 458 // sliceForAppend extends the input slice by n bytes. head is the full extended 459 // slice, while tail is the appended part. If the original slice has sufficient 460 // capacity no allocation is performed. 461 func sliceForAppend(in []byte, n int) (head, tail []byte) { 462 if total := len(in) + n; cap(in) >= total { 463 head = in[:total] 464 } else { 465 head = make([]byte, total) 466 copy(head, in) 467 } 468 tail = head[len(in):] 469 return 470 } 471 472 // encrypt encrypts payload, adding the appropriate nonce and/or MAC, and 473 // appends it to record, which must already contain the record header. 474 func (hc *halfConn) encrypt(record, payload []byte, rand io.Reader) ([]byte, error) { 475 if hc.cipher == nil { 476 return append(record, payload...), nil 477 } 478 479 var explicitNonce []byte 480 if explicitNonceLen := hc.explicitNonceLen(); explicitNonceLen > 0 { 481 record, explicitNonce = sliceForAppend(record, explicitNonceLen) 482 if _, isCBC := hc.cipher.(cbcMode); !isCBC && explicitNonceLen < 16 { 483 // The AES-GCM construction in TLS has an explicit nonce so that the 484 // nonce can be random. However, the nonce is only 8 bytes which is 485 // too small for a secure, random nonce. Therefore we use the 486 // sequence number as the nonce. The 3DES-CBC construction also has 487 // an 8 bytes nonce but its nonces must be unpredictable (see RFC 488 // 5246, Appendix F.3), forcing us to use randomness. That's not 489 // 3DES' biggest problem anyway because the birthday bound on block 490 // collision is reached first due to its similarly small block size 491 // (see the Sweet32 attack). 492 copy(explicitNonce, hc.seq[:]) 493 } else { 494 if _, err := io.ReadFull(rand, explicitNonce); err != nil { 495 return nil, err 496 } 497 } 498 } 499 500 var dst []byte 501 switch c := hc.cipher.(type) { 502 case cipher.Stream: 503 mac := tls10MAC(hc.mac, hc.scratchBuf[:0], hc.seq[:], record[:recordHeaderLen], payload, nil) 504 record, dst = sliceForAppend(record, len(payload)+len(mac)) 505 c.XORKeyStream(dst[:len(payload)], payload) 506 c.XORKeyStream(dst[len(payload):], mac) 507 case aead: 508 nonce := explicitNonce 509 if len(nonce) == 0 { 510 nonce = hc.seq[:] 511 } 512 513 if hc.version == VersionTLS13 { 514 record = append(record, payload...) 515 516 // Encrypt the actual ContentType and replace the plaintext one. 517 record = append(record, record[0]) 518 record[0] = byte(recordTypeApplicationData) 519 520 n := len(payload) + 1 + c.Overhead() 521 record[3] = byte(n >> 8) 522 record[4] = byte(n) 523 524 record = c.Seal(record[:recordHeaderLen], 525 nonce, record[recordHeaderLen:], record[:recordHeaderLen]) 526 } else { 527 additionalData := append(hc.scratchBuf[:0], hc.seq[:]...) 528 additionalData = append(additionalData, record[:recordHeaderLen]...) 529 record = c.Seal(record, nonce, payload, additionalData) 530 } 531 case cbcMode: 532 mac := tls10MAC(hc.mac, hc.scratchBuf[:0], hc.seq[:], record[:recordHeaderLen], payload, nil) 533 blockSize := c.BlockSize() 534 plaintextLen := len(payload) + len(mac) 535 paddingLen := blockSize - plaintextLen%blockSize 536 record, dst = sliceForAppend(record, plaintextLen+paddingLen) 537 copy(dst, payload) 538 copy(dst[len(payload):], mac) 539 for i := plaintextLen; i < len(dst); i++ { 540 dst[i] = byte(paddingLen - 1) 541 } 542 if len(explicitNonce) > 0 { 543 c.SetIV(explicitNonce) 544 } 545 c.CryptBlocks(dst, dst) 546 default: 547 panic("unknown cipher type") 548 } 549 550 // Update length to include nonce, MAC and any block padding needed. 551 n := len(record) - recordHeaderLen 552 record[3] = byte(n >> 8) 553 record[4] = byte(n) 554 hc.incSeq() 555 556 return record, nil 557 } 558 559 // RecordHeaderError is returned when a TLS record header is invalid. 560 type RecordHeaderError struct { 561 // Msg contains a human readable string that describes the error. 562 Msg string 563 // RecordHeader contains the five bytes of TLS record header that 564 // triggered the error. 565 RecordHeader [5]byte 566 // Conn provides the underlying net.Conn in the case that a client 567 // sent an initial handshake that didn't look like TLS. 568 // It is nil if there's already been a handshake or a TLS alert has 569 // been written to the connection. 570 Conn net.Conn 571 } 572 573 func (e RecordHeaderError) Error() string { return "tls: " + e.Msg } 574 575 func (c *Conn) newRecordHeaderError(conn net.Conn, msg string) (err RecordHeaderError) { 576 err.Msg = msg 577 err.Conn = conn 578 copy(err.RecordHeader[:], c.rawInput.Bytes()) 579 return err 580 } 581 582 func (c *Conn) readRecord() error { 583 return c.readRecordOrCCS(false) 584 } 585 586 func (c *Conn) readChangeCipherSpec() error { 587 return c.readRecordOrCCS(true) 588 } 589 590 // readRecordOrCCS reads one or more TLS records from the connection and 591 // updates the record layer state. Some invariants: 592 // - c.in must be locked 593 // - c.input must be empty 594 // 595 // During the handshake one and only one of the following will happen: 596 // - c.hand grows 597 // - c.in.changeCipherSpec is called 598 // - an error is returned 599 // 600 // After the handshake one and only one of the following will happen: 601 // - c.hand grows 602 // - c.input is set 603 // - an error is returned 604 func (c *Conn) readRecordOrCCS(expectChangeCipherSpec bool) error { 605 if c.in.err != nil { 606 return c.in.err 607 } 608 handshakeComplete := c.isHandshakeComplete.Load() 609 610 // This function modifies c.rawInput, which owns the c.input memory. 611 if c.input.Len() != 0 { 612 return c.in.setErrorLocked(errors.New("tls: internal error: attempted to read record with pending application data")) 613 } 614 c.input.Reset(nil) 615 616 // Read header, payload. 617 if err := c.readFromUntil(c.conn, recordHeaderLen); err != nil { 618 // RFC 8446, Section 6.1 suggests that EOF without an alertCloseNotify 619 // is an error, but popular web sites seem to do this, so we accept it 620 // if and only if at the record boundary. 621 if err == io.ErrUnexpectedEOF && c.rawInput.Len() == 0 { 622 err = io.EOF 623 } 624 if e, ok := err.(net.Error); !ok || !e.Temporary() { 625 c.in.setErrorLocked(err) 626 } 627 return err 628 } 629 hdr := c.rawInput.Bytes()[:recordHeaderLen] 630 typ := recordType(hdr[0]) 631 632 // No valid TLS record has a type of 0x80, however SSLv2 handshakes 633 // start with a uint16 length where the MSB is set and the first record 634 // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests 635 // an SSLv2 client. 636 if !handshakeComplete && typ == 0x80 { 637 c.sendAlert(alertProtocolVersion) 638 return c.in.setErrorLocked(c.newRecordHeaderError(nil, "unsupported SSLv2 handshake received")) 639 } 640 641 vers := uint16(hdr[1])<<8 | uint16(hdr[2]) 642 n := int(hdr[3])<<8 | int(hdr[4]) 643 if c.haveVers && c.vers != VersionTLS13 && vers != c.vers { 644 c.sendAlert(alertProtocolVersion) 645 msg := fmt.Sprintf("received record with version %x when expecting version %x", vers, c.vers) 646 return c.in.setErrorLocked(c.newRecordHeaderError(nil, msg)) 647 } 648 if !c.haveVers { 649 // First message, be extra suspicious: this might not be a TLS 650 // client. Bail out before reading a full 'body', if possible. 651 // The current max version is 3.3 so if the version is >= 16.0, 652 // it's probably not real. 653 if (typ != recordTypeAlert && typ != recordTypeHandshake) || vers >= 0x1000 { 654 return c.in.setErrorLocked(c.newRecordHeaderError(c.conn, "first record does not look like a TLS handshake")) 655 } 656 } 657 if c.vers == VersionTLS13 && n > maxCiphertextTLS13 || n > maxCiphertext { 658 c.sendAlert(alertRecordOverflow) 659 msg := fmt.Sprintf("oversized record received with length %d", n) 660 return c.in.setErrorLocked(c.newRecordHeaderError(nil, msg)) 661 } 662 if err := c.readFromUntil(c.conn, recordHeaderLen+n); err != nil { 663 if e, ok := err.(net.Error); !ok || !e.Temporary() { 664 c.in.setErrorLocked(err) 665 } 666 return err 667 } 668 669 // Process message. 670 record := c.rawInput.Next(recordHeaderLen + n) 671 data, typ, err := c.in.decrypt(record) 672 if err != nil { 673 return c.in.setErrorLocked(c.sendAlert(err.(alert))) 674 } 675 if len(data) > maxPlaintext { 676 return c.in.setErrorLocked(c.sendAlert(alertRecordOverflow)) 677 } 678 679 // Application Data messages are always protected. 680 if c.in.cipher == nil && typ == recordTypeApplicationData { 681 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 682 } 683 684 if typ != recordTypeAlert && typ != recordTypeChangeCipherSpec && len(data) > 0 { 685 // This is a state-advancing message: reset the retry count. 686 c.retryCount = 0 687 } 688 689 // Handshake messages MUST NOT be interleaved with other record types in TLS 1.3. 690 if c.vers == VersionTLS13 && typ != recordTypeHandshake && c.hand.Len() > 0 { 691 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 692 } 693 694 switch typ { 695 default: 696 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 697 698 case recordTypeAlert: 699 if len(data) != 2 { 700 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 701 } 702 if alert(data[1]) == alertCloseNotify { 703 return c.in.setErrorLocked(io.EOF) 704 } 705 if c.vers == VersionTLS13 { 706 return c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])}) 707 } 708 switch data[0] { 709 case alertLevelWarning: 710 // Drop the record on the floor and retry. 711 return c.retryReadRecord(expectChangeCipherSpec) 712 case alertLevelError: 713 return c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])}) 714 default: 715 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 716 } 717 718 case recordTypeChangeCipherSpec: 719 if len(data) != 1 || data[0] != 1 { 720 return c.in.setErrorLocked(c.sendAlert(alertDecodeError)) 721 } 722 // Handshake messages are not allowed to fragment across the CCS. 723 if c.hand.Len() > 0 { 724 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 725 } 726 // In TLS 1.3, change_cipher_spec records are ignored until the 727 // Finished. See RFC 8446, Appendix D.4. Note that according to Section 728 // 5, a server can send a ChangeCipherSpec before its ServerHello, when 729 // c.vers is still unset. That's not useful though and suspicious if the 730 // server then selects a lower protocol version, so don't allow that. 731 if c.vers == VersionTLS13 { 732 return c.retryReadRecord(expectChangeCipherSpec) 733 } 734 if !expectChangeCipherSpec { 735 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 736 } 737 if err := c.in.changeCipherSpec(); err != nil { 738 return c.in.setErrorLocked(c.sendAlert(err.(alert))) 739 } 740 741 case recordTypeApplicationData: 742 if !handshakeComplete || expectChangeCipherSpec { 743 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 744 } 745 // Some OpenSSL servers send empty records in order to randomize the 746 // CBC IV. Ignore a limited number of empty records. 747 if len(data) == 0 { 748 return c.retryReadRecord(expectChangeCipherSpec) 749 } 750 // Note that data is owned by c.rawInput, following the Next call above, 751 // to avoid copying the plaintext. This is safe because c.rawInput is 752 // not read from or written to until c.input is drained. 753 c.input.Reset(data) 754 755 case recordTypeHandshake: 756 if len(data) == 0 || expectChangeCipherSpec { 757 return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 758 } 759 c.hand.Write(data) 760 } 761 762 return nil 763 } 764 765 // retryReadRecord recurs into readRecordOrCCS to drop a non-advancing record, like 766 // a warning alert, empty application_data, or a change_cipher_spec in TLS 1.3. 767 func (c *Conn) retryReadRecord(expectChangeCipherSpec bool) error { 768 c.retryCount++ 769 if c.retryCount > maxUselessRecords { 770 c.sendAlert(alertUnexpectedMessage) 771 return c.in.setErrorLocked(errors.New("tls: too many ignored records")) 772 } 773 return c.readRecordOrCCS(expectChangeCipherSpec) 774 } 775 776 // atLeastReader reads from R, stopping with EOF once at least N bytes have been 777 // read. It is different from an io.LimitedReader in that it doesn't cut short 778 // the last Read call, and in that it considers an early EOF an error. 779 type atLeastReader struct { 780 R io.Reader 781 N int64 782 } 783 784 func (r *atLeastReader) Read(p []byte) (int, error) { 785 if r.N <= 0 { 786 return 0, io.EOF 787 } 788 n, err := r.R.Read(p) 789 r.N -= int64(n) // won't underflow unless len(p) >= n > 9223372036854775809 790 if r.N > 0 && err == io.EOF { 791 return n, io.ErrUnexpectedEOF 792 } 793 if r.N <= 0 && err == nil { 794 return n, io.EOF 795 } 796 return n, err 797 } 798 799 // readFromUntil reads from r into c.rawInput until c.rawInput contains 800 // at least n bytes or else returns an error. 801 func (c *Conn) readFromUntil(r io.Reader, n int) error { 802 if c.rawInput.Len() >= n { 803 return nil 804 } 805 needs := n - c.rawInput.Len() 806 // There might be extra input waiting on the wire. Make a best effort 807 // attempt to fetch it so that it can be used in (*Conn).Read to 808 // "predict" closeNotify alerts. 809 c.rawInput.Grow(needs + bytes.MinRead) 810 _, err := c.rawInput.ReadFrom(&atLeastReader{r, int64(needs)}) 811 return err 812 } 813 814 // sendAlertLocked sends a TLS alert message. 815 func (c *Conn) sendAlertLocked(err alert) error { 816 switch err { 817 case alertNoRenegotiation, alertCloseNotify: 818 c.tmp[0] = alertLevelWarning 819 default: 820 c.tmp[0] = alertLevelError 821 } 822 c.tmp[1] = byte(err) 823 824 _, writeErr := c.writeRecordLocked(recordTypeAlert, c.tmp[0:2]) 825 if err == alertCloseNotify { 826 // closeNotify is a special case in that it isn't an error. 827 return writeErr 828 } 829 830 return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err}) 831 } 832 833 // sendAlert sends a TLS alert message. 834 func (c *Conn) sendAlert(err alert) error { 835 c.out.Lock() 836 defer c.out.Unlock() 837 return c.sendAlertLocked(err) 838 } 839 840 const ( 841 // tcpMSSEstimate is a conservative estimate of the TCP maximum segment 842 // size (MSS). A constant is used, rather than querying the kernel for 843 // the actual MSS, to avoid complexity. The value here is the IPv6 844 // minimum MTU (1280 bytes) minus the overhead of an IPv6 header (40 845 // bytes) and a TCP header with timestamps (32 bytes). 846 tcpMSSEstimate = 1208 847 848 // recordSizeBoostThreshold is the number of bytes of application data 849 // sent after which the TLS record size will be increased to the 850 // maximum. 851 recordSizeBoostThreshold = 128 * 1024 852 ) 853 854 // maxPayloadSizeForWrite returns the maximum TLS payload size to use for the 855 // next application data record. There is the following trade-off: 856 // 857 // - For latency-sensitive applications, such as web browsing, each TLS 858 // record should fit in one TCP segment. 859 // - For throughput-sensitive applications, such as large file transfers, 860 // larger TLS records better amortize framing and encryption overheads. 861 // 862 // A simple heuristic that works well in practice is to use small records for 863 // the first 1MB of data, then use larger records for subsequent data, and 864 // reset back to smaller records after the connection becomes idle. See "High 865 // Performance Web Networking", Chapter 4, or: 866 // https://www.igvita.com/2013/10/24/optimizing-tls-record-size-and-buffering-latency/ 867 // 868 // In the interests of simplicity and determinism, this code does not attempt 869 // to reset the record size once the connection is idle, however. 870 func (c *Conn) maxPayloadSizeForWrite(typ recordType) int { 871 if c.config.DynamicRecordSizingDisabled || typ != recordTypeApplicationData { 872 return maxPlaintext 873 } 874 875 if c.bytesSent >= recordSizeBoostThreshold { 876 return maxPlaintext 877 } 878 879 // Subtract TLS overheads to get the maximum payload size. 880 payloadBytes := tcpMSSEstimate - recordHeaderLen - c.out.explicitNonceLen() 881 if c.out.cipher != nil { 882 switch ciph := c.out.cipher.(type) { 883 case cipher.Stream: 884 payloadBytes -= c.out.mac.Size() 885 case cipher.AEAD: 886 payloadBytes -= ciph.Overhead() 887 case cbcMode: 888 blockSize := ciph.BlockSize() 889 // The payload must fit in a multiple of blockSize, with 890 // room for at least one padding byte. 891 payloadBytes = (payloadBytes & ^(blockSize - 1)) - 1 892 // The MAC is appended before padding so affects the 893 // payload size directly. 894 payloadBytes -= c.out.mac.Size() 895 default: 896 panic("unknown cipher type") 897 } 898 } 899 if c.vers == VersionTLS13 { 900 payloadBytes-- // encrypted ContentType 901 } 902 903 // Allow packet growth in arithmetic progression up to max. 904 pkt := c.packetsSent 905 c.packetsSent++ 906 if pkt > 1000 { 907 return maxPlaintext // avoid overflow in multiply below 908 } 909 910 n := payloadBytes * int(pkt+1) 911 if n > maxPlaintext { 912 n = maxPlaintext 913 } 914 return n 915 } 916 917 func (c *Conn) write(data []byte) (int, error) { 918 if c.buffering { 919 c.sendBuf = append(c.sendBuf, data...) 920 return len(data), nil 921 } 922 923 n, err := c.conn.Write(data) 924 c.bytesSent += int64(n) 925 return n, err 926 } 927 928 func (c *Conn) flush() (int, error) { 929 if len(c.sendBuf) == 0 { 930 return 0, nil 931 } 932 933 n, err := c.conn.Write(c.sendBuf) 934 c.bytesSent += int64(n) 935 c.sendBuf = nil 936 c.buffering = false 937 return n, err 938 } 939 940 // outBufPool pools the record-sized scratch buffers used by writeRecordLocked. 941 var outBufPool = sync.Pool{ 942 New: func() any { 943 return new([]byte) 944 }, 945 } 946 947 // writeRecordLocked writes a TLS record with the given type and payload to the 948 // connection and updates the record layer state. 949 func (c *Conn) writeRecordLocked(typ recordType, data []byte) (int, error) { 950 outBufPtr := outBufPool.Get().(*[]byte) 951 outBuf := *outBufPtr 952 defer func() { 953 // You might be tempted to simplify this by just passing &outBuf to Put, 954 // but that would make the local copy of the outBuf slice header escape 955 // to the heap, causing an allocation. Instead, we keep around the 956 // pointer to the slice header returned by Get, which is already on the 957 // heap, and overwrite and return that. 958 *outBufPtr = outBuf 959 outBufPool.Put(outBufPtr) 960 }() 961 962 var n int 963 for len(data) > 0 { 964 m := len(data) 965 if maxPayload := c.maxPayloadSizeForWrite(typ); m > maxPayload { 966 m = maxPayload 967 } 968 969 _, outBuf = sliceForAppend(outBuf[:0], recordHeaderLen) 970 outBuf[0] = byte(typ) 971 vers := c.vers 972 if vers == 0 { 973 // Some TLS servers fail if the record version is 974 // greater than TLS 1.0 for the initial ClientHello. 975 vers = VersionTLS10 976 } else if vers == VersionTLS13 { 977 // TLS 1.3 froze the record layer version to 1.2. 978 // See RFC 8446, Section 5.1. 979 vers = VersionTLS12 980 } 981 outBuf[1] = byte(vers >> 8) 982 outBuf[2] = byte(vers) 983 outBuf[3] = byte(m >> 8) 984 outBuf[4] = byte(m) 985 986 var err error 987 outBuf, err = c.out.encrypt(outBuf, data[:m], c.config.rand()) 988 if err != nil { 989 return n, err 990 } 991 if _, err := c.write(outBuf); err != nil { 992 return n, err 993 } 994 n += m 995 data = data[m:] 996 } 997 998 if typ == recordTypeChangeCipherSpec && c.vers != VersionTLS13 { 999 if err := c.out.changeCipherSpec(); err != nil { 1000 return n, c.sendAlertLocked(err.(alert)) 1001 } 1002 } 1003 1004 return n, nil 1005 } 1006 1007 // writeHandshakeRecord writes a handshake message to the connection and updates 1008 // the record layer state. If transcript is non-nil the marshalled message is 1009 // written to it. 1010 func (c *Conn) writeHandshakeRecord(msg handshakeMessage, transcript transcriptHash) (int, error) { 1011 c.out.Lock() 1012 defer c.out.Unlock() 1013 1014 data, err := msg.marshal() 1015 if err != nil { 1016 return 0, err 1017 } 1018 if transcript != nil { 1019 transcript.Write(data) 1020 } 1021 1022 return c.writeRecordLocked(recordTypeHandshake, data) 1023 } 1024 1025 // writeChangeCipherRecord writes a ChangeCipherSpec message to the connection and 1026 // updates the record layer state. 1027 func (c *Conn) writeChangeCipherRecord() error { 1028 c.out.Lock() 1029 defer c.out.Unlock() 1030 _, err := c.writeRecordLocked(recordTypeChangeCipherSpec, []byte{1}) 1031 return err 1032 } 1033 1034 // readHandshake reads the next handshake message from 1035 // the record layer. If transcript is non-nil, the message 1036 // is written to the passed transcriptHash. 1037 func (c *Conn) readHandshake(transcript transcriptHash) (any, error) { 1038 for c.hand.Len() < 4 { 1039 if err := c.readRecord(); err != nil { 1040 return nil, err 1041 } 1042 } 1043 1044 data := c.hand.Bytes() 1045 n := int(data[1])<<16 | int(data[2])<<8 | int(data[3]) 1046 if n > maxHandshake { 1047 c.sendAlertLocked(alertInternalError) 1048 return nil, c.in.setErrorLocked(fmt.Errorf("tls: handshake message of length %d bytes exceeds maximum of %d bytes", n, maxHandshake)) 1049 } 1050 for c.hand.Len() < 4+n { 1051 if err := c.readRecord(); err != nil { 1052 return nil, err 1053 } 1054 } 1055 data = c.hand.Next(4 + n) 1056 var m handshakeMessage 1057 switch data[0] { 1058 case typeHelloRequest: 1059 m = new(helloRequestMsg) 1060 case typeClientHello: 1061 m = new(clientHelloMsg) 1062 case typeServerHello: 1063 m = new(serverHelloMsg) 1064 case typeNewSessionTicket: 1065 if c.vers == VersionTLS13 { 1066 m = new(newSessionTicketMsgTLS13) 1067 } else { 1068 m = new(newSessionTicketMsg) 1069 } 1070 case typeCertificate: 1071 if c.vers == VersionTLS13 { 1072 m = new(certificateMsgTLS13) 1073 } else { 1074 m = new(certificateMsg) 1075 } 1076 case typeCertificateRequest: 1077 if c.vers == VersionTLS13 { 1078 m = new(certificateRequestMsgTLS13) 1079 } else { 1080 m = &certificateRequestMsg{ 1081 hasSignatureAlgorithm: c.vers >= VersionTLS12, 1082 } 1083 } 1084 case typeCertificateStatus: 1085 m = new(certificateStatusMsg) 1086 case typeServerKeyExchange: 1087 m = new(serverKeyExchangeMsg) 1088 case typeServerHelloDone: 1089 m = new(serverHelloDoneMsg) 1090 case typeClientKeyExchange: 1091 m = new(clientKeyExchangeMsg) 1092 case typeCertificateVerify: 1093 m = &certificateVerifyMsg{ 1094 hasSignatureAlgorithm: c.vers >= VersionTLS12, 1095 } 1096 case typeFinished: 1097 m = new(finishedMsg) 1098 case typeEncryptedExtensions: 1099 m = new(encryptedExtensionsMsg) 1100 case typeEndOfEarlyData: 1101 m = new(endOfEarlyDataMsg) 1102 case typeKeyUpdate: 1103 m = new(keyUpdateMsg) 1104 default: 1105 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 1106 } 1107 1108 // The handshake message unmarshalers 1109 // expect to be able to keep references to data, 1110 // so pass in a fresh copy that won't be overwritten. 1111 data = append([]byte(nil), data...) 1112 1113 if !m.unmarshal(data) { 1114 return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) 1115 } 1116 1117 if transcript != nil { 1118 transcript.Write(data) 1119 } 1120 1121 return m, nil 1122 } 1123 1124 var ( 1125 errShutdown = errors.New("tls: protocol is shutdown") 1126 ) 1127 1128 // Write writes data to the connection. 1129 // 1130 // As Write calls Handshake, in order to prevent indefinite blocking a deadline 1131 // must be set for both Read and Write before Write is called when the handshake 1132 // has not yet completed. See SetDeadline, SetReadDeadline, and 1133 // SetWriteDeadline. 1134 func (c *Conn) Write(b []byte) (int, error) { 1135 // interlock with Close below 1136 for { 1137 x := c.activeCall.Load() 1138 if x&1 != 0 { 1139 return 0, net.ErrClosed 1140 } 1141 if c.activeCall.CompareAndSwap(x, x+2) { 1142 break 1143 } 1144 } 1145 defer c.activeCall.Add(-2) 1146 1147 if err := c.Handshake(); err != nil { 1148 return 0, err 1149 } 1150 1151 c.out.Lock() 1152 defer c.out.Unlock() 1153 1154 if err := c.out.err; err != nil { 1155 return 0, err 1156 } 1157 1158 if !c.isHandshakeComplete.Load() { 1159 return 0, alertInternalError 1160 } 1161 1162 if c.closeNotifySent { 1163 return 0, errShutdown 1164 } 1165 1166 // TLS 1.0 is susceptible to a chosen-plaintext 1167 // attack when using block mode ciphers due to predictable IVs. 1168 // This can be prevented by splitting each Application Data 1169 // record into two records, effectively randomizing the IV. 1170 // 1171 // https://www.openssl.org/~bodo/tls-cbc.txt 1172 // https://bugzilla.mozilla.org/show_bug.cgi?id=665814 1173 // https://www.imperialviolet.org/2012/01/15/beastfollowup.html 1174 1175 var m int 1176 if len(b) > 1 && c.vers == VersionTLS10 { 1177 if _, ok := c.out.cipher.(cipher.BlockMode); ok { 1178 n, err := c.writeRecordLocked(recordTypeApplicationData, b[:1]) 1179 if err != nil { 1180 return n, c.out.setErrorLocked(err) 1181 } 1182 m, b = 1, b[1:] 1183 } 1184 } 1185 1186 n, err := c.writeRecordLocked(recordTypeApplicationData, b) 1187 return n + m, c.out.setErrorLocked(err) 1188 } 1189 1190 // handleRenegotiation processes a HelloRequest handshake message. 1191 func (c *Conn) handleRenegotiation() error { 1192 if c.vers == VersionTLS13 { 1193 return errors.New("tls: internal error: unexpected renegotiation") 1194 } 1195 1196 msg, err := c.readHandshake(nil) 1197 if err != nil { 1198 return err 1199 } 1200 1201 helloReq, ok := msg.(*helloRequestMsg) 1202 if !ok { 1203 c.sendAlert(alertUnexpectedMessage) 1204 return unexpectedMessageError(helloReq, msg) 1205 } 1206 1207 if !c.isClient { 1208 return c.sendAlert(alertNoRenegotiation) 1209 } 1210 1211 switch c.config.Renegotiation { 1212 case RenegotiateNever: 1213 return c.sendAlert(alertNoRenegotiation) 1214 case RenegotiateOnceAsClient: 1215 if c.handshakes > 1 { 1216 return c.sendAlert(alertNoRenegotiation) 1217 } 1218 case RenegotiateFreelyAsClient: 1219 // Ok. 1220 default: 1221 c.sendAlert(alertInternalError) 1222 return errors.New("tls: unknown Renegotiation value") 1223 } 1224 1225 c.handshakeMutex.Lock() 1226 defer c.handshakeMutex.Unlock() 1227 1228 c.isHandshakeComplete.Store(false) 1229 if c.handshakeErr = c.clientHandshake(context.Background()); c.handshakeErr == nil { 1230 c.handshakes++ 1231 } 1232 return c.handshakeErr 1233 } 1234 1235 // handlePostHandshakeMessage processes a handshake message arrived after the 1236 // handshake is complete. Up to TLS 1.2, it indicates the start of a renegotiation. 1237 func (c *Conn) handlePostHandshakeMessage() error { 1238 if c.vers != VersionTLS13 { 1239 return c.handleRenegotiation() 1240 } 1241 1242 msg, err := c.readHandshake(nil) 1243 if err != nil { 1244 return err 1245 } 1246 1247 c.retryCount++ 1248 if c.retryCount > maxUselessRecords { 1249 c.sendAlert(alertUnexpectedMessage) 1250 return c.in.setErrorLocked(errors.New("tls: too many non-advancing records")) 1251 } 1252 1253 switch msg := msg.(type) { 1254 case *newSessionTicketMsgTLS13: 1255 return c.handleNewSessionTicket(msg) 1256 case *keyUpdateMsg: 1257 return c.handleKeyUpdate(msg) 1258 default: 1259 c.sendAlert(alertUnexpectedMessage) 1260 return fmt.Errorf("tls: received unexpected handshake message of type %T", msg) 1261 } 1262 } 1263 1264 func (c *Conn) handleKeyUpdate(keyUpdate *keyUpdateMsg) error { 1265 cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite) 1266 if cipherSuite == nil { 1267 return c.in.setErrorLocked(c.sendAlert(alertInternalError)) 1268 } 1269 1270 newSecret := cipherSuite.nextTrafficSecret(c.in.trafficSecret) 1271 c.in.setTrafficSecret(cipherSuite, newSecret) 1272 1273 if keyUpdate.updateRequested { 1274 c.out.Lock() 1275 defer c.out.Unlock() 1276 1277 msg := &keyUpdateMsg{} 1278 msgBytes, err := msg.marshal() 1279 if err != nil { 1280 return err 1281 } 1282 _, err = c.writeRecordLocked(recordTypeHandshake, msgBytes) 1283 if err != nil { 1284 // Surface the error at the next write. 1285 c.out.setErrorLocked(err) 1286 return nil 1287 } 1288 1289 newSecret := cipherSuite.nextTrafficSecret(c.out.trafficSecret) 1290 c.out.setTrafficSecret(cipherSuite, newSecret) 1291 } 1292 1293 return nil 1294 } 1295 1296 // Read reads data from the connection. 1297 // 1298 // As Read calls Handshake, in order to prevent indefinite blocking a deadline 1299 // must be set for both Read and Write before Read is called when the handshake 1300 // has not yet completed. See SetDeadline, SetReadDeadline, and 1301 // SetWriteDeadline. 1302 func (c *Conn) Read(b []byte) (int, error) { 1303 if err := c.Handshake(); err != nil { 1304 return 0, err 1305 } 1306 if len(b) == 0 { 1307 // Put this after Handshake, in case people were calling 1308 // Read(nil) for the side effect of the Handshake. 1309 return 0, nil 1310 } 1311 1312 c.in.Lock() 1313 defer c.in.Unlock() 1314 1315 for c.input.Len() == 0 { 1316 if err := c.readRecord(); err != nil { 1317 return 0, err 1318 } 1319 for c.hand.Len() > 0 { 1320 if err := c.handlePostHandshakeMessage(); err != nil { 1321 return 0, err 1322 } 1323 } 1324 } 1325 1326 n, _ := c.input.Read(b) 1327 1328 // If a close-notify alert is waiting, read it so that we can return (n, 1329 // EOF) instead of (n, nil), to signal to the HTTP response reading 1330 // goroutine that the connection is now closed. This eliminates a race 1331 // where the HTTP response reading goroutine would otherwise not observe 1332 // the EOF until its next read, by which time a client goroutine might 1333 // have already tried to reuse the HTTP connection for a new request. 1334 // See https://golang.org/cl/76400046 and https://golang.org/issue/3514 1335 if n != 0 && c.input.Len() == 0 && c.rawInput.Len() > 0 && 1336 recordType(c.rawInput.Bytes()[0]) == recordTypeAlert { 1337 if err := c.readRecord(); err != nil { 1338 return n, err // will be io.EOF on closeNotify 1339 } 1340 } 1341 1342 return n, nil 1343 } 1344 1345 // Close closes the connection. 1346 func (c *Conn) Close() error { 1347 // Interlock with Conn.Write above. 1348 var x int32 1349 for { 1350 x = c.activeCall.Load() 1351 if x&1 != 0 { 1352 return net.ErrClosed 1353 } 1354 if c.activeCall.CompareAndSwap(x, x|1) { 1355 break 1356 } 1357 } 1358 if x != 0 { 1359 // io.Writer and io.Closer should not be used concurrently. 1360 // If Close is called while a Write is currently in-flight, 1361 // interpret that as a sign that this Close is really just 1362 // being used to break the Write and/or clean up resources and 1363 // avoid sending the alertCloseNotify, which may block 1364 // waiting on handshakeMutex or the c.out mutex. 1365 return c.conn.Close() 1366 } 1367 1368 var alertErr error 1369 if c.isHandshakeComplete.Load() { 1370 if err := c.closeNotify(); err != nil { 1371 alertErr = fmt.Errorf("tls: failed to send closeNotify alert (but connection was closed anyway): %w", err) 1372 } 1373 } 1374 1375 if err := c.conn.Close(); err != nil { 1376 return err 1377 } 1378 return alertErr 1379 } 1380 1381 var errEarlyCloseWrite = errors.New("tls: CloseWrite called before handshake complete") 1382 1383 // CloseWrite shuts down the writing side of the connection. It should only be 1384 // called once the handshake has completed and does not call CloseWrite on the 1385 // underlying connection. Most callers should just use Close. 1386 func (c *Conn) CloseWrite() error { 1387 if !c.isHandshakeComplete.Load() { 1388 return errEarlyCloseWrite 1389 } 1390 1391 return c.closeNotify() 1392 } 1393 1394 func (c *Conn) closeNotify() error { 1395 c.out.Lock() 1396 defer c.out.Unlock() 1397 1398 if !c.closeNotifySent { 1399 // Set a Write Deadline to prevent possibly blocking forever. 1400 c.SetWriteDeadline(time.Now().Add(time.Second * 5)) 1401 c.closeNotifyErr = c.sendAlertLocked(alertCloseNotify) 1402 c.closeNotifySent = true 1403 // Any subsequent writes will fail. 1404 c.SetWriteDeadline(time.Now()) 1405 } 1406 return c.closeNotifyErr 1407 } 1408 1409 // Handshake runs the client or server handshake 1410 // protocol if it has not yet been run. 1411 // 1412 // Most uses of this package need not call Handshake explicitly: the 1413 // first Read or Write will call it automatically. 1414 // 1415 // For control over canceling or setting a timeout on a handshake, use 1416 // HandshakeContext or the Dialer's DialContext method instead. 1417 func (c *Conn) Handshake() error { 1418 return c.HandshakeContext(context.Background()) 1419 } 1420 1421 // HandshakeContext runs the client or server handshake 1422 // protocol if it has not yet been run. 1423 // 1424 // The provided Context must be non-nil. If the context is canceled before 1425 // the handshake is complete, the handshake is interrupted and an error is returned. 1426 // Once the handshake has completed, cancellation of the context will not affect the 1427 // connection. 1428 // 1429 // Most uses of this package need not call HandshakeContext explicitly: the 1430 // first Read or Write will call it automatically. 1431 func (c *Conn) HandshakeContext(ctx context.Context) error { 1432 // Delegate to unexported method for named return 1433 // without confusing documented signature. 1434 return c.handshakeContext(ctx) 1435 } 1436 1437 func (c *Conn) handshakeContext(ctx context.Context) (ret error) { 1438 // Fast sync/atomic-based exit if there is no handshake in flight and the 1439 // last one succeeded without an error. Avoids the expensive context setup 1440 // and mutex for most Read and Write calls. 1441 if c.isHandshakeComplete.Load() { 1442 return nil 1443 } 1444 1445 handshakeCtx, cancel := context.WithCancel(ctx) 1446 // Note: defer this before starting the "interrupter" goroutine 1447 // so that we can tell the difference between the input being canceled and 1448 // this cancellation. In the former case, we need to close the connection. 1449 defer cancel() 1450 1451 // Start the "interrupter" goroutine, if this context might be canceled. 1452 // (The background context cannot). 1453 // 1454 // The interrupter goroutine waits for the input context to be done and 1455 // closes the connection if this happens before the function returns. 1456 if ctx.Done() != nil { 1457 done := make(chan struct{}) 1458 interruptRes := make(chan error, 1) 1459 defer func() { 1460 close(done) 1461 if ctxErr := <-interruptRes; ctxErr != nil { 1462 // Return context error to user. 1463 ret = ctxErr 1464 } 1465 }() 1466 go func() { 1467 select { 1468 case <-handshakeCtx.Done(): 1469 // Close the connection, discarding the error 1470 _ = c.conn.Close() 1471 interruptRes <- handshakeCtx.Err() 1472 case <-done: 1473 interruptRes <- nil 1474 } 1475 }() 1476 } 1477 1478 c.handshakeMutex.Lock() 1479 defer c.handshakeMutex.Unlock() 1480 1481 if err := c.handshakeErr; err != nil { 1482 return err 1483 } 1484 if c.isHandshakeComplete.Load() { 1485 return nil 1486 } 1487 1488 c.in.Lock() 1489 defer c.in.Unlock() 1490 1491 c.handshakeErr = c.handshakeFn(handshakeCtx) 1492 if c.handshakeErr == nil { 1493 c.handshakes++ 1494 } else { 1495 // If an error occurred during the handshake try to flush the 1496 // alert that might be left in the buffer. 1497 c.flush() 1498 } 1499 1500 if c.handshakeErr == nil && !c.isHandshakeComplete.Load() { 1501 c.handshakeErr = errors.New("tls: internal error: handshake should have had a result") 1502 } 1503 if c.handshakeErr != nil && c.isHandshakeComplete.Load() { 1504 panic("tls: internal error: handshake returned an error but is marked successful") 1505 } 1506 1507 return c.handshakeErr 1508 } 1509 1510 // ConnectionState returns basic TLS details about the connection. 1511 func (c *Conn) ConnectionState() ConnectionState { 1512 c.handshakeMutex.Lock() 1513 defer c.handshakeMutex.Unlock() 1514 return c.connectionStateLocked() 1515 } 1516 1517 func (c *Conn) connectionStateLocked() ConnectionState { 1518 var state ConnectionState 1519 state.HandshakeComplete = c.isHandshakeComplete.Load() 1520 state.Version = c.vers 1521 state.NegotiatedProtocol = c.clientProtocol 1522 state.DidResume = c.didResume 1523 state.NegotiatedProtocolIsMutual = true 1524 state.ServerName = c.serverName 1525 state.CipherSuite = c.cipherSuite 1526 state.PeerCertificates = c.peerCertificates 1527 state.VerifiedChains = c.verifiedChains 1528 state.SignedCertificateTimestamps = c.scts 1529 state.OCSPResponse = c.ocspResponse 1530 if !c.didResume && c.vers != VersionTLS13 { 1531 if c.clientFinishedIsFirst { 1532 state.TLSUnique = c.clientFinished[:] 1533 } else { 1534 state.TLSUnique = c.serverFinished[:] 1535 } 1536 } 1537 if c.config.Renegotiation != RenegotiateNever { 1538 state.ekm = noExportedKeyingMaterial 1539 } else { 1540 state.ekm = c.ekm 1541 } 1542 return state 1543 } 1544 1545 // OCSPResponse returns the stapled OCSP response from the TLS server, if 1546 // any. (Only valid for client connections.) 1547 func (c *Conn) OCSPResponse() []byte { 1548 c.handshakeMutex.Lock() 1549 defer c.handshakeMutex.Unlock() 1550 1551 return c.ocspResponse 1552 } 1553 1554 // VerifyHostname checks that the peer certificate chain is valid for 1555 // connecting to host. If so, it returns nil; if not, it returns an error 1556 // describing the problem. 1557 func (c *Conn) VerifyHostname(host string) error { 1558 c.handshakeMutex.Lock() 1559 defer c.handshakeMutex.Unlock() 1560 if !c.isClient { 1561 return errors.New("tls: VerifyHostname called on TLS server connection") 1562 } 1563 if !c.isHandshakeComplete.Load() { 1564 return errors.New("tls: handshake has not yet been performed") 1565 } 1566 if len(c.verifiedChains) == 0 { 1567 return errors.New("tls: handshake did not verify certificate chain") 1568 } 1569 return c.peerCertificates[0].VerifyHostname(host) 1570 }