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