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