Source file
src/crypto/tls/handshake_server_tls13.go
1
2
3
4
5 package tls
6
7 import (
8 "bytes"
9 "context"
10 "crypto"
11 "crypto/hmac"
12 "crypto/rsa"
13 "encoding/binary"
14 "errors"
15 "hash"
16 "io"
17 "sync/atomic"
18 "time"
19 )
20
21
22
23
24 const maxClientPSKIdentities = 5
25
26 type serverHandshakeStateTLS13 struct {
27 c *Conn
28 ctx context.Context
29 clientHello *clientHelloMsg
30 hello *serverHelloMsg
31 sentDummyCCS bool
32 usingPSK bool
33 suite *cipherSuiteTLS13
34 cert *Certificate
35 sigAlg SignatureScheme
36 earlySecret []byte
37 sharedKey []byte
38 handshakeSecret []byte
39 masterSecret []byte
40 trafficSecret []byte
41 transcript hash.Hash
42 clientFinished []byte
43 }
44
45 func (hs *serverHandshakeStateTLS13) handshake() error {
46 c := hs.c
47
48
49 if err := hs.processClientHello(); err != nil {
50 return err
51 }
52 if err := hs.checkForResumption(); err != nil {
53 return err
54 }
55 if err := hs.pickCertificate(); err != nil {
56 return err
57 }
58 c.buffering = true
59 if err := hs.sendServerParameters(); err != nil {
60 return err
61 }
62 if err := hs.sendServerCertificate(); err != nil {
63 return err
64 }
65 if err := hs.sendServerFinished(); err != nil {
66 return err
67 }
68
69
70
71 if _, err := c.flush(); err != nil {
72 return err
73 }
74 if err := hs.readClientCertificate(); err != nil {
75 return err
76 }
77 if err := hs.readClientFinished(); err != nil {
78 return err
79 }
80
81 atomic.StoreUint32(&c.handshakeStatus, 1)
82
83 return nil
84 }
85
86 func (hs *serverHandshakeStateTLS13) processClientHello() error {
87 c := hs.c
88
89 hs.hello = new(serverHelloMsg)
90
91
92
93 hs.hello.vers = VersionTLS12
94 hs.hello.supportedVersion = c.vers
95
96 if len(hs.clientHello.supportedVersions) == 0 {
97 c.sendAlert(alertIllegalParameter)
98 return errors.New("tls: client used the legacy version field to negotiate TLS 1.3")
99 }
100
101
102
103
104
105
106
107
108
109
110 for _, id := range hs.clientHello.cipherSuites {
111 if id == TLS_FALLBACK_SCSV {
112
113
114 if c.vers < c.config.maxSupportedVersion() {
115 c.sendAlert(alertInappropriateFallback)
116 return errors.New("tls: client using inappropriate protocol fallback")
117 }
118 break
119 }
120 }
121
122 if len(hs.clientHello.compressionMethods) != 1 ||
123 hs.clientHello.compressionMethods[0] != compressionNone {
124 c.sendAlert(alertIllegalParameter)
125 return errors.New("tls: TLS 1.3 client supports illegal compression methods")
126 }
127
128 hs.hello.random = make([]byte, 32)
129 if _, err := io.ReadFull(c.config.rand(), hs.hello.random); err != nil {
130 c.sendAlert(alertInternalError)
131 return err
132 }
133
134 if len(hs.clientHello.secureRenegotiation) != 0 {
135 c.sendAlert(alertHandshakeFailure)
136 return errors.New("tls: initial handshake had non-empty renegotiation extension")
137 }
138
139 if hs.clientHello.earlyData {
140
141
142
143
144
145
146 c.sendAlert(alertUnsupportedExtension)
147 return errors.New("tls: client sent unexpected early data")
148 }
149
150 hs.hello.sessionId = hs.clientHello.sessionId
151 hs.hello.compressionMethod = compressionNone
152
153 preferenceList := defaultCipherSuitesTLS13
154 if !hasAESGCMHardwareSupport || !aesgcmPreferred(hs.clientHello.cipherSuites) {
155 preferenceList = defaultCipherSuitesTLS13NoAES
156 }
157 for _, suiteID := range preferenceList {
158 hs.suite = mutualCipherSuiteTLS13(hs.clientHello.cipherSuites, suiteID)
159 if hs.suite != nil {
160 break
161 }
162 }
163 if hs.suite == nil {
164 c.sendAlert(alertHandshakeFailure)
165 return errors.New("tls: no cipher suite supported by both client and server")
166 }
167 c.cipherSuite = hs.suite.id
168 hs.hello.cipherSuite = hs.suite.id
169 hs.transcript = hs.suite.hash.New()
170
171
172
173 var selectedGroup CurveID
174 var clientKeyShare *keyShare
175 GroupSelection:
176 for _, preferredGroup := range c.config.curvePreferences() {
177 for _, ks := range hs.clientHello.keyShares {
178 if ks.group == preferredGroup {
179 selectedGroup = ks.group
180 clientKeyShare = &ks
181 break GroupSelection
182 }
183 }
184 if selectedGroup != 0 {
185 continue
186 }
187 for _, group := range hs.clientHello.supportedCurves {
188 if group == preferredGroup {
189 selectedGroup = group
190 break
191 }
192 }
193 }
194 if selectedGroup == 0 {
195 c.sendAlert(alertHandshakeFailure)
196 return errors.New("tls: no ECDHE curve supported by both client and server")
197 }
198 if clientKeyShare == nil {
199 if err := hs.doHelloRetryRequest(selectedGroup); err != nil {
200 return err
201 }
202 clientKeyShare = &hs.clientHello.keyShares[0]
203 }
204
205 if _, ok := curveForCurveID(selectedGroup); selectedGroup != X25519 && !ok {
206 c.sendAlert(alertInternalError)
207 return errors.New("tls: CurvePreferences includes unsupported curve")
208 }
209 params, err := generateECDHEParameters(c.config.rand(), selectedGroup)
210 if err != nil {
211 c.sendAlert(alertInternalError)
212 return err
213 }
214 hs.hello.serverShare = keyShare{group: selectedGroup, data: params.PublicKey()}
215 hs.sharedKey = params.SharedKey(clientKeyShare.data)
216 if hs.sharedKey == nil {
217 c.sendAlert(alertIllegalParameter)
218 return errors.New("tls: invalid client key share")
219 }
220
221 c.serverName = hs.clientHello.serverName
222 return nil
223 }
224
225 func (hs *serverHandshakeStateTLS13) checkForResumption() error {
226 c := hs.c
227
228 if c.config.SessionTicketsDisabled {
229 return nil
230 }
231
232 modeOK := false
233 for _, mode := range hs.clientHello.pskModes {
234 if mode == pskModeDHE {
235 modeOK = true
236 break
237 }
238 }
239 if !modeOK {
240 return nil
241 }
242
243 if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) {
244 c.sendAlert(alertIllegalParameter)
245 return errors.New("tls: invalid or missing PSK binders")
246 }
247 if len(hs.clientHello.pskIdentities) == 0 {
248 return nil
249 }
250
251 for i, identity := range hs.clientHello.pskIdentities {
252 if i >= maxClientPSKIdentities {
253 break
254 }
255
256 plaintext, _ := c.decryptTicket(identity.label)
257 if plaintext == nil {
258 continue
259 }
260 sessionState := new(sessionStateTLS13)
261 if ok := sessionState.unmarshal(plaintext); !ok {
262 continue
263 }
264
265 createdAt := time.Unix(int64(sessionState.createdAt), 0)
266 if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
267 continue
268 }
269
270
271
272
273
274 pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite)
275 if pskSuite == nil || pskSuite.hash != hs.suite.hash {
276 continue
277 }
278
279
280
281
282 sessionHasClientCerts := len(sessionState.certificate.Certificate) != 0
283 needClientCerts := requiresClientCert(c.config.ClientAuth)
284 if needClientCerts && !sessionHasClientCerts {
285 continue
286 }
287 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
288 continue
289 }
290
291 psk := hs.suite.expandLabel(sessionState.resumptionSecret, "resumption",
292 nil, hs.suite.hash.Size())
293 hs.earlySecret = hs.suite.extract(psk, nil)
294 binderKey := hs.suite.deriveSecret(hs.earlySecret, resumptionBinderLabel, nil)
295
296 transcript := cloneHash(hs.transcript, hs.suite.hash)
297 if transcript == nil {
298 c.sendAlert(alertInternalError)
299 return errors.New("tls: internal error: failed to clone hash")
300 }
301 transcript.Write(hs.clientHello.marshalWithoutBinders())
302 pskBinder := hs.suite.finishedHash(binderKey, transcript)
303 if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) {
304 c.sendAlert(alertDecryptError)
305 return errors.New("tls: invalid PSK binder")
306 }
307
308 c.didResume = true
309 if err := c.processCertsFromClient(sessionState.certificate); err != nil {
310 return err
311 }
312
313 hs.hello.selectedIdentityPresent = true
314 hs.hello.selectedIdentity = uint16(i)
315 hs.usingPSK = true
316 return nil
317 }
318
319 return nil
320 }
321
322
323
324
325 func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash {
326
327 type binaryMarshaler interface {
328 MarshalBinary() (data []byte, err error)
329 UnmarshalBinary(data []byte) error
330 }
331 marshaler, ok := in.(binaryMarshaler)
332 if !ok {
333 return nil
334 }
335 state, err := marshaler.MarshalBinary()
336 if err != nil {
337 return nil
338 }
339 out := h.New()
340 unmarshaler, ok := out.(binaryMarshaler)
341 if !ok {
342 return nil
343 }
344 if err := unmarshaler.UnmarshalBinary(state); err != nil {
345 return nil
346 }
347 return out
348 }
349
350 func (hs *serverHandshakeStateTLS13) pickCertificate() error {
351 c := hs.c
352
353
354 if hs.usingPSK {
355 return nil
356 }
357
358
359 if len(hs.clientHello.supportedSignatureAlgorithms) == 0 {
360 return c.sendAlert(alertMissingExtension)
361 }
362
363 certificate, err := c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello))
364 if err != nil {
365 if err == errNoCertificates {
366 c.sendAlert(alertUnrecognizedName)
367 } else {
368 c.sendAlert(alertInternalError)
369 }
370 return err
371 }
372 hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms)
373 if err != nil {
374
375
376 c.sendAlert(alertHandshakeFailure)
377 return err
378 }
379 hs.cert = certificate
380
381 return nil
382 }
383
384
385
386 func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
387 if hs.sentDummyCCS {
388 return nil
389 }
390 hs.sentDummyCCS = true
391
392 _, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
393 return err
394 }
395
396 func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) error {
397 c := hs.c
398
399
400
401 hs.transcript.Write(hs.clientHello.marshal())
402 chHash := hs.transcript.Sum(nil)
403 hs.transcript.Reset()
404 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
405 hs.transcript.Write(chHash)
406
407 helloRetryRequest := &serverHelloMsg{
408 vers: hs.hello.vers,
409 random: helloRetryRequestRandom,
410 sessionId: hs.hello.sessionId,
411 cipherSuite: hs.hello.cipherSuite,
412 compressionMethod: hs.hello.compressionMethod,
413 supportedVersion: hs.hello.supportedVersion,
414 selectedGroup: selectedGroup,
415 }
416
417 hs.transcript.Write(helloRetryRequest.marshal())
418 if _, err := c.writeRecord(recordTypeHandshake, helloRetryRequest.marshal()); err != nil {
419 return err
420 }
421
422 if err := hs.sendDummyChangeCipherSpec(); err != nil {
423 return err
424 }
425
426 msg, err := c.readHandshake()
427 if err != nil {
428 return err
429 }
430
431 clientHello, ok := msg.(*clientHelloMsg)
432 if !ok {
433 c.sendAlert(alertUnexpectedMessage)
434 return unexpectedMessageError(clientHello, msg)
435 }
436
437 if len(clientHello.keyShares) != 1 || clientHello.keyShares[0].group != selectedGroup {
438 c.sendAlert(alertIllegalParameter)
439 return errors.New("tls: client sent invalid key share in second ClientHello")
440 }
441
442 if clientHello.earlyData {
443 c.sendAlert(alertIllegalParameter)
444 return errors.New("tls: client indicated early data in second ClientHello")
445 }
446
447 if illegalClientHelloChange(clientHello, hs.clientHello) {
448 c.sendAlert(alertIllegalParameter)
449 return errors.New("tls: client illegally modified second ClientHello")
450 }
451
452 hs.clientHello = clientHello
453 return nil
454 }
455
456
457
458
459 func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool {
460 if len(ch.supportedVersions) != len(ch1.supportedVersions) ||
461 len(ch.cipherSuites) != len(ch1.cipherSuites) ||
462 len(ch.supportedCurves) != len(ch1.supportedCurves) ||
463 len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) ||
464 len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) ||
465 len(ch.alpnProtocols) != len(ch1.alpnProtocols) {
466 return true
467 }
468 for i := range ch.supportedVersions {
469 if ch.supportedVersions[i] != ch1.supportedVersions[i] {
470 return true
471 }
472 }
473 for i := range ch.cipherSuites {
474 if ch.cipherSuites[i] != ch1.cipherSuites[i] {
475 return true
476 }
477 }
478 for i := range ch.supportedCurves {
479 if ch.supportedCurves[i] != ch1.supportedCurves[i] {
480 return true
481 }
482 }
483 for i := range ch.supportedSignatureAlgorithms {
484 if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] {
485 return true
486 }
487 }
488 for i := range ch.supportedSignatureAlgorithmsCert {
489 if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] {
490 return true
491 }
492 }
493 for i := range ch.alpnProtocols {
494 if ch.alpnProtocols[i] != ch1.alpnProtocols[i] {
495 return true
496 }
497 }
498 return ch.vers != ch1.vers ||
499 !bytes.Equal(ch.random, ch1.random) ||
500 !bytes.Equal(ch.sessionId, ch1.sessionId) ||
501 !bytes.Equal(ch.compressionMethods, ch1.compressionMethods) ||
502 ch.serverName != ch1.serverName ||
503 ch.ocspStapling != ch1.ocspStapling ||
504 !bytes.Equal(ch.supportedPoints, ch1.supportedPoints) ||
505 ch.ticketSupported != ch1.ticketSupported ||
506 !bytes.Equal(ch.sessionTicket, ch1.sessionTicket) ||
507 ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported ||
508 !bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) ||
509 ch.scts != ch1.scts ||
510 !bytes.Equal(ch.cookie, ch1.cookie) ||
511 !bytes.Equal(ch.pskModes, ch1.pskModes)
512 }
513
514 func (hs *serverHandshakeStateTLS13) sendServerParameters() error {
515 c := hs.c
516
517 hs.transcript.Write(hs.clientHello.marshal())
518 hs.transcript.Write(hs.hello.marshal())
519 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
520 return err
521 }
522
523 if err := hs.sendDummyChangeCipherSpec(); err != nil {
524 return err
525 }
526
527 earlySecret := hs.earlySecret
528 if earlySecret == nil {
529 earlySecret = hs.suite.extract(nil, nil)
530 }
531 hs.handshakeSecret = hs.suite.extract(hs.sharedKey,
532 hs.suite.deriveSecret(earlySecret, "derived", nil))
533
534 clientSecret := hs.suite.deriveSecret(hs.handshakeSecret,
535 clientHandshakeTrafficLabel, hs.transcript)
536 c.in.setTrafficSecret(hs.suite, clientSecret)
537 serverSecret := hs.suite.deriveSecret(hs.handshakeSecret,
538 serverHandshakeTrafficLabel, hs.transcript)
539 c.out.setTrafficSecret(hs.suite, serverSecret)
540
541 err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret)
542 if err != nil {
543 c.sendAlert(alertInternalError)
544 return err
545 }
546 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret)
547 if err != nil {
548 c.sendAlert(alertInternalError)
549 return err
550 }
551
552 encryptedExtensions := new(encryptedExtensionsMsg)
553
554 selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols)
555 if err != nil {
556 c.sendAlert(alertNoApplicationProtocol)
557 return err
558 }
559 encryptedExtensions.alpnProtocol = selectedProto
560 c.clientProtocol = selectedProto
561
562 hs.transcript.Write(encryptedExtensions.marshal())
563 if _, err := c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()); err != nil {
564 return err
565 }
566
567 return nil
568 }
569
570 func (hs *serverHandshakeStateTLS13) requestClientCert() bool {
571 return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK
572 }
573
574 func (hs *serverHandshakeStateTLS13) sendServerCertificate() error {
575 c := hs.c
576
577
578 if hs.usingPSK {
579 return nil
580 }
581
582 if hs.requestClientCert() {
583
584 certReq := new(certificateRequestMsgTLS13)
585 certReq.ocspStapling = true
586 certReq.scts = true
587 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms
588 if c.config.ClientCAs != nil {
589 certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
590 }
591
592 hs.transcript.Write(certReq.marshal())
593 if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
594 return err
595 }
596 }
597
598 certMsg := new(certificateMsgTLS13)
599
600 certMsg.certificate = *hs.cert
601 certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0
602 certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0
603
604 hs.transcript.Write(certMsg.marshal())
605 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
606 return err
607 }
608
609 certVerifyMsg := new(certificateVerifyMsg)
610 certVerifyMsg.hasSignatureAlgorithm = true
611 certVerifyMsg.signatureAlgorithm = hs.sigAlg
612
613 sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg)
614 if err != nil {
615 return c.sendAlert(alertInternalError)
616 }
617
618 signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
619 signOpts := crypto.SignerOpts(sigHash)
620 if sigType == signatureRSAPSS {
621 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
622 }
623 sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
624 if err != nil {
625 public := hs.cert.PrivateKey.(crypto.Signer).Public()
626 if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS &&
627 rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 {
628 c.sendAlert(alertHandshakeFailure)
629 } else {
630 c.sendAlert(alertInternalError)
631 }
632 return errors.New("tls: failed to sign handshake: " + err.Error())
633 }
634 certVerifyMsg.signature = sig
635
636 hs.transcript.Write(certVerifyMsg.marshal())
637 if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil {
638 return err
639 }
640
641 return nil
642 }
643
644 func (hs *serverHandshakeStateTLS13) sendServerFinished() error {
645 c := hs.c
646
647 finished := &finishedMsg{
648 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
649 }
650
651 hs.transcript.Write(finished.marshal())
652 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
653 return err
654 }
655
656
657
658 hs.masterSecret = hs.suite.extract(nil,
659 hs.suite.deriveSecret(hs.handshakeSecret, "derived", nil))
660
661 hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
662 clientApplicationTrafficLabel, hs.transcript)
663 serverSecret := hs.suite.deriveSecret(hs.masterSecret,
664 serverApplicationTrafficLabel, hs.transcript)
665 c.out.setTrafficSecret(hs.suite, serverSecret)
666
667 err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret)
668 if err != nil {
669 c.sendAlert(alertInternalError)
670 return err
671 }
672 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret)
673 if err != nil {
674 c.sendAlert(alertInternalError)
675 return err
676 }
677
678 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
679
680
681
682
683 if !hs.requestClientCert() {
684 if err := hs.sendSessionTickets(); err != nil {
685 return err
686 }
687 }
688
689 return nil
690 }
691
692 func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool {
693 if hs.c.config.SessionTicketsDisabled {
694 return false
695 }
696
697
698 for _, pskMode := range hs.clientHello.pskModes {
699 if pskMode == pskModeDHE {
700 return true
701 }
702 }
703 return false
704 }
705
706 func (hs *serverHandshakeStateTLS13) sendSessionTickets() error {
707 c := hs.c
708
709 hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
710 finishedMsg := &finishedMsg{
711 verifyData: hs.clientFinished,
712 }
713 hs.transcript.Write(finishedMsg.marshal())
714
715 if !hs.shouldSendSessionTickets() {
716 return nil
717 }
718
719 resumptionSecret := hs.suite.deriveSecret(hs.masterSecret,
720 resumptionLabel, hs.transcript)
721
722 m := new(newSessionTicketMsgTLS13)
723
724 var certsFromClient [][]byte
725 for _, cert := range c.peerCertificates {
726 certsFromClient = append(certsFromClient, cert.Raw)
727 }
728 state := sessionStateTLS13{
729 cipherSuite: hs.suite.id,
730 createdAt: uint64(c.config.time().Unix()),
731 resumptionSecret: resumptionSecret,
732 certificate: Certificate{
733 Certificate: certsFromClient,
734 OCSPStaple: c.ocspResponse,
735 SignedCertificateTimestamps: c.scts,
736 },
737 }
738 var err error
739 m.label, err = c.encryptTicket(state.marshal())
740 if err != nil {
741 return err
742 }
743 m.lifetime = uint32(maxSessionTicketLifetime / time.Second)
744
745
746
747
748 ageAdd := make([]byte, 4)
749 _, err = hs.c.config.rand().Read(ageAdd)
750 if err != nil {
751 return err
752 }
753 m.ageAdd = binary.LittleEndian.Uint32(ageAdd)
754
755
756
757
758 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
759 return err
760 }
761
762 return nil
763 }
764
765 func (hs *serverHandshakeStateTLS13) readClientCertificate() error {
766 c := hs.c
767
768 if !hs.requestClientCert() {
769
770
771 if c.config.VerifyConnection != nil {
772 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
773 c.sendAlert(alertBadCertificate)
774 return err
775 }
776 }
777 return nil
778 }
779
780
781
782
783 msg, err := c.readHandshake()
784 if err != nil {
785 return err
786 }
787
788 certMsg, ok := msg.(*certificateMsgTLS13)
789 if !ok {
790 c.sendAlert(alertUnexpectedMessage)
791 return unexpectedMessageError(certMsg, msg)
792 }
793 hs.transcript.Write(certMsg.marshal())
794
795 if err := c.processCertsFromClient(certMsg.certificate); err != nil {
796 return err
797 }
798
799 if c.config.VerifyConnection != nil {
800 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
801 c.sendAlert(alertBadCertificate)
802 return err
803 }
804 }
805
806 if len(certMsg.certificate.Certificate) != 0 {
807 msg, err = c.readHandshake()
808 if err != nil {
809 return err
810 }
811
812 certVerify, ok := msg.(*certificateVerifyMsg)
813 if !ok {
814 c.sendAlert(alertUnexpectedMessage)
815 return unexpectedMessageError(certVerify, msg)
816 }
817
818
819 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms) {
820 c.sendAlert(alertIllegalParameter)
821 return errors.New("tls: client certificate used with invalid signature algorithm")
822 }
823 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
824 if err != nil {
825 return c.sendAlert(alertInternalError)
826 }
827 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
828 c.sendAlert(alertIllegalParameter)
829 return errors.New("tls: client certificate used with invalid signature algorithm")
830 }
831 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
832 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
833 sigHash, signed, certVerify.signature); err != nil {
834 c.sendAlert(alertDecryptError)
835 return errors.New("tls: invalid signature by the client certificate: " + err.Error())
836 }
837
838 hs.transcript.Write(certVerify.marshal())
839 }
840
841
842
843 if err := hs.sendSessionTickets(); err != nil {
844 return err
845 }
846
847 return nil
848 }
849
850 func (hs *serverHandshakeStateTLS13) readClientFinished() error {
851 c := hs.c
852
853 msg, err := c.readHandshake()
854 if err != nil {
855 return err
856 }
857
858 finished, ok := msg.(*finishedMsg)
859 if !ok {
860 c.sendAlert(alertUnexpectedMessage)
861 return unexpectedMessageError(finished, msg)
862 }
863
864 if !hmac.Equal(hs.clientFinished, finished.verifyData) {
865 c.sendAlert(alertDecryptError)
866 return errors.New("tls: invalid client finished hash")
867 }
868
869 c.in.setTrafficSecret(hs.suite, hs.trafficSecret)
870
871 return nil
872 }
873
View as plain text