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