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