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