Source file
src/crypto/tls/handshake_server_tls13.go
1
2
3
4
5 package tls
6
7 import (
8 "bytes"
9 "crypto"
10 "crypto/hmac"
11 "crypto/rsa"
12 "errors"
13 "hash"
14 "io"
15 "sync/atomic"
16 "time"
17 )
18
19
20
21
22 const maxClientPSKIdentities = 5
23
24 type serverHandshakeStateTLS13 struct {
25 c *Conn
26 clientHello *clientHelloMsg
27 hello *serverHelloMsg
28 sentDummyCCS bool
29 usingPSK bool
30 suite *cipherSuiteTLS13
31 cert *Certificate
32 sigAlg SignatureScheme
33 earlySecret []byte
34 sharedKey []byte
35 handshakeSecret []byte
36 masterSecret []byte
37 trafficSecret []byte
38 transcript hash.Hash
39 clientFinished []byte
40 }
41
42 func (hs *serverHandshakeStateTLS13) handshake() error {
43 c := hs.c
44
45
46 if err := hs.processClientHello(); err != nil {
47 return err
48 }
49 if err := hs.checkForResumption(); err != nil {
50 return err
51 }
52 if err := hs.pickCertificate(); err != nil {
53 return err
54 }
55 c.buffering = true
56 if err := hs.sendServerParameters(); err != nil {
57 return err
58 }
59 if err := hs.sendServerCertificate(); err != nil {
60 return err
61 }
62 if err := hs.sendServerFinished(); err != nil {
63 return err
64 }
65
66
67
68 if _, err := c.flush(); err != nil {
69 return err
70 }
71 if err := hs.readClientCertificate(); err != nil {
72 return err
73 }
74 if err := hs.readClientFinished(); err != nil {
75 return err
76 }
77
78 atomic.StoreUint32(&c.handshakeStatus, 1)
79
80 return nil
81 }
82
83 func (hs *serverHandshakeStateTLS13) processClientHello() error {
84 c := hs.c
85
86 hs.hello = new(serverHelloMsg)
87
88
89
90 hs.hello.vers = VersionTLS12
91 hs.hello.supportedVersion = c.vers
92
93 if len(hs.clientHello.supportedVersions) == 0 {
94 c.sendAlert(alertIllegalParameter)
95 return errors.New("tls: client used the legacy version field to negotiate TLS 1.3")
96 }
97
98
99
100
101
102
103
104
105
106
107 for _, id := range hs.clientHello.cipherSuites {
108 if id == TLS_FALLBACK_SCSV {
109
110
111 if c.vers < c.config.maxSupportedVersion() {
112 c.sendAlert(alertInappropriateFallback)
113 return errors.New("tls: client using inappropriate protocol fallback")
114 }
115 break
116 }
117 }
118
119 if len(hs.clientHello.compressionMethods) != 1 ||
120 hs.clientHello.compressionMethods[0] != compressionNone {
121 c.sendAlert(alertIllegalParameter)
122 return errors.New("tls: TLS 1.3 client supports illegal compression methods")
123 }
124
125 hs.hello.random = make([]byte, 32)
126 if _, err := io.ReadFull(c.config.rand(), hs.hello.random); err != nil {
127 c.sendAlert(alertInternalError)
128 return err
129 }
130
131 if len(hs.clientHello.secureRenegotiation) != 0 {
132 c.sendAlert(alertHandshakeFailure)
133 return errors.New("tls: initial handshake had non-empty renegotiation extension")
134 }
135
136 if hs.clientHello.earlyData {
137
138
139
140
141
142
143 c.sendAlert(alertUnsupportedExtension)
144 return errors.New("tls: client sent unexpected early data")
145 }
146
147 hs.hello.sessionId = hs.clientHello.sessionId
148 hs.hello.compressionMethod = compressionNone
149
150 var preferenceList, supportedList []uint16
151 if c.config.PreferServerCipherSuites {
152 preferenceList = defaultCipherSuitesTLS13()
153 supportedList = hs.clientHello.cipherSuites
154 } else {
155 preferenceList = hs.clientHello.cipherSuites
156 supportedList = defaultCipherSuitesTLS13()
157 }
158 for _, suiteID := range preferenceList {
159 hs.suite = mutualCipherSuiteTLS13(supportedList, suiteID)
160 if hs.suite != nil {
161 break
162 }
163 }
164 if hs.suite == nil {
165 c.sendAlert(alertHandshakeFailure)
166 return errors.New("tls: no cipher suite supported by both client and server")
167 }
168 c.cipherSuite = hs.suite.id
169 hs.hello.cipherSuite = hs.suite.id
170 hs.transcript = hs.suite.hash.New()
171
172
173
174 var selectedGroup CurveID
175 var clientKeyShare *keyShare
176 GroupSelection:
177 for _, preferredGroup := range c.config.curvePreferences() {
178 for _, ks := range hs.clientHello.keyShares {
179 if ks.group == preferredGroup {
180 selectedGroup = ks.group
181 clientKeyShare = &ks
182 break GroupSelection
183 }
184 }
185 if selectedGroup != 0 {
186 continue
187 }
188 for _, group := range hs.clientHello.supportedCurves {
189 if group == preferredGroup {
190 selectedGroup = group
191 break
192 }
193 }
194 }
195 if selectedGroup == 0 {
196 c.sendAlert(alertHandshakeFailure)
197 return errors.New("tls: no ECDHE curve supported by both client and server")
198 }
199 if clientKeyShare == nil {
200 if err := hs.doHelloRetryRequest(selectedGroup); err != nil {
201 return err
202 }
203 clientKeyShare = &hs.clientHello.keyShares[0]
204 }
205
206 if _, ok := curveForCurveID(selectedGroup); selectedGroup != X25519 && !ok {
207 c.sendAlert(alertInternalError)
208 return errors.New("tls: CurvePreferences includes unsupported curve")
209 }
210 params, err := generateECDHEParameters(c.config.rand(), selectedGroup)
211 if err != nil {
212 c.sendAlert(alertInternalError)
213 return err
214 }
215 hs.hello.serverShare = keyShare{group: selectedGroup, data: params.PublicKey()}
216 hs.sharedKey = params.SharedKey(clientKeyShare.data)
217 if hs.sharedKey == nil {
218 c.sendAlert(alertIllegalParameter)
219 return errors.New("tls: invalid client key share")
220 }
221
222 c.serverName = hs.clientHello.serverName
223 return nil
224 }
225
226 func (hs *serverHandshakeStateTLS13) checkForResumption() error {
227 c := hs.c
228
229 if c.config.SessionTicketsDisabled {
230 return nil
231 }
232
233 modeOK := false
234 for _, mode := range hs.clientHello.pskModes {
235 if mode == pskModeDHE {
236 modeOK = true
237 break
238 }
239 }
240 if !modeOK {
241 return nil
242 }
243
244 if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) {
245 c.sendAlert(alertIllegalParameter)
246 return errors.New("tls: invalid or missing PSK binders")
247 }
248 if len(hs.clientHello.pskIdentities) == 0 {
249 return nil
250 }
251
252 for i, identity := range hs.clientHello.pskIdentities {
253 if i >= maxClientPSKIdentities {
254 break
255 }
256
257 plaintext, _ := c.decryptTicket(identity.label)
258 if plaintext == nil {
259 continue
260 }
261 sessionState := new(sessionStateTLS13)
262 if ok := sessionState.unmarshal(plaintext); !ok {
263 continue
264 }
265
266 createdAt := time.Unix(int64(sessionState.createdAt), 0)
267 if c.config.time().Sub(createdAt) > maxSessionTicketLifetime {
268 continue
269 }
270
271
272
273
274
275 pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite)
276 if pskSuite == nil || pskSuite.hash != hs.suite.hash {
277 continue
278 }
279
280
281
282
283 sessionHasClientCerts := len(sessionState.certificate.Certificate) != 0
284 needClientCerts := requiresClientCert(c.config.ClientAuth)
285 if needClientCerts && !sessionHasClientCerts {
286 continue
287 }
288 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
289 continue
290 }
291
292 psk := hs.suite.expandLabel(sessionState.resumptionSecret, "resumption",
293 nil, hs.suite.hash.Size())
294 hs.earlySecret = hs.suite.extract(psk, nil)
295 binderKey := hs.suite.deriveSecret(hs.earlySecret, resumptionBinderLabel, nil)
296
297 transcript := cloneHash(hs.transcript, hs.suite.hash)
298 if transcript == nil {
299 c.sendAlert(alertInternalError)
300 return errors.New("tls: internal error: failed to clone hash")
301 }
302 transcript.Write(hs.clientHello.marshalWithoutBinders())
303 pskBinder := hs.suite.finishedHash(binderKey, transcript)
304 if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) {
305 c.sendAlert(alertDecryptError)
306 return errors.New("tls: invalid PSK binder")
307 }
308
309 c.didResume = true
310 if err := c.processCertsFromClient(sessionState.certificate); err != nil {
311 return err
312 }
313
314 hs.hello.selectedIdentityPresent = true
315 hs.hello.selectedIdentity = uint16(i)
316 hs.usingPSK = true
317 return nil
318 }
319
320 return nil
321 }
322
323
324
325
326 func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash {
327
328 type binaryMarshaler interface {
329 MarshalBinary() (data []byte, err error)
330 UnmarshalBinary(data []byte) error
331 }
332 marshaler, ok := in.(binaryMarshaler)
333 if !ok {
334 return nil
335 }
336 state, err := marshaler.MarshalBinary()
337 if err != nil {
338 return nil
339 }
340 out := h.New()
341 unmarshaler, ok := out.(binaryMarshaler)
342 if !ok {
343 return nil
344 }
345 if err := unmarshaler.UnmarshalBinary(state); err != nil {
346 return nil
347 }
348 return out
349 }
350
351 func (hs *serverHandshakeStateTLS13) pickCertificate() error {
352 c := hs.c
353
354
355 if hs.usingPSK {
356 return nil
357 }
358
359
360 if len(hs.clientHello.supportedSignatureAlgorithms) == 0 {
361 return c.sendAlert(alertMissingExtension)
362 }
363
364 certificate, err := c.config.getCertificate(clientHelloInfo(c, hs.clientHello))
365 if err != nil {
366 if err == errNoCertificates {
367 c.sendAlert(alertUnrecognizedName)
368 } else {
369 c.sendAlert(alertInternalError)
370 }
371 return err
372 }
373 hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms)
374 if err != nil {
375
376
377 c.sendAlert(alertHandshakeFailure)
378 return err
379 }
380 hs.cert = certificate
381
382 return nil
383 }
384
385
386
387 func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
388 if hs.sentDummyCCS {
389 return nil
390 }
391 hs.sentDummyCCS = true
392
393 _, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
394 return err
395 }
396
397 func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) error {
398 c := hs.c
399
400
401
402 hs.transcript.Write(hs.clientHello.marshal())
403 chHash := hs.transcript.Sum(nil)
404 hs.transcript.Reset()
405 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
406 hs.transcript.Write(chHash)
407
408 helloRetryRequest := &serverHelloMsg{
409 vers: hs.hello.vers,
410 random: helloRetryRequestRandom,
411 sessionId: hs.hello.sessionId,
412 cipherSuite: hs.hello.cipherSuite,
413 compressionMethod: hs.hello.compressionMethod,
414 supportedVersion: hs.hello.supportedVersion,
415 selectedGroup: selectedGroup,
416 }
417
418 hs.transcript.Write(helloRetryRequest.marshal())
419 if _, err := c.writeRecord(recordTypeHandshake, helloRetryRequest.marshal()); err != nil {
420 return err
421 }
422
423 if err := hs.sendDummyChangeCipherSpec(); err != nil {
424 return err
425 }
426
427 msg, err := c.readHandshake()
428 if err != nil {
429 return err
430 }
431
432 clientHello, ok := msg.(*clientHelloMsg)
433 if !ok {
434 c.sendAlert(alertUnexpectedMessage)
435 return unexpectedMessageError(clientHello, msg)
436 }
437
438 if len(clientHello.keyShares) != 1 || clientHello.keyShares[0].group != selectedGroup {
439 c.sendAlert(alertIllegalParameter)
440 return errors.New("tls: client sent invalid key share in second ClientHello")
441 }
442
443 if clientHello.earlyData {
444 c.sendAlert(alertIllegalParameter)
445 return errors.New("tls: client indicated early data in second ClientHello")
446 }
447
448 if illegalClientHelloChange(clientHello, hs.clientHello) {
449 c.sendAlert(alertIllegalParameter)
450 return errors.New("tls: client illegally modified second ClientHello")
451 }
452
453 hs.clientHello = clientHello
454 return nil
455 }
456
457
458
459
460 func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool {
461 if len(ch.supportedVersions) != len(ch1.supportedVersions) ||
462 len(ch.cipherSuites) != len(ch1.cipherSuites) ||
463 len(ch.supportedCurves) != len(ch1.supportedCurves) ||
464 len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) ||
465 len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) ||
466 len(ch.alpnProtocols) != len(ch1.alpnProtocols) {
467 return true
468 }
469 for i := range ch.supportedVersions {
470 if ch.supportedVersions[i] != ch1.supportedVersions[i] {
471 return true
472 }
473 }
474 for i := range ch.cipherSuites {
475 if ch.cipherSuites[i] != ch1.cipherSuites[i] {
476 return true
477 }
478 }
479 for i := range ch.supportedCurves {
480 if ch.supportedCurves[i] != ch1.supportedCurves[i] {
481 return true
482 }
483 }
484 for i := range ch.supportedSignatureAlgorithms {
485 if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] {
486 return true
487 }
488 }
489 for i := range ch.supportedSignatureAlgorithmsCert {
490 if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] {
491 return true
492 }
493 }
494 for i := range ch.alpnProtocols {
495 if ch.alpnProtocols[i] != ch1.alpnProtocols[i] {
496 return true
497 }
498 }
499 return ch.vers != ch1.vers ||
500 !bytes.Equal(ch.random, ch1.random) ||
501 !bytes.Equal(ch.sessionId, ch1.sessionId) ||
502 !bytes.Equal(ch.compressionMethods, ch1.compressionMethods) ||
503 ch.serverName != ch1.serverName ||
504 ch.ocspStapling != ch1.ocspStapling ||
505 !bytes.Equal(ch.supportedPoints, ch1.supportedPoints) ||
506 ch.ticketSupported != ch1.ticketSupported ||
507 !bytes.Equal(ch.sessionTicket, ch1.sessionTicket) ||
508 ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported ||
509 !bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) ||
510 ch.scts != ch1.scts ||
511 !bytes.Equal(ch.cookie, ch1.cookie) ||
512 !bytes.Equal(ch.pskModes, ch1.pskModes)
513 }
514
515 func (hs *serverHandshakeStateTLS13) sendServerParameters() error {
516 c := hs.c
517
518 hs.transcript.Write(hs.clientHello.marshal())
519 hs.transcript.Write(hs.hello.marshal())
520 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
521 return err
522 }
523
524 if err := hs.sendDummyChangeCipherSpec(); err != nil {
525 return err
526 }
527
528 earlySecret := hs.earlySecret
529 if earlySecret == nil {
530 earlySecret = hs.suite.extract(nil, nil)
531 }
532 hs.handshakeSecret = hs.suite.extract(hs.sharedKey,
533 hs.suite.deriveSecret(earlySecret, "derived", nil))
534
535 clientSecret := hs.suite.deriveSecret(hs.handshakeSecret,
536 clientHandshakeTrafficLabel, hs.transcript)
537 c.in.setTrafficSecret(hs.suite, clientSecret)
538 serverSecret := hs.suite.deriveSecret(hs.handshakeSecret,
539 serverHandshakeTrafficLabel, hs.transcript)
540 c.out.setTrafficSecret(hs.suite, serverSecret)
541
542 err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret)
543 if err != nil {
544 c.sendAlert(alertInternalError)
545 return err
546 }
547 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret)
548 if err != nil {
549 c.sendAlert(alertInternalError)
550 return err
551 }
552
553 encryptedExtensions := new(encryptedExtensionsMsg)
554
555 if len(hs.clientHello.alpnProtocols) > 0 {
556 if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
557 encryptedExtensions.alpnProtocol = selectedProto
558 c.clientProtocol = selectedProto
559 }
560 }
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 if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
746 return err
747 }
748
749 return nil
750 }
751
752 func (hs *serverHandshakeStateTLS13) readClientCertificate() error {
753 c := hs.c
754
755 if !hs.requestClientCert() {
756
757
758 if c.config.VerifyConnection != nil {
759 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
760 c.sendAlert(alertBadCertificate)
761 return err
762 }
763 }
764 return nil
765 }
766
767
768
769
770 msg, err := c.readHandshake()
771 if err != nil {
772 return err
773 }
774
775 certMsg, ok := msg.(*certificateMsgTLS13)
776 if !ok {
777 c.sendAlert(alertUnexpectedMessage)
778 return unexpectedMessageError(certMsg, msg)
779 }
780 hs.transcript.Write(certMsg.marshal())
781
782 if err := c.processCertsFromClient(certMsg.certificate); err != nil {
783 return err
784 }
785
786 if c.config.VerifyConnection != nil {
787 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
788 c.sendAlert(alertBadCertificate)
789 return err
790 }
791 }
792
793 if len(certMsg.certificate.Certificate) != 0 {
794 msg, err = c.readHandshake()
795 if err != nil {
796 return err
797 }
798
799 certVerify, ok := msg.(*certificateVerifyMsg)
800 if !ok {
801 c.sendAlert(alertUnexpectedMessage)
802 return unexpectedMessageError(certVerify, msg)
803 }
804
805
806 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms) {
807 c.sendAlert(alertIllegalParameter)
808 return errors.New("tls: client certificate used with invalid signature algorithm")
809 }
810 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
811 if err != nil {
812 return c.sendAlert(alertInternalError)
813 }
814 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
815 c.sendAlert(alertIllegalParameter)
816 return errors.New("tls: client certificate used with invalid signature algorithm")
817 }
818 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
819 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey,
820 sigHash, signed, certVerify.signature); err != nil {
821 c.sendAlert(alertDecryptError)
822 return errors.New("tls: invalid signature by the client certificate: " + err.Error())
823 }
824
825 hs.transcript.Write(certVerify.marshal())
826 }
827
828
829
830 if err := hs.sendSessionTickets(); err != nil {
831 return err
832 }
833
834 return nil
835 }
836
837 func (hs *serverHandshakeStateTLS13) readClientFinished() error {
838 c := hs.c
839
840 msg, err := c.readHandshake()
841 if err != nil {
842 return err
843 }
844
845 finished, ok := msg.(*finishedMsg)
846 if !ok {
847 c.sendAlert(alertUnexpectedMessage)
848 return unexpectedMessageError(finished, msg)
849 }
850
851 if !hmac.Equal(hs.clientFinished, finished.verifyData) {
852 c.sendAlert(alertDecryptError)
853 return errors.New("tls: invalid client finished hash")
854 }
855
856 c.in.setTrafficSecret(hs.suite, hs.trafficSecret)
857
858 return nil
859 }
860
View as plain text