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