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