handshake_client_tls13.mx raw

   1  // Copyright 2018 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  package tls
   6  
   7  import (
   8  	"bytes"
   9  	"context"
  10  	"crypto"
  11  	"crypto/hkdf"
  12  	"crypto/hmac"
  13  	"crypto/internal/fips140/tls13"
  14  	"crypto/rsa"
  15  	"crypto/subtle"
  16  	"errors"
  17  	"hash"
  18  	"slices"
  19  	"time"
  20  )
  21  
  22  type clientHandshakeStateTLS13 struct {
  23  	c            *Conn
  24  	ctx          context.Context
  25  	serverHello  *serverHelloMsg
  26  	hello        *clientHelloMsg
  27  	keyShareKeys *keySharePrivateKeys
  28  
  29  	session     *SessionState
  30  	earlySecret *tls13.EarlySecret
  31  	binderKey   []byte
  32  
  33  	certReq       *certificateRequestMsgTLS13
  34  	usingPSK      bool
  35  	sentDummyCCS  bool
  36  	suite         *cipherSuiteTLS13
  37  	transcript    hash.Hash
  38  	masterSecret  *tls13.MasterSecret
  39  	trafficSecret []byte // client_application_traffic_secret_0
  40  
  41  	echContext *echClientContext
  42  }
  43  
  44  // handshake requires hs.c, hs.hello, hs.serverHello, hs.keyShareKeys, and,
  45  // optionally, hs.session, hs.earlySecret and hs.binderKey to be set.
  46  func (hs *clientHandshakeStateTLS13) handshake() error {
  47  	c := hs.c
  48  
  49  	// The server must not select TLS 1.3 in a renegotiation. See RFC 8446,
  50  	// sections 4.1.2 and 4.1.3.
  51  	if c.handshakes > 0 {
  52  		c.sendAlert(alertProtocolVersion)
  53  		return errors.New("tls: server selected TLS 1.3 in a renegotiation")
  54  	}
  55  
  56  	// Consistency check on the presence of a keyShare and its parameters.
  57  	if hs.keyShareKeys == nil || hs.keyShareKeys.ecdhe == nil || len(hs.hello.keyShares) == 0 {
  58  		return c.sendAlert(alertInternalError)
  59  	}
  60  
  61  	if err := hs.checkServerHelloOrHRR(); err != nil {
  62  		return err
  63  	}
  64  
  65  	hs.transcript = hs.suite.hash.New()
  66  
  67  	if err := transcriptMsg(hs.hello, hs.transcript); err != nil {
  68  		return err
  69  	}
  70  
  71  	if hs.echContext != nil {
  72  		hs.echContext.innerTranscript = hs.suite.hash.New()
  73  		if err := transcriptMsg(hs.echContext.innerHello, hs.echContext.innerTranscript); err != nil {
  74  			return err
  75  		}
  76  	}
  77  
  78  	if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
  79  		if err := hs.sendDummyChangeCipherSpec(); err != nil {
  80  			return err
  81  		}
  82  		if err := hs.processHelloRetryRequest(); err != nil {
  83  			return err
  84  		}
  85  	}
  86  
  87  	if hs.echContext != nil {
  88  		confTranscript := cloneHash(hs.echContext.innerTranscript, hs.suite.hash)
  89  		confTranscript.Write(hs.serverHello.original[:30])
  90  		confTranscript.Write([]byte{:8})
  91  		confTranscript.Write(hs.serverHello.original[38:])
  92  		h := hs.suite.hash.New
  93  		prk, err := hkdf.Extract(h, hs.echContext.innerHello.random, nil)
  94  		if err != nil {
  95  			c.sendAlert(alertInternalError)
  96  			return err
  97  		}
  98  		acceptConfirmation := tls13.ExpandLabel(h, prk, "ech accept confirmation", confTranscript.Sum(nil), 8)
  99  		if subtle.ConstantTimeCompare(acceptConfirmation, hs.serverHello.random[len(hs.serverHello.random)-8:]) == 1 {
 100  			hs.hello = hs.echContext.innerHello
 101  			c.serverName = c.config.ServerName
 102  			hs.transcript = hs.echContext.innerTranscript
 103  			c.echAccepted = true
 104  
 105  			if hs.serverHello.encryptedClientHello != nil {
 106  				c.sendAlert(alertUnsupportedExtension)
 107  				return errors.New("tls: unexpected encrypted client hello extension in server hello despite ECH being accepted")
 108  			}
 109  
 110  			if hs.hello.serverName == "" && hs.serverHello.serverNameAck {
 111  				c.sendAlert(alertUnsupportedExtension)
 112  				return errors.New("tls: unexpected server_name extension in server hello")
 113  			}
 114  		} else {
 115  			hs.echContext.echRejected = true
 116  		}
 117  	}
 118  
 119  	if err := transcriptMsg(hs.serverHello, hs.transcript); err != nil {
 120  		return err
 121  	}
 122  
 123  	c.buffering = true
 124  	if err := hs.processServerHello(); err != nil {
 125  		return err
 126  	}
 127  	if err := hs.sendDummyChangeCipherSpec(); err != nil {
 128  		return err
 129  	}
 130  	if err := hs.establishHandshakeKeys(); err != nil {
 131  		return err
 132  	}
 133  	if err := hs.readServerParameters(); err != nil {
 134  		return err
 135  	}
 136  	if err := hs.readServerCertificate(); err != nil {
 137  		return err
 138  	}
 139  	if err := hs.readServerFinished(); err != nil {
 140  		return err
 141  	}
 142  	if err := hs.sendClientCertificate(); err != nil {
 143  		return err
 144  	}
 145  	if err := hs.sendClientFinished(); err != nil {
 146  		return err
 147  	}
 148  	if _, err := c.flush(); err != nil {
 149  		return err
 150  	}
 151  
 152  	if hs.echContext != nil && hs.echContext.echRejected {
 153  		c.sendAlert(alertECHRequired)
 154  		return &ECHRejectionError{hs.echContext.retryConfigs}
 155  	}
 156  
 157  	c.isHandshakeComplete.Store(true)
 158  
 159  	return nil
 160  }
 161  
 162  // checkServerHelloOrHRR does validity checks that apply to both ServerHello and
 163  // HelloRetryRequest messages. It sets hs.suite.
 164  func (hs *clientHandshakeStateTLS13) checkServerHelloOrHRR() error {
 165  	c := hs.c
 166  
 167  	if hs.serverHello.supportedVersion == 0 {
 168  		c.sendAlert(alertMissingExtension)
 169  		return errors.New("tls: server selected TLS 1.3 using the legacy version field")
 170  	}
 171  
 172  	if hs.serverHello.supportedVersion != VersionTLS13 {
 173  		c.sendAlert(alertIllegalParameter)
 174  		return errors.New("tls: server selected an invalid version after a HelloRetryRequest")
 175  	}
 176  
 177  	if hs.serverHello.vers != VersionTLS12 {
 178  		c.sendAlert(alertIllegalParameter)
 179  		return errors.New("tls: server sent an incorrect legacy version")
 180  	}
 181  
 182  	if hs.serverHello.ocspStapling ||
 183  		hs.serverHello.ticketSupported ||
 184  		hs.serverHello.extendedMasterSecret ||
 185  		hs.serverHello.secureRenegotiationSupported ||
 186  		len(hs.serverHello.secureRenegotiation) != 0 ||
 187  		len(hs.serverHello.alpnProtocol) != 0 ||
 188  		len(hs.serverHello.scts) != 0 {
 189  		c.sendAlert(alertUnsupportedExtension)
 190  		return errors.New("tls: server sent a ServerHello extension forbidden in TLS 1.3")
 191  	}
 192  
 193  	if !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) {
 194  		c.sendAlert(alertIllegalParameter)
 195  		return errors.New("tls: server did not echo the legacy session ID")
 196  	}
 197  
 198  	if hs.serverHello.compressionMethod != compressionNone {
 199  		c.sendAlert(alertDecodeError)
 200  		return errors.New("tls: server sent non-zero legacy TLS compression method")
 201  	}
 202  
 203  	selectedSuite := mutualCipherSuiteTLS13(hs.hello.cipherSuites, hs.serverHello.cipherSuite)
 204  	if hs.suite != nil && selectedSuite != hs.suite {
 205  		c.sendAlert(alertIllegalParameter)
 206  		return errors.New("tls: server changed cipher suite after a HelloRetryRequest")
 207  	}
 208  	if selectedSuite == nil {
 209  		c.sendAlert(alertIllegalParameter)
 210  		return errors.New("tls: server chose an unconfigured cipher suite")
 211  	}
 212  	hs.suite = selectedSuite
 213  	c.cipherSuite = hs.suite.id
 214  
 215  	return nil
 216  }
 217  
 218  // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
 219  // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
 220  func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
 221  	if hs.c.quic != nil {
 222  		return nil
 223  	}
 224  	if hs.sentDummyCCS {
 225  		return nil
 226  	}
 227  	hs.sentDummyCCS = true
 228  
 229  	return hs.c.writeChangeCipherRecord()
 230  }
 231  
 232  // processHelloRetryRequest handles the HRR in hs.serverHello, modifies and
 233  // resends hs.hello, and reads the new ServerHello into hs.serverHello.
 234  func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error {
 235  	c := hs.c
 236  
 237  	// The first ClientHello gets double-hashed into the transcript upon a
 238  	// HelloRetryRequest. (The idea is that the server might offload transcript
 239  	// storage to the client in the cookie.) See RFC 8446, Section 4.4.1.
 240  	chHash := hs.transcript.Sum(nil)
 241  	hs.transcript.Reset()
 242  	hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
 243  	hs.transcript.Write(chHash)
 244  	if err := transcriptMsg(hs.serverHello, hs.transcript); err != nil {
 245  		return err
 246  	}
 247  
 248  	var isInnerHello bool
 249  	hello := hs.hello
 250  	if hs.echContext != nil {
 251  		chHash = hs.echContext.innerTranscript.Sum(nil)
 252  		hs.echContext.innerTranscript.Reset()
 253  		hs.echContext.innerTranscript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
 254  		hs.echContext.innerTranscript.Write(chHash)
 255  
 256  		if hs.serverHello.encryptedClientHello != nil {
 257  			if len(hs.serverHello.encryptedClientHello) != 8 {
 258  				hs.c.sendAlert(alertDecodeError)
 259  				return errors.New("tls: malformed encrypted client hello extension")
 260  			}
 261  
 262  			confTranscript := cloneHash(hs.echContext.innerTranscript, hs.suite.hash)
 263  			hrrHello := []byte{:len(hs.serverHello.original)}
 264  			copy(hrrHello, hs.serverHello.original)
 265  			hrrHello = bytes.Replace(hrrHello, hs.serverHello.encryptedClientHello, []byte{:8}, 1)
 266  			confTranscript.Write(hrrHello)
 267  			h := hs.suite.hash.New
 268  			prk, err := hkdf.Extract(h, hs.echContext.innerHello.random, nil)
 269  			if err != nil {
 270  				c.sendAlert(alertInternalError)
 271  				return err
 272  			}
 273  			acceptConfirmation := tls13.ExpandLabel(h, prk, "hrr ech accept confirmation", confTranscript.Sum(nil), 8)
 274  			if subtle.ConstantTimeCompare(acceptConfirmation, hs.serverHello.encryptedClientHello) == 1 {
 275  				hello = hs.echContext.innerHello
 276  				c.serverName = c.config.ServerName
 277  				isInnerHello = true
 278  				c.echAccepted = true
 279  			}
 280  		}
 281  
 282  		if err := transcriptMsg(hs.serverHello, hs.echContext.innerTranscript); err != nil {
 283  			return err
 284  		}
 285  	} else if hs.serverHello.encryptedClientHello != nil {
 286  		// Unsolicited ECH extension should be rejected
 287  		c.sendAlert(alertUnsupportedExtension)
 288  		return errors.New("tls: unexpected encrypted client hello extension in serverHello")
 289  	}
 290  
 291  	// The only HelloRetryRequest extensions we support are key_share and
 292  	// cookie, and clients must abort the handshake if the HRR would not result
 293  	// in any change in the ClientHello.
 294  	if hs.serverHello.selectedGroup == 0 && hs.serverHello.cookie == nil {
 295  		c.sendAlert(alertIllegalParameter)
 296  		return errors.New("tls: server sent an unnecessary HelloRetryRequest message")
 297  	}
 298  
 299  	if hs.serverHello.cookie != nil {
 300  		hello.cookie = hs.serverHello.cookie
 301  	}
 302  
 303  	if hs.serverHello.serverShare.group != 0 {
 304  		c.sendAlert(alertDecodeError)
 305  		return errors.New("tls: received malformed key_share extension")
 306  	}
 307  
 308  	// If the server sent a key_share extension selecting a group, ensure it's
 309  	// a group we advertised but did not send a key share for, and send a key
 310  	// share for it this time.
 311  	if curveID := hs.serverHello.selectedGroup; curveID != 0 {
 312  		if !slices.Contains(hello.supportedCurves, curveID) {
 313  			c.sendAlert(alertIllegalParameter)
 314  			return errors.New("tls: server selected unsupported group")
 315  		}
 316  		if slices.ContainsFunc(hs.hello.keyShares, func(ks keyShare) bool {
 317  			return ks.group == curveID
 318  		}) {
 319  			c.sendAlert(alertIllegalParameter)
 320  			return errors.New("tls: server sent an unnecessary HelloRetryRequest key_share")
 321  		}
 322  		ke, err := keyExchangeForCurveID(curveID)
 323  		if err != nil {
 324  			c.sendAlert(alertInternalError)
 325  			return errors.New("tls: CurvePreferences includes unsupported curve")
 326  		}
 327  		hs.keyShareKeys, hello.keyShares, err = ke.keyShares(c.config.rand())
 328  		if err != nil {
 329  			c.sendAlert(alertInternalError)
 330  			return err
 331  		}
 332  		// Do not send the fallback ECDH key share in a HRR response.
 333  		hello.keyShares = hello.keyShares[:1]
 334  	}
 335  
 336  	if len(hello.pskIdentities) > 0 {
 337  		pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
 338  		if pskSuite == nil {
 339  			return c.sendAlert(alertInternalError)
 340  		}
 341  		if pskSuite.hash == hs.suite.hash {
 342  			// Update binders and obfuscated_ticket_age.
 343  			ticketAge := c.config.time().Sub(time.Unix(int64(hs.session.createdAt), 0))
 344  			hello.pskIdentities[0].obfuscatedTicketAge = uint32(ticketAge/time.Millisecond) + hs.session.ageAdd
 345  
 346  			transcript := hs.suite.hash.New()
 347  			transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
 348  			transcript.Write(chHash)
 349  			if err := transcriptMsg(hs.serverHello, transcript); err != nil {
 350  				return err
 351  			}
 352  
 353  			if err := computeAndUpdatePSK(hello, hs.binderKey, transcript, hs.suite.finishedHash); err != nil {
 354  				return err
 355  			}
 356  		} else {
 357  			// Server selected a cipher suite incompatible with the PSK.
 358  			hello.pskIdentities = nil
 359  			hello.pskBinders = nil
 360  		}
 361  	}
 362  
 363  	if hello.earlyData {
 364  		hello.earlyData = false
 365  		c.quicRejectedEarlyData()
 366  	}
 367  
 368  	if isInnerHello {
 369  		// Any extensions which have changed in hello, but are mirrored in the
 370  		// outer hello and compressed, need to be copied to the outer hello, so
 371  		// they can be properly decompressed by the server. For now, the only
 372  		// extension which may have changed is keyShares.
 373  		hs.hello.keyShares = hello.keyShares
 374  		hs.echContext.innerHello = hello
 375  		if err := transcriptMsg(hs.echContext.innerHello, hs.echContext.innerTranscript); err != nil {
 376  			return err
 377  		}
 378  
 379  		if err := computeAndUpdateOuterECHExtension(hs.hello, hs.echContext.innerHello, hs.echContext, false); err != nil {
 380  			return err
 381  		}
 382  	} else {
 383  		hs.hello = hello
 384  	}
 385  
 386  	if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil {
 387  		return err
 388  	}
 389  
 390  	// serverHelloMsg is not included in the transcript
 391  	msg, err := c.readHandshake(nil)
 392  	if err != nil {
 393  		return err
 394  	}
 395  
 396  	serverHello, ok := msg.(*serverHelloMsg)
 397  	if !ok {
 398  		c.sendAlert(alertUnexpectedMessage)
 399  		return unexpectedMessageError(serverHello, msg)
 400  	}
 401  	hs.serverHello = serverHello
 402  
 403  	if err := hs.checkServerHelloOrHRR(); err != nil {
 404  		return err
 405  	}
 406  
 407  	c.didHRR = true
 408  	return nil
 409  }
 410  
 411  func (hs *clientHandshakeStateTLS13) processServerHello() error {
 412  	c := hs.c
 413  
 414  	if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
 415  		c.sendAlert(alertUnexpectedMessage)
 416  		return errors.New("tls: server sent two HelloRetryRequest messages")
 417  	}
 418  
 419  	if len(hs.serverHello.cookie) != 0 {
 420  		c.sendAlert(alertUnsupportedExtension)
 421  		return errors.New("tls: server sent a cookie in a normal ServerHello")
 422  	}
 423  
 424  	if hs.serverHello.selectedGroup != 0 {
 425  		c.sendAlert(alertDecodeError)
 426  		return errors.New("tls: malformed key_share extension")
 427  	}
 428  
 429  	if hs.serverHello.serverShare.group == 0 {
 430  		c.sendAlert(alertIllegalParameter)
 431  		return errors.New("tls: server did not send a key share")
 432  	}
 433  	if !slices.ContainsFunc(hs.hello.keyShares, func(ks keyShare) bool {
 434  		return ks.group == hs.serverHello.serverShare.group
 435  	}) {
 436  		c.sendAlert(alertIllegalParameter)
 437  		return errors.New("tls: server selected unsupported group")
 438  	}
 439  
 440  	if !hs.serverHello.selectedIdentityPresent {
 441  		return nil
 442  	}
 443  
 444  	if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) {
 445  		c.sendAlert(alertIllegalParameter)
 446  		return errors.New("tls: server selected an invalid PSK")
 447  	}
 448  
 449  	if len(hs.hello.pskIdentities) != 1 || hs.session == nil {
 450  		return c.sendAlert(alertInternalError)
 451  	}
 452  	pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
 453  	if pskSuite == nil {
 454  		return c.sendAlert(alertInternalError)
 455  	}
 456  	if pskSuite.hash != hs.suite.hash {
 457  		c.sendAlert(alertIllegalParameter)
 458  		return errors.New("tls: server selected an invalid PSK and cipher suite pair")
 459  	}
 460  
 461  	hs.usingPSK = true
 462  	c.didResume = true
 463  	c.peerCertificates = hs.session.peerCertificates
 464  	c.verifiedChains = hs.session.verifiedChains
 465  	c.ocspResponse = hs.session.ocspResponse
 466  	c.scts = hs.session.scts
 467  	return nil
 468  }
 469  
 470  func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error {
 471  	c := hs.c
 472  
 473  	ke, err := keyExchangeForCurveID(hs.serverHello.serverShare.group)
 474  	if err != nil {
 475  		c.sendAlert(alertInternalError)
 476  		return err
 477  	}
 478  	sharedKey, err := ke.clientSharedSecret(hs.keyShareKeys, hs.serverHello.serverShare.data)
 479  	if err != nil {
 480  		c.sendAlert(alertIllegalParameter)
 481  		return errors.New("tls: invalid server key share")
 482  	}
 483  	c.curveID = hs.serverHello.serverShare.group
 484  
 485  	earlySecret := hs.earlySecret
 486  	if !hs.usingPSK {
 487  		earlySecret = tls13.NewEarlySecret(hs.suite.hash.New, nil)
 488  	}
 489  
 490  	handshakeSecret := earlySecret.HandshakeSecret(sharedKey)
 491  
 492  	clientSecret := handshakeSecret.ClientHandshakeTrafficSecret(hs.transcript)
 493  	c.setWriteTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, clientSecret)
 494  	serverSecret := handshakeSecret.ServerHandshakeTrafficSecret(hs.transcript)
 495  	if err := c.setReadTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret); err != nil {
 496  		return err
 497  	}
 498  
 499  	if c.quic != nil {
 500  		c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, clientSecret)
 501  		if err := c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret); err != nil {
 502  			return err
 503  		}
 504  	}
 505  
 506  	err = c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret)
 507  	if err != nil {
 508  		c.sendAlert(alertInternalError)
 509  		return err
 510  	}
 511  	err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret)
 512  	if err != nil {
 513  		c.sendAlert(alertInternalError)
 514  		return err
 515  	}
 516  
 517  	hs.masterSecret = handshakeSecret.MasterSecret()
 518  
 519  	return nil
 520  }
 521  
 522  func (hs *clientHandshakeStateTLS13) readServerParameters() error {
 523  	c := hs.c
 524  
 525  	msg, err := c.readHandshake(hs.transcript)
 526  	if err != nil {
 527  		return err
 528  	}
 529  
 530  	encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
 531  	if !ok {
 532  		c.sendAlert(alertUnexpectedMessage)
 533  		return unexpectedMessageError(encryptedExtensions, msg)
 534  	}
 535  
 536  	if err := checkALPN(hs.hello.alpnProtocols, encryptedExtensions.alpnProtocol, c.quic != nil); err != nil {
 537  		// RFC 8446 specifies that no_application_protocol is sent by servers, but
 538  		// does not specify how clients handle the selection of an incompatible protocol.
 539  		// RFC 9001 Section 8.1 specifies that QUIC clients send no_application_protocol
 540  		// in this case. Always sending no_application_protocol seems reasonable.
 541  		c.sendAlert(alertNoApplicationProtocol)
 542  		return err
 543  	}
 544  	c.clientProtocol = encryptedExtensions.alpnProtocol
 545  
 546  	if c.quic != nil {
 547  		if encryptedExtensions.quicTransportParameters == nil {
 548  			// RFC 9001 Section 8.2.
 549  			c.sendAlert(alertMissingExtension)
 550  			return errors.New("tls: server did not send a quic_transport_parameters extension")
 551  		}
 552  		c.quicSetTransportParameters(encryptedExtensions.quicTransportParameters)
 553  	} else {
 554  		if encryptedExtensions.quicTransportParameters != nil {
 555  			c.sendAlert(alertUnsupportedExtension)
 556  			return errors.New("tls: server sent an unexpected quic_transport_parameters extension")
 557  		}
 558  	}
 559  
 560  	if !hs.hello.earlyData && encryptedExtensions.earlyData {
 561  		c.sendAlert(alertUnsupportedExtension)
 562  		return errors.New("tls: server sent an unexpected early_data extension")
 563  	}
 564  	if hs.hello.earlyData && !encryptedExtensions.earlyData {
 565  		c.quicRejectedEarlyData()
 566  	}
 567  	if encryptedExtensions.earlyData {
 568  		if hs.session.cipherSuite != c.cipherSuite {
 569  			c.sendAlert(alertHandshakeFailure)
 570  			return errors.New("tls: server accepted 0-RTT with the wrong cipher suite")
 571  		}
 572  		if hs.session.alpnProtocol != c.clientProtocol {
 573  			c.sendAlert(alertHandshakeFailure)
 574  			return errors.New("tls: server accepted 0-RTT with the wrong ALPN")
 575  		}
 576  	}
 577  	if hs.echContext != nil {
 578  		if hs.echContext.echRejected {
 579  			hs.echContext.retryConfigs = encryptedExtensions.echRetryConfigs
 580  		} else if encryptedExtensions.echRetryConfigs != nil {
 581  			c.sendAlert(alertUnsupportedExtension)
 582  			return errors.New("tls: server sent encrypted client hello retry configs after accepting encrypted client hello")
 583  		}
 584  	}
 585  
 586  	return nil
 587  }
 588  
 589  func (hs *clientHandshakeStateTLS13) readServerCertificate() error {
 590  	c := hs.c
 591  
 592  	// Either a PSK or a certificate is always used, but not both.
 593  	// See RFC 8446, Section 4.1.1.
 594  	if hs.usingPSK {
 595  		// Make sure the connection is still being verified whether or not this
 596  		// is a resumption. Resumptions currently don't reverify certificates so
 597  		// they don't call verifyServerCertificate. See Issue 31641.
 598  		if c.config.VerifyConnection != nil {
 599  			if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
 600  				c.sendAlert(alertBadCertificate)
 601  				return err
 602  			}
 603  		}
 604  		return nil
 605  	}
 606  
 607  	msg, err := c.readHandshake(hs.transcript)
 608  	if err != nil {
 609  		return err
 610  	}
 611  
 612  	certReq, ok := msg.(*certificateRequestMsgTLS13)
 613  	if ok {
 614  		hs.certReq = certReq
 615  
 616  		msg, err = c.readHandshake(hs.transcript)
 617  		if err != nil {
 618  			return err
 619  		}
 620  	}
 621  
 622  	certMsg, ok := msg.(*certificateMsgTLS13)
 623  	if !ok {
 624  		c.sendAlert(alertUnexpectedMessage)
 625  		return unexpectedMessageError(certMsg, msg)
 626  	}
 627  	if len(certMsg.certificate.Certificate) == 0 {
 628  		c.sendAlert(alertDecodeError)
 629  		return errors.New("tls: received empty certificates message")
 630  	}
 631  
 632  	c.scts = certMsg.certificate.SignedCertificateTimestamps
 633  	c.ocspResponse = certMsg.certificate.OCSPStaple
 634  
 635  	if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil {
 636  		return err
 637  	}
 638  
 639  	// certificateVerifyMsg is included in the transcript, but not until
 640  	// after we verify the handshake signature, since the state before
 641  	// this message was sent is used.
 642  	msg, err = c.readHandshake(nil)
 643  	if err != nil {
 644  		return err
 645  	}
 646  
 647  	certVerify, ok := msg.(*certificateVerifyMsg)
 648  	if !ok {
 649  		c.sendAlert(alertUnexpectedMessage)
 650  		return unexpectedMessageError(certVerify, msg)
 651  	}
 652  
 653  	// See RFC 8446, Section 4.4.3.
 654  	// We don't use hs.hello.supportedSignatureAlgorithms because it might
 655  	// include PKCS#1 v1.5 and SHA-1 if the ClientHello also supported TLS 1.2.
 656  	if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms(c.vers)) ||
 657  		!isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, signatureSchemesForPublicKey(c.vers, c.peerCertificates[0].PublicKey)) {
 658  		c.sendAlert(alertIllegalParameter)
 659  		return errors.New("tls: certificate used with invalid signature algorithm")
 660  	}
 661  	sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
 662  	if err != nil {
 663  		return c.sendAlert(alertInternalError)
 664  	}
 665  	if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
 666  		return c.sendAlert(alertInternalError)
 667  	}
 668  	signed := signedMessage(serverSignatureContext, hs.transcript)
 669  	if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
 670  		sigHash, signed, certVerify.signature); err != nil {
 671  		c.sendAlert(alertDecryptError)
 672  		return errors.New("tls: invalid signature by the server certificate: " + err.Error())
 673  	}
 674  	c.peerSigAlg = certVerify.signatureAlgorithm
 675  
 676  	if err := transcriptMsg(certVerify, hs.transcript); err != nil {
 677  		return err
 678  	}
 679  
 680  	return nil
 681  }
 682  
 683  func (hs *clientHandshakeStateTLS13) readServerFinished() error {
 684  	c := hs.c
 685  
 686  	// finishedMsg is included in the transcript, but not until after we
 687  	// check the client version, since the state before this message was
 688  	// sent is used during verification.
 689  	msg, err := c.readHandshake(nil)
 690  	if err != nil {
 691  		return err
 692  	}
 693  
 694  	finished, ok := msg.(*finishedMsg)
 695  	if !ok {
 696  		c.sendAlert(alertUnexpectedMessage)
 697  		return unexpectedMessageError(finished, msg)
 698  	}
 699  
 700  	expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
 701  	if !hmac.Equal(expectedMAC, finished.verifyData) {
 702  		c.sendAlert(alertDecryptError)
 703  		return errors.New("tls: invalid server finished hash")
 704  	}
 705  
 706  	if err := transcriptMsg(finished, hs.transcript); err != nil {
 707  		return err
 708  	}
 709  
 710  	// Derive secrets that take context through the server Finished.
 711  
 712  	hs.trafficSecret = hs.masterSecret.ClientApplicationTrafficSecret(hs.transcript)
 713  	serverSecret := hs.masterSecret.ServerApplicationTrafficSecret(hs.transcript)
 714  	if err := c.setReadTrafficSecret(hs.suite, QUICEncryptionLevelApplication, serverSecret); err != nil {
 715  		return err
 716  	}
 717  
 718  	err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret)
 719  	if err != nil {
 720  		c.sendAlert(alertInternalError)
 721  		return err
 722  	}
 723  	err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret)
 724  	if err != nil {
 725  		c.sendAlert(alertInternalError)
 726  		return err
 727  	}
 728  
 729  	c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
 730  
 731  	return nil
 732  }
 733  
 734  func (hs *clientHandshakeStateTLS13) sendClientCertificate() error {
 735  	c := hs.c
 736  
 737  	if hs.certReq == nil {
 738  		return nil
 739  	}
 740  
 741  	if hs.echContext != nil && hs.echContext.echRejected {
 742  		if _, err := hs.c.writeHandshakeRecord(&certificateMsgTLS13{}, hs.transcript); err != nil {
 743  			return err
 744  		}
 745  		return nil
 746  	}
 747  
 748  	cert, err := c.getClientCertificate(&CertificateRequestInfo{
 749  		AcceptableCAs:    hs.certReq.certificateAuthorities,
 750  		SignatureSchemes: hs.certReq.supportedSignatureAlgorithms,
 751  		Version:          c.vers,
 752  		ctx:              hs.ctx,
 753  	})
 754  	if err != nil {
 755  		return err
 756  	}
 757  
 758  	certMsg := &certificateMsgTLS13{}
 759  
 760  	certMsg.certificate = *cert
 761  	certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0
 762  	certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0
 763  
 764  	if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil {
 765  		return err
 766  	}
 767  
 768  	// If we sent an empty certificate message, skip the CertificateVerify.
 769  	if len(cert.Certificate) == 0 {
 770  		return nil
 771  	}
 772  
 773  	certVerifyMsg := &certificateVerifyMsg{}
 774  	certVerifyMsg.hasSignatureAlgorithm = true
 775  
 776  	certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms)
 777  	if err != nil {
 778  		// getClientCertificate returned a certificate incompatible with the
 779  		// CertificateRequestInfo supported signature algorithms.
 780  		c.sendAlert(alertHandshakeFailure)
 781  		return err
 782  	}
 783  
 784  	sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm)
 785  	if err != nil {
 786  		return c.sendAlert(alertInternalError)
 787  	}
 788  
 789  	signed := signedMessage(clientSignatureContext, hs.transcript)
 790  	signOpts := crypto.SignerOpts(sigHash)
 791  	if sigType == signatureRSAPSS {
 792  		signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
 793  	}
 794  	sig, err := crypto.SignMessage(cert.PrivateKey.(crypto.Signer), c.config.rand(), signed, signOpts)
 795  	if err != nil {
 796  		c.sendAlert(alertInternalError)
 797  		return errors.New("tls: failed to sign handshake: " + err.Error())
 798  	}
 799  	certVerifyMsg.signature = sig
 800  
 801  	if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil {
 802  		return err
 803  	}
 804  
 805  	return nil
 806  }
 807  
 808  func (hs *clientHandshakeStateTLS13) sendClientFinished() error {
 809  	c := hs.c
 810  
 811  	finished := &finishedMsg{
 812  		verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
 813  	}
 814  
 815  	if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil {
 816  		return err
 817  	}
 818  
 819  	c.setWriteTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret)
 820  
 821  	if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil {
 822  		c.resumptionSecret = hs.masterSecret.ResumptionMasterSecret(hs.transcript)
 823  	}
 824  
 825  	if c.quic != nil {
 826  		c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, hs.trafficSecret)
 827  	}
 828  
 829  	return nil
 830  }
 831  
 832  func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error {
 833  	if !c.isClient {
 834  		c.sendAlert(alertUnexpectedMessage)
 835  		return errors.New("tls: received new session ticket from a client")
 836  	}
 837  
 838  	if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
 839  		return nil
 840  	}
 841  
 842  	// See RFC 8446, Section 4.6.1.
 843  	if msg.lifetime == 0 {
 844  		return nil
 845  	}
 846  	lifetime := time.Duration(msg.lifetime) * time.Second
 847  	if lifetime > maxSessionTicketLifetime {
 848  		c.sendAlert(alertIllegalParameter)
 849  		return errors.New("tls: received a session ticket with invalid lifetime")
 850  	}
 851  
 852  	if len(msg.label) == 0 {
 853  		c.sendAlert(alertDecodeError)
 854  		return errors.New("tls: received a session ticket with empty opaque ticket label")
 855  	}
 856  
 857  	// RFC 9001, Section 4.6.1
 858  	if c.quic != nil && msg.maxEarlyData != 0 && msg.maxEarlyData != 0xffffffff {
 859  		c.sendAlert(alertIllegalParameter)
 860  		return errors.New("tls: invalid early data for QUIC connection")
 861  	}
 862  
 863  	cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
 864  	if cipherSuite == nil || c.resumptionSecret == nil {
 865  		return c.sendAlert(alertInternalError)
 866  	}
 867  
 868  	psk := tls13.ExpandLabel(cipherSuite.hash.New, c.resumptionSecret, "resumption",
 869  		msg.nonce, cipherSuite.hash.Size())
 870  
 871  	session := c.sessionState()
 872  	session.secret = psk
 873  	session.useBy = uint64(c.config.time().Add(lifetime).Unix())
 874  	session.ageAdd = msg.ageAdd
 875  	session.EarlyData = c.quic != nil && msg.maxEarlyData == 0xffffffff // RFC 9001, Section 4.6.1
 876  	session.ticket = msg.label
 877  	if c.quic != nil && c.quic.enableSessionEvents {
 878  		c.quicStoreSession(session)
 879  		return nil
 880  	}
 881  	cs := &ClientSessionState{session: session}
 882  	if cacheKey := c.clientSessionCacheKey(); cacheKey != "" {
 883  		c.config.ClientSessionCache.Put(cacheKey, cs)
 884  	}
 885  
 886  	return nil
 887  }
 888