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