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