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