Source file src/crypto/tls/handshake_server.go

     1  // Copyright 2009 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  	"context"
     9  	"crypto"
    10  	"crypto/ecdsa"
    11  	"crypto/ed25519"
    12  	"crypto/rsa"
    13  	"crypto/subtle"
    14  	"crypto/x509"
    15  	"errors"
    16  	"fmt"
    17  	"hash"
    18  	"internal/byteorder"
    19  	"io"
    20  	"time"
    21  )
    22  
    23  // serverHandshakeState contains details of a server handshake in progress.
    24  // It's discarded once the handshake has completed.
    25  type serverHandshakeState struct {
    26  	c            *Conn
    27  	ctx          context.Context
    28  	clientHello  *clientHelloMsg
    29  	hello        *serverHelloMsg
    30  	suite        *cipherSuite
    31  	ecdheOk      bool
    32  	ecSignOk     bool
    33  	rsaDecryptOk bool
    34  	rsaSignOk    bool
    35  	sessionState *SessionState
    36  	finishedHash finishedHash
    37  	masterSecret []byte
    38  	cert         *Certificate
    39  }
    40  
    41  // serverHandshake performs a TLS handshake as a server.
    42  func (c *Conn) serverHandshake(ctx context.Context) error {
    43  	clientHello, err := c.readClientHello(ctx)
    44  	if err != nil {
    45  		return err
    46  	}
    47  
    48  	if c.vers == VersionTLS13 {
    49  		hs := serverHandshakeStateTLS13{
    50  			c:           c,
    51  			ctx:         ctx,
    52  			clientHello: clientHello,
    53  		}
    54  		return hs.handshake()
    55  	}
    56  
    57  	hs := serverHandshakeState{
    58  		c:           c,
    59  		ctx:         ctx,
    60  		clientHello: clientHello,
    61  	}
    62  	return hs.handshake()
    63  }
    64  
    65  func (hs *serverHandshakeState) handshake() error {
    66  	c := hs.c
    67  
    68  	if err := hs.processClientHello(); err != nil {
    69  		return err
    70  	}
    71  
    72  	// For an overview of TLS handshaking, see RFC 5246, Section 7.3.
    73  	c.buffering = true
    74  	if err := hs.checkForResumption(); err != nil {
    75  		return err
    76  	}
    77  	if hs.sessionState != nil {
    78  		// The client has included a session ticket and so we do an abbreviated handshake.
    79  		if err := hs.doResumeHandshake(); err != nil {
    80  			return err
    81  		}
    82  		if err := hs.establishKeys(); err != nil {
    83  			return err
    84  		}
    85  		if err := hs.sendSessionTicket(); err != nil {
    86  			return err
    87  		}
    88  		if err := hs.sendFinished(c.serverFinished[:]); err != nil {
    89  			return err
    90  		}
    91  		if _, err := c.flush(); err != nil {
    92  			return err
    93  		}
    94  		c.clientFinishedIsFirst = false
    95  		if err := hs.readFinished(nil); err != nil {
    96  			return err
    97  		}
    98  	} else {
    99  		// The client didn't include a session ticket, or it wasn't
   100  		// valid so we do a full handshake.
   101  		if err := hs.pickCipherSuite(); err != nil {
   102  			return err
   103  		}
   104  		if err := hs.doFullHandshake(); err != nil {
   105  			return err
   106  		}
   107  		if err := hs.establishKeys(); err != nil {
   108  			return err
   109  		}
   110  		if err := hs.readFinished(c.clientFinished[:]); err != nil {
   111  			return err
   112  		}
   113  		c.clientFinishedIsFirst = true
   114  		c.buffering = true
   115  		if err := hs.sendSessionTicket(); err != nil {
   116  			return err
   117  		}
   118  		if err := hs.sendFinished(nil); err != nil {
   119  			return err
   120  		}
   121  		if _, err := c.flush(); err != nil {
   122  			return err
   123  		}
   124  	}
   125  
   126  	c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random)
   127  	c.isHandshakeComplete.Store(true)
   128  
   129  	return nil
   130  }
   131  
   132  // readClientHello reads a ClientHello message and selects the protocol version.
   133  func (c *Conn) readClientHello(ctx context.Context) (*clientHelloMsg, error) {
   134  	// clientHelloMsg is included in the transcript, but we haven't initialized
   135  	// it yet. The respective handshake functions will record it themselves.
   136  	msg, err := c.readHandshake(nil)
   137  	if err != nil {
   138  		return nil, err
   139  	}
   140  	clientHello, ok := msg.(*clientHelloMsg)
   141  	if !ok {
   142  		c.sendAlert(alertUnexpectedMessage)
   143  		return nil, unexpectedMessageError(clientHello, msg)
   144  	}
   145  
   146  	var configForClient *Config
   147  	originalConfig := c.config
   148  	if c.config.GetConfigForClient != nil {
   149  		chi := clientHelloInfo(ctx, c, clientHello)
   150  		if configForClient, err = c.config.GetConfigForClient(chi); err != nil {
   151  			c.sendAlert(alertInternalError)
   152  			return nil, err
   153  		} else if configForClient != nil {
   154  			c.config = configForClient
   155  		}
   156  	}
   157  	c.ticketKeys = originalConfig.ticketKeys(configForClient)
   158  
   159  	clientVersions := clientHello.supportedVersions
   160  	if len(clientHello.supportedVersions) == 0 {
   161  		clientVersions = supportedVersionsFromMax(clientHello.vers)
   162  	}
   163  	c.vers, ok = c.config.mutualVersion(roleServer, clientVersions)
   164  	if !ok {
   165  		c.sendAlert(alertProtocolVersion)
   166  		return nil, fmt.Errorf("tls: client offered only unsupported versions: %x", clientVersions)
   167  	}
   168  	c.haveVers = true
   169  	c.in.version = c.vers
   170  	c.out.version = c.vers
   171  
   172  	if c.config.MinVersion == 0 && c.vers < VersionTLS12 {
   173  		tls10server.Value() // ensure godebug is initialized
   174  		tls10server.IncNonDefault()
   175  	}
   176  
   177  	return clientHello, nil
   178  }
   179  
   180  func (hs *serverHandshakeState) processClientHello() error {
   181  	c := hs.c
   182  
   183  	hs.hello = new(serverHelloMsg)
   184  	hs.hello.vers = c.vers
   185  
   186  	foundCompression := false
   187  	// We only support null compression, so check that the client offered it.
   188  	for _, compression := range hs.clientHello.compressionMethods {
   189  		if compression == compressionNone {
   190  			foundCompression = true
   191  			break
   192  		}
   193  	}
   194  
   195  	if !foundCompression {
   196  		c.sendAlert(alertHandshakeFailure)
   197  		return errors.New("tls: client does not support uncompressed connections")
   198  	}
   199  
   200  	hs.hello.random = make([]byte, 32)
   201  	serverRandom := hs.hello.random
   202  	// Downgrade protection canaries. See RFC 8446, Section 4.1.3.
   203  	maxVers := c.config.maxSupportedVersion(roleServer)
   204  	if maxVers >= VersionTLS12 && c.vers < maxVers || testingOnlyForceDowngradeCanary {
   205  		if c.vers == VersionTLS12 {
   206  			copy(serverRandom[24:], downgradeCanaryTLS12)
   207  		} else {
   208  			copy(serverRandom[24:], downgradeCanaryTLS11)
   209  		}
   210  		serverRandom = serverRandom[:24]
   211  	}
   212  	_, err := io.ReadFull(c.config.rand(), serverRandom)
   213  	if err != nil {
   214  		c.sendAlert(alertInternalError)
   215  		return err
   216  	}
   217  
   218  	if len(hs.clientHello.secureRenegotiation) != 0 {
   219  		c.sendAlert(alertHandshakeFailure)
   220  		return errors.New("tls: initial handshake had non-empty renegotiation extension")
   221  	}
   222  
   223  	hs.hello.extendedMasterSecret = hs.clientHello.extendedMasterSecret
   224  	hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported
   225  	hs.hello.compressionMethod = compressionNone
   226  	if len(hs.clientHello.serverName) > 0 {
   227  		c.serverName = hs.clientHello.serverName
   228  	}
   229  
   230  	selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols, false)
   231  	if err != nil {
   232  		c.sendAlert(alertNoApplicationProtocol)
   233  		return err
   234  	}
   235  	hs.hello.alpnProtocol = selectedProto
   236  	c.clientProtocol = selectedProto
   237  
   238  	hs.cert, err = c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello))
   239  	if err != nil {
   240  		if err == errNoCertificates {
   241  			c.sendAlert(alertUnrecognizedName)
   242  		} else {
   243  			c.sendAlert(alertInternalError)
   244  		}
   245  		return err
   246  	}
   247  	if hs.clientHello.scts {
   248  		hs.hello.scts = hs.cert.SignedCertificateTimestamps
   249  	}
   250  
   251  	hs.ecdheOk = supportsECDHE(c.config, c.vers, hs.clientHello.supportedCurves, hs.clientHello.supportedPoints)
   252  
   253  	if hs.ecdheOk && len(hs.clientHello.supportedPoints) > 0 {
   254  		// Although omitting the ec_point_formats extension is permitted, some
   255  		// old OpenSSL version will refuse to handshake if not present.
   256  		//
   257  		// Per RFC 4492, section 5.1.2, implementations MUST support the
   258  		// uncompressed point format. See golang.org/issue/31943.
   259  		hs.hello.supportedPoints = []uint8{pointFormatUncompressed}
   260  	}
   261  
   262  	if priv, ok := hs.cert.PrivateKey.(crypto.Signer); ok {
   263  		switch priv.Public().(type) {
   264  		case *ecdsa.PublicKey:
   265  			hs.ecSignOk = true
   266  		case ed25519.PublicKey:
   267  			hs.ecSignOk = true
   268  		case *rsa.PublicKey:
   269  			hs.rsaSignOk = true
   270  		default:
   271  			c.sendAlert(alertInternalError)
   272  			return fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public())
   273  		}
   274  	}
   275  	if priv, ok := hs.cert.PrivateKey.(crypto.Decrypter); ok {
   276  		switch priv.Public().(type) {
   277  		case *rsa.PublicKey:
   278  			hs.rsaDecryptOk = true
   279  		default:
   280  			c.sendAlert(alertInternalError)
   281  			return fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public())
   282  		}
   283  	}
   284  
   285  	return nil
   286  }
   287  
   288  // negotiateALPN picks a shared ALPN protocol that both sides support in server
   289  // preference order. If ALPN is not configured or the peer doesn't support it,
   290  // it returns "" and no error.
   291  func negotiateALPN(serverProtos, clientProtos []string, quic bool) (string, error) {
   292  	if len(serverProtos) == 0 || len(clientProtos) == 0 {
   293  		if quic && len(serverProtos) != 0 {
   294  			// RFC 9001, Section 8.1
   295  			return "", fmt.Errorf("tls: client did not request an application protocol")
   296  		}
   297  		return "", nil
   298  	}
   299  	var http11fallback bool
   300  	for _, s := range serverProtos {
   301  		for _, c := range clientProtos {
   302  			if s == c {
   303  				return s, nil
   304  			}
   305  			if s == "h2" && c == "http/1.1" {
   306  				http11fallback = true
   307  			}
   308  		}
   309  	}
   310  	// As a special case, let http/1.1 clients connect to h2 servers as if they
   311  	// didn't support ALPN. We used not to enforce protocol overlap, so over
   312  	// time a number of HTTP servers were configured with only "h2", but
   313  	// expected to accept connections from "http/1.1" clients. See Issue 46310.
   314  	if http11fallback {
   315  		return "", nil
   316  	}
   317  	return "", fmt.Errorf("tls: client requested unsupported application protocols (%s)", clientProtos)
   318  }
   319  
   320  // supportsECDHE returns whether ECDHE key exchanges can be used with this
   321  // pre-TLS 1.3 client.
   322  func supportsECDHE(c *Config, version uint16, supportedCurves []CurveID, supportedPoints []uint8) bool {
   323  	supportsCurve := false
   324  	for _, curve := range supportedCurves {
   325  		if c.supportsCurve(version, curve) {
   326  			supportsCurve = true
   327  			break
   328  		}
   329  	}
   330  
   331  	supportsPointFormat := false
   332  	for _, pointFormat := range supportedPoints {
   333  		if pointFormat == pointFormatUncompressed {
   334  			supportsPointFormat = true
   335  			break
   336  		}
   337  	}
   338  	// Per RFC 8422, Section 5.1.2, if the Supported Point Formats extension is
   339  	// missing, uncompressed points are supported. If supportedPoints is empty,
   340  	// the extension must be missing, as an empty extension body is rejected by
   341  	// the parser. See https://go.dev/issue/49126.
   342  	if len(supportedPoints) == 0 {
   343  		supportsPointFormat = true
   344  	}
   345  
   346  	return supportsCurve && supportsPointFormat
   347  }
   348  
   349  func (hs *serverHandshakeState) pickCipherSuite() error {
   350  	c := hs.c
   351  
   352  	preferenceOrder := cipherSuitesPreferenceOrder
   353  	if !hasAESGCMHardwareSupport || !aesgcmPreferred(hs.clientHello.cipherSuites) {
   354  		preferenceOrder = cipherSuitesPreferenceOrderNoAES
   355  	}
   356  
   357  	configCipherSuites := c.config.cipherSuites()
   358  	preferenceList := make([]uint16, 0, len(configCipherSuites))
   359  	for _, suiteID := range preferenceOrder {
   360  		for _, id := range configCipherSuites {
   361  			if id == suiteID {
   362  				preferenceList = append(preferenceList, id)
   363  				break
   364  			}
   365  		}
   366  	}
   367  
   368  	hs.suite = selectCipherSuite(preferenceList, hs.clientHello.cipherSuites, hs.cipherSuiteOk)
   369  	if hs.suite == nil {
   370  		c.sendAlert(alertHandshakeFailure)
   371  		return errors.New("tls: no cipher suite supported by both client and server")
   372  	}
   373  	c.cipherSuite = hs.suite.id
   374  
   375  	if c.config.CipherSuites == nil && !needFIPS() && rsaKexCiphers[hs.suite.id] {
   376  		tlsrsakex.Value() // ensure godebug is initialized
   377  		tlsrsakex.IncNonDefault()
   378  	}
   379  	if c.config.CipherSuites == nil && !needFIPS() && tdesCiphers[hs.suite.id] {
   380  		tls3des.Value() // ensure godebug is initialized
   381  		tls3des.IncNonDefault()
   382  	}
   383  
   384  	for _, id := range hs.clientHello.cipherSuites {
   385  		if id == TLS_FALLBACK_SCSV {
   386  			// The client is doing a fallback connection. See RFC 7507.
   387  			if hs.clientHello.vers < c.config.maxSupportedVersion(roleServer) {
   388  				c.sendAlert(alertInappropriateFallback)
   389  				return errors.New("tls: client using inappropriate protocol fallback")
   390  			}
   391  			break
   392  		}
   393  	}
   394  
   395  	return nil
   396  }
   397  
   398  func (hs *serverHandshakeState) cipherSuiteOk(c *cipherSuite) bool {
   399  	if c.flags&suiteECDHE != 0 {
   400  		if !hs.ecdheOk {
   401  			return false
   402  		}
   403  		if c.flags&suiteECSign != 0 {
   404  			if !hs.ecSignOk {
   405  				return false
   406  			}
   407  		} else if !hs.rsaSignOk {
   408  			return false
   409  		}
   410  	} else if !hs.rsaDecryptOk {
   411  		return false
   412  	}
   413  	if hs.c.vers < VersionTLS12 && c.flags&suiteTLS12 != 0 {
   414  		return false
   415  	}
   416  	return true
   417  }
   418  
   419  // checkForResumption reports whether we should perform resumption on this connection.
   420  func (hs *serverHandshakeState) checkForResumption() error {
   421  	c := hs.c
   422  
   423  	if c.config.SessionTicketsDisabled {
   424  		return nil
   425  	}
   426  
   427  	var sessionState *SessionState
   428  	if c.config.UnwrapSession != nil {
   429  		ss, err := c.config.UnwrapSession(hs.clientHello.sessionTicket, c.connectionStateLocked())
   430  		if err != nil {
   431  			return err
   432  		}
   433  		if ss == nil {
   434  			return nil
   435  		}
   436  		sessionState = ss
   437  	} else {
   438  		plaintext := c.config.decryptTicket(hs.clientHello.sessionTicket, c.ticketKeys)
   439  		if plaintext == nil {
   440  			return nil
   441  		}
   442  		ss, err := ParseSessionState(plaintext)
   443  		if err != nil {
   444  			return nil
   445  		}
   446  		sessionState = ss
   447  	}
   448  
   449  	// TLS 1.2 tickets don't natively have a lifetime, but we want to avoid
   450  	// re-wrapping the same master secret in different tickets over and over for
   451  	// too long, weakening forward secrecy.
   452  	createdAt := time.Unix(int64(sessionState.createdAt), 0)
   453  	if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
   454  		return nil
   455  	}
   456  
   457  	// Never resume a session for a different TLS version.
   458  	if c.vers != sessionState.version {
   459  		return nil
   460  	}
   461  
   462  	cipherSuiteOk := false
   463  	// Check that the client is still offering the ciphersuite in the session.
   464  	for _, id := range hs.clientHello.cipherSuites {
   465  		if id == sessionState.cipherSuite {
   466  			cipherSuiteOk = true
   467  			break
   468  		}
   469  	}
   470  	if !cipherSuiteOk {
   471  		return nil
   472  	}
   473  
   474  	// Check that we also support the ciphersuite from the session.
   475  	suite := selectCipherSuite([]uint16{sessionState.cipherSuite},
   476  		c.config.cipherSuites(), hs.cipherSuiteOk)
   477  	if suite == nil {
   478  		return nil
   479  	}
   480  
   481  	sessionHasClientCerts := len(sessionState.peerCertificates) != 0
   482  	needClientCerts := requiresClientCert(c.config.ClientAuth)
   483  	if needClientCerts && !sessionHasClientCerts {
   484  		return nil
   485  	}
   486  	if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
   487  		return nil
   488  	}
   489  	if sessionHasClientCerts && c.config.time().After(sessionState.peerCertificates[0].NotAfter) {
   490  		return nil
   491  	}
   492  	if sessionHasClientCerts && c.config.ClientAuth >= VerifyClientCertIfGiven &&
   493  		len(sessionState.verifiedChains) == 0 {
   494  		return nil
   495  	}
   496  
   497  	// RFC 7627, Section 5.3
   498  	if !sessionState.extMasterSecret && hs.clientHello.extendedMasterSecret {
   499  		return nil
   500  	}
   501  	if sessionState.extMasterSecret && !hs.clientHello.extendedMasterSecret {
   502  		// Aborting is somewhat harsh, but it's a MUST and it would indicate a
   503  		// weird downgrade in client capabilities.
   504  		return errors.New("tls: session supported extended_master_secret but client does not")
   505  	}
   506  
   507  	c.peerCertificates = sessionState.peerCertificates
   508  	c.ocspResponse = sessionState.ocspResponse
   509  	c.scts = sessionState.scts
   510  	c.verifiedChains = sessionState.verifiedChains
   511  	c.extMasterSecret = sessionState.extMasterSecret
   512  	hs.sessionState = sessionState
   513  	hs.suite = suite
   514  	c.didResume = true
   515  	return nil
   516  }
   517  
   518  func (hs *serverHandshakeState) doResumeHandshake() error {
   519  	c := hs.c
   520  
   521  	hs.hello.cipherSuite = hs.suite.id
   522  	c.cipherSuite = hs.suite.id
   523  	// We echo the client's session ID in the ServerHello to let it know
   524  	// that we're doing a resumption.
   525  	hs.hello.sessionId = hs.clientHello.sessionId
   526  	// We always send a new session ticket, even if it wraps the same master
   527  	// secret and it's potentially encrypted with the same key, to help the
   528  	// client avoid cross-connection tracking from a network observer.
   529  	hs.hello.ticketSupported = true
   530  	hs.finishedHash = newFinishedHash(c.vers, hs.suite)
   531  	hs.finishedHash.discardHandshakeBuffer()
   532  	if err := transcriptMsg(hs.clientHello, &hs.finishedHash); err != nil {
   533  		return err
   534  	}
   535  	if _, err := hs.c.writeHandshakeRecord(hs.hello, &hs.finishedHash); err != nil {
   536  		return err
   537  	}
   538  
   539  	if c.config.VerifyConnection != nil {
   540  		if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
   541  			c.sendAlert(alertBadCertificate)
   542  			return err
   543  		}
   544  	}
   545  
   546  	hs.masterSecret = hs.sessionState.secret
   547  
   548  	return nil
   549  }
   550  
   551  func (hs *serverHandshakeState) doFullHandshake() error {
   552  	c := hs.c
   553  
   554  	if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
   555  		hs.hello.ocspStapling = true
   556  	}
   557  
   558  	hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled
   559  	hs.hello.cipherSuite = hs.suite.id
   560  
   561  	hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite)
   562  	if c.config.ClientAuth == NoClientCert {
   563  		// No need to keep a full record of the handshake if client
   564  		// certificates won't be used.
   565  		hs.finishedHash.discardHandshakeBuffer()
   566  	}
   567  	if err := transcriptMsg(hs.clientHello, &hs.finishedHash); err != nil {
   568  		return err
   569  	}
   570  	if _, err := hs.c.writeHandshakeRecord(hs.hello, &hs.finishedHash); err != nil {
   571  		return err
   572  	}
   573  
   574  	certMsg := new(certificateMsg)
   575  	certMsg.certificates = hs.cert.Certificate
   576  	if _, err := hs.c.writeHandshakeRecord(certMsg, &hs.finishedHash); err != nil {
   577  		return err
   578  	}
   579  
   580  	if hs.hello.ocspStapling {
   581  		certStatus := new(certificateStatusMsg)
   582  		certStatus.response = hs.cert.OCSPStaple
   583  		if _, err := hs.c.writeHandshakeRecord(certStatus, &hs.finishedHash); err != nil {
   584  			return err
   585  		}
   586  	}
   587  
   588  	keyAgreement := hs.suite.ka(c.vers)
   589  	skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.cert, hs.clientHello, hs.hello)
   590  	if err != nil {
   591  		c.sendAlert(alertHandshakeFailure)
   592  		return err
   593  	}
   594  	if skx != nil {
   595  		if len(skx.key) >= 3 && skx.key[0] == 3 /* named curve */ {
   596  			c.curveID = CurveID(byteorder.BeUint16(skx.key[1:]))
   597  		}
   598  		if _, err := hs.c.writeHandshakeRecord(skx, &hs.finishedHash); err != nil {
   599  			return err
   600  		}
   601  	}
   602  
   603  	var certReq *certificateRequestMsg
   604  	if c.config.ClientAuth >= RequestClientCert {
   605  		// Request a client certificate
   606  		certReq = new(certificateRequestMsg)
   607  		certReq.certificateTypes = []byte{
   608  			byte(certTypeRSASign),
   609  			byte(certTypeECDSASign),
   610  		}
   611  		if c.vers >= VersionTLS12 {
   612  			certReq.hasSignatureAlgorithm = true
   613  			certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms()
   614  		}
   615  
   616  		// An empty list of certificateAuthorities signals to
   617  		// the client that it may send any certificate in response
   618  		// to our request. When we know the CAs we trust, then
   619  		// we can send them down, so that the client can choose
   620  		// an appropriate certificate to give to us.
   621  		if c.config.ClientCAs != nil {
   622  			certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
   623  		}
   624  		if _, err := hs.c.writeHandshakeRecord(certReq, &hs.finishedHash); err != nil {
   625  			return err
   626  		}
   627  	}
   628  
   629  	helloDone := new(serverHelloDoneMsg)
   630  	if _, err := hs.c.writeHandshakeRecord(helloDone, &hs.finishedHash); err != nil {
   631  		return err
   632  	}
   633  
   634  	if _, err := c.flush(); err != nil {
   635  		return err
   636  	}
   637  
   638  	var pub crypto.PublicKey // public key for client auth, if any
   639  
   640  	msg, err := c.readHandshake(&hs.finishedHash)
   641  	if err != nil {
   642  		return err
   643  	}
   644  
   645  	// If we requested a client certificate, then the client must send a
   646  	// certificate message, even if it's empty.
   647  	if c.config.ClientAuth >= RequestClientCert {
   648  		certMsg, ok := msg.(*certificateMsg)
   649  		if !ok {
   650  			c.sendAlert(alertUnexpectedMessage)
   651  			return unexpectedMessageError(certMsg, msg)
   652  		}
   653  
   654  		if err := c.processCertsFromClient(Certificate{
   655  			Certificate: certMsg.certificates,
   656  		}); err != nil {
   657  			return err
   658  		}
   659  		if len(certMsg.certificates) != 0 {
   660  			pub = c.peerCertificates[0].PublicKey
   661  		}
   662  
   663  		msg, err = c.readHandshake(&hs.finishedHash)
   664  		if err != nil {
   665  			return err
   666  		}
   667  	}
   668  	if c.config.VerifyConnection != nil {
   669  		if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
   670  			c.sendAlert(alertBadCertificate)
   671  			return err
   672  		}
   673  	}
   674  
   675  	// Get client key exchange
   676  	ckx, ok := msg.(*clientKeyExchangeMsg)
   677  	if !ok {
   678  		c.sendAlert(alertUnexpectedMessage)
   679  		return unexpectedMessageError(ckx, msg)
   680  	}
   681  
   682  	preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.cert, ckx, c.vers)
   683  	if err != nil {
   684  		c.sendAlert(alertHandshakeFailure)
   685  		return err
   686  	}
   687  	if hs.hello.extendedMasterSecret {
   688  		c.extMasterSecret = true
   689  		hs.masterSecret = extMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
   690  			hs.finishedHash.Sum())
   691  	} else {
   692  		hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret,
   693  			hs.clientHello.random, hs.hello.random)
   694  	}
   695  	if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.clientHello.random, hs.masterSecret); err != nil {
   696  		c.sendAlert(alertInternalError)
   697  		return err
   698  	}
   699  
   700  	// If we received a client cert in response to our certificate request message,
   701  	// the client will send us a certificateVerifyMsg immediately after the
   702  	// clientKeyExchangeMsg. This message is a digest of all preceding
   703  	// handshake-layer messages that is signed using the private key corresponding
   704  	// to the client's certificate. This allows us to verify that the client is in
   705  	// possession of the private key of the certificate.
   706  	if len(c.peerCertificates) > 0 {
   707  		// certificateVerifyMsg is included in the transcript, but not until
   708  		// after we verify the handshake signature, since the state before
   709  		// this message was sent is used.
   710  		msg, err = c.readHandshake(nil)
   711  		if err != nil {
   712  			return err
   713  		}
   714  		certVerify, ok := msg.(*certificateVerifyMsg)
   715  		if !ok {
   716  			c.sendAlert(alertUnexpectedMessage)
   717  			return unexpectedMessageError(certVerify, msg)
   718  		}
   719  
   720  		var sigType uint8
   721  		var sigHash crypto.Hash
   722  		if c.vers >= VersionTLS12 {
   723  			if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, certReq.supportedSignatureAlgorithms) {
   724  				c.sendAlert(alertIllegalParameter)
   725  				return errors.New("tls: client certificate used with invalid signature algorithm")
   726  			}
   727  			sigType, sigHash, err = typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
   728  			if err != nil {
   729  				return c.sendAlert(alertInternalError)
   730  			}
   731  		} else {
   732  			sigType, sigHash, err = legacyTypeAndHashFromPublicKey(pub)
   733  			if err != nil {
   734  				c.sendAlert(alertIllegalParameter)
   735  				return err
   736  			}
   737  		}
   738  
   739  		signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash)
   740  		if err := verifyHandshakeSignature(sigType, pub, sigHash, signed, certVerify.signature); err != nil {
   741  			c.sendAlert(alertDecryptError)
   742  			return errors.New("tls: invalid signature by the client certificate: " + err.Error())
   743  		}
   744  
   745  		if err := transcriptMsg(certVerify, &hs.finishedHash); err != nil {
   746  			return err
   747  		}
   748  	}
   749  
   750  	hs.finishedHash.discardHandshakeBuffer()
   751  
   752  	return nil
   753  }
   754  
   755  func (hs *serverHandshakeState) establishKeys() error {
   756  	c := hs.c
   757  
   758  	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
   759  		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
   760  
   761  	var clientCipher, serverCipher any
   762  	var clientHash, serverHash hash.Hash
   763  
   764  	if hs.suite.aead == nil {
   765  		clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
   766  		clientHash = hs.suite.mac(clientMAC)
   767  		serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
   768  		serverHash = hs.suite.mac(serverMAC)
   769  	} else {
   770  		clientCipher = hs.suite.aead(clientKey, clientIV)
   771  		serverCipher = hs.suite.aead(serverKey, serverIV)
   772  	}
   773  
   774  	c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
   775  	c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
   776  
   777  	return nil
   778  }
   779  
   780  func (hs *serverHandshakeState) readFinished(out []byte) error {
   781  	c := hs.c
   782  
   783  	if err := c.readChangeCipherSpec(); err != nil {
   784  		return err
   785  	}
   786  
   787  	// finishedMsg is included in the transcript, but not until after we
   788  	// check the client version, since the state before this message was
   789  	// sent is used during verification.
   790  	msg, err := c.readHandshake(nil)
   791  	if err != nil {
   792  		return err
   793  	}
   794  	clientFinished, ok := msg.(*finishedMsg)
   795  	if !ok {
   796  		c.sendAlert(alertUnexpectedMessage)
   797  		return unexpectedMessageError(clientFinished, msg)
   798  	}
   799  
   800  	verify := hs.finishedHash.clientSum(hs.masterSecret)
   801  	if len(verify) != len(clientFinished.verifyData) ||
   802  		subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
   803  		c.sendAlert(alertHandshakeFailure)
   804  		return errors.New("tls: client's Finished message is incorrect")
   805  	}
   806  
   807  	if err := transcriptMsg(clientFinished, &hs.finishedHash); err != nil {
   808  		return err
   809  	}
   810  
   811  	copy(out, verify)
   812  	return nil
   813  }
   814  
   815  func (hs *serverHandshakeState) sendSessionTicket() error {
   816  	if !hs.hello.ticketSupported {
   817  		return nil
   818  	}
   819  
   820  	c := hs.c
   821  	m := new(newSessionTicketMsg)
   822  
   823  	state := c.sessionState()
   824  	state.secret = hs.masterSecret
   825  	if hs.sessionState != nil {
   826  		// If this is re-wrapping an old key, then keep
   827  		// the original time it was created.
   828  		state.createdAt = hs.sessionState.createdAt
   829  	}
   830  	if c.config.WrapSession != nil {
   831  		var err error
   832  		m.ticket, err = c.config.WrapSession(c.connectionStateLocked(), state)
   833  		if err != nil {
   834  			return err
   835  		}
   836  	} else {
   837  		stateBytes, err := state.Bytes()
   838  		if err != nil {
   839  			return err
   840  		}
   841  		m.ticket, err = c.config.encryptTicket(stateBytes, c.ticketKeys)
   842  		if err != nil {
   843  			return err
   844  		}
   845  	}
   846  
   847  	if _, err := hs.c.writeHandshakeRecord(m, &hs.finishedHash); err != nil {
   848  		return err
   849  	}
   850  
   851  	return nil
   852  }
   853  
   854  func (hs *serverHandshakeState) sendFinished(out []byte) error {
   855  	c := hs.c
   856  
   857  	if err := c.writeChangeCipherRecord(); err != nil {
   858  		return err
   859  	}
   860  
   861  	finished := new(finishedMsg)
   862  	finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
   863  	if _, err := hs.c.writeHandshakeRecord(finished, &hs.finishedHash); err != nil {
   864  		return err
   865  	}
   866  
   867  	copy(out, finished.verifyData)
   868  
   869  	return nil
   870  }
   871  
   872  // processCertsFromClient takes a chain of client certificates either from a
   873  // Certificates message and verifies them.
   874  func (c *Conn) processCertsFromClient(certificate Certificate) error {
   875  	certificates := certificate.Certificate
   876  	certs := make([]*x509.Certificate, len(certificates))
   877  	var err error
   878  	for i, asn1Data := range certificates {
   879  		if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
   880  			c.sendAlert(alertBadCertificate)
   881  			return errors.New("tls: failed to parse client certificate: " + err.Error())
   882  		}
   883  		if certs[i].PublicKeyAlgorithm == x509.RSA {
   884  			n := certs[i].PublicKey.(*rsa.PublicKey).N.BitLen()
   885  			if max, ok := checkKeySize(n); !ok {
   886  				c.sendAlert(alertBadCertificate)
   887  				return fmt.Errorf("tls: client sent certificate containing RSA key larger than %d bits", max)
   888  			}
   889  		}
   890  	}
   891  
   892  	if len(certs) == 0 && requiresClientCert(c.config.ClientAuth) {
   893  		if c.vers == VersionTLS13 {
   894  			c.sendAlert(alertCertificateRequired)
   895  		} else {
   896  			c.sendAlert(alertBadCertificate)
   897  		}
   898  		return errors.New("tls: client didn't provide a certificate")
   899  	}
   900  
   901  	if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
   902  		opts := x509.VerifyOptions{
   903  			Roots:         c.config.ClientCAs,
   904  			CurrentTime:   c.config.time(),
   905  			Intermediates: x509.NewCertPool(),
   906  			KeyUsages:     []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
   907  		}
   908  
   909  		for _, cert := range certs[1:] {
   910  			opts.Intermediates.AddCert(cert)
   911  		}
   912  
   913  		chains, err := certs[0].Verify(opts)
   914  		if err != nil {
   915  			var errCertificateInvalid x509.CertificateInvalidError
   916  			if errors.As(err, &x509.UnknownAuthorityError{}) {
   917  				c.sendAlert(alertUnknownCA)
   918  			} else if errors.As(err, &errCertificateInvalid) && errCertificateInvalid.Reason == x509.Expired {
   919  				c.sendAlert(alertCertificateExpired)
   920  			} else {
   921  				c.sendAlert(alertBadCertificate)
   922  			}
   923  			return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err}
   924  		}
   925  
   926  		c.verifiedChains = chains
   927  	}
   928  
   929  	c.peerCertificates = certs
   930  	c.ocspResponse = certificate.OCSPStaple
   931  	c.scts = certificate.SignedCertificateTimestamps
   932  
   933  	if len(certs) > 0 {
   934  		switch certs[0].PublicKey.(type) {
   935  		case *ecdsa.PublicKey, *rsa.PublicKey, ed25519.PublicKey:
   936  		default:
   937  			c.sendAlert(alertUnsupportedCertificate)
   938  			return fmt.Errorf("tls: client certificate contains an unsupported public key of type %T", certs[0].PublicKey)
   939  		}
   940  	}
   941  
   942  	if c.config.VerifyPeerCertificate != nil {
   943  		if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
   944  			c.sendAlert(alertBadCertificate)
   945  			return err
   946  		}
   947  	}
   948  
   949  	return nil
   950  }
   951  
   952  func clientHelloInfo(ctx context.Context, c *Conn, clientHello *clientHelloMsg) *ClientHelloInfo {
   953  	supportedVersions := clientHello.supportedVersions
   954  	if len(clientHello.supportedVersions) == 0 {
   955  		supportedVersions = supportedVersionsFromMax(clientHello.vers)
   956  	}
   957  
   958  	return &ClientHelloInfo{
   959  		CipherSuites:      clientHello.cipherSuites,
   960  		ServerName:        clientHello.serverName,
   961  		SupportedCurves:   clientHello.supportedCurves,
   962  		SupportedPoints:   clientHello.supportedPoints,
   963  		SignatureSchemes:  clientHello.supportedSignatureAlgorithms,
   964  		SupportedProtos:   clientHello.alpnProtocols,
   965  		SupportedVersions: supportedVersions,
   966  		Conn:              c.conn,
   967  		config:            c.config,
   968  		ctx:               ctx,
   969  	}
   970  }
   971  

View as plain text