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