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