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