...

Source file src/crypto/tls/handshake_client.go

Documentation: crypto/tls

		 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  	"bytes"
		 9  	"context"
		10  	"crypto"
		11  	"crypto/ecdsa"
		12  	"crypto/ed25519"
		13  	"crypto/rsa"
		14  	"crypto/subtle"
		15  	"crypto/x509"
		16  	"errors"
		17  	"fmt"
		18  	"hash"
		19  	"io"
		20  	"net"
		21  	"strings"
		22  	"sync/atomic"
		23  	"time"
		24  )
		25  
		26  type clientHandshakeState struct {
		27  	c						*Conn
		28  	ctx					context.Context
		29  	serverHello	*serverHelloMsg
		30  	hello				*clientHelloMsg
		31  	suite				*cipherSuite
		32  	finishedHash finishedHash
		33  	masterSecret []byte
		34  	session			*ClientSessionState
		35  }
		36  
		37  func (c *Conn) makeClientHello() (*clientHelloMsg, ecdheParameters, error) {
		38  	config := c.config
		39  	if len(config.ServerName) == 0 && !config.InsecureSkipVerify {
		40  		return nil, nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
		41  	}
		42  
		43  	nextProtosLength := 0
		44  	for _, proto := range config.NextProtos {
		45  		if l := len(proto); l == 0 || l > 255 {
		46  			return nil, nil, errors.New("tls: invalid NextProtos value")
		47  		} else {
		48  			nextProtosLength += 1 + l
		49  		}
		50  	}
		51  	if nextProtosLength > 0xffff {
		52  		return nil, nil, errors.New("tls: NextProtos values too large")
		53  	}
		54  
		55  	supportedVersions := config.supportedVersions()
		56  	if len(supportedVersions) == 0 {
		57  		return nil, nil, errors.New("tls: no supported versions satisfy MinVersion and MaxVersion")
		58  	}
		59  
		60  	clientHelloVersion := config.maxSupportedVersion()
		61  	// The version at the beginning of the ClientHello was capped at TLS 1.2
		62  	// for compatibility reasons. The supported_versions extension is used
		63  	// to negotiate versions now. See RFC 8446, Section 4.2.1.
		64  	if clientHelloVersion > VersionTLS12 {
		65  		clientHelloVersion = VersionTLS12
		66  	}
		67  
		68  	hello := &clientHelloMsg{
		69  		vers:												 clientHelloVersion,
		70  		compressionMethods:					 []uint8{compressionNone},
		71  		random:											 make([]byte, 32),
		72  		sessionId:										make([]byte, 32),
		73  		ocspStapling:								 true,
		74  		scts:												 true,
		75  		serverName:									 hostnameInSNI(config.ServerName),
		76  		supportedCurves:							config.curvePreferences(),
		77  		supportedPoints:							[]uint8{pointFormatUncompressed},
		78  		secureRenegotiationSupported: true,
		79  		alpnProtocols:								config.NextProtos,
		80  		supportedVersions:						supportedVersions,
		81  	}
		82  
		83  	if c.handshakes > 0 {
		84  		hello.secureRenegotiation = c.clientFinished[:]
		85  	}
		86  
		87  	preferenceOrder := cipherSuitesPreferenceOrder
		88  	if !hasAESGCMHardwareSupport {
		89  		preferenceOrder = cipherSuitesPreferenceOrderNoAES
		90  	}
		91  	configCipherSuites := config.cipherSuites()
		92  	hello.cipherSuites = make([]uint16, 0, len(configCipherSuites))
		93  
		94  	for _, suiteId := range preferenceOrder {
		95  		suite := mutualCipherSuite(configCipherSuites, suiteId)
		96  		if suite == nil {
		97  			continue
		98  		}
		99  		// Don't advertise TLS 1.2-only cipher suites unless
	 100  		// we're attempting TLS 1.2.
	 101  		if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
	 102  			continue
	 103  		}
	 104  		hello.cipherSuites = append(hello.cipherSuites, suiteId)
	 105  	}
	 106  
	 107  	_, err := io.ReadFull(config.rand(), hello.random)
	 108  	if err != nil {
	 109  		return nil, nil, errors.New("tls: short read from Rand: " + err.Error())
	 110  	}
	 111  
	 112  	// A random session ID is used to detect when the server accepted a ticket
	 113  	// and is resuming a session (see RFC 5077). In TLS 1.3, it's always set as
	 114  	// a compatibility measure (see RFC 8446, Section 4.1.2).
	 115  	if _, err := io.ReadFull(config.rand(), hello.sessionId); err != nil {
	 116  		return nil, nil, errors.New("tls: short read from Rand: " + err.Error())
	 117  	}
	 118  
	 119  	if hello.vers >= VersionTLS12 {
	 120  		hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms
	 121  	}
	 122  
	 123  	var params ecdheParameters
	 124  	if hello.supportedVersions[0] == VersionTLS13 {
	 125  		if hasAESGCMHardwareSupport {
	 126  			hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13...)
	 127  		} else {
	 128  			hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13NoAES...)
	 129  		}
	 130  
	 131  		curveID := config.curvePreferences()[0]
	 132  		if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok {
	 133  			return nil, nil, errors.New("tls: CurvePreferences includes unsupported curve")
	 134  		}
	 135  		params, err = generateECDHEParameters(config.rand(), curveID)
	 136  		if err != nil {
	 137  			return nil, nil, err
	 138  		}
	 139  		hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}}
	 140  	}
	 141  
	 142  	return hello, params, nil
	 143  }
	 144  
	 145  func (c *Conn) clientHandshake(ctx context.Context) (err error) {
	 146  	if c.config == nil {
	 147  		c.config = defaultConfig()
	 148  	}
	 149  
	 150  	// This may be a renegotiation handshake, in which case some fields
	 151  	// need to be reset.
	 152  	c.didResume = false
	 153  
	 154  	hello, ecdheParams, err := c.makeClientHello()
	 155  	if err != nil {
	 156  		return err
	 157  	}
	 158  	c.serverName = hello.serverName
	 159  
	 160  	cacheKey, session, earlySecret, binderKey := c.loadSession(hello)
	 161  	if cacheKey != "" && session != nil {
	 162  		defer func() {
	 163  			// If we got a handshake failure when resuming a session, throw away
	 164  			// the session ticket. See RFC 5077, Section 3.2.
	 165  			//
	 166  			// RFC 8446 makes no mention of dropping tickets on failure, but it
	 167  			// does require servers to abort on invalid binders, so we need to
	 168  			// delete tickets to recover from a corrupted PSK.
	 169  			if err != nil {
	 170  				c.config.ClientSessionCache.Put(cacheKey, nil)
	 171  			}
	 172  		}()
	 173  	}
	 174  
	 175  	if _, err := c.writeRecord(recordTypeHandshake, hello.marshal()); err != nil {
	 176  		return err
	 177  	}
	 178  
	 179  	msg, err := c.readHandshake()
	 180  	if err != nil {
	 181  		return err
	 182  	}
	 183  
	 184  	serverHello, ok := msg.(*serverHelloMsg)
	 185  	if !ok {
	 186  		c.sendAlert(alertUnexpectedMessage)
	 187  		return unexpectedMessageError(serverHello, msg)
	 188  	}
	 189  
	 190  	if err := c.pickTLSVersion(serverHello); err != nil {
	 191  		return err
	 192  	}
	 193  
	 194  	// If we are negotiating a protocol version that's lower than what we
	 195  	// support, check for the server downgrade canaries.
	 196  	// See RFC 8446, Section 4.1.3.
	 197  	maxVers := c.config.maxSupportedVersion()
	 198  	tls12Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS12
	 199  	tls11Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS11
	 200  	if maxVers == VersionTLS13 && c.vers <= VersionTLS12 && (tls12Downgrade || tls11Downgrade) ||
	 201  		maxVers == VersionTLS12 && c.vers <= VersionTLS11 && tls11Downgrade {
	 202  		c.sendAlert(alertIllegalParameter)
	 203  		return errors.New("tls: downgrade attempt detected, possibly due to a MitM attack or a broken middlebox")
	 204  	}
	 205  
	 206  	if c.vers == VersionTLS13 {
	 207  		hs := &clientHandshakeStateTLS13{
	 208  			c:					 c,
	 209  			ctx:				 ctx,
	 210  			serverHello: serverHello,
	 211  			hello:			 hello,
	 212  			ecdheParams: ecdheParams,
	 213  			session:		 session,
	 214  			earlySecret: earlySecret,
	 215  			binderKey:	 binderKey,
	 216  		}
	 217  
	 218  		// In TLS 1.3, session tickets are delivered after the handshake.
	 219  		return hs.handshake()
	 220  	}
	 221  
	 222  	hs := &clientHandshakeState{
	 223  		c:					 c,
	 224  		ctx:				 ctx,
	 225  		serverHello: serverHello,
	 226  		hello:			 hello,
	 227  		session:		 session,
	 228  	}
	 229  
	 230  	if err := hs.handshake(); err != nil {
	 231  		return err
	 232  	}
	 233  
	 234  	// If we had a successful handshake and hs.session is different from
	 235  	// the one already cached - cache a new one.
	 236  	if cacheKey != "" && hs.session != nil && session != hs.session {
	 237  		c.config.ClientSessionCache.Put(cacheKey, hs.session)
	 238  	}
	 239  
	 240  	return nil
	 241  }
	 242  
	 243  func (c *Conn) loadSession(hello *clientHelloMsg) (cacheKey string,
	 244  	session *ClientSessionState, earlySecret, binderKey []byte) {
	 245  	if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
	 246  		return "", nil, nil, nil
	 247  	}
	 248  
	 249  	hello.ticketSupported = true
	 250  
	 251  	if hello.supportedVersions[0] == VersionTLS13 {
	 252  		// Require DHE on resumption as it guarantees forward secrecy against
	 253  		// compromise of the session ticket key. See RFC 8446, Section 4.2.9.
	 254  		hello.pskModes = []uint8{pskModeDHE}
	 255  	}
	 256  
	 257  	// Session resumption is not allowed if renegotiating because
	 258  	// renegotiation is primarily used to allow a client to send a client
	 259  	// certificate, which would be skipped if session resumption occurred.
	 260  	if c.handshakes != 0 {
	 261  		return "", nil, nil, nil
	 262  	}
	 263  
	 264  	// Try to resume a previously negotiated TLS session, if available.
	 265  	cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
	 266  	session, ok := c.config.ClientSessionCache.Get(cacheKey)
	 267  	if !ok || session == nil {
	 268  		return cacheKey, nil, nil, nil
	 269  	}
	 270  
	 271  	// Check that version used for the previous session is still valid.
	 272  	versOk := false
	 273  	for _, v := range hello.supportedVersions {
	 274  		if v == session.vers {
	 275  			versOk = true
	 276  			break
	 277  		}
	 278  	}
	 279  	if !versOk {
	 280  		return cacheKey, nil, nil, nil
	 281  	}
	 282  
	 283  	// Check that the cached server certificate is not expired, and that it's
	 284  	// valid for the ServerName. This should be ensured by the cache key, but
	 285  	// protect the application from a faulty ClientSessionCache implementation.
	 286  	if !c.config.InsecureSkipVerify {
	 287  		if len(session.verifiedChains) == 0 {
	 288  			// The original connection had InsecureSkipVerify, while this doesn't.
	 289  			return cacheKey, nil, nil, nil
	 290  		}
	 291  		serverCert := session.serverCertificates[0]
	 292  		if c.config.time().After(serverCert.NotAfter) {
	 293  			// Expired certificate, delete the entry.
	 294  			c.config.ClientSessionCache.Put(cacheKey, nil)
	 295  			return cacheKey, nil, nil, nil
	 296  		}
	 297  		if err := serverCert.VerifyHostname(c.config.ServerName); err != nil {
	 298  			return cacheKey, nil, nil, nil
	 299  		}
	 300  	}
	 301  
	 302  	if session.vers != VersionTLS13 {
	 303  		// In TLS 1.2 the cipher suite must match the resumed session. Ensure we
	 304  		// are still offering it.
	 305  		if mutualCipherSuite(hello.cipherSuites, session.cipherSuite) == nil {
	 306  			return cacheKey, nil, nil, nil
	 307  		}
	 308  
	 309  		hello.sessionTicket = session.sessionTicket
	 310  		return
	 311  	}
	 312  
	 313  	// Check that the session ticket is not expired.
	 314  	if c.config.time().After(session.useBy) {
	 315  		c.config.ClientSessionCache.Put(cacheKey, nil)
	 316  		return cacheKey, nil, nil, nil
	 317  	}
	 318  
	 319  	// In TLS 1.3 the KDF hash must match the resumed session. Ensure we
	 320  	// offer at least one cipher suite with that hash.
	 321  	cipherSuite := cipherSuiteTLS13ByID(session.cipherSuite)
	 322  	if cipherSuite == nil {
	 323  		return cacheKey, nil, nil, nil
	 324  	}
	 325  	cipherSuiteOk := false
	 326  	for _, offeredID := range hello.cipherSuites {
	 327  		offeredSuite := cipherSuiteTLS13ByID(offeredID)
	 328  		if offeredSuite != nil && offeredSuite.hash == cipherSuite.hash {
	 329  			cipherSuiteOk = true
	 330  			break
	 331  		}
	 332  	}
	 333  	if !cipherSuiteOk {
	 334  		return cacheKey, nil, nil, nil
	 335  	}
	 336  
	 337  	// Set the pre_shared_key extension. See RFC 8446, Section 4.2.11.1.
	 338  	ticketAge := uint32(c.config.time().Sub(session.receivedAt) / time.Millisecond)
	 339  	identity := pskIdentity{
	 340  		label:							 session.sessionTicket,
	 341  		obfuscatedTicketAge: ticketAge + session.ageAdd,
	 342  	}
	 343  	hello.pskIdentities = []pskIdentity{identity}
	 344  	hello.pskBinders = [][]byte{make([]byte, cipherSuite.hash.Size())}
	 345  
	 346  	// Compute the PSK binders. See RFC 8446, Section 4.2.11.2.
	 347  	psk := cipherSuite.expandLabel(session.masterSecret, "resumption",
	 348  		session.nonce, cipherSuite.hash.Size())
	 349  	earlySecret = cipherSuite.extract(psk, nil)
	 350  	binderKey = cipherSuite.deriveSecret(earlySecret, resumptionBinderLabel, nil)
	 351  	transcript := cipherSuite.hash.New()
	 352  	transcript.Write(hello.marshalWithoutBinders())
	 353  	pskBinders := [][]byte{cipherSuite.finishedHash(binderKey, transcript)}
	 354  	hello.updateBinders(pskBinders)
	 355  
	 356  	return
	 357  }
	 358  
	 359  func (c *Conn) pickTLSVersion(serverHello *serverHelloMsg) error {
	 360  	peerVersion := serverHello.vers
	 361  	if serverHello.supportedVersion != 0 {
	 362  		peerVersion = serverHello.supportedVersion
	 363  	}
	 364  
	 365  	vers, ok := c.config.mutualVersion([]uint16{peerVersion})
	 366  	if !ok {
	 367  		c.sendAlert(alertProtocolVersion)
	 368  		return fmt.Errorf("tls: server selected unsupported protocol version %x", peerVersion)
	 369  	}
	 370  
	 371  	c.vers = vers
	 372  	c.haveVers = true
	 373  	c.in.version = vers
	 374  	c.out.version = vers
	 375  
	 376  	return nil
	 377  }
	 378  
	 379  // Does the handshake, either a full one or resumes old session. Requires hs.c,
	 380  // hs.hello, hs.serverHello, and, optionally, hs.session to be set.
	 381  func (hs *clientHandshakeState) handshake() error {
	 382  	c := hs.c
	 383  
	 384  	isResume, err := hs.processServerHello()
	 385  	if err != nil {
	 386  		return err
	 387  	}
	 388  
	 389  	hs.finishedHash = newFinishedHash(c.vers, hs.suite)
	 390  
	 391  	// No signatures of the handshake are needed in a resumption.
	 392  	// Otherwise, in a full handshake, if we don't have any certificates
	 393  	// configured then we will never send a CertificateVerify message and
	 394  	// thus no signatures are needed in that case either.
	 395  	if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
	 396  		hs.finishedHash.discardHandshakeBuffer()
	 397  	}
	 398  
	 399  	hs.finishedHash.Write(hs.hello.marshal())
	 400  	hs.finishedHash.Write(hs.serverHello.marshal())
	 401  
	 402  	c.buffering = true
	 403  	c.didResume = isResume
	 404  	if isResume {
	 405  		if err := hs.establishKeys(); err != nil {
	 406  			return err
	 407  		}
	 408  		if err := hs.readSessionTicket(); err != nil {
	 409  			return err
	 410  		}
	 411  		if err := hs.readFinished(c.serverFinished[:]); err != nil {
	 412  			return err
	 413  		}
	 414  		c.clientFinishedIsFirst = false
	 415  		// Make sure the connection is still being verified whether or not this
	 416  		// is a resumption. Resumptions currently don't reverify certificates so
	 417  		// they don't call verifyServerCertificate. See Issue 31641.
	 418  		if c.config.VerifyConnection != nil {
	 419  			if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
	 420  				c.sendAlert(alertBadCertificate)
	 421  				return err
	 422  			}
	 423  		}
	 424  		if err := hs.sendFinished(c.clientFinished[:]); err != nil {
	 425  			return err
	 426  		}
	 427  		if _, err := c.flush(); err != nil {
	 428  			return err
	 429  		}
	 430  	} else {
	 431  		if err := hs.doFullHandshake(); err != nil {
	 432  			return err
	 433  		}
	 434  		if err := hs.establishKeys(); err != nil {
	 435  			return err
	 436  		}
	 437  		if err := hs.sendFinished(c.clientFinished[:]); err != nil {
	 438  			return err
	 439  		}
	 440  		if _, err := c.flush(); err != nil {
	 441  			return err
	 442  		}
	 443  		c.clientFinishedIsFirst = true
	 444  		if err := hs.readSessionTicket(); err != nil {
	 445  			return err
	 446  		}
	 447  		if err := hs.readFinished(c.serverFinished[:]); err != nil {
	 448  			return err
	 449  		}
	 450  	}
	 451  
	 452  	c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random)
	 453  	atomic.StoreUint32(&c.handshakeStatus, 1)
	 454  
	 455  	return nil
	 456  }
	 457  
	 458  func (hs *clientHandshakeState) pickCipherSuite() error {
	 459  	if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
	 460  		hs.c.sendAlert(alertHandshakeFailure)
	 461  		return errors.New("tls: server chose an unconfigured cipher suite")
	 462  	}
	 463  
	 464  	hs.c.cipherSuite = hs.suite.id
	 465  	return nil
	 466  }
	 467  
	 468  func (hs *clientHandshakeState) doFullHandshake() error {
	 469  	c := hs.c
	 470  
	 471  	msg, err := c.readHandshake()
	 472  	if err != nil {
	 473  		return err
	 474  	}
	 475  	certMsg, ok := msg.(*certificateMsg)
	 476  	if !ok || len(certMsg.certificates) == 0 {
	 477  		c.sendAlert(alertUnexpectedMessage)
	 478  		return unexpectedMessageError(certMsg, msg)
	 479  	}
	 480  	hs.finishedHash.Write(certMsg.marshal())
	 481  
	 482  	msg, err = c.readHandshake()
	 483  	if err != nil {
	 484  		return err
	 485  	}
	 486  
	 487  	cs, ok := msg.(*certificateStatusMsg)
	 488  	if ok {
	 489  		// RFC4366 on Certificate Status Request:
	 490  		// The server MAY return a "certificate_status" message.
	 491  
	 492  		if !hs.serverHello.ocspStapling {
	 493  			// If a server returns a "CertificateStatus" message, then the
	 494  			// server MUST have included an extension of type "status_request"
	 495  			// with empty "extension_data" in the extended server hello.
	 496  
	 497  			c.sendAlert(alertUnexpectedMessage)
	 498  			return errors.New("tls: received unexpected CertificateStatus message")
	 499  		}
	 500  		hs.finishedHash.Write(cs.marshal())
	 501  
	 502  		c.ocspResponse = cs.response
	 503  
	 504  		msg, err = c.readHandshake()
	 505  		if err != nil {
	 506  			return err
	 507  		}
	 508  	}
	 509  
	 510  	if c.handshakes == 0 {
	 511  		// If this is the first handshake on a connection, process and
	 512  		// (optionally) verify the server's certificates.
	 513  		if err := c.verifyServerCertificate(certMsg.certificates); err != nil {
	 514  			return err
	 515  		}
	 516  	} else {
	 517  		// This is a renegotiation handshake. We require that the
	 518  		// server's identity (i.e. leaf certificate) is unchanged and
	 519  		// thus any previous trust decision is still valid.
	 520  		//
	 521  		// See https://mitls.org/pages/attacks/3SHAKE for the
	 522  		// motivation behind this requirement.
	 523  		if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
	 524  			c.sendAlert(alertBadCertificate)
	 525  			return errors.New("tls: server's identity changed during renegotiation")
	 526  		}
	 527  	}
	 528  
	 529  	keyAgreement := hs.suite.ka(c.vers)
	 530  
	 531  	skx, ok := msg.(*serverKeyExchangeMsg)
	 532  	if ok {
	 533  		hs.finishedHash.Write(skx.marshal())
	 534  		err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
	 535  		if err != nil {
	 536  			c.sendAlert(alertUnexpectedMessage)
	 537  			return err
	 538  		}
	 539  
	 540  		msg, err = c.readHandshake()
	 541  		if err != nil {
	 542  			return err
	 543  		}
	 544  	}
	 545  
	 546  	var chainToSend *Certificate
	 547  	var certRequested bool
	 548  	certReq, ok := msg.(*certificateRequestMsg)
	 549  	if ok {
	 550  		certRequested = true
	 551  		hs.finishedHash.Write(certReq.marshal())
	 552  
	 553  		cri := certificateRequestInfoFromMsg(hs.ctx, c.vers, certReq)
	 554  		if chainToSend, err = c.getClientCertificate(cri); err != nil {
	 555  			c.sendAlert(alertInternalError)
	 556  			return err
	 557  		}
	 558  
	 559  		msg, err = c.readHandshake()
	 560  		if err != nil {
	 561  			return err
	 562  		}
	 563  	}
	 564  
	 565  	shd, ok := msg.(*serverHelloDoneMsg)
	 566  	if !ok {
	 567  		c.sendAlert(alertUnexpectedMessage)
	 568  		return unexpectedMessageError(shd, msg)
	 569  	}
	 570  	hs.finishedHash.Write(shd.marshal())
	 571  
	 572  	// If the server requested a certificate then we have to send a
	 573  	// Certificate message, even if it's empty because we don't have a
	 574  	// certificate to send.
	 575  	if certRequested {
	 576  		certMsg = new(certificateMsg)
	 577  		certMsg.certificates = chainToSend.Certificate
	 578  		hs.finishedHash.Write(certMsg.marshal())
	 579  		if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
	 580  			return err
	 581  		}
	 582  	}
	 583  
	 584  	preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
	 585  	if err != nil {
	 586  		c.sendAlert(alertInternalError)
	 587  		return err
	 588  	}
	 589  	if ckx != nil {
	 590  		hs.finishedHash.Write(ckx.marshal())
	 591  		if _, err := c.writeRecord(recordTypeHandshake, ckx.marshal()); err != nil {
	 592  			return err
	 593  		}
	 594  	}
	 595  
	 596  	if chainToSend != nil && len(chainToSend.Certificate) > 0 {
	 597  		certVerify := &certificateVerifyMsg{}
	 598  
	 599  		key, ok := chainToSend.PrivateKey.(crypto.Signer)
	 600  		if !ok {
	 601  			c.sendAlert(alertInternalError)
	 602  			return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
	 603  		}
	 604  
	 605  		var sigType uint8
	 606  		var sigHash crypto.Hash
	 607  		if c.vers >= VersionTLS12 {
	 608  			signatureAlgorithm, err := selectSignatureScheme(c.vers, chainToSend, certReq.supportedSignatureAlgorithms)
	 609  			if err != nil {
	 610  				c.sendAlert(alertIllegalParameter)
	 611  				return err
	 612  			}
	 613  			sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm)
	 614  			if err != nil {
	 615  				return c.sendAlert(alertInternalError)
	 616  			}
	 617  			certVerify.hasSignatureAlgorithm = true
	 618  			certVerify.signatureAlgorithm = signatureAlgorithm
	 619  		} else {
	 620  			sigType, sigHash, err = legacyTypeAndHashFromPublicKey(key.Public())
	 621  			if err != nil {
	 622  				c.sendAlert(alertIllegalParameter)
	 623  				return err
	 624  			}
	 625  		}
	 626  
	 627  		signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash, hs.masterSecret)
	 628  		signOpts := crypto.SignerOpts(sigHash)
	 629  		if sigType == signatureRSAPSS {
	 630  			signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
	 631  		}
	 632  		certVerify.signature, err = key.Sign(c.config.rand(), signed, signOpts)
	 633  		if err != nil {
	 634  			c.sendAlert(alertInternalError)
	 635  			return err
	 636  		}
	 637  
	 638  		hs.finishedHash.Write(certVerify.marshal())
	 639  		if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil {
	 640  			return err
	 641  		}
	 642  	}
	 643  
	 644  	hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
	 645  	if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.hello.random, hs.masterSecret); err != nil {
	 646  		c.sendAlert(alertInternalError)
	 647  		return errors.New("tls: failed to write to key log: " + err.Error())
	 648  	}
	 649  
	 650  	hs.finishedHash.discardHandshakeBuffer()
	 651  
	 652  	return nil
	 653  }
	 654  
	 655  func (hs *clientHandshakeState) establishKeys() error {
	 656  	c := hs.c
	 657  
	 658  	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
	 659  		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
	 660  	var clientCipher, serverCipher interface{}
	 661  	var clientHash, serverHash hash.Hash
	 662  	if hs.suite.cipher != nil {
	 663  		clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
	 664  		clientHash = hs.suite.mac(clientMAC)
	 665  		serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
	 666  		serverHash = hs.suite.mac(serverMAC)
	 667  	} else {
	 668  		clientCipher = hs.suite.aead(clientKey, clientIV)
	 669  		serverCipher = hs.suite.aead(serverKey, serverIV)
	 670  	}
	 671  
	 672  	c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
	 673  	c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
	 674  	return nil
	 675  }
	 676  
	 677  func (hs *clientHandshakeState) serverResumedSession() bool {
	 678  	// If the server responded with the same sessionId then it means the
	 679  	// sessionTicket is being used to resume a TLS session.
	 680  	return hs.session != nil && hs.hello.sessionId != nil &&
	 681  		bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
	 682  }
	 683  
	 684  func (hs *clientHandshakeState) processServerHello() (bool, error) {
	 685  	c := hs.c
	 686  
	 687  	if err := hs.pickCipherSuite(); err != nil {
	 688  		return false, err
	 689  	}
	 690  
	 691  	if hs.serverHello.compressionMethod != compressionNone {
	 692  		c.sendAlert(alertUnexpectedMessage)
	 693  		return false, errors.New("tls: server selected unsupported compression format")
	 694  	}
	 695  
	 696  	if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
	 697  		c.secureRenegotiation = true
	 698  		if len(hs.serverHello.secureRenegotiation) != 0 {
	 699  			c.sendAlert(alertHandshakeFailure)
	 700  			return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
	 701  		}
	 702  	}
	 703  
	 704  	if c.handshakes > 0 && c.secureRenegotiation {
	 705  		var expectedSecureRenegotiation [24]byte
	 706  		copy(expectedSecureRenegotiation[:], c.clientFinished[:])
	 707  		copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
	 708  		if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
	 709  			c.sendAlert(alertHandshakeFailure)
	 710  			return false, errors.New("tls: incorrect renegotiation extension contents")
	 711  		}
	 712  	}
	 713  
	 714  	if err := checkALPN(hs.hello.alpnProtocols, hs.serverHello.alpnProtocol); err != nil {
	 715  		c.sendAlert(alertUnsupportedExtension)
	 716  		return false, err
	 717  	}
	 718  	c.clientProtocol = hs.serverHello.alpnProtocol
	 719  
	 720  	c.scts = hs.serverHello.scts
	 721  
	 722  	if !hs.serverResumedSession() {
	 723  		return false, nil
	 724  	}
	 725  
	 726  	if hs.session.vers != c.vers {
	 727  		c.sendAlert(alertHandshakeFailure)
	 728  		return false, errors.New("tls: server resumed a session with a different version")
	 729  	}
	 730  
	 731  	if hs.session.cipherSuite != hs.suite.id {
	 732  		c.sendAlert(alertHandshakeFailure)
	 733  		return false, errors.New("tls: server resumed a session with a different cipher suite")
	 734  	}
	 735  
	 736  	// Restore masterSecret, peerCerts, and ocspResponse from previous state
	 737  	hs.masterSecret = hs.session.masterSecret
	 738  	c.peerCertificates = hs.session.serverCertificates
	 739  	c.verifiedChains = hs.session.verifiedChains
	 740  	c.ocspResponse = hs.session.ocspResponse
	 741  	// Let the ServerHello SCTs override the session SCTs from the original
	 742  	// connection, if any are provided
	 743  	if len(c.scts) == 0 && len(hs.session.scts) != 0 {
	 744  		c.scts = hs.session.scts
	 745  	}
	 746  
	 747  	return true, nil
	 748  }
	 749  
	 750  // checkALPN ensure that the server's choice of ALPN protocol is compatible with
	 751  // the protocols that we advertised in the Client Hello.
	 752  func checkALPN(clientProtos []string, serverProto string) error {
	 753  	if serverProto == "" {
	 754  		return nil
	 755  	}
	 756  	if len(clientProtos) == 0 {
	 757  		return errors.New("tls: server advertised unrequested ALPN extension")
	 758  	}
	 759  	for _, proto := range clientProtos {
	 760  		if proto == serverProto {
	 761  			return nil
	 762  		}
	 763  	}
	 764  	return errors.New("tls: server selected unadvertised ALPN protocol")
	 765  }
	 766  
	 767  func (hs *clientHandshakeState) readFinished(out []byte) error {
	 768  	c := hs.c
	 769  
	 770  	if err := c.readChangeCipherSpec(); err != nil {
	 771  		return err
	 772  	}
	 773  
	 774  	msg, err := c.readHandshake()
	 775  	if err != nil {
	 776  		return err
	 777  	}
	 778  	serverFinished, ok := msg.(*finishedMsg)
	 779  	if !ok {
	 780  		c.sendAlert(alertUnexpectedMessage)
	 781  		return unexpectedMessageError(serverFinished, msg)
	 782  	}
	 783  
	 784  	verify := hs.finishedHash.serverSum(hs.masterSecret)
	 785  	if len(verify) != len(serverFinished.verifyData) ||
	 786  		subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
	 787  		c.sendAlert(alertHandshakeFailure)
	 788  		return errors.New("tls: server's Finished message was incorrect")
	 789  	}
	 790  	hs.finishedHash.Write(serverFinished.marshal())
	 791  	copy(out, verify)
	 792  	return nil
	 793  }
	 794  
	 795  func (hs *clientHandshakeState) readSessionTicket() error {
	 796  	if !hs.serverHello.ticketSupported {
	 797  		return nil
	 798  	}
	 799  
	 800  	c := hs.c
	 801  	msg, err := c.readHandshake()
	 802  	if err != nil {
	 803  		return err
	 804  	}
	 805  	sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
	 806  	if !ok {
	 807  		c.sendAlert(alertUnexpectedMessage)
	 808  		return unexpectedMessageError(sessionTicketMsg, msg)
	 809  	}
	 810  	hs.finishedHash.Write(sessionTicketMsg.marshal())
	 811  
	 812  	hs.session = &ClientSessionState{
	 813  		sessionTicket:			sessionTicketMsg.ticket,
	 814  		vers:							 c.vers,
	 815  		cipherSuite:				hs.suite.id,
	 816  		masterSecret:			 hs.masterSecret,
	 817  		serverCertificates: c.peerCertificates,
	 818  		verifiedChains:		 c.verifiedChains,
	 819  		receivedAt:				 c.config.time(),
	 820  		ocspResponse:			 c.ocspResponse,
	 821  		scts:							 c.scts,
	 822  	}
	 823  
	 824  	return nil
	 825  }
	 826  
	 827  func (hs *clientHandshakeState) sendFinished(out []byte) error {
	 828  	c := hs.c
	 829  
	 830  	if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
	 831  		return err
	 832  	}
	 833  
	 834  	finished := new(finishedMsg)
	 835  	finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
	 836  	hs.finishedHash.Write(finished.marshal())
	 837  	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
	 838  		return err
	 839  	}
	 840  	copy(out, finished.verifyData)
	 841  	return nil
	 842  }
	 843  
	 844  // verifyServerCertificate parses and verifies the provided chain, setting
	 845  // c.verifiedChains and c.peerCertificates or sending the appropriate alert.
	 846  func (c *Conn) verifyServerCertificate(certificates [][]byte) error {
	 847  	certs := make([]*x509.Certificate, len(certificates))
	 848  	for i, asn1Data := range certificates {
	 849  		cert, err := x509.ParseCertificate(asn1Data)
	 850  		if err != nil {
	 851  			c.sendAlert(alertBadCertificate)
	 852  			return errors.New("tls: failed to parse certificate from server: " + err.Error())
	 853  		}
	 854  		certs[i] = cert
	 855  	}
	 856  
	 857  	if !c.config.InsecureSkipVerify {
	 858  		opts := x509.VerifyOptions{
	 859  			Roots:				 c.config.RootCAs,
	 860  			CurrentTime:	 c.config.time(),
	 861  			DNSName:			 c.config.ServerName,
	 862  			Intermediates: x509.NewCertPool(),
	 863  		}
	 864  		for _, cert := range certs[1:] {
	 865  			opts.Intermediates.AddCert(cert)
	 866  		}
	 867  		var err error
	 868  		c.verifiedChains, err = certs[0].Verify(opts)
	 869  		if err != nil {
	 870  			c.sendAlert(alertBadCertificate)
	 871  			return err
	 872  		}
	 873  	}
	 874  
	 875  	switch certs[0].PublicKey.(type) {
	 876  	case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey:
	 877  		break
	 878  	default:
	 879  		c.sendAlert(alertUnsupportedCertificate)
	 880  		return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
	 881  	}
	 882  
	 883  	c.peerCertificates = certs
	 884  
	 885  	if c.config.VerifyPeerCertificate != nil {
	 886  		if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
	 887  			c.sendAlert(alertBadCertificate)
	 888  			return err
	 889  		}
	 890  	}
	 891  
	 892  	if c.config.VerifyConnection != nil {
	 893  		if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
	 894  			c.sendAlert(alertBadCertificate)
	 895  			return err
	 896  		}
	 897  	}
	 898  
	 899  	return nil
	 900  }
	 901  
	 902  // certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS
	 903  // <= 1.2 CertificateRequest, making an effort to fill in missing information.
	 904  func certificateRequestInfoFromMsg(ctx context.Context, vers uint16, certReq *certificateRequestMsg) *CertificateRequestInfo {
	 905  	cri := &CertificateRequestInfo{
	 906  		AcceptableCAs: certReq.certificateAuthorities,
	 907  		Version:			 vers,
	 908  		ctx:					 ctx,
	 909  	}
	 910  
	 911  	var rsaAvail, ecAvail bool
	 912  	for _, certType := range certReq.certificateTypes {
	 913  		switch certType {
	 914  		case certTypeRSASign:
	 915  			rsaAvail = true
	 916  		case certTypeECDSASign:
	 917  			ecAvail = true
	 918  		}
	 919  	}
	 920  
	 921  	if !certReq.hasSignatureAlgorithm {
	 922  		// Prior to TLS 1.2, signature schemes did not exist. In this case we
	 923  		// make up a list based on the acceptable certificate types, to help
	 924  		// GetClientCertificate and SupportsCertificate select the right certificate.
	 925  		// The hash part of the SignatureScheme is a lie here, because
	 926  		// TLS 1.0 and 1.1 always use MD5+SHA1 for RSA and SHA1 for ECDSA.
	 927  		switch {
	 928  		case rsaAvail && ecAvail:
	 929  			cri.SignatureSchemes = []SignatureScheme{
	 930  				ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
	 931  				PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
	 932  			}
	 933  		case rsaAvail:
	 934  			cri.SignatureSchemes = []SignatureScheme{
	 935  				PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1,
	 936  			}
	 937  		case ecAvail:
	 938  			cri.SignatureSchemes = []SignatureScheme{
	 939  				ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512,
	 940  			}
	 941  		}
	 942  		return cri
	 943  	}
	 944  
	 945  	// Filter the signature schemes based on the certificate types.
	 946  	// See RFC 5246, Section 7.4.4 (where it calls this "somewhat complicated").
	 947  	cri.SignatureSchemes = make([]SignatureScheme, 0, len(certReq.supportedSignatureAlgorithms))
	 948  	for _, sigScheme := range certReq.supportedSignatureAlgorithms {
	 949  		sigType, _, err := typeAndHashFromSignatureScheme(sigScheme)
	 950  		if err != nil {
	 951  			continue
	 952  		}
	 953  		switch sigType {
	 954  		case signatureECDSA, signatureEd25519:
	 955  			if ecAvail {
	 956  				cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
	 957  			}
	 958  		case signatureRSAPSS, signaturePKCS1v15:
	 959  			if rsaAvail {
	 960  				cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
	 961  			}
	 962  		}
	 963  	}
	 964  
	 965  	return cri
	 966  }
	 967  
	 968  func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error) {
	 969  	if c.config.GetClientCertificate != nil {
	 970  		return c.config.GetClientCertificate(cri)
	 971  	}
	 972  
	 973  	for _, chain := range c.config.Certificates {
	 974  		if err := cri.SupportsCertificate(&chain); err != nil {
	 975  			continue
	 976  		}
	 977  		return &chain, nil
	 978  	}
	 979  
	 980  	// No acceptable certificate found. Don't send a certificate.
	 981  	return new(Certificate), nil
	 982  }
	 983  
	 984  // clientSessionCacheKey returns a key used to cache sessionTickets that could
	 985  // be used to resume previously negotiated TLS sessions with a server.
	 986  func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
	 987  	if len(config.ServerName) > 0 {
	 988  		return config.ServerName
	 989  	}
	 990  	return serverAddr.String()
	 991  }
	 992  
	 993  // hostnameInSNI converts name into an appropriate hostname for SNI.
	 994  // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
	 995  // See RFC 6066, Section 3.
	 996  func hostnameInSNI(name string) string {
	 997  	host := name
	 998  	if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
	 999  		host = host[1 : len(host)-1]
	1000  	}
	1001  	if i := strings.LastIndex(host, "%"); i > 0 {
	1002  		host = host[:i]
	1003  	}
	1004  	if net.ParseIP(host) != nil {
	1005  		return ""
	1006  	}
	1007  	for len(name) > 0 && name[len(name)-1] == '.' {
	1008  		name = name[:len(name)-1]
	1009  	}
	1010  	return name
	1011  }
	1012  

View as plain text