Home | History | Annotate | Download | only in 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 	"crypto"
     10 	"crypto/ecdsa"
     11 	"crypto/rsa"
     12 	"crypto/subtle"
     13 	"crypto/x509"
     14 	"errors"
     15 	"fmt"
     16 	"io"
     17 	"net"
     18 	"strconv"
     19 	"strings"
     20 )
     21 
     22 type clientHandshakeState struct {
     23 	c            *Conn
     24 	serverHello  *serverHelloMsg
     25 	hello        *clientHelloMsg
     26 	suite        *cipherSuite
     27 	finishedHash finishedHash
     28 	masterSecret []byte
     29 	session      *ClientSessionState
     30 }
     31 
     32 // c.out.Mutex <= L; c.handshakeMutex <= L.
     33 func (c *Conn) clientHandshake() error {
     34 	if c.config == nil {
     35 		c.config = defaultConfig()
     36 	}
     37 
     38 	// This may be a renegotiation handshake, in which case some fields
     39 	// need to be reset.
     40 	c.didResume = false
     41 
     42 	if len(c.config.ServerName) == 0 && !c.config.InsecureSkipVerify {
     43 		return errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
     44 	}
     45 
     46 	nextProtosLength := 0
     47 	for _, proto := range c.config.NextProtos {
     48 		if l := len(proto); l == 0 || l > 255 {
     49 			return errors.New("tls: invalid NextProtos value")
     50 		} else {
     51 			nextProtosLength += 1 + l
     52 		}
     53 	}
     54 	if nextProtosLength > 0xffff {
     55 		return errors.New("tls: NextProtos values too large")
     56 	}
     57 
     58 	hello := &clientHelloMsg{
     59 		vers:                         c.config.maxVersion(),
     60 		compressionMethods:           []uint8{compressionNone},
     61 		random:                       make([]byte, 32),
     62 		ocspStapling:                 true,
     63 		scts:                         true,
     64 		serverName:                   hostnameInSNI(c.config.ServerName),
     65 		supportedCurves:              c.config.curvePreferences(),
     66 		supportedPoints:              []uint8{pointFormatUncompressed},
     67 		nextProtoNeg:                 len(c.config.NextProtos) > 0,
     68 		secureRenegotiationSupported: true,
     69 		alpnProtocols:                c.config.NextProtos,
     70 	}
     71 
     72 	if c.handshakes > 0 {
     73 		hello.secureRenegotiation = c.clientFinished[:]
     74 	}
     75 
     76 	possibleCipherSuites := c.config.cipherSuites()
     77 	hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
     78 
     79 NextCipherSuite:
     80 	for _, suiteId := range possibleCipherSuites {
     81 		for _, suite := range cipherSuites {
     82 			if suite.id != suiteId {
     83 				continue
     84 			}
     85 			// Don't advertise TLS 1.2-only cipher suites unless
     86 			// we're attempting TLS 1.2.
     87 			if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
     88 				continue
     89 			}
     90 			hello.cipherSuites = append(hello.cipherSuites, suiteId)
     91 			continue NextCipherSuite
     92 		}
     93 	}
     94 
     95 	_, err := io.ReadFull(c.config.rand(), hello.random)
     96 	if err != nil {
     97 		c.sendAlert(alertInternalError)
     98 		return errors.New("tls: short read from Rand: " + err.Error())
     99 	}
    100 
    101 	if hello.vers >= VersionTLS12 {
    102 		hello.signatureAndHashes = supportedSignatureAlgorithms
    103 	}
    104 
    105 	var session *ClientSessionState
    106 	var cacheKey string
    107 	sessionCache := c.config.ClientSessionCache
    108 	if c.config.SessionTicketsDisabled {
    109 		sessionCache = nil
    110 	}
    111 
    112 	if sessionCache != nil {
    113 		hello.ticketSupported = true
    114 	}
    115 
    116 	// Session resumption is not allowed if renegotiating because
    117 	// renegotiation is primarily used to allow a client to send a client
    118 	// certificate, which would be skipped if session resumption occurred.
    119 	if sessionCache != nil && c.handshakes == 0 {
    120 		// Try to resume a previously negotiated TLS session, if
    121 		// available.
    122 		cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
    123 		candidateSession, ok := sessionCache.Get(cacheKey)
    124 		if ok {
    125 			// Check that the ciphersuite/version used for the
    126 			// previous session are still valid.
    127 			cipherSuiteOk := false
    128 			for _, id := range hello.cipherSuites {
    129 				if id == candidateSession.cipherSuite {
    130 					cipherSuiteOk = true
    131 					break
    132 				}
    133 			}
    134 
    135 			versOk := candidateSession.vers >= c.config.minVersion() &&
    136 				candidateSession.vers <= c.config.maxVersion()
    137 			if versOk && cipherSuiteOk {
    138 				session = candidateSession
    139 			}
    140 		}
    141 	}
    142 
    143 	if session != nil {
    144 		hello.sessionTicket = session.sessionTicket
    145 		// A random session ID is used to detect when the
    146 		// server accepted the ticket and is resuming a session
    147 		// (see RFC 5077).
    148 		hello.sessionId = make([]byte, 16)
    149 		if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
    150 			c.sendAlert(alertInternalError)
    151 			return errors.New("tls: short read from Rand: " + err.Error())
    152 		}
    153 	}
    154 
    155 	if _, err := c.writeRecord(recordTypeHandshake, hello.marshal()); err != nil {
    156 		return err
    157 	}
    158 
    159 	msg, err := c.readHandshake()
    160 	if err != nil {
    161 		return err
    162 	}
    163 	serverHello, ok := msg.(*serverHelloMsg)
    164 	if !ok {
    165 		c.sendAlert(alertUnexpectedMessage)
    166 		return unexpectedMessageError(serverHello, msg)
    167 	}
    168 
    169 	vers, ok := c.config.mutualVersion(serverHello.vers)
    170 	if !ok || vers < VersionTLS10 {
    171 		// TLS 1.0 is the minimum version supported as a client.
    172 		c.sendAlert(alertProtocolVersion)
    173 		return fmt.Errorf("tls: server selected unsupported protocol version %x", serverHello.vers)
    174 	}
    175 	c.vers = vers
    176 	c.haveVers = true
    177 
    178 	suite := mutualCipherSuite(hello.cipherSuites, serverHello.cipherSuite)
    179 	if suite == nil {
    180 		c.sendAlert(alertHandshakeFailure)
    181 		return errors.New("tls: server chose an unconfigured cipher suite")
    182 	}
    183 
    184 	hs := &clientHandshakeState{
    185 		c:            c,
    186 		serverHello:  serverHello,
    187 		hello:        hello,
    188 		suite:        suite,
    189 		finishedHash: newFinishedHash(c.vers, suite),
    190 		session:      session,
    191 	}
    192 
    193 	isResume, err := hs.processServerHello()
    194 	if err != nil {
    195 		return err
    196 	}
    197 
    198 	// No signatures of the handshake are needed in a resumption.
    199 	// Otherwise, in a full handshake, if we don't have any certificates
    200 	// configured then we will never send a CertificateVerify message and
    201 	// thus no signatures are needed in that case either.
    202 	if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
    203 		hs.finishedHash.discardHandshakeBuffer()
    204 	}
    205 
    206 	hs.finishedHash.Write(hs.hello.marshal())
    207 	hs.finishedHash.Write(hs.serverHello.marshal())
    208 
    209 	c.buffering = true
    210 	if isResume {
    211 		if err := hs.establishKeys(); err != nil {
    212 			return err
    213 		}
    214 		if err := hs.readSessionTicket(); err != nil {
    215 			return err
    216 		}
    217 		if err := hs.readFinished(c.serverFinished[:]); err != nil {
    218 			return err
    219 		}
    220 		c.clientFinishedIsFirst = false
    221 		if err := hs.sendFinished(c.clientFinished[:]); err != nil {
    222 			return err
    223 		}
    224 		if _, err := c.flush(); err != nil {
    225 			return err
    226 		}
    227 	} else {
    228 		if err := hs.doFullHandshake(); err != nil {
    229 			return err
    230 		}
    231 		if err := hs.establishKeys(); err != nil {
    232 			return err
    233 		}
    234 		if err := hs.sendFinished(c.clientFinished[:]); err != nil {
    235 			return err
    236 		}
    237 		if _, err := c.flush(); err != nil {
    238 			return err
    239 		}
    240 		c.clientFinishedIsFirst = true
    241 		if err := hs.readSessionTicket(); err != nil {
    242 			return err
    243 		}
    244 		if err := hs.readFinished(c.serverFinished[:]); err != nil {
    245 			return err
    246 		}
    247 	}
    248 
    249 	if sessionCache != nil && hs.session != nil && session != hs.session {
    250 		sessionCache.Put(cacheKey, hs.session)
    251 	}
    252 
    253 	c.didResume = isResume
    254 	c.handshakeComplete = true
    255 	c.cipherSuite = suite.id
    256 	return nil
    257 }
    258 
    259 func (hs *clientHandshakeState) doFullHandshake() error {
    260 	c := hs.c
    261 
    262 	msg, err := c.readHandshake()
    263 	if err != nil {
    264 		return err
    265 	}
    266 	certMsg, ok := msg.(*certificateMsg)
    267 	if !ok || len(certMsg.certificates) == 0 {
    268 		c.sendAlert(alertUnexpectedMessage)
    269 		return unexpectedMessageError(certMsg, msg)
    270 	}
    271 	hs.finishedHash.Write(certMsg.marshal())
    272 
    273 	if c.handshakes == 0 {
    274 		// If this is the first handshake on a connection, process and
    275 		// (optionally) verify the server's certificates.
    276 		certs := make([]*x509.Certificate, len(certMsg.certificates))
    277 		for i, asn1Data := range certMsg.certificates {
    278 			cert, err := x509.ParseCertificate(asn1Data)
    279 			if err != nil {
    280 				c.sendAlert(alertBadCertificate)
    281 				return errors.New("tls: failed to parse certificate from server: " + err.Error())
    282 			}
    283 			certs[i] = cert
    284 		}
    285 
    286 		if !c.config.InsecureSkipVerify {
    287 			opts := x509.VerifyOptions{
    288 				Roots:         c.config.RootCAs,
    289 				CurrentTime:   c.config.time(),
    290 				DNSName:       c.config.ServerName,
    291 				Intermediates: x509.NewCertPool(),
    292 			}
    293 
    294 			for i, cert := range certs {
    295 				if i == 0 {
    296 					continue
    297 				}
    298 				opts.Intermediates.AddCert(cert)
    299 			}
    300 			c.verifiedChains, err = certs[0].Verify(opts)
    301 			if err != nil {
    302 				c.sendAlert(alertBadCertificate)
    303 				return err
    304 			}
    305 		}
    306 
    307 		if c.config.VerifyPeerCertificate != nil {
    308 			if err := c.config.VerifyPeerCertificate(certMsg.certificates, c.verifiedChains); err != nil {
    309 				c.sendAlert(alertBadCertificate)
    310 				return err
    311 			}
    312 		}
    313 
    314 		switch certs[0].PublicKey.(type) {
    315 		case *rsa.PublicKey, *ecdsa.PublicKey:
    316 			break
    317 		default:
    318 			c.sendAlert(alertUnsupportedCertificate)
    319 			return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
    320 		}
    321 
    322 		c.peerCertificates = certs
    323 	} else {
    324 		// This is a renegotiation handshake. We require that the
    325 		// server's identity (i.e. leaf certificate) is unchanged and
    326 		// thus any previous trust decision is still valid.
    327 		//
    328 		// See https://mitls.org/pages/attacks/3SHAKE for the
    329 		// motivation behind this requirement.
    330 		if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
    331 			c.sendAlert(alertBadCertificate)
    332 			return errors.New("tls: server's identity changed during renegotiation")
    333 		}
    334 	}
    335 
    336 	if hs.serverHello.ocspStapling {
    337 		msg, err = c.readHandshake()
    338 		if err != nil {
    339 			return err
    340 		}
    341 		cs, ok := msg.(*certificateStatusMsg)
    342 		if !ok {
    343 			c.sendAlert(alertUnexpectedMessage)
    344 			return unexpectedMessageError(cs, msg)
    345 		}
    346 		hs.finishedHash.Write(cs.marshal())
    347 
    348 		if cs.statusType == statusTypeOCSP {
    349 			c.ocspResponse = cs.response
    350 		}
    351 	}
    352 
    353 	msg, err = c.readHandshake()
    354 	if err != nil {
    355 		return err
    356 	}
    357 
    358 	keyAgreement := hs.suite.ka(c.vers)
    359 
    360 	skx, ok := msg.(*serverKeyExchangeMsg)
    361 	if ok {
    362 		hs.finishedHash.Write(skx.marshal())
    363 		err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
    364 		if err != nil {
    365 			c.sendAlert(alertUnexpectedMessage)
    366 			return err
    367 		}
    368 
    369 		msg, err = c.readHandshake()
    370 		if err != nil {
    371 			return err
    372 		}
    373 	}
    374 
    375 	var chainToSend *Certificate
    376 	var certRequested bool
    377 	certReq, ok := msg.(*certificateRequestMsg)
    378 	if ok {
    379 		certRequested = true
    380 		hs.finishedHash.Write(certReq.marshal())
    381 
    382 		if chainToSend, err = hs.getCertificate(certReq); err != nil {
    383 			c.sendAlert(alertInternalError)
    384 			return err
    385 		}
    386 
    387 		msg, err = c.readHandshake()
    388 		if err != nil {
    389 			return err
    390 		}
    391 	}
    392 
    393 	shd, ok := msg.(*serverHelloDoneMsg)
    394 	if !ok {
    395 		c.sendAlert(alertUnexpectedMessage)
    396 		return unexpectedMessageError(shd, msg)
    397 	}
    398 	hs.finishedHash.Write(shd.marshal())
    399 
    400 	// If the server requested a certificate then we have to send a
    401 	// Certificate message, even if it's empty because we don't have a
    402 	// certificate to send.
    403 	if certRequested {
    404 		certMsg = new(certificateMsg)
    405 		certMsg.certificates = chainToSend.Certificate
    406 		hs.finishedHash.Write(certMsg.marshal())
    407 		if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
    408 			return err
    409 		}
    410 	}
    411 
    412 	preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
    413 	if err != nil {
    414 		c.sendAlert(alertInternalError)
    415 		return err
    416 	}
    417 	if ckx != nil {
    418 		hs.finishedHash.Write(ckx.marshal())
    419 		if _, err := c.writeRecord(recordTypeHandshake, ckx.marshal()); err != nil {
    420 			return err
    421 		}
    422 	}
    423 
    424 	if chainToSend != nil && len(chainToSend.Certificate) > 0 {
    425 		certVerify := &certificateVerifyMsg{
    426 			hasSignatureAndHash: c.vers >= VersionTLS12,
    427 		}
    428 
    429 		key, ok := chainToSend.PrivateKey.(crypto.Signer)
    430 		if !ok {
    431 			c.sendAlert(alertInternalError)
    432 			return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
    433 		}
    434 
    435 		var signatureType uint8
    436 		switch key.Public().(type) {
    437 		case *ecdsa.PublicKey:
    438 			signatureType = signatureECDSA
    439 		case *rsa.PublicKey:
    440 			signatureType = signatureRSA
    441 		default:
    442 			c.sendAlert(alertInternalError)
    443 			return fmt.Errorf("tls: failed to sign handshake with client certificate: unknown client certificate key type: %T", key)
    444 		}
    445 
    446 		certVerify.signatureAndHash, err = hs.finishedHash.selectClientCertSignatureAlgorithm(certReq.signatureAndHashes, signatureType)
    447 		if err != nil {
    448 			c.sendAlert(alertInternalError)
    449 			return err
    450 		}
    451 		digest, hashFunc, err := hs.finishedHash.hashForClientCertificate(certVerify.signatureAndHash, hs.masterSecret)
    452 		if err != nil {
    453 			c.sendAlert(alertInternalError)
    454 			return err
    455 		}
    456 		certVerify.signature, err = key.Sign(c.config.rand(), digest, hashFunc)
    457 		if err != nil {
    458 			c.sendAlert(alertInternalError)
    459 			return err
    460 		}
    461 
    462 		hs.finishedHash.Write(certVerify.marshal())
    463 		if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil {
    464 			return err
    465 		}
    466 	}
    467 
    468 	hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
    469 	if err := c.config.writeKeyLog(hs.hello.random, hs.masterSecret); err != nil {
    470 		c.sendAlert(alertInternalError)
    471 		return errors.New("tls: failed to write to key log: " + err.Error())
    472 	}
    473 
    474 	hs.finishedHash.discardHandshakeBuffer()
    475 
    476 	return nil
    477 }
    478 
    479 func (hs *clientHandshakeState) establishKeys() error {
    480 	c := hs.c
    481 
    482 	clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
    483 		keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
    484 	var clientCipher, serverCipher interface{}
    485 	var clientHash, serverHash macFunction
    486 	if hs.suite.cipher != nil {
    487 		clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
    488 		clientHash = hs.suite.mac(c.vers, clientMAC)
    489 		serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
    490 		serverHash = hs.suite.mac(c.vers, serverMAC)
    491 	} else {
    492 		clientCipher = hs.suite.aead(clientKey, clientIV)
    493 		serverCipher = hs.suite.aead(serverKey, serverIV)
    494 	}
    495 
    496 	c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
    497 	c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
    498 	return nil
    499 }
    500 
    501 func (hs *clientHandshakeState) serverResumedSession() bool {
    502 	// If the server responded with the same sessionId then it means the
    503 	// sessionTicket is being used to resume a TLS session.
    504 	return hs.session != nil && hs.hello.sessionId != nil &&
    505 		bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
    506 }
    507 
    508 func (hs *clientHandshakeState) processServerHello() (bool, error) {
    509 	c := hs.c
    510 
    511 	if hs.serverHello.compressionMethod != compressionNone {
    512 		c.sendAlert(alertUnexpectedMessage)
    513 		return false, errors.New("tls: server selected unsupported compression format")
    514 	}
    515 
    516 	if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
    517 		c.secureRenegotiation = true
    518 		if len(hs.serverHello.secureRenegotiation) != 0 {
    519 			c.sendAlert(alertHandshakeFailure)
    520 			return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
    521 		}
    522 	}
    523 
    524 	if c.handshakes > 0 && c.secureRenegotiation {
    525 		var expectedSecureRenegotiation [24]byte
    526 		copy(expectedSecureRenegotiation[:], c.clientFinished[:])
    527 		copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
    528 		if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
    529 			c.sendAlert(alertHandshakeFailure)
    530 			return false, errors.New("tls: incorrect renegotiation extension contents")
    531 		}
    532 	}
    533 
    534 	clientDidNPN := hs.hello.nextProtoNeg
    535 	clientDidALPN := len(hs.hello.alpnProtocols) > 0
    536 	serverHasNPN := hs.serverHello.nextProtoNeg
    537 	serverHasALPN := len(hs.serverHello.alpnProtocol) > 0
    538 
    539 	if !clientDidNPN && serverHasNPN {
    540 		c.sendAlert(alertHandshakeFailure)
    541 		return false, errors.New("tls: server advertised unrequested NPN extension")
    542 	}
    543 
    544 	if !clientDidALPN && serverHasALPN {
    545 		c.sendAlert(alertHandshakeFailure)
    546 		return false, errors.New("tls: server advertised unrequested ALPN extension")
    547 	}
    548 
    549 	if serverHasNPN && serverHasALPN {
    550 		c.sendAlert(alertHandshakeFailure)
    551 		return false, errors.New("tls: server advertised both NPN and ALPN extensions")
    552 	}
    553 
    554 	if serverHasALPN {
    555 		c.clientProtocol = hs.serverHello.alpnProtocol
    556 		c.clientProtocolFallback = false
    557 	}
    558 	c.scts = hs.serverHello.scts
    559 
    560 	if !hs.serverResumedSession() {
    561 		return false, nil
    562 	}
    563 
    564 	if hs.session.vers != c.vers {
    565 		c.sendAlert(alertHandshakeFailure)
    566 		return false, errors.New("tls: server resumed a session with a different version")
    567 	}
    568 
    569 	if hs.session.cipherSuite != hs.suite.id {
    570 		c.sendAlert(alertHandshakeFailure)
    571 		return false, errors.New("tls: server resumed a session with a different cipher suite")
    572 	}
    573 
    574 	// Restore masterSecret and peerCerts from previous state
    575 	hs.masterSecret = hs.session.masterSecret
    576 	c.peerCertificates = hs.session.serverCertificates
    577 	c.verifiedChains = hs.session.verifiedChains
    578 	return true, nil
    579 }
    580 
    581 func (hs *clientHandshakeState) readFinished(out []byte) error {
    582 	c := hs.c
    583 
    584 	c.readRecord(recordTypeChangeCipherSpec)
    585 	if c.in.err != nil {
    586 		return c.in.err
    587 	}
    588 
    589 	msg, err := c.readHandshake()
    590 	if err != nil {
    591 		return err
    592 	}
    593 	serverFinished, ok := msg.(*finishedMsg)
    594 	if !ok {
    595 		c.sendAlert(alertUnexpectedMessage)
    596 		return unexpectedMessageError(serverFinished, msg)
    597 	}
    598 
    599 	verify := hs.finishedHash.serverSum(hs.masterSecret)
    600 	if len(verify) != len(serverFinished.verifyData) ||
    601 		subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
    602 		c.sendAlert(alertHandshakeFailure)
    603 		return errors.New("tls: server's Finished message was incorrect")
    604 	}
    605 	hs.finishedHash.Write(serverFinished.marshal())
    606 	copy(out, verify)
    607 	return nil
    608 }
    609 
    610 func (hs *clientHandshakeState) readSessionTicket() error {
    611 	if !hs.serverHello.ticketSupported {
    612 		return nil
    613 	}
    614 
    615 	c := hs.c
    616 	msg, err := c.readHandshake()
    617 	if err != nil {
    618 		return err
    619 	}
    620 	sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
    621 	if !ok {
    622 		c.sendAlert(alertUnexpectedMessage)
    623 		return unexpectedMessageError(sessionTicketMsg, msg)
    624 	}
    625 	hs.finishedHash.Write(sessionTicketMsg.marshal())
    626 
    627 	hs.session = &ClientSessionState{
    628 		sessionTicket:      sessionTicketMsg.ticket,
    629 		vers:               c.vers,
    630 		cipherSuite:        hs.suite.id,
    631 		masterSecret:       hs.masterSecret,
    632 		serverCertificates: c.peerCertificates,
    633 		verifiedChains:     c.verifiedChains,
    634 	}
    635 
    636 	return nil
    637 }
    638 
    639 func (hs *clientHandshakeState) sendFinished(out []byte) error {
    640 	c := hs.c
    641 
    642 	if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
    643 		return err
    644 	}
    645 	if hs.serverHello.nextProtoNeg {
    646 		nextProto := new(nextProtoMsg)
    647 		proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos)
    648 		nextProto.proto = proto
    649 		c.clientProtocol = proto
    650 		c.clientProtocolFallback = fallback
    651 
    652 		hs.finishedHash.Write(nextProto.marshal())
    653 		if _, err := c.writeRecord(recordTypeHandshake, nextProto.marshal()); err != nil {
    654 			return err
    655 		}
    656 	}
    657 
    658 	finished := new(finishedMsg)
    659 	finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
    660 	hs.finishedHash.Write(finished.marshal())
    661 	if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
    662 		return err
    663 	}
    664 	copy(out, finished.verifyData)
    665 	return nil
    666 }
    667 
    668 // tls11SignatureSchemes contains the signature schemes that we synthesise for
    669 // a TLS <= 1.1 connection, based on the supported certificate types.
    670 var tls11SignatureSchemes = []SignatureScheme{ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1}
    671 
    672 const (
    673 	// tls11SignatureSchemesNumECDSA is the number of initial elements of
    674 	// tls11SignatureSchemes that use ECDSA.
    675 	tls11SignatureSchemesNumECDSA = 3
    676 	// tls11SignatureSchemesNumRSA is the number of trailing elements of
    677 	// tls11SignatureSchemes that use RSA.
    678 	tls11SignatureSchemesNumRSA = 4
    679 )
    680 
    681 func (hs *clientHandshakeState) getCertificate(certReq *certificateRequestMsg) (*Certificate, error) {
    682 	c := hs.c
    683 
    684 	var rsaAvail, ecdsaAvail bool
    685 	for _, certType := range certReq.certificateTypes {
    686 		switch certType {
    687 		case certTypeRSASign:
    688 			rsaAvail = true
    689 		case certTypeECDSASign:
    690 			ecdsaAvail = true
    691 		}
    692 	}
    693 
    694 	if c.config.GetClientCertificate != nil {
    695 		var signatureSchemes []SignatureScheme
    696 
    697 		if !certReq.hasSignatureAndHash {
    698 			// Prior to TLS 1.2, the signature schemes were not
    699 			// included in the certificate request message. In this
    700 			// case we use a plausible list based on the acceptable
    701 			// certificate types.
    702 			signatureSchemes = tls11SignatureSchemes
    703 			if !ecdsaAvail {
    704 				signatureSchemes = signatureSchemes[tls11SignatureSchemesNumECDSA:]
    705 			}
    706 			if !rsaAvail {
    707 				signatureSchemes = signatureSchemes[:len(signatureSchemes)-tls11SignatureSchemesNumRSA]
    708 			}
    709 		} else {
    710 			signatureSchemes = make([]SignatureScheme, 0, len(certReq.signatureAndHashes))
    711 			for _, sah := range certReq.signatureAndHashes {
    712 				signatureSchemes = append(signatureSchemes, SignatureScheme(sah.hash)<<8+SignatureScheme(sah.signature))
    713 			}
    714 		}
    715 
    716 		return c.config.GetClientCertificate(&CertificateRequestInfo{
    717 			AcceptableCAs:    certReq.certificateAuthorities,
    718 			SignatureSchemes: signatureSchemes,
    719 		})
    720 	}
    721 
    722 	// RFC 4346 on the certificateAuthorities field: A list of the
    723 	// distinguished names of acceptable certificate authorities.
    724 	// These distinguished names may specify a desired
    725 	// distinguished name for a root CA or for a subordinate CA;
    726 	// thus, this message can be used to describe both known roots
    727 	// and a desired authorization space. If the
    728 	// certificate_authorities list is empty then the client MAY
    729 	// send any certificate of the appropriate
    730 	// ClientCertificateType, unless there is some external
    731 	// arrangement to the contrary.
    732 
    733 	// We need to search our list of client certs for one
    734 	// where SignatureAlgorithm is acceptable to the server and the
    735 	// Issuer is in certReq.certificateAuthorities
    736 findCert:
    737 	for i, chain := range c.config.Certificates {
    738 		if !rsaAvail && !ecdsaAvail {
    739 			continue
    740 		}
    741 
    742 		for j, cert := range chain.Certificate {
    743 			x509Cert := chain.Leaf
    744 			// parse the certificate if this isn't the leaf
    745 			// node, or if chain.Leaf was nil
    746 			if j != 0 || x509Cert == nil {
    747 				var err error
    748 				if x509Cert, err = x509.ParseCertificate(cert); err != nil {
    749 					c.sendAlert(alertInternalError)
    750 					return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
    751 				}
    752 			}
    753 
    754 			switch {
    755 			case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
    756 			case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
    757 			default:
    758 				continue findCert
    759 			}
    760 
    761 			if len(certReq.certificateAuthorities) == 0 {
    762 				// they gave us an empty list, so just take the
    763 				// first cert from c.config.Certificates
    764 				return &chain, nil
    765 			}
    766 
    767 			for _, ca := range certReq.certificateAuthorities {
    768 				if bytes.Equal(x509Cert.RawIssuer, ca) {
    769 					return &chain, nil
    770 				}
    771 			}
    772 		}
    773 	}
    774 
    775 	// No acceptable certificate found. Don't send a certificate.
    776 	return new(Certificate), nil
    777 }
    778 
    779 // clientSessionCacheKey returns a key used to cache sessionTickets that could
    780 // be used to resume previously negotiated TLS sessions with a server.
    781 func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
    782 	if len(config.ServerName) > 0 {
    783 		return config.ServerName
    784 	}
    785 	return serverAddr.String()
    786 }
    787 
    788 // mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
    789 // given list of possible protocols and a list of the preference order. The
    790 // first list must not be empty. It returns the resulting protocol and flag
    791 // indicating if the fallback case was reached.
    792 func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
    793 	for _, s := range preferenceProtos {
    794 		for _, c := range protos {
    795 			if s == c {
    796 				return s, false
    797 			}
    798 		}
    799 	}
    800 
    801 	return protos[0], true
    802 }
    803 
    804 // hostnameInSNI converts name into an approriate hostname for SNI.
    805 // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
    806 // See https://tools.ietf.org/html/rfc6066#section-3.
    807 func hostnameInSNI(name string) string {
    808 	host := name
    809 	if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
    810 		host = host[1 : len(host)-1]
    811 	}
    812 	if i := strings.LastIndex(host, "%"); i > 0 {
    813 		host = host[:i]
    814 	}
    815 	if net.ParseIP(host) != nil {
    816 		return ""
    817 	}
    818 	if len(name) > 0 && name[len(name)-1] == '.' {
    819 		name = name[:len(name)-1]
    820 	}
    821 	return name
    822 }
    823