Debian Codegraph @

client-state-machine.go

raw symbols SCIP
1 package mint
2
3 import (
4 "bytes"
5 "crypto"
6 "crypto/x509"
7 "hash"
8 "time"
9 )
10
11 // Client State Machine
12 //
13 // START <----+
14 // Send ClientHello | | Recv HelloRetryRequest
15 // / v |
16 // | WAIT_SH ---+
17 // Can | | Recv ServerHello
18 // send | V
19 // early | WAIT_EE
20 // data | | Recv EncryptedExtensions
21 // | +--------+--------+
22 // | Using | | Using certificate
23 // | PSK | v
24 // | | WAIT_CERT_CR
25 // | | Recv | | Recv CertificateRequest
26 // | | Certificate | v
27 // | | | WAIT_CERT
28 // | | | | Recv Certificate
29 // | | v v
30 // | | WAIT_CV
31 // | | | Recv CertificateVerify
32 // | +> WAIT_FINISHED <+
33 // | | Recv Finished
34 // \ |
35 // | [Send EndOfEarlyData]
36 // | [Send Certificate [+ CertificateVerify]]
37 // | Send Finished
38 // Can send v
39 // app data --> CONNECTED
40 // after
41 // here
42 //
43 // State Instructions
44 // START Send(CH); [RekeyOut; SendEarlyData]
45 // WAIT_SH Send(CH) || RekeyIn
46 // WAIT_EE {}
47 // WAIT_CERT_CR {}
48 // WAIT_CERT {}
49 // WAIT_CV {}
50 // WAIT_FINISHED RekeyIn; [Send(EOED);] RekeyOut; [SendCert; SendCV;] SendFin; RekeyOut;
51 // CONNECTED StoreTicket || (RekeyIn; [RekeyOut])
52
53 type clientStateStart struct {
54 Config *Config
55 Opts ConnectionOptions
56 Params ConnectionParameters
57
58 cookie []byte
59 firstClientHello *HandshakeMessage
60 helloRetryRequest *HandshakeMessage
61 hsCtx *HandshakeContext
62 }
63
64 var _ HandshakeState = &clientStateStart{}
65
66 func (state clientStateStart) State() State {
67 return StateClientStart
68 }
69
70 func (state clientStateStart) Next(hr handshakeMessageReader) (HandshakeState, []HandshakeAction, Alert) {
71 // key_shares
72 offeredDH := map[NamedGroup][]byte{}
73 ks := KeyShareExtension{
74 HandshakeType: HandshakeTypeClientHello,
75 Shares: make([]KeyShareEntry, len(state.Config.Groups)),
76 }
77 for i, group := range state.Config.Groups {
78 pub, priv, err := newKeyShare(group)
79 if err != nil {
80 logf(logTypeHandshake, "[ClientStateStart] Error generating key share [%v]", err)
81 return nil, nil, AlertInternalError
82 }
83
84 ks.Shares[i].Group = group
85 ks.Shares[i].KeyExchange = pub
86 offeredDH[group] = priv
87 }
88
89 logf(logTypeHandshake, "opts: %+v", state.Opts)
90
91 // supported_versions, supported_groups, signature_algorithms, server_name
92 sv := SupportedVersionsExtension{HandshakeType: HandshakeTypeClientHello, Versions: []uint16{tls13Version}}
93 sni := ServerNameExtension(state.Opts.ServerName)
94 sg := SupportedGroupsExtension{Groups: state.Config.Groups}
95 sa := SignatureAlgorithmsExtension{Algorithms: state.Config.SignatureSchemes}
96
97 state.Params.ServerName = state.Opts.ServerName
98
99 // Application Layer Protocol Negotiation
100 var alpn *ALPNExtension
101 if (state.Opts.NextProtos != nil) && (len(state.Opts.NextProtos) > 0) {
102 alpn = &ALPNExtension{Protocols: state.Opts.NextProtos}
103 }
104
105 // Construct base ClientHello
106 ch := &ClientHelloBody{
107 LegacyVersion: wireVersion(state.hsCtx.hIn),
108 CipherSuites: state.Config.CipherSuites,
109 }
110 _, err := prng.Read(ch.Random[:])
111 if err != nil {
112 logf(logTypeHandshake, "[ClientStateStart] Error creating ClientHello random [%v]", err)
113 return nil, nil, AlertInternalError
114 }
115 for _, ext := range []ExtensionBody{&sv, &sni, &ks, &sg, &sa} {
116 err := ch.Extensions.Add(ext)
117 if err != nil {
118 logf(logTypeHandshake, "[ClientStateStart] Error adding extension type=[%v] [%v]", ext.Type(), err)
119 return nil, nil, AlertInternalError
120 }
121 }
122 // XXX: These optional extensions can't be folded into the above because Go
123 // interface-typed values are never reported as nil
124 if alpn != nil {
125 err := ch.Extensions.Add(alpn)
126 if err != nil {
127 logf(logTypeHandshake, "[ClientStateStart] Error adding ALPN extension [%v]", err)
128 return nil, nil, AlertInternalError
129 }
130 }
131 if state.cookie != nil {
132 err := ch.Extensions.Add(&CookieExtension{Cookie: state.cookie})
133 if err != nil {
134 logf(logTypeHandshake, "[ClientStateStart] Error adding ALPN extension [%v]", err)
135 return nil, nil, AlertInternalError
136 }
137 }
138
139 if len(state.Config.PSKModes) != 0 {
140 kem := &PSKKeyExchangeModesExtension{KEModes: state.Config.PSKModes}
141 err = ch.Extensions.Add(kem)
142 if err != nil {
143 logf(logTypeHandshake, "Error adding PSKKeyExchangeModes extension: %v", err)
144 return nil, nil, AlertInternalError
145 }
146 }
147
148 // Run the external extension handler.
149 if state.Config.ExtensionHandler != nil {
150 err := state.Config.ExtensionHandler.Send(HandshakeTypeClientHello, &ch.Extensions)
151 if err != nil {
152 logf(logTypeHandshake, "[ClientStateStart] Error running external extension sender [%v]", err)
153 return nil, nil, AlertInternalError
154 }
155 }
156
157 // Handle PSK and EarlyData just before transmitting, so that we can
158 // calculate the PSK binder value
159 var psk *PreSharedKeyExtension
160 var ed *EarlyDataExtension
161 var offeredPSK PreSharedKey
162 var earlyHash crypto.Hash
163 var earlySecret []byte
164 var clientEarlyTrafficKeys KeySet
165 var clientHello *HandshakeMessage
166 if key, ok := state.Config.PSKs.Get(state.Opts.ServerName); ok {
167 offeredPSK = key
168
169 // Narrow ciphersuites to ones that match PSK hash
170 params, ok := cipherSuiteMap[key.CipherSuite]
171 if !ok {
172 logf(logTypeHandshake, "[ClientStateStart] PSK for unknown ciphersuite")
173 return nil, nil, AlertInternalError
174 }
175
176 compatibleSuites := []CipherSuite{}
177 for _, suite := range ch.CipherSuites {
178 if cipherSuiteMap[suite].Hash == params.Hash {
179 compatibleSuites = append(compatibleSuites, suite)
180 }
181 }
182 ch.CipherSuites = compatibleSuites
183
184 // TODO([email protected]): Check that the ticket can be used for early
185 // data.
186 // Signal early data if we're going to do it
187 if state.Config.AllowEarlyData && state.helloRetryRequest == nil {
188 state.Params.ClientSendingEarlyData = true
189 ed = &EarlyDataExtension{}
190 err = ch.Extensions.Add(ed)
191 if err != nil {
192 logf(logTypeHandshake, "Error adding early data extension: %v", err)
193 return nil, nil, AlertInternalError
194 }
195 }
196
197 // Signal supported PSK key exchange modes
198 if len(state.Config.PSKModes) == 0 {
199 logf(logTypeHandshake, "PSK selected, but no PSKModes")
200 return nil, nil, AlertInternalError
201 }
202
203 // Add the shim PSK extension to the ClientHello
204 logf(logTypeHandshake, "Adding PSK extension with id = %x", key.Identity)
205 psk = &PreSharedKeyExtension{
206 HandshakeType: HandshakeTypeClientHello,
207 Identities: []PSKIdentity{
208 {
209 Identity: key.Identity,
210 ObfuscatedTicketAge: uint32(time.Since(key.ReceivedAt)/time.Millisecond) + key.TicketAgeAdd,
211 },
212 },
213 Binders: []PSKBinderEntry{
214 // Note: Stub to get the length fields right
215 {Binder: bytes.Repeat([]byte{0x00}, params.Hash.Size())},
216 },
217 }
218 ch.Extensions.Add(psk)
219
220 // Compute the binder key
221 h0 := params.Hash.New().Sum(nil)
222 zero := bytes.Repeat([]byte{0}, params.Hash.Size())
223
224 earlyHash = params.Hash
225 earlySecret = HkdfExtract(params.Hash, zero, key.Key)
226 logf(logTypeCrypto, "early secret: [%d] %x", len(earlySecret), earlySecret)
227
228 binderLabel := labelExternalBinder
229 if key.IsResumption {
230 binderLabel = labelResumptionBinder
231 }
232 binderKey := deriveSecret(params, earlySecret, binderLabel, h0)
233 logf(logTypeCrypto, "binder key: [%d] %x", len(binderKey), binderKey)
234
235 // Compute the binder value
236 trunc, err := ch.Truncated()
237 if err != nil {
238 logf(logTypeHandshake, "[ClientStateStart] Error marshaling truncated ClientHello [%v]", err)
239 return nil, nil, AlertInternalError
240 }
241
242 truncHash := params.Hash.New()
243 truncHash.Write(trunc)
244
245 binder := computeFinishedData(params, binderKey, truncHash.Sum(nil))
246
247 // Replace the PSK extension
248 psk.Binders[0].Binder = binder
249 ch.Extensions.Add(psk)
250
251 // If we got here, the earlier marshal succeeded (in ch.Truncated()), so
252 // this one should too.
253 clientHello, _ = state.hsCtx.hOut.HandshakeMessageFromBody(ch)
254
255 // Compute early traffic keys
256 h := params.Hash.New()
257 h.Write(clientHello.Marshal())
258 chHash := h.Sum(nil)
259
260 earlyTrafficSecret := deriveSecret(params, earlySecret, labelEarlyTrafficSecret, chHash)
261 logf(logTypeCrypto, "early traffic secret: [%d] %x", len(earlyTrafficSecret), earlyTrafficSecret)
262 clientEarlyTrafficKeys = makeTrafficKeys(params, earlyTrafficSecret)
263 } else {
264 clientHello, err = state.hsCtx.hOut.HandshakeMessageFromBody(ch)
265 if err != nil {
266 logf(logTypeHandshake, "[ClientStateStart] Error marshaling ClientHello [%v]", err)
267 return nil, nil, AlertInternalError
268 }
269 }
270
271 logf(logTypeHandshake, "[ClientStateStart] -> [ClientStateWaitSH]")
272 state.hsCtx.SetVersion(tls12Version) // Everything after this should be 1.2.
273 nextState := clientStateWaitSH{
274 Config: state.Config,
275 Opts: state.Opts,
276 Params: state.Params,
277 hsCtx: state.hsCtx,
278 OfferedDH: offeredDH,
279 OfferedPSK: offeredPSK,
280
281 earlySecret: earlySecret,
282 earlyHash: earlyHash,
283
284 firstClientHello: state.firstClientHello,
285 helloRetryRequest: state.helloRetryRequest,
286 clientHello: clientHello,
287 }
288
289 toSend := []HandshakeAction{
290 QueueHandshakeMessage{clientHello},
291 SendQueuedHandshake{},
292 }
293 if state.Params.ClientSendingEarlyData {
294 toSend = append(toSend, []HandshakeAction{
295 RekeyOut{epoch: EpochEarlyData, KeySet: clientEarlyTrafficKeys},
296 }...)
297 }
298
299 return nextState, toSend, AlertNoAlert
300 }
301
302 type clientStateWaitSH struct {
303 Config *Config
304 Opts ConnectionOptions
305 Params ConnectionParameters
306 hsCtx *HandshakeContext
307 OfferedDH map[NamedGroup][]byte
308 OfferedPSK PreSharedKey
309 PSK []byte
310
311 earlySecret []byte
312 earlyHash crypto.Hash
313
314 firstClientHello *HandshakeMessage
315 helloRetryRequest *HandshakeMessage
316 clientHello *HandshakeMessage
317 }
318
319 var _ HandshakeState = &clientStateWaitSH{}
320
321 func (state clientStateWaitSH) State() State {
322 return StateClientWaitSH
323 }
324
325 func (state clientStateWaitSH) Next(hr handshakeMessageReader) (HandshakeState, []HandshakeAction, Alert) {
326 hm, alert := hr.ReadMessage()
327 if alert != AlertNoAlert {
328 return nil, nil, alert
329 }
330
331 if hm == nil || hm.msgType != HandshakeTypeServerHello {
332 logf(logTypeHandshake, "[ClientStateWaitSH] Unexpected message")
333 return nil, nil, AlertUnexpectedMessage
334 }
335
336 sh := &ServerHelloBody{}
337 if _, err := sh.Unmarshal(hm.body); err != nil {
338 logf(logTypeHandshake, "[ClientStateWaitSH] unexpected message")
339 return nil, nil, AlertUnexpectedMessage
340 }
341
342 // Common SH/HRR processing first.
343 // 1. Check that sh.version is TLS 1.2
344 if sh.Version != tls12Version {
345 logf(logTypeHandshake, "[ClientStateWaitSH] illegal legacy version [%v]", sh.Version)
346 return nil, nil, AlertIllegalParameter
347 }
348
349 // 2. Check that it responded with a valid version.
350 supportedVersions := SupportedVersionsExtension{HandshakeType: HandshakeTypeServerHello}
351 foundSupportedVersions, err := sh.Extensions.Find(&supportedVersions)
352 if err != nil {
353 logf(logTypeHandshake, "[ClientStateWaitSH] invalid supported_versions extension [%v]", err)
354 return nil, nil, AlertDecodeError
355 }
356 if !foundSupportedVersions {
357 logf(logTypeHandshake, "[ClientStateWaitSH] no supported_versions extension")
358 return nil, nil, AlertMissingExtension
359 }
360 if supportedVersions.Versions[0] != tls13Version {
361 logf(logTypeHandshake, "[ClientStateWaitSH] unsupported version [%x]", supportedVersions.Versions[0])
362 return nil, nil, AlertProtocolVersion
363 }
364 // 3. Check that the server provided a supported ciphersuite
365 supportedCipherSuite := false
366 for _, suite := range state.Config.CipherSuites {
367 supportedCipherSuite = supportedCipherSuite || (suite == sh.CipherSuite)
368 }
369 if !supportedCipherSuite {
370 logf(logTypeHandshake, "[ClientStateWaitSH] Unsupported ciphersuite [%04x]", sh.CipherSuite)
371 return nil, nil, AlertHandshakeFailure
372 }
373
374 // Now check for the sentinel.
375
376 if sh.Random == hrrRandomSentinel {
377 // This is actually HRR.
378 hrr := sh
379
380 // Narrow the supported ciphersuites to the server-provided one
381 state.Config.CipherSuites = []CipherSuite{hrr.CipherSuite}
382
383 // Handle external extensions.
384 if state.Config.ExtensionHandler != nil {
385 err := state.Config.ExtensionHandler.Receive(HandshakeTypeHelloRetryRequest, &hrr.Extensions)
386 if err != nil {
387 logf(logTypeHandshake, "[ClientWaitSH] Error running external extension handler [%v]", err)
388 return nil, nil, AlertInternalError
389 }
390 }
391
392 // The only thing we know how to respond to in an HRR is the Cookie
393 // extension, so if there is either no Cookie extension or anything other
394 // than a Cookie extension and SupportedVersions we have to fail.
395 serverCookie := new(CookieExtension)
396 foundCookie, err := hrr.Extensions.Find(serverCookie)
397 if err != nil {
398 logf(logTypeHandshake, "[ClientStateWaitSH] Invalid server cookie extension [%v]", err)
399 return nil, nil, AlertDecodeError
400 }
401 if !foundCookie || len(hrr.Extensions) != 2 {
402 logf(logTypeHandshake, "[ClientStateWaitSH] No Cookie or extra extensions [%v] [%d]", foundCookie, len(hrr.Extensions))
403 return nil, nil, AlertIllegalParameter
404 }
405
406 // Hash the body into a pseudo-message
407 // XXX: Ignoring some errors here
408 params := cipherSuiteMap[hrr.CipherSuite]
409 h := params.Hash.New()
410 h.Write(state.clientHello.Marshal())
411 firstClientHello := &HandshakeMessage{
412 msgType: HandshakeTypeMessageHash,
413 body: h.Sum(nil),
414 }
415
416 state.hsCtx.receivedEndOfFlight()
417
418 // TODO([email protected]): Need to rekey with cleartext if we are on 0-RTT
419 // mode. In DTLS, we also need to bump the sequence number.
420 // This is a pre-existing defect in Mint. Issue #175.
421 logf(logTypeHandshake, "[ClientStateWaitSH] -> [ClientStateStart]")
422 state.hsCtx.SetVersion(tls12Version) // Everything after this should be 1.2.
423 return clientStateStart{
424 Config: state.Config,
425 Opts: state.Opts,
426 hsCtx: state.hsCtx,
427 cookie: serverCookie.Cookie,
428 firstClientHello: firstClientHello,
429 helloRetryRequest: hm,
430 }, []HandshakeAction{ResetOut{1}}, AlertNoAlert
431 }
432
433 // This is SH.
434 // Handle external extensions.
435 if state.Config.ExtensionHandler != nil {
436 err := state.Config.ExtensionHandler.Receive(HandshakeTypeServerHello, &sh.Extensions)
437 if err != nil {
438 logf(logTypeHandshake, "[ClientWaitSH] Error running external extension handler [%v]", err)
439 return nil, nil, AlertInternalError
440 }
441 }
442
443 // Do PSK or key agreement depending on extensions
444 serverPSK := PreSharedKeyExtension{HandshakeType: HandshakeTypeServerHello}
445 serverKeyShare := KeyShareExtension{HandshakeType: HandshakeTypeServerHello}
446
447 foundExts, err := sh.Extensions.Parse(
448 []ExtensionBody{
449 &serverPSK,
450 &serverKeyShare,
451 })
452 if err != nil {
453 logf(logTypeHandshake, "[ClientWaitSH] Error processing extensions [%v]", err)
454 return nil, nil, AlertDecodeError
455 }
456
457 if foundExts[ExtensionTypePreSharedKey] && (serverPSK.SelectedIdentity == 0) {
458 state.Params.UsingPSK = true
459 }
460
461 var dhSecret []byte
462 if foundExts[ExtensionTypeKeyShare] {
463 sks := serverKeyShare.Shares[0]
464 priv, ok := state.OfferedDH[sks.Group]
465 if !ok {
466 logf(logTypeHandshake, "[ClientStateWaitSH] Key share for unknown group")
467 return nil, nil, AlertIllegalParameter
468 }
469
470 state.Params.UsingDH = true
471 dhSecret, _ = keyAgreement(sks.Group, sks.KeyExchange, priv)
472 }
473
474 suite := sh.CipherSuite
475 state.Params.CipherSuite = suite
476
477 params, ok := cipherSuiteMap[suite]
478 if !ok {
479 logf(logTypeCrypto, "Unsupported ciphersuite [%04x]", suite)
480 return nil, nil, AlertHandshakeFailure
481 }
482
483 // Start up the handshake hash
484 handshakeHash := params.Hash.New()
485 handshakeHash.Write(state.firstClientHello.Marshal())
486 handshakeHash.Write(state.helloRetryRequest.Marshal())
487 handshakeHash.Write(state.clientHello.Marshal())
488 handshakeHash.Write(hm.Marshal())
489
490 // Compute handshake secrets
491 zero := bytes.Repeat([]byte{0}, params.Hash.Size())
492
493 var earlySecret []byte
494 if state.Params.UsingPSK {
495 if params.Hash != state.earlyHash {
496 logf(logTypeCrypto, "Change of hash between early and normal init early=[%02x] suite=[%04x] hash=[%02x]",
497 state.earlyHash, suite, params.Hash)
498 }
499
500 earlySecret = state.earlySecret
501 } else {
502 earlySecret = HkdfExtract(params.Hash, zero, zero)
503 }
504
505 if dhSecret == nil {
506 dhSecret = zero
507 }
508
509 h0 := params.Hash.New().Sum(nil)
510 h2 := handshakeHash.Sum(nil)
511 preHandshakeSecret := deriveSecret(params, earlySecret, labelDerived, h0)
512 handshakeSecret := HkdfExtract(params.Hash, preHandshakeSecret, dhSecret)
513 clientHandshakeTrafficSecret := deriveSecret(params, handshakeSecret, labelClientHandshakeTrafficSecret, h2)
514 serverHandshakeTrafficSecret := deriveSecret(params, handshakeSecret, labelServerHandshakeTrafficSecret, h2)
515 preMasterSecret := deriveSecret(params, handshakeSecret, labelDerived, h0)
516 masterSecret := HkdfExtract(params.Hash, preMasterSecret, zero)
517
518 logf(logTypeCrypto, "early secret: [%d] %x", len(earlySecret), earlySecret)
519 logf(logTypeCrypto, "handshake secret: [%d] %x", len(handshakeSecret), handshakeSecret)
520 logf(logTypeCrypto, "client handshake traffic secret: [%d] %x", len(clientHandshakeTrafficSecret), clientHandshakeTrafficSecret)
521 logf(logTypeCrypto, "server handshake traffic secret: [%d] %x", len(serverHandshakeTrafficSecret), serverHandshakeTrafficSecret)
522 logf(logTypeCrypto, "master secret: [%d] %x", len(masterSecret), masterSecret)
523
524 serverHandshakeKeys := makeTrafficKeys(params, serverHandshakeTrafficSecret)
525 logf(logTypeHandshake, "[ClientStateWaitSH] -> [ClientStateWaitEE]")
526 nextState := clientStateWaitEE{
527 Config: state.Config,
528 Params: state.Params,
529 hsCtx: state.hsCtx,
530 cryptoParams: params,
531 handshakeHash: handshakeHash,
532 masterSecret: masterSecret,
533 clientHandshakeTrafficSecret: clientHandshakeTrafficSecret,
534 serverHandshakeTrafficSecret: serverHandshakeTrafficSecret,
535 }
536 toSend := []HandshakeAction{
537 RekeyIn{epoch: EpochHandshakeData, KeySet: serverHandshakeKeys},
538 }
539 // We're definitely not going to have to send anything with
540 // early data.
541 if !state.Params.ClientSendingEarlyData {
542 toSend = append(toSend, RekeyOut{epoch: EpochHandshakeData,
543 KeySet: makeTrafficKeys(params, clientHandshakeTrafficSecret)})
544 }
545
546 return nextState, toSend, AlertNoAlert
547 }
548
549 type clientStateWaitEE struct {
550 Config *Config
551 Params ConnectionParameters
552 hsCtx *HandshakeContext
553 cryptoParams CipherSuiteParams
554 handshakeHash hash.Hash
555 masterSecret []byte
556 clientHandshakeTrafficSecret []byte
557 serverHandshakeTrafficSecret []byte
558 }
559
560 var _ HandshakeState = &clientStateWaitEE{}
561
562 func (state clientStateWaitEE) State() State {
563 return StateClientWaitEE
564 }
565
566 func (state clientStateWaitEE) Next(hr handshakeMessageReader) (HandshakeState, []HandshakeAction, Alert) {
567 hm, alert := hr.ReadMessage()
568 if alert != AlertNoAlert {
569 return nil, nil, alert
570 }
571 if hm == nil || hm.msgType != HandshakeTypeEncryptedExtensions {
572 logf(logTypeHandshake, "[ClientStateWaitEE] Unexpected message")
573 return nil, nil, AlertUnexpectedMessage
574 }
575
576 ee := EncryptedExtensionsBody{}
577 if err := safeUnmarshal(&ee, hm.body); err != nil {
578 logf(logTypeHandshake, "[ClientStateWaitEE] Error decoding message: %v", err)
579 return nil, nil, AlertDecodeError
580 }
581
582 // Handle external extensions.
583 if state.Config.ExtensionHandler != nil {
584 err := state.Config.ExtensionHandler.Receive(HandshakeTypeEncryptedExtensions, &ee.Extensions)
585 if err != nil {
586 logf(logTypeHandshake, "[ClientWaitStateEE] Error running external extension handler [%v]", err)
587 return nil, nil, AlertInternalError
588 }
589 }
590
591 serverALPN := &ALPNExtension{}
592 serverEarlyData := &EarlyDataExtension{}
593
594 foundExts, err := ee.Extensions.Parse(
595 []ExtensionBody{
596 serverALPN,
597 serverEarlyData,
598 })
599 if err != nil {
600 logf(logTypeHandshake, "[ClientStateWaitEE] Error decoding extensions: %v", err)
601 return nil, nil, AlertDecodeError
602 }
603
604 state.Params.UsingEarlyData = foundExts[ExtensionTypeEarlyData]
605
606 if foundExts[ExtensionTypeALPN] && len(serverALPN.Protocols) > 0 {
607 state.Params.NextProto = serverALPN.Protocols[0]
608 }
609
610 state.handshakeHash.Write(hm.Marshal())
611
612 toSend := []HandshakeAction{}
613
614 if state.Params.ClientSendingEarlyData && !state.Params.UsingEarlyData {
615 // We didn't get 0-RTT, so rekey to handshake.
616 toSend = append(toSend, RekeyOut{epoch: EpochHandshakeData,
617 KeySet: makeTrafficKeys(state.cryptoParams, state.clientHandshakeTrafficSecret)})
618 }
619
620 if state.Params.UsingPSK {
621 logf(logTypeHandshake, "[ClientStateWaitEE] -> [ClientStateWaitFinished]")
622 nextState := clientStateWaitFinished{
623 Params: state.Params,
624 hsCtx: state.hsCtx,
625 cryptoParams: state.cryptoParams,
626 handshakeHash: state.handshakeHash,
627 certificates: state.Config.Certificates,
628 masterSecret: state.masterSecret,
629 clientHandshakeTrafficSecret: state.clientHandshakeTrafficSecret,
630 serverHandshakeTrafficSecret: state.serverHandshakeTrafficSecret,
631 }
632 return nextState, toSend, AlertNoAlert
633 }
634
635 logf(logTypeHandshake, "[ClientStateWaitEE] -> [ClientStateWaitCertCR]")
636 nextState := clientStateWaitCertCR{
637 Config: state.Config,
638 Params: state.Params,
639 hsCtx: state.hsCtx,
640 cryptoParams: state.cryptoParams,
641 handshakeHash: state.handshakeHash,
642 masterSecret: state.masterSecret,
643 clientHandshakeTrafficSecret: state.clientHandshakeTrafficSecret,
644 serverHandshakeTrafficSecret: state.serverHandshakeTrafficSecret,
645 }
646 return nextState, toSend, AlertNoAlert
647 }
648
649 type clientStateWaitCertCR struct {
650 Config *Config
651 Params ConnectionParameters
652 hsCtx *HandshakeContext
653 cryptoParams CipherSuiteParams
654 handshakeHash hash.Hash
655 masterSecret []byte
656 clientHandshakeTrafficSecret []byte
657 serverHandshakeTrafficSecret []byte
658 }
659
660 var _ HandshakeState = &clientStateWaitCertCR{}
661
662 func (state clientStateWaitCertCR) State() State {
663 return StateClientWaitCertCR
664 }
665
666 func (state clientStateWaitCertCR) Next(hr handshakeMessageReader) (HandshakeState, []HandshakeAction, Alert) {
667 hm, alert := hr.ReadMessage()
668 if alert != AlertNoAlert {
669 return nil, nil, alert
670 }
671 if hm == nil {
672 logf(logTypeHandshake, "[ClientStateWaitCertCR] Unexpected message")
673 return nil, nil, AlertUnexpectedMessage
674 }
675
676 bodyGeneric, err := hm.ToBody()
677 if err != nil {
678 logf(logTypeHandshake, "[ClientStateWaitCertCR] Error decoding message: %v", err)
679 return nil, nil, AlertDecodeError
680 }
681
682 state.handshakeHash.Write(hm.Marshal())
683
684 switch body := bodyGeneric.(type) {
685 case *CertificateBody:
686 logf(logTypeHandshake, "[ClientStateWaitCertCR] -> [ClientStateWaitCV]")
687 nextState := clientStateWaitCV{
688 Config: state.Config,
689 Params: state.Params,
690 hsCtx: state.hsCtx,
691 cryptoParams: state.cryptoParams,
692 handshakeHash: state.handshakeHash,
693 serverCertificate: body,
694 masterSecret: state.masterSecret,
695 clientHandshakeTrafficSecret: state.clientHandshakeTrafficSecret,
696 serverHandshakeTrafficSecret: state.serverHandshakeTrafficSecret,
697 }
698 return nextState, nil, AlertNoAlert
699
700 case *CertificateRequestBody:
701 // A certificate request in the handshake should have a zero-length context
702 if len(body.CertificateRequestContext) > 0 {
703 logf(logTypeHandshake, "[ClientStateWaitCertCR] Certificate request with non-empty context: %v", err)
704 return nil, nil, AlertIllegalParameter
705 }
706
707 state.Params.UsingClientAuth = true
708
709 logf(logTypeHandshake, "[ClientStateWaitCertCR] -> [ClientStateWaitCert]")
710 nextState := clientStateWaitCert{
711 Config: state.Config,
712 Params: state.Params,
713 hsCtx: state.hsCtx,
714 cryptoParams: state.cryptoParams,
715 handshakeHash: state.handshakeHash,
716 serverCertificateRequest: body,
717 masterSecret: state.masterSecret,
718 clientHandshakeTrafficSecret: state.clientHandshakeTrafficSecret,
719 serverHandshakeTrafficSecret: state.serverHandshakeTrafficSecret,
720 }
721 return nextState, nil, AlertNoAlert
722 }
723
724 return nil, nil, AlertUnexpectedMessage
725 }
726
727 type clientStateWaitCert struct {
728 Config *Config
729 Params ConnectionParameters
730 hsCtx *HandshakeContext
731 cryptoParams CipherSuiteParams
732 handshakeHash hash.Hash
733
734 serverCertificateRequest *CertificateRequestBody
735
736 masterSecret []byte
737 clientHandshakeTrafficSecret []byte
738 serverHandshakeTrafficSecret []byte
739 }
740
741 var _ HandshakeState = &clientStateWaitCert{}
742
743 func (state clientStateWaitCert) State() State {
744 return StateClientWaitCert
745 }
746
747 func (state clientStateWaitCert) Next(hr handshakeMessageReader) (HandshakeState, []HandshakeAction, Alert) {
748 hm, alert := hr.ReadMessage()
749 if alert != AlertNoAlert {
750 return nil, nil, alert
751 }
752 if hm == nil || hm.msgType != HandshakeTypeCertificate {
753 logf(logTypeHandshake, "[ClientStateWaitCert] Unexpected message")
754 return nil, nil, AlertUnexpectedMessage
755 }
756
757 cert := &CertificateBody{}
758 if err := safeUnmarshal(cert, hm.body); err != nil {
759 logf(logTypeHandshake, "[ClientStateWaitCert] Error decoding message: %v", err)
760 return nil, nil, AlertDecodeError
761 }
762
763 state.handshakeHash.Write(hm.Marshal())
764
765 logf(logTypeHandshake, "[ClientStateWaitCert] -> [ClientStateWaitCV]")
766 nextState := clientStateWaitCV{
767 Config: state.Config,
768 Params: state.Params,
769 hsCtx: state.hsCtx,
770 cryptoParams: state.cryptoParams,
771 handshakeHash: state.handshakeHash,
772 serverCertificate: cert,
773 serverCertificateRequest: state.serverCertificateRequest,
774 masterSecret: state.masterSecret,
775 clientHandshakeTrafficSecret: state.clientHandshakeTrafficSecret,
776 serverHandshakeTrafficSecret: state.serverHandshakeTrafficSecret,
777 }
778 return nextState, nil, AlertNoAlert
779 }
780
781 type clientStateWaitCV struct {
782 Config *Config
783 Params ConnectionParameters
784 hsCtx *HandshakeContext
785 cryptoParams CipherSuiteParams
786 handshakeHash hash.Hash
787
788 serverCertificate *CertificateBody
789 serverCertificateRequest *CertificateRequestBody
790
791 masterSecret []byte
792 clientHandshakeTrafficSecret []byte
793 serverHandshakeTrafficSecret []byte
794 }
795
796 var _ HandshakeState = &clientStateWaitCV{}
797
798 func (state clientStateWaitCV) State() State {
799 return StateClientWaitCV
800 }
801
802 func (state clientStateWaitCV) Next(hr handshakeMessageReader) (HandshakeState, []HandshakeAction, Alert) {
803 hm, alert := hr.ReadMessage()
804 if alert != AlertNoAlert {
805 return nil, nil, alert
806 }
807 if hm == nil || hm.msgType != HandshakeTypeCertificateVerify {
808 logf(logTypeHandshake, "[ClientStateWaitCV] Unexpected message")
809 return nil, nil, AlertUnexpectedMessage
810 }
811
812 certVerify := CertificateVerifyBody{}
813 if err := safeUnmarshal(&certVerify, hm.body); err != nil {
814 logf(logTypeHandshake, "[ClientStateWaitCV] Error decoding message: %v", err)
815 return nil, nil, AlertDecodeError
816 }
817
818 hcv := state.handshakeHash.Sum(nil)
819 logf(logTypeHandshake, "Handshake Hash to be verified: [%d] %x", len(hcv), hcv)
820
821 serverPublicKey := state.serverCertificate.CertificateList[0].CertData.PublicKey
822 if err := certVerify.Verify(serverPublicKey, hcv); err != nil {
823 logf(logTypeHandshake, "[ClientStateWaitCV] Server signature failed to verify")
824 return nil, nil, AlertHandshakeFailure
825 }
826
827 certs := make([]*x509.Certificate, len(state.serverCertificate.CertificateList))
828 rawCerts := make([][]byte, len(state.serverCertificate.CertificateList))
829 for i, certEntry := range state.serverCertificate.CertificateList {
830 certs[i] = certEntry.CertData
831 rawCerts[i] = certEntry.CertData.Raw
832 }
833
834 var verifiedChains [][]*x509.Certificate
835 if !state.Config.InsecureSkipVerify {
836 opts := x509.VerifyOptions{
837 Roots: state.Config.RootCAs,
838 CurrentTime: state.Config.time(),
839 DNSName: state.Config.ServerName,
840 Intermediates: x509.NewCertPool(),
841 }
842
843 for i, cert := range certs {
844 if i == 0 {
845 continue
846 }
847 opts.Intermediates.AddCert(cert)
848 }
849 var err error
850 verifiedChains, err = certs[0].Verify(opts)
851 if err != nil {
852 logf(logTypeHandshake, "[ClientStateWaitCV] Certificate verification failed: %s", err)
853 return nil, nil, AlertBadCertificate
854 }
855 }
856
857 if state.Config.VerifyPeerCertificate != nil {
858 if err := state.Config.VerifyPeerCertificate(rawCerts, verifiedChains); err != nil {
859 logf(logTypeHandshake, "[ClientStateWaitCV] Application rejected server certificate: %s", err)
860 return nil, nil, AlertBadCertificate
861 }
862 }
863
864 state.handshakeHash.Write(hm.Marshal())
865
866 logf(logTypeHandshake, "[ClientStateWaitCV] -> [ClientStateWaitFinished]")
867 nextState := clientStateWaitFinished{
868 Params: state.Params,
869 hsCtx: state.hsCtx,
870 cryptoParams: state.cryptoParams,
871 handshakeHash: state.handshakeHash,
872 certificates: state.Config.Certificates,
873 serverCertificateRequest: state.serverCertificateRequest,
874 masterSecret: state.masterSecret,
875 clientHandshakeTrafficSecret: state.clientHandshakeTrafficSecret,
876 serverHandshakeTrafficSecret: state.serverHandshakeTrafficSecret,
877 peerCertificates: certs,
878 verifiedChains: verifiedChains,
879 }
880 return nextState, nil, AlertNoAlert
881 }
882
883 type clientStateWaitFinished struct {
884 Params ConnectionParameters
885 hsCtx *HandshakeContext
886 cryptoParams CipherSuiteParams
887 handshakeHash hash.Hash
888
889 certificates []*Certificate
890 serverCertificateRequest *CertificateRequestBody
891 peerCertificates []*x509.Certificate
892 verifiedChains [][]*x509.Certificate
893
894 masterSecret []byte
895 clientHandshakeTrafficSecret []byte
896 serverHandshakeTrafficSecret []byte
897 }
898
899 var _ HandshakeState = &clientStateWaitFinished{}
900
901 func (state clientStateWaitFinished) State() State {
902 return StateClientWaitFinished
903 }
904
905 func (state clientStateWaitFinished) Next(hr handshakeMessageReader) (HandshakeState, []HandshakeAction, Alert) {
906 hm, alert := hr.ReadMessage()
907 if alert != AlertNoAlert {
908 return nil, nil, alert
909 }
910 if hm == nil || hm.msgType != HandshakeTypeFinished {
911 logf(logTypeHandshake, "[ClientStateWaitFinished] Unexpected message")
912 return nil, nil, AlertUnexpectedMessage
913 }
914
915 // Verify server's Finished
916 h3 := state.handshakeHash.Sum(nil)
917 logf(logTypeCrypto, "handshake hash 3 [%d] %x", len(h3), h3)
918 logf(logTypeCrypto, "handshake hash for server Finished: [%d] %x", len(h3), h3)
919
920 serverFinishedData := computeFinishedData(state.cryptoParams, state.serverHandshakeTrafficSecret, h3)
921 logf(logTypeCrypto, "server finished data: [%d] %x", len(serverFinishedData), serverFinishedData)
922
923 fin := &FinishedBody{VerifyDataLen: len(serverFinishedData)}
924 if err := safeUnmarshal(fin, hm.body); err != nil {
925 logf(logTypeHandshake, "[ClientStateWaitFinished] Error decoding message: %v", err)
926 return nil, nil, AlertDecodeError
927 }
928
929 if !bytes.Equal(fin.VerifyData, serverFinishedData) {
930 logf(logTypeHandshake, "[ClientStateWaitFinished] Server's Finished failed to verify [%x] != [%x]",
931 fin.VerifyData, serverFinishedData)
932 return nil, nil, AlertHandshakeFailure
933 }
934
935 // Update the handshake hash with the Finished
936 state.handshakeHash.Write(hm.Marshal())
937 logf(logTypeCrypto, "input to handshake hash [%d]: %x", len(hm.Marshal()), hm.Marshal())
938 h4 := state.handshakeHash.Sum(nil)
939 logf(logTypeCrypto, "handshake hash 4 [%d]: %x", len(h4), h4)
940
941 // Compute traffic secrets and keys
942 clientTrafficSecret := deriveSecret(state.cryptoParams, state.masterSecret, labelClientApplicationTrafficSecret, h4)
943 serverTrafficSecret := deriveSecret(state.cryptoParams, state.masterSecret, labelServerApplicationTrafficSecret, h4)
944 logf(logTypeCrypto, "client traffic secret: [%d] %x", len(clientTrafficSecret), clientTrafficSecret)
945 logf(logTypeCrypto, "server traffic secret: [%d] %x", len(serverTrafficSecret), serverTrafficSecret)
946
947 clientTrafficKeys := makeTrafficKeys(state.cryptoParams, clientTrafficSecret)
948 serverTrafficKeys := makeTrafficKeys(state.cryptoParams, serverTrafficSecret)
949
950 exporterSecret := deriveSecret(state.cryptoParams, state.masterSecret, labelExporterSecret, h4)
951 logf(logTypeCrypto, "client exporter secret: [%d] %x", len(exporterSecret), exporterSecret)
952
953 // Assemble client's second flight
954 toSend := []HandshakeAction{}
955
956 if state.Params.UsingEarlyData {
957 logf(logTypeHandshake, "Sending end of early data")
958 // Note: We only send EOED if the server is actually going to use the early
959 // data. Otherwise, it will never see it, and the transcripts will
960 // mismatch.
961 // EOED marshal is infallible
962 eoedm, _ := state.hsCtx.hOut.HandshakeMessageFromBody(&EndOfEarlyDataBody{})
963 toSend = append(toSend, QueueHandshakeMessage{eoedm})
964
965 state.handshakeHash.Write(eoedm.Marshal())
966 logf(logTypeCrypto, "input to handshake hash [%d]: %x", len(eoedm.Marshal()), eoedm.Marshal())
967
968 // And then rekey to handshake
969 toSend = append(toSend, RekeyOut{epoch: EpochHandshakeData,
970 KeySet: makeTrafficKeys(state.cryptoParams, state.clientHandshakeTrafficSecret)})
971 }
972
973 if state.Params.UsingClientAuth {
974 // Extract constraints from certicateRequest
975 schemes := SignatureAlgorithmsExtension{}
976 gotSchemes, err := state.serverCertificateRequest.Extensions.Find(&schemes)
977 if err != nil {
978 logf(logTypeHandshake, "[ClientStateWaitFinished] WARNING invalid signature_schemes extension [%v]", err)
979 return nil, nil, AlertDecodeError
980 }
981 if !gotSchemes {
982 logf(logTypeHandshake, "[ClientStateWaitFinished] WARNING no appropriate certificate found")
983 return nil, nil, AlertIllegalParameter
984 }
985
986 // Select a certificate
987 cert, certScheme, err := CertificateSelection(nil, schemes.Algorithms, state.certificates)
988 if err != nil {
989 // XXX: Signal this to the application layer?
990 logf(logTypeHandshake, "[ClientStateWaitFinished] WARNING no appropriate certificate found [%v]", err)
991
992 certificate := &CertificateBody{}
993 certm, err := state.hsCtx.hOut.HandshakeMessageFromBody(certificate)
994 if err != nil {
995 logf(logTypeHandshake, "[ClientStateWaitFinished] Error marshaling Certificate [%v]", err)
996 return nil, nil, AlertInternalError
997 }
998
999 toSend = append(toSend, QueueHandshakeMessage{certm})
1000 state.handshakeHash.Write(certm.Marshal())
1001 } else {
1002 // Create and send Certificate, CertificateVerify
1003 certificate := &CertificateBody{
1004 CertificateList: make([]CertificateEntry, len(cert.Chain)),
1005 }
1006 for i, entry := range cert.Chain {
1007 certificate.CertificateList[i] = CertificateEntry{CertData: entry}
1008 }
1009 certm, err := state.hsCtx.hOut.HandshakeMessageFromBody(certificate)
1010 if err != nil {
1011 logf(logTypeHandshake, "[ClientStateWaitFinished] Error marshaling Certificate [%v]", err)
1012 return nil, nil, AlertInternalError
1013 }
1014
1015 toSend = append(toSend, QueueHandshakeMessage{certm})
1016 state.handshakeHash.Write(certm.Marshal())
1017
1018 hcv := state.handshakeHash.Sum(nil)
1019 logf(logTypeHandshake, "Handshake Hash to be verified: [%d] %x", len(hcv), hcv)
1020
1021 certificateVerify := &CertificateVerifyBody{Algorithm: certScheme}
1022 logf(logTypeHandshake, "Creating CertVerify: %04x %v", certScheme, state.cryptoParams.Hash)
1023
1024 err = certificateVerify.Sign(cert.PrivateKey, hcv)
1025 if err != nil {
1026 logf(logTypeHandshake, "[ClientStateWaitFinished] Error signing CertificateVerify [%v]", err)
1027 return nil, nil, AlertInternalError
1028 }
1029 certvm, err := state.hsCtx.hOut.HandshakeMessageFromBody(certificateVerify)
1030 if err != nil {
1031 logf(logTypeHandshake, "[ClientStateWaitFinished] Error marshaling CertificateVerify [%v]", err)
1032 return nil, nil, AlertInternalError
1033 }
1034
1035 toSend = append(toSend, QueueHandshakeMessage{certvm})
1036 state.handshakeHash.Write(certvm.Marshal())
1037 }
1038 }
1039
1040 // Compute the client's Finished message
1041 h5 := state.handshakeHash.Sum(nil)
1042 logf(logTypeCrypto, "handshake hash for client Finished: [%d] %x", len(h5), h5)
1043
1044 clientFinishedData := computeFinishedData(state.cryptoParams, state.clientHandshakeTrafficSecret, h5)
1045 logf(logTypeCrypto, "client Finished data: [%d] %x", len(clientFinishedData), clientFinishedData)
1046
1047 fin = &FinishedBody{
1048 VerifyDataLen: len(clientFinishedData),
1049 VerifyData: clientFinishedData,
1050 }
1051 finm, err := state.hsCtx.hOut.HandshakeMessageFromBody(fin)
1052 if err != nil {
1053 logf(logTypeHandshake, "[ClientStateWaitFinished] Error marshaling client Finished [%v]", err)
1054 return nil, nil, AlertInternalError
1055 }
1056
1057 // Compute the resumption secret
1058 state.handshakeHash.Write(finm.Marshal())
1059 h6 := state.handshakeHash.Sum(nil)
1060
1061 resumptionSecret := deriveSecret(state.cryptoParams, state.masterSecret, labelResumptionSecret, h6)
1062 logf(logTypeCrypto, "resumption secret: [%d] %x", len(resumptionSecret), resumptionSecret)
1063
1064 toSend = append(toSend, []HandshakeAction{
1065 QueueHandshakeMessage{finm},
1066 SendQueuedHandshake{},
1067 RekeyIn{epoch: EpochApplicationData, KeySet: serverTrafficKeys},
1068 RekeyOut{epoch: EpochApplicationData, KeySet: clientTrafficKeys},
1069 }...)
1070
1071 state.hsCtx.receivedEndOfFlight()
1072
1073 logf(logTypeHandshake, "[ClientStateWaitFinished] -> [StateConnected]")
1074 nextState := stateConnected{
1075 Params: state.Params,
1076 hsCtx: state.hsCtx,
1077 isClient: true,
1078 cryptoParams: state.cryptoParams,
1079 resumptionSecret: resumptionSecret,
1080 clientTrafficSecret: clientTrafficSecret,
1081 serverTrafficSecret: serverTrafficSecret,
1082 exporterSecret: exporterSecret,
1083 peerCertificates: state.peerCertificates,
1084 verifiedChains: state.verifiedChains,
1085 }
1086 return nextState, toSend, AlertNoAlert
1087 }