blob: 8aca9ccf5b1419509b0c3005837ed4d85510a057 [file] [log] [blame]
Adam Langley95c29f32014-06-20 12:00:00 -07001// 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
5package main
6
7import (
8 "bytes"
9 "crypto/ecdsa"
David Benjamind30a9902014-08-24 01:44:23 -040010 "crypto/elliptic"
Adam Langley95c29f32014-06-20 12:00:00 -070011 "crypto/rsa"
12 "crypto/subtle"
13 "crypto/x509"
14 "encoding/asn1"
15 "errors"
16 "fmt"
17 "io"
David Benjaminde620d92014-07-18 15:03:41 -040018 "math/big"
Adam Langley95c29f32014-06-20 12:00:00 -070019 "net"
20 "strconv"
21)
22
23type clientHandshakeState struct {
David Benjamin83f90402015-01-27 01:09:43 -050024 c *Conn
25 serverHello *serverHelloMsg
26 hello *clientHelloMsg
27 suite *cipherSuite
28 finishedHash finishedHash
29 masterSecret []byte
30 session *ClientSessionState
31 finishedBytes []byte
Adam Langley95c29f32014-06-20 12:00:00 -070032}
33
34func (c *Conn) clientHandshake() error {
35 if c.config == nil {
36 c.config = defaultConfig()
37 }
38
39 if len(c.config.ServerName) == 0 && !c.config.InsecureSkipVerify {
40 return errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
41 }
42
David Benjamin83c0bc92014-08-04 01:23:53 -040043 c.sendHandshakeSeq = 0
44 c.recvHandshakeSeq = 0
45
David Benjaminfa055a22014-09-15 16:51:51 -040046 nextProtosLength := 0
47 for _, proto := range c.config.NextProtos {
48 if l := len(proto); l == 0 || l > 255 {
49 return errors.New("tls: invalid NextProtos value")
50 } else {
51 nextProtosLength += 1 + l
52 }
53 }
54 if nextProtosLength > 0xffff {
55 return errors.New("tls: NextProtos values too large")
56 }
57
Adam Langley95c29f32014-06-20 12:00:00 -070058 hello := &clientHelloMsg{
David Benjaminca6c8262014-11-15 19:06:08 -050059 isDTLS: c.isDTLS,
60 vers: c.config.maxVersion(),
61 compressionMethods: []uint8{compressionNone},
62 random: make([]byte, 32),
63 ocspStapling: true,
64 serverName: c.config.ServerName,
65 supportedCurves: c.config.curvePreferences(),
66 supportedPoints: []uint8{pointFormatUncompressed},
67 nextProtoNeg: len(c.config.NextProtos) > 0,
68 secureRenegotiation: []byte{},
69 alpnProtocols: c.config.NextProtos,
70 duplicateExtension: c.config.Bugs.DuplicateExtension,
71 channelIDSupported: c.config.ChannelID != nil,
72 npnLast: c.config.Bugs.SwapNPNAndALPN,
73 extendedMasterSecret: c.config.maxVersion() >= VersionTLS10,
74 srtpProtectionProfiles: c.config.SRTPProtectionProfiles,
75 srtpMasterKeyIdentifier: c.config.Bugs.SRTPMasterKeyIdentifer,
Adam Langley95c29f32014-06-20 12:00:00 -070076 }
77
David Benjamin98e882e2014-08-08 13:24:34 -040078 if c.config.Bugs.SendClientVersion != 0 {
79 hello.vers = c.config.Bugs.SendClientVersion
80 }
81
Adam Langley75712922014-10-10 16:23:43 -070082 if c.config.Bugs.NoExtendedMasterSecret {
83 hello.extendedMasterSecret = false
84 }
85
Adam Langley2ae77d22014-10-28 17:29:33 -070086 if len(c.clientVerify) > 0 && !c.config.Bugs.EmptyRenegotiationInfo {
87 if c.config.Bugs.BadRenegotiationInfo {
88 hello.secureRenegotiation = append(hello.secureRenegotiation, c.clientVerify...)
89 hello.secureRenegotiation[0] ^= 0x80
90 } else {
91 hello.secureRenegotiation = c.clientVerify
92 }
93 }
94
David Benjaminca6554b2014-11-08 12:31:52 -050095 if c.config.Bugs.NoRenegotiationInfo {
96 hello.secureRenegotiation = nil
97 }
98
Adam Langley95c29f32014-06-20 12:00:00 -070099 possibleCipherSuites := c.config.cipherSuites()
100 hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
101
102NextCipherSuite:
103 for _, suiteId := range possibleCipherSuites {
104 for _, suite := range cipherSuites {
105 if suite.id != suiteId {
106 continue
107 }
108 // Don't advertise TLS 1.2-only cipher suites unless
109 // we're attempting TLS 1.2.
110 if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
111 continue
112 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400113 // Don't advertise non-DTLS cipher suites on DTLS.
114 if c.isDTLS && suite.flags&suiteNoDTLS != 0 {
115 continue
116 }
Adam Langley95c29f32014-06-20 12:00:00 -0700117 hello.cipherSuites = append(hello.cipherSuites, suiteId)
118 continue NextCipherSuite
119 }
120 }
121
David Benjaminbef270a2014-08-02 04:22:02 -0400122 if c.config.Bugs.SendFallbackSCSV {
123 hello.cipherSuites = append(hello.cipherSuites, fallbackSCSV)
124 }
125
Adam Langley95c29f32014-06-20 12:00:00 -0700126 _, err := io.ReadFull(c.config.rand(), hello.random)
127 if err != nil {
128 c.sendAlert(alertInternalError)
129 return errors.New("tls: short read from Rand: " + err.Error())
130 }
131
David Benjamin3c9746a2015-03-19 15:00:10 -0400132 if hello.vers >= VersionTLS12 && !c.config.Bugs.NoSignatureAndHashes && (c.cipherSuite == 0 || !c.config.Bugs.NoSignatureAlgorithmsOnRenego) {
David Benjamin000800a2014-11-14 01:43:59 -0500133 hello.signatureAndHashes = c.config.signatureAndHashesForClient()
Adam Langley95c29f32014-06-20 12:00:00 -0700134 }
135
136 var session *ClientSessionState
137 var cacheKey string
138 sessionCache := c.config.ClientSessionCache
David Benjamincdea40c2015-03-19 14:09:43 -0400139 if c.config.Bugs.NeverResumeOnRenego && c.cipherSuite != 0 {
140 sessionCache = nil
141 }
Adam Langley95c29f32014-06-20 12:00:00 -0700142
143 if sessionCache != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500144 hello.ticketSupported = !c.config.SessionTicketsDisabled
Adam Langley95c29f32014-06-20 12:00:00 -0700145
146 // Try to resume a previously negotiated TLS session, if
147 // available.
148 cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
149 candidateSession, ok := sessionCache.Get(cacheKey)
150 if ok {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500151 ticketOk := !c.config.SessionTicketsDisabled || candidateSession.sessionTicket == nil
152
Adam Langley95c29f32014-06-20 12:00:00 -0700153 // Check that the ciphersuite/version used for the
154 // previous session are still valid.
155 cipherSuiteOk := false
156 for _, id := range hello.cipherSuites {
157 if id == candidateSession.cipherSuite {
158 cipherSuiteOk = true
159 break
160 }
161 }
162
163 versOk := candidateSession.vers >= c.config.minVersion() &&
164 candidateSession.vers <= c.config.maxVersion()
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500165 if ticketOk && versOk && cipherSuiteOk {
Adam Langley95c29f32014-06-20 12:00:00 -0700166 session = candidateSession
167 }
168 }
169 }
170
171 if session != nil {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500172 if session.sessionTicket != nil {
173 hello.sessionTicket = session.sessionTicket
174 if c.config.Bugs.CorruptTicket {
175 hello.sessionTicket = make([]byte, len(session.sessionTicket))
176 copy(hello.sessionTicket, session.sessionTicket)
177 if len(hello.sessionTicket) > 0 {
178 offset := 40
179 if offset > len(hello.sessionTicket) {
180 offset = len(hello.sessionTicket) - 1
181 }
182 hello.sessionTicket[offset] ^= 0x40
Adam Langley38311732014-10-16 19:04:35 -0700183 }
Adam Langley38311732014-10-16 19:04:35 -0700184 }
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500185 // A random session ID is used to detect when the
186 // server accepted the ticket and is resuming a session
187 // (see RFC 5077).
188 sessionIdLen := 16
189 if c.config.Bugs.OversizedSessionId {
190 sessionIdLen = 33
191 }
192 hello.sessionId = make([]byte, sessionIdLen)
193 if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
194 c.sendAlert(alertInternalError)
195 return errors.New("tls: short read from Rand: " + err.Error())
196 }
197 } else {
198 hello.sessionId = session.sessionId
Adam Langley95c29f32014-06-20 12:00:00 -0700199 }
200 }
201
David Benjamind86c7672014-08-02 04:07:12 -0400202 var helloBytes []byte
203 if c.config.Bugs.SendV2ClientHello {
David Benjamin94d701b2014-11-30 13:54:41 -0500204 // Test that the peer left-pads random.
205 hello.random[0] = 0
David Benjamind86c7672014-08-02 04:07:12 -0400206 v2Hello := &v2ClientHelloMsg{
207 vers: hello.vers,
208 cipherSuites: hello.cipherSuites,
209 // No session resumption for V2ClientHello.
210 sessionId: nil,
David Benjamin94d701b2014-11-30 13:54:41 -0500211 challenge: hello.random[1:],
David Benjamind86c7672014-08-02 04:07:12 -0400212 }
213 helloBytes = v2Hello.marshal()
214 c.writeV2Record(helloBytes)
215 } else {
216 helloBytes = hello.marshal()
217 c.writeRecord(recordTypeHandshake, helloBytes)
218 }
David Benjamina4e6d482015-03-02 19:10:53 -0500219 c.dtlsFlushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700220
David Benjamin83f90402015-01-27 01:09:43 -0500221 if err := c.simulatePacketLoss(nil); err != nil {
222 return err
223 }
Adam Langley95c29f32014-06-20 12:00:00 -0700224 msg, err := c.readHandshake()
225 if err != nil {
226 return err
227 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400228
229 if c.isDTLS {
230 helloVerifyRequest, ok := msg.(*helloVerifyRequestMsg)
231 if ok {
David Benjamin8bc38f52014-08-16 12:07:27 -0400232 if helloVerifyRequest.vers != VersionTLS10 {
233 // Per RFC 6347, the version field in
234 // HelloVerifyRequest SHOULD be always DTLS
235 // 1.0. Enforce this for testing purposes.
236 return errors.New("dtls: bad HelloVerifyRequest version")
237 }
238
David Benjamin83c0bc92014-08-04 01:23:53 -0400239 hello.raw = nil
240 hello.cookie = helloVerifyRequest.cookie
241 helloBytes = hello.marshal()
242 c.writeRecord(recordTypeHandshake, helloBytes)
David Benjamina4e6d482015-03-02 19:10:53 -0500243 c.dtlsFlushHandshake()
David Benjamin83c0bc92014-08-04 01:23:53 -0400244
David Benjamin83f90402015-01-27 01:09:43 -0500245 if err := c.simulatePacketLoss(nil); err != nil {
246 return err
247 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400248 msg, err = c.readHandshake()
249 if err != nil {
250 return err
251 }
252 }
253 }
254
Adam Langley95c29f32014-06-20 12:00:00 -0700255 serverHello, ok := msg.(*serverHelloMsg)
256 if !ok {
257 c.sendAlert(alertUnexpectedMessage)
258 return unexpectedMessageError(serverHello, msg)
259 }
260
David Benjamin76d8abe2014-08-14 16:25:34 -0400261 c.vers, ok = c.config.mutualVersion(serverHello.vers)
262 if !ok {
Adam Langley95c29f32014-06-20 12:00:00 -0700263 c.sendAlert(alertProtocolVersion)
264 return fmt.Errorf("tls: server selected unsupported protocol version %x", serverHello.vers)
265 }
Adam Langley95c29f32014-06-20 12:00:00 -0700266 c.haveVers = true
267
268 suite := mutualCipherSuite(c.config.cipherSuites(), serverHello.cipherSuite)
269 if suite == nil {
270 c.sendAlert(alertHandshakeFailure)
271 return fmt.Errorf("tls: server selected an unsupported cipher suite")
272 }
273
David Benjaminca6554b2014-11-08 12:31:52 -0500274 if len(c.clientVerify) > 0 && !c.config.Bugs.NoRenegotiationInfo {
Adam Langley2ae77d22014-10-28 17:29:33 -0700275 var expectedRenegInfo []byte
276 expectedRenegInfo = append(expectedRenegInfo, c.clientVerify...)
277 expectedRenegInfo = append(expectedRenegInfo, c.serverVerify...)
278 if !bytes.Equal(serverHello.secureRenegotiation, expectedRenegInfo) {
279 c.sendAlert(alertHandshakeFailure)
280 return fmt.Errorf("tls: renegotiation mismatch")
281 }
282 }
283
Adam Langley95c29f32014-06-20 12:00:00 -0700284 hs := &clientHandshakeState{
285 c: c,
286 serverHello: serverHello,
287 hello: hello,
288 suite: suite,
289 finishedHash: newFinishedHash(c.vers, suite),
290 session: session,
291 }
292
David Benjamin83c0bc92014-08-04 01:23:53 -0400293 hs.writeHash(helloBytes, hs.c.sendHandshakeSeq-1)
294 hs.writeServerHash(hs.serverHello.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700295
David Benjaminf3ec83d2014-07-21 22:42:34 -0400296 if c.config.Bugs.EarlyChangeCipherSpec > 0 {
297 hs.establishKeys()
298 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
299 }
300
Adam Langley95c29f32014-06-20 12:00:00 -0700301 isResume, err := hs.processServerHello()
302 if err != nil {
303 return err
304 }
305
306 if isResume {
David Benjaminf3ec83d2014-07-21 22:42:34 -0400307 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
308 if err := hs.establishKeys(); err != nil {
309 return err
310 }
Adam Langley95c29f32014-06-20 12:00:00 -0700311 }
312 if err := hs.readSessionTicket(); err != nil {
313 return err
314 }
315 if err := hs.readFinished(); err != nil {
316 return err
317 }
David Benjamind30a9902014-08-24 01:44:23 -0400318 if err := hs.sendFinished(isResume); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700319 return err
320 }
321 } else {
322 if err := hs.doFullHandshake(); err != nil {
323 return err
324 }
325 if err := hs.establishKeys(); err != nil {
326 return err
327 }
David Benjamind30a9902014-08-24 01:44:23 -0400328 if err := hs.sendFinished(isResume); err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700329 return err
330 }
David Benjamin83f90402015-01-27 01:09:43 -0500331 // Most retransmits are triggered by a timeout, but the final
332 // leg of the handshake is retransmited upon re-receiving a
333 // Finished.
David Benjaminb3774b92015-01-31 17:16:01 -0500334 if err := c.simulatePacketLoss(func() {
335 c.writeRecord(recordTypeHandshake, hs.finishedBytes)
David Benjamina4e6d482015-03-02 19:10:53 -0500336 c.dtlsFlushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -0500337 }); err != nil {
David Benjamin83f90402015-01-27 01:09:43 -0500338 return err
339 }
Adam Langley95c29f32014-06-20 12:00:00 -0700340 if err := hs.readSessionTicket(); err != nil {
341 return err
342 }
343 if err := hs.readFinished(); err != nil {
344 return err
345 }
346 }
347
348 if sessionCache != nil && hs.session != nil && session != hs.session {
349 sessionCache.Put(cacheKey, hs.session)
350 }
351
352 c.didResume = isResume
353 c.handshakeComplete = true
354 c.cipherSuite = suite.id
355 return nil
356}
357
358func (hs *clientHandshakeState) doFullHandshake() error {
359 c := hs.c
360
David Benjamin48cae082014-10-27 01:06:24 -0400361 var leaf *x509.Certificate
362 if hs.suite.flags&suitePSK == 0 {
363 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700364 if err != nil {
Adam Langley95c29f32014-06-20 12:00:00 -0700365 return err
366 }
Adam Langley95c29f32014-06-20 12:00:00 -0700367
David Benjamin48cae082014-10-27 01:06:24 -0400368 certMsg, ok := msg.(*certificateMsg)
369 if !ok || len(certMsg.certificates) == 0 {
370 c.sendAlert(alertUnexpectedMessage)
371 return unexpectedMessageError(certMsg, msg)
372 }
373 hs.writeServerHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700374
David Benjamin48cae082014-10-27 01:06:24 -0400375 certs := make([]*x509.Certificate, len(certMsg.certificates))
376 for i, asn1Data := range certMsg.certificates {
377 cert, err := x509.ParseCertificate(asn1Data)
378 if err != nil {
379 c.sendAlert(alertBadCertificate)
380 return errors.New("tls: failed to parse certificate from server: " + err.Error())
381 }
382 certs[i] = cert
383 }
384 leaf = certs[0]
385
386 if !c.config.InsecureSkipVerify {
387 opts := x509.VerifyOptions{
388 Roots: c.config.RootCAs,
389 CurrentTime: c.config.time(),
390 DNSName: c.config.ServerName,
391 Intermediates: x509.NewCertPool(),
392 }
393
394 for i, cert := range certs {
395 if i == 0 {
396 continue
397 }
398 opts.Intermediates.AddCert(cert)
399 }
400 c.verifiedChains, err = leaf.Verify(opts)
401 if err != nil {
402 c.sendAlert(alertBadCertificate)
403 return err
404 }
405 }
406
407 switch leaf.PublicKey.(type) {
408 case *rsa.PublicKey, *ecdsa.PublicKey:
409 break
410 default:
411 c.sendAlert(alertUnsupportedCertificate)
412 return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", leaf.PublicKey)
413 }
414
415 c.peerCertificates = certs
416 }
Adam Langley95c29f32014-06-20 12:00:00 -0700417
418 if hs.serverHello.ocspStapling {
David Benjamin48cae082014-10-27 01:06:24 -0400419 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700420 if err != nil {
421 return err
422 }
423 cs, ok := msg.(*certificateStatusMsg)
424 if !ok {
425 c.sendAlert(alertUnexpectedMessage)
426 return unexpectedMessageError(cs, msg)
427 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400428 hs.writeServerHash(cs.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700429
430 if cs.statusType == statusTypeOCSP {
431 c.ocspResponse = cs.response
432 }
433 }
434
David Benjamin48cae082014-10-27 01:06:24 -0400435 msg, err := c.readHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700436 if err != nil {
437 return err
438 }
439
440 keyAgreement := hs.suite.ka(c.vers)
441
442 skx, ok := msg.(*serverKeyExchangeMsg)
443 if ok {
David Benjamin83c0bc92014-08-04 01:23:53 -0400444 hs.writeServerHash(skx.marshal())
David Benjamin48cae082014-10-27 01:06:24 -0400445 err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, leaf, skx)
Adam Langley95c29f32014-06-20 12:00:00 -0700446 if err != nil {
447 c.sendAlert(alertUnexpectedMessage)
448 return err
449 }
450
451 msg, err = c.readHandshake()
452 if err != nil {
453 return err
454 }
455 }
456
457 var chainToSend *Certificate
458 var certRequested bool
459 certReq, ok := msg.(*certificateRequestMsg)
460 if ok {
461 certRequested = true
462
463 // RFC 4346 on the certificateAuthorities field:
464 // A list of the distinguished names of acceptable certificate
465 // authorities. These distinguished names may specify a desired
466 // distinguished name for a root CA or for a subordinate CA;
467 // thus, this message can be used to describe both known roots
468 // and a desired authorization space. If the
469 // certificate_authorities list is empty then the client MAY
470 // send any certificate of the appropriate
471 // ClientCertificateType, unless there is some external
472 // arrangement to the contrary.
473
David Benjamin83c0bc92014-08-04 01:23:53 -0400474 hs.writeServerHash(certReq.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700475
476 var rsaAvail, ecdsaAvail bool
477 for _, certType := range certReq.certificateTypes {
478 switch certType {
David Benjamin7b030512014-07-08 17:30:11 -0400479 case CertTypeRSASign:
Adam Langley95c29f32014-06-20 12:00:00 -0700480 rsaAvail = true
David Benjamin7b030512014-07-08 17:30:11 -0400481 case CertTypeECDSASign:
Adam Langley95c29f32014-06-20 12:00:00 -0700482 ecdsaAvail = true
483 }
484 }
485
486 // We need to search our list of client certs for one
487 // where SignatureAlgorithm is RSA and the Issuer is in
488 // certReq.certificateAuthorities
489 findCert:
490 for i, chain := range c.config.Certificates {
491 if !rsaAvail && !ecdsaAvail {
492 continue
493 }
494
495 for j, cert := range chain.Certificate {
496 x509Cert := chain.Leaf
497 // parse the certificate if this isn't the leaf
498 // node, or if chain.Leaf was nil
499 if j != 0 || x509Cert == nil {
500 if x509Cert, err = x509.ParseCertificate(cert); err != nil {
501 c.sendAlert(alertInternalError)
502 return errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
503 }
504 }
505
506 switch {
507 case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
508 case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
509 default:
510 continue findCert
511 }
512
513 if len(certReq.certificateAuthorities) == 0 {
514 // they gave us an empty list, so just take the
515 // first RSA cert from c.config.Certificates
516 chainToSend = &chain
517 break findCert
518 }
519
520 for _, ca := range certReq.certificateAuthorities {
521 if bytes.Equal(x509Cert.RawIssuer, ca) {
522 chainToSend = &chain
523 break findCert
524 }
525 }
526 }
527 }
528
529 msg, err = c.readHandshake()
530 if err != nil {
531 return err
532 }
533 }
534
535 shd, ok := msg.(*serverHelloDoneMsg)
536 if !ok {
537 c.sendAlert(alertUnexpectedMessage)
538 return unexpectedMessageError(shd, msg)
539 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400540 hs.writeServerHash(shd.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700541
542 // If the server requested a certificate then we have to send a
543 // Certificate message, even if it's empty because we don't have a
544 // certificate to send.
545 if certRequested {
David Benjamin48cae082014-10-27 01:06:24 -0400546 certMsg := new(certificateMsg)
Adam Langley95c29f32014-06-20 12:00:00 -0700547 if chainToSend != nil {
548 certMsg.certificates = chainToSend.Certificate
549 }
David Benjamin83c0bc92014-08-04 01:23:53 -0400550 hs.writeClientHash(certMsg.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700551 c.writeRecord(recordTypeHandshake, certMsg.marshal())
552 }
553
David Benjamin48cae082014-10-27 01:06:24 -0400554 preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, leaf)
Adam Langley95c29f32014-06-20 12:00:00 -0700555 if err != nil {
556 c.sendAlert(alertInternalError)
557 return err
558 }
559 if ckx != nil {
David Benjaminf3ec83d2014-07-21 22:42:34 -0400560 if c.config.Bugs.EarlyChangeCipherSpec < 2 {
David Benjamin83c0bc92014-08-04 01:23:53 -0400561 hs.writeClientHash(ckx.marshal())
David Benjaminf3ec83d2014-07-21 22:42:34 -0400562 }
Adam Langley95c29f32014-06-20 12:00:00 -0700563 c.writeRecord(recordTypeHandshake, ckx.marshal())
564 }
565
Adam Langley75712922014-10-10 16:23:43 -0700566 if hs.serverHello.extendedMasterSecret && c.vers >= VersionTLS10 {
567 hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
568 c.extendedMasterSecret = true
569 } else {
570 if c.config.Bugs.RequireExtendedMasterSecret {
571 return errors.New("tls: extended master secret required but not supported by peer")
572 }
573 hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
574 }
David Benjamine098ec22014-08-27 23:13:20 -0400575
Adam Langley95c29f32014-06-20 12:00:00 -0700576 if chainToSend != nil {
577 var signed []byte
578 certVerify := &certificateVerifyMsg{
579 hasSignatureAndHash: c.vers >= VersionTLS12,
580 }
581
David Benjamin72dc7832015-03-16 17:49:43 -0400582 // Determine the hash to sign.
583 var signatureType uint8
584 switch c.config.Certificates[0].PrivateKey.(type) {
585 case *ecdsa.PrivateKey:
586 signatureType = signatureECDSA
587 case *rsa.PrivateKey:
588 signatureType = signatureRSA
589 default:
590 c.sendAlert(alertInternalError)
591 return errors.New("unknown private key type")
592 }
593 if c.config.Bugs.IgnorePeerSignatureAlgorithmPreferences {
594 certReq.signatureAndHashes = c.config.signatureAndHashesForClient()
595 }
596 certVerify.signatureAndHash, err = hs.finishedHash.selectClientCertSignatureAlgorithm(certReq.signatureAndHashes, c.config.signatureAndHashesForClient(), signatureType)
597 if err != nil {
598 c.sendAlert(alertInternalError)
599 return err
600 }
601 digest, hashFunc, err := hs.finishedHash.hashForClientCertificate(certVerify.signatureAndHash, hs.masterSecret)
602 if err != nil {
603 c.sendAlert(alertInternalError)
604 return err
605 }
606
Adam Langley95c29f32014-06-20 12:00:00 -0700607 switch key := c.config.Certificates[0].PrivateKey.(type) {
608 case *ecdsa.PrivateKey:
David Benjaminde620d92014-07-18 15:03:41 -0400609 var r, s *big.Int
610 r, s, err = ecdsa.Sign(c.config.rand(), key, digest)
Adam Langley95c29f32014-06-20 12:00:00 -0700611 if err == nil {
612 signed, err = asn1.Marshal(ecdsaSignature{r, s})
613 }
Adam Langley95c29f32014-06-20 12:00:00 -0700614 case *rsa.PrivateKey:
Adam Langley95c29f32014-06-20 12:00:00 -0700615 signed, err = rsa.SignPKCS1v15(c.config.rand(), key, hashFunc, digest)
Adam Langley95c29f32014-06-20 12:00:00 -0700616 default:
617 err = errors.New("unknown private key type")
618 }
619 if err != nil {
620 c.sendAlert(alertInternalError)
621 return errors.New("tls: failed to sign handshake with client certificate: " + err.Error())
622 }
623 certVerify.signature = signed
624
David Benjamin83c0bc92014-08-04 01:23:53 -0400625 hs.writeClientHash(certVerify.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700626 c.writeRecord(recordTypeHandshake, certVerify.marshal())
627 }
David Benjamina4e6d482015-03-02 19:10:53 -0500628 c.dtlsFlushHandshake()
Adam Langley95c29f32014-06-20 12:00:00 -0700629
David Benjamine098ec22014-08-27 23:13:20 -0400630 hs.finishedHash.discardHandshakeBuffer()
631
Adam Langley95c29f32014-06-20 12:00:00 -0700632 return nil
633}
634
635func (hs *clientHandshakeState) establishKeys() error {
636 c := hs.c
637
638 clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
639 keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
640 var clientCipher, serverCipher interface{}
641 var clientHash, serverHash macFunction
642 if hs.suite.cipher != nil {
643 clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
644 clientHash = hs.suite.mac(c.vers, clientMAC)
645 serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
646 serverHash = hs.suite.mac(c.vers, serverMAC)
647 } else {
648 clientCipher = hs.suite.aead(clientKey, clientIV)
649 serverCipher = hs.suite.aead(serverKey, serverIV)
650 }
651
652 c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
653 c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
654 return nil
655}
656
657func (hs *clientHandshakeState) serverResumedSession() bool {
658 // If the server responded with the same sessionId then it means the
659 // sessionTicket is being used to resume a TLS session.
660 return hs.session != nil && hs.hello.sessionId != nil &&
661 bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
662}
663
664func (hs *clientHandshakeState) processServerHello() (bool, error) {
665 c := hs.c
666
667 if hs.serverHello.compressionMethod != compressionNone {
668 c.sendAlert(alertUnexpectedMessage)
669 return false, errors.New("tls: server selected unsupported compression format")
670 }
671
David Benjaminfa055a22014-09-15 16:51:51 -0400672 clientDidNPN := hs.hello.nextProtoNeg
673 clientDidALPN := len(hs.hello.alpnProtocols) > 0
674 serverHasNPN := hs.serverHello.nextProtoNeg
675 serverHasALPN := len(hs.serverHello.alpnProtocol) > 0
676
677 if !clientDidNPN && serverHasNPN {
Adam Langley95c29f32014-06-20 12:00:00 -0700678 c.sendAlert(alertHandshakeFailure)
679 return false, errors.New("server advertised unrequested NPN extension")
680 }
681
David Benjaminfa055a22014-09-15 16:51:51 -0400682 if !clientDidALPN && serverHasALPN {
683 c.sendAlert(alertHandshakeFailure)
684 return false, errors.New("server advertised unrequested ALPN extension")
685 }
686
687 if serverHasNPN && serverHasALPN {
688 c.sendAlert(alertHandshakeFailure)
689 return false, errors.New("server advertised both NPN and ALPN extensions")
690 }
691
692 if serverHasALPN {
693 c.clientProtocol = hs.serverHello.alpnProtocol
694 c.clientProtocolFallback = false
David Benjaminfc7b0862014-09-06 13:21:53 -0400695 c.usedALPN = true
David Benjaminfa055a22014-09-15 16:51:51 -0400696 }
697
David Benjamind30a9902014-08-24 01:44:23 -0400698 if !hs.hello.channelIDSupported && hs.serverHello.channelIDRequested {
699 c.sendAlert(alertHandshakeFailure)
700 return false, errors.New("server advertised unrequested Channel ID extension")
701 }
702
David Benjaminca6c8262014-11-15 19:06:08 -0500703 if hs.serverHello.srtpProtectionProfile != 0 {
704 if hs.serverHello.srtpMasterKeyIdentifier != "" {
705 return false, errors.New("tls: server selected SRTP MKI value")
706 }
707
708 found := false
709 for _, p := range c.config.SRTPProtectionProfiles {
710 if p == hs.serverHello.srtpProtectionProfile {
711 found = true
712 break
713 }
714 }
715 if !found {
716 return false, errors.New("tls: server advertised unsupported SRTP profile")
717 }
718
719 c.srtpProtectionProfile = hs.serverHello.srtpProtectionProfile
720 }
721
Adam Langley95c29f32014-06-20 12:00:00 -0700722 if hs.serverResumedSession() {
723 // Restore masterSecret and peerCerts from previous state
724 hs.masterSecret = hs.session.masterSecret
725 c.peerCertificates = hs.session.serverCertificates
Adam Langley75712922014-10-10 16:23:43 -0700726 c.extendedMasterSecret = hs.session.extendedMasterSecret
David Benjamine098ec22014-08-27 23:13:20 -0400727 hs.finishedHash.discardHandshakeBuffer()
Adam Langley95c29f32014-06-20 12:00:00 -0700728 return true, nil
729 }
730 return false, nil
731}
732
733func (hs *clientHandshakeState) readFinished() error {
734 c := hs.c
735
736 c.readRecord(recordTypeChangeCipherSpec)
737 if err := c.in.error(); err != nil {
738 return err
739 }
740
741 msg, err := c.readHandshake()
742 if err != nil {
743 return err
744 }
745 serverFinished, ok := msg.(*finishedMsg)
746 if !ok {
747 c.sendAlert(alertUnexpectedMessage)
748 return unexpectedMessageError(serverFinished, msg)
749 }
750
David Benjaminf3ec83d2014-07-21 22:42:34 -0400751 if c.config.Bugs.EarlyChangeCipherSpec == 0 {
752 verify := hs.finishedHash.serverSum(hs.masterSecret)
753 if len(verify) != len(serverFinished.verifyData) ||
754 subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
755 c.sendAlert(alertHandshakeFailure)
756 return errors.New("tls: server's Finished message was incorrect")
757 }
Adam Langley95c29f32014-06-20 12:00:00 -0700758 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700759 c.serverVerify = append(c.serverVerify[:0], serverFinished.verifyData...)
David Benjamin83c0bc92014-08-04 01:23:53 -0400760 hs.writeServerHash(serverFinished.marshal())
Adam Langley95c29f32014-06-20 12:00:00 -0700761 return nil
762}
763
764func (hs *clientHandshakeState) readSessionTicket() error {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500765 c := hs.c
766
767 // Create a session with no server identifier. Either a
768 // session ID or session ticket will be attached.
769 session := &ClientSessionState{
770 vers: c.vers,
771 cipherSuite: hs.suite.id,
772 masterSecret: hs.masterSecret,
773 handshakeHash: hs.finishedHash.server.Sum(nil),
774 serverCertificates: c.peerCertificates,
775 }
776
Adam Langley95c29f32014-06-20 12:00:00 -0700777 if !hs.serverHello.ticketSupported {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500778 if hs.session == nil && len(hs.serverHello.sessionId) > 0 {
779 session.sessionId = hs.serverHello.sessionId
780 hs.session = session
781 }
Adam Langley95c29f32014-06-20 12:00:00 -0700782 return nil
783 }
784
Adam Langley95c29f32014-06-20 12:00:00 -0700785 msg, err := c.readHandshake()
786 if err != nil {
787 return err
788 }
789 sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
790 if !ok {
791 c.sendAlert(alertUnexpectedMessage)
792 return unexpectedMessageError(sessionTicketMsg, msg)
793 }
Adam Langley95c29f32014-06-20 12:00:00 -0700794
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500795 session.sessionTicket = sessionTicketMsg.ticket
796 hs.session = session
Adam Langley95c29f32014-06-20 12:00:00 -0700797
David Benjamind30a9902014-08-24 01:44:23 -0400798 hs.writeServerHash(sessionTicketMsg.marshal())
799
Adam Langley95c29f32014-06-20 12:00:00 -0700800 return nil
801}
802
David Benjamind30a9902014-08-24 01:44:23 -0400803func (hs *clientHandshakeState) sendFinished(isResume bool) error {
Adam Langley95c29f32014-06-20 12:00:00 -0700804 c := hs.c
805
David Benjamin86271ee2014-07-21 16:14:03 -0400806 var postCCSBytes []byte
David Benjamin83c0bc92014-08-04 01:23:53 -0400807 seqno := hs.c.sendHandshakeSeq
Adam Langley95c29f32014-06-20 12:00:00 -0700808 if hs.serverHello.nextProtoNeg {
809 nextProto := new(nextProtoMsg)
810 proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos)
811 nextProto.proto = proto
812 c.clientProtocol = proto
813 c.clientProtocolFallback = fallback
814
David Benjamin86271ee2014-07-21 16:14:03 -0400815 nextProtoBytes := nextProto.marshal()
David Benjamin83c0bc92014-08-04 01:23:53 -0400816 hs.writeHash(nextProtoBytes, seqno)
817 seqno++
David Benjamin86271ee2014-07-21 16:14:03 -0400818 postCCSBytes = append(postCCSBytes, nextProtoBytes...)
Adam Langley95c29f32014-06-20 12:00:00 -0700819 }
820
David Benjamind30a9902014-08-24 01:44:23 -0400821 if hs.serverHello.channelIDRequested {
822 encryptedExtensions := new(encryptedExtensionsMsg)
823 if c.config.ChannelID.Curve != elliptic.P256() {
824 return fmt.Errorf("tls: Channel ID is not on P-256.")
825 }
826 var resumeHash []byte
827 if isResume {
828 resumeHash = hs.session.handshakeHash
829 }
830 r, s, err := ecdsa.Sign(c.config.rand(), c.config.ChannelID, hs.finishedHash.hashForChannelID(resumeHash))
831 if err != nil {
832 return err
833 }
834 channelID := make([]byte, 128)
835 writeIntPadded(channelID[0:32], c.config.ChannelID.X)
836 writeIntPadded(channelID[32:64], c.config.ChannelID.Y)
837 writeIntPadded(channelID[64:96], r)
838 writeIntPadded(channelID[96:128], s)
839 encryptedExtensions.channelID = channelID
840
841 c.channelID = &c.config.ChannelID.PublicKey
842
843 encryptedExtensionsBytes := encryptedExtensions.marshal()
844 hs.writeHash(encryptedExtensionsBytes, seqno)
845 seqno++
846 postCCSBytes = append(postCCSBytes, encryptedExtensionsBytes...)
847 }
848
Adam Langley95c29f32014-06-20 12:00:00 -0700849 finished := new(finishedMsg)
David Benjaminf3ec83d2014-07-21 22:42:34 -0400850 if c.config.Bugs.EarlyChangeCipherSpec == 2 {
851 finished.verifyData = hs.finishedHash.clientSum(nil)
852 } else {
853 finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
854 }
Adam Langley2ae77d22014-10-28 17:29:33 -0700855 c.clientVerify = append(c.clientVerify[:0], finished.verifyData...)
David Benjamin83f90402015-01-27 01:09:43 -0500856 hs.finishedBytes = finished.marshal()
857 hs.writeHash(hs.finishedBytes, seqno)
858 postCCSBytes = append(postCCSBytes, hs.finishedBytes...)
David Benjamin86271ee2014-07-21 16:14:03 -0400859
860 if c.config.Bugs.FragmentAcrossChangeCipherSpec {
861 c.writeRecord(recordTypeHandshake, postCCSBytes[:5])
862 postCCSBytes = postCCSBytes[5:]
863 }
David Benjamina4e6d482015-03-02 19:10:53 -0500864 c.dtlsFlushHandshake()
David Benjamin86271ee2014-07-21 16:14:03 -0400865
866 if !c.config.Bugs.SkipChangeCipherSpec &&
867 c.config.Bugs.EarlyChangeCipherSpec == 0 {
868 c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
869 }
870
David Benjamin4189bd92015-01-25 23:52:39 -0500871 if c.config.Bugs.AppDataAfterChangeCipherSpec != nil {
872 c.writeRecord(recordTypeApplicationData, c.config.Bugs.AppDataAfterChangeCipherSpec)
873 }
David Benjamindc3da932015-03-12 15:09:02 -0400874 if c.config.Bugs.AlertAfterChangeCipherSpec != 0 {
875 c.sendAlert(c.config.Bugs.AlertAfterChangeCipherSpec)
876 return errors.New("tls: simulating post-CCS alert")
877 }
David Benjamin4189bd92015-01-25 23:52:39 -0500878
David Benjaminb80168e2015-02-08 18:30:14 -0500879 if !c.config.Bugs.SkipFinished {
880 c.writeRecord(recordTypeHandshake, postCCSBytes)
David Benjamina4e6d482015-03-02 19:10:53 -0500881 c.dtlsFlushHandshake()
David Benjaminb3774b92015-01-31 17:16:01 -0500882 }
Adam Langley95c29f32014-06-20 12:00:00 -0700883 return nil
884}
885
David Benjamin83c0bc92014-08-04 01:23:53 -0400886func (hs *clientHandshakeState) writeClientHash(msg []byte) {
887 // writeClientHash is called before writeRecord.
888 hs.writeHash(msg, hs.c.sendHandshakeSeq)
889}
890
891func (hs *clientHandshakeState) writeServerHash(msg []byte) {
892 // writeServerHash is called after readHandshake.
893 hs.writeHash(msg, hs.c.recvHandshakeSeq-1)
894}
895
896func (hs *clientHandshakeState) writeHash(msg []byte, seqno uint16) {
897 if hs.c.isDTLS {
898 // This is somewhat hacky. DTLS hashes a slightly different format.
899 // First, the TLS header.
900 hs.finishedHash.Write(msg[:4])
901 // Then the sequence number and reassembled fragment offset (always 0).
902 hs.finishedHash.Write([]byte{byte(seqno >> 8), byte(seqno), 0, 0, 0})
903 // Then the reassembled fragment (always equal to the message length).
904 hs.finishedHash.Write(msg[1:4])
905 // And then the message body.
906 hs.finishedHash.Write(msg[4:])
907 } else {
908 hs.finishedHash.Write(msg)
909 }
910}
911
Adam Langley95c29f32014-06-20 12:00:00 -0700912// clientSessionCacheKey returns a key used to cache sessionTickets that could
913// be used to resume previously negotiated TLS sessions with a server.
914func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
915 if len(config.ServerName) > 0 {
916 return config.ServerName
917 }
918 return serverAddr.String()
919}
920
David Benjaminfa055a22014-09-15 16:51:51 -0400921// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
922// given list of possible protocols and a list of the preference order. The
923// first list must not be empty. It returns the resulting protocol and flag
Adam Langley95c29f32014-06-20 12:00:00 -0700924// indicating if the fallback case was reached.
David Benjaminfa055a22014-09-15 16:51:51 -0400925func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
926 for _, s := range preferenceProtos {
927 for _, c := range protos {
Adam Langley95c29f32014-06-20 12:00:00 -0700928 if s == c {
929 return s, false
930 }
931 }
932 }
933
David Benjaminfa055a22014-09-15 16:51:51 -0400934 return protos[0], true
Adam Langley95c29f32014-06-20 12:00:00 -0700935}
David Benjamind30a9902014-08-24 01:44:23 -0400936
937// writeIntPadded writes x into b, padded up with leading zeros as
938// needed.
939func writeIntPadded(b []byte, x *big.Int) {
940 for i := range b {
941 b[i] = 0
942 }
943 xb := x.Bytes()
944 copy(b[len(b)-len(xb):], xb)
945}