1// Copyright 2018 The Go Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style 3// license that can be found in the LICENSE file. 4 5package tls 6 7import ( 8 "bytes" 9 "context" 10 "crypto" 11 "crypto/hmac" 12 "crypto/internal/mlkem768" 13 "crypto/rsa" 14 "crypto/subtle" 15 "errors" 16 "hash" 17 "slices" 18 "time" 19) 20 21type clientHandshakeStateTLS13 struct { 22 c *Conn 23 ctx context.Context 24 serverHello *serverHelloMsg 25 hello *clientHelloMsg 26 keyShareKeys *keySharePrivateKeys 27 28 session *SessionState 29 earlySecret []byte 30 binderKey []byte 31 32 certReq *certificateRequestMsgTLS13 33 usingPSK bool 34 sentDummyCCS bool 35 suite *cipherSuiteTLS13 36 transcript hash.Hash 37 masterSecret []byte 38 trafficSecret []byte // client_application_traffic_secret_0 39 40 echContext *echContext 41} 42 43// handshake requires hs.c, hs.hello, hs.serverHello, hs.keyShareKeys, and, 44// optionally, hs.session, hs.earlySecret and hs.binderKey to be set. 45func (hs *clientHandshakeStateTLS13) handshake() error { 46 c := hs.c 47 48 if needFIPS() { 49 return errors.New("tls: internal error: TLS 1.3 reached in FIPS mode") 50 } 51 52 // The server must not select TLS 1.3 in a renegotiation. See RFC 8446, 53 // sections 4.1.2 and 4.1.3. 54 if c.handshakes > 0 { 55 c.sendAlert(alertProtocolVersion) 56 return errors.New("tls: server selected TLS 1.3 in a renegotiation") 57 } 58 59 // Consistency check on the presence of a keyShare and its parameters. 60 if hs.keyShareKeys == nil || hs.keyShareKeys.ecdhe == nil || len(hs.hello.keyShares) == 0 { 61 return c.sendAlert(alertInternalError) 62 } 63 64 if err := hs.checkServerHelloOrHRR(); err != nil { 65 return err 66 } 67 68 hs.transcript = hs.suite.hash.New() 69 70 if err := transcriptMsg(hs.hello, hs.transcript); err != nil { 71 return err 72 } 73 74 if hs.echContext != nil { 75 hs.echContext.innerTranscript = hs.suite.hash.New() 76 if err := transcriptMsg(hs.echContext.innerHello, hs.echContext.innerTranscript); err != nil { 77 return err 78 } 79 } 80 81 if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) { 82 if err := hs.sendDummyChangeCipherSpec(); err != nil { 83 return err 84 } 85 if err := hs.processHelloRetryRequest(); err != nil { 86 return err 87 } 88 } 89 90 var echRetryConfigList []byte 91 if hs.echContext != nil { 92 confTranscript := cloneHash(hs.echContext.innerTranscript, hs.suite.hash) 93 confTranscript.Write(hs.serverHello.original[:30]) 94 confTranscript.Write(make([]byte, 8)) 95 confTranscript.Write(hs.serverHello.original[38:]) 96 acceptConfirmation := hs.suite.expandLabel( 97 hs.suite.extract(hs.echContext.innerHello.random, nil), 98 "ech accept confirmation", 99 confTranscript.Sum(nil), 100 8, 101 ) 102 if subtle.ConstantTimeCompare(acceptConfirmation, hs.serverHello.random[len(hs.serverHello.random)-8:]) == 1 { 103 hs.hello = hs.echContext.innerHello 104 c.serverName = c.config.ServerName 105 hs.transcript = hs.echContext.innerTranscript 106 c.echAccepted = true 107 108 if hs.serverHello.encryptedClientHello != nil { 109 c.sendAlert(alertUnsupportedExtension) 110 return errors.New("tls: unexpected encrypted_client_hello extension in server hello despite ECH being accepted") 111 } 112 113 if hs.hello.serverName == "" && hs.serverHello.serverNameAck { 114 c.sendAlert(alertUnsupportedExtension) 115 return errors.New("tls: unexpected server_name extension in server hello") 116 } 117 } else { 118 hs.echContext.echRejected = true 119 // If the server sent us retry configs, we'll return these to 120 // the user so they can update their Config. 121 echRetryConfigList = hs.serverHello.encryptedClientHello 122 } 123 } 124 125 if err := transcriptMsg(hs.serverHello, hs.transcript); err != nil { 126 return err 127 } 128 129 c.buffering = true 130 if err := hs.processServerHello(); err != nil { 131 return err 132 } 133 if err := hs.sendDummyChangeCipherSpec(); err != nil { 134 return err 135 } 136 if err := hs.establishHandshakeKeys(); err != nil { 137 return err 138 } 139 if err := hs.readServerParameters(); err != nil { 140 return err 141 } 142 if err := hs.readServerCertificate(); err != nil { 143 return err 144 } 145 if err := hs.readServerFinished(); err != nil { 146 return err 147 } 148 if err := hs.sendClientCertificate(); err != nil { 149 return err 150 } 151 if err := hs.sendClientFinished(); err != nil { 152 return err 153 } 154 if _, err := c.flush(); err != nil { 155 return err 156 } 157 158 if hs.echContext != nil && hs.echContext.echRejected { 159 c.sendAlert(alertECHRequired) 160 return &ECHRejectionError{echRetryConfigList} 161 } 162 163 c.isHandshakeComplete.Store(true) 164 165 return nil 166} 167 168// checkServerHelloOrHRR does validity checks that apply to both ServerHello and 169// HelloRetryRequest messages. It sets hs.suite. 170func (hs *clientHandshakeStateTLS13) checkServerHelloOrHRR() error { 171 c := hs.c 172 173 if hs.serverHello.supportedVersion == 0 { 174 c.sendAlert(alertMissingExtension) 175 return errors.New("tls: server selected TLS 1.3 using the legacy version field") 176 } 177 178 if hs.serverHello.supportedVersion != VersionTLS13 { 179 c.sendAlert(alertIllegalParameter) 180 return errors.New("tls: server selected an invalid version after a HelloRetryRequest") 181 } 182 183 if hs.serverHello.vers != VersionTLS12 { 184 c.sendAlert(alertIllegalParameter) 185 return errors.New("tls: server sent an incorrect legacy version") 186 } 187 188 if hs.serverHello.ocspStapling || 189 hs.serverHello.ticketSupported || 190 hs.serverHello.extendedMasterSecret || 191 hs.serverHello.secureRenegotiationSupported || 192 len(hs.serverHello.secureRenegotiation) != 0 || 193 len(hs.serverHello.alpnProtocol) != 0 || 194 len(hs.serverHello.scts) != 0 { 195 c.sendAlert(alertUnsupportedExtension) 196 return errors.New("tls: server sent a ServerHello extension forbidden in TLS 1.3") 197 } 198 199 if !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) { 200 c.sendAlert(alertIllegalParameter) 201 return errors.New("tls: server did not echo the legacy session ID") 202 } 203 204 if hs.serverHello.compressionMethod != compressionNone { 205 c.sendAlert(alertIllegalParameter) 206 return errors.New("tls: server selected unsupported compression format") 207 } 208 209 selectedSuite := mutualCipherSuiteTLS13(hs.hello.cipherSuites, hs.serverHello.cipherSuite) 210 if hs.suite != nil && selectedSuite != hs.suite { 211 c.sendAlert(alertIllegalParameter) 212 return errors.New("tls: server changed cipher suite after a HelloRetryRequest") 213 } 214 if selectedSuite == nil { 215 c.sendAlert(alertIllegalParameter) 216 return errors.New("tls: server chose an unconfigured cipher suite") 217 } 218 hs.suite = selectedSuite 219 c.cipherSuite = hs.suite.id 220 221 return nil 222} 223 224// sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility 225// with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4. 226func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error { 227 if hs.c.quic != nil { 228 return nil 229 } 230 if hs.sentDummyCCS { 231 return nil 232 } 233 hs.sentDummyCCS = true 234 235 return hs.c.writeChangeCipherRecord() 236} 237 238// processHelloRetryRequest handles the HRR in hs.serverHello, modifies and 239// resends hs.hello, and reads the new ServerHello into hs.serverHello. 240func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error { 241 c := hs.c 242 243 // The first ClientHello gets double-hashed into the transcript upon a 244 // HelloRetryRequest. (The idea is that the server might offload transcript 245 // storage to the client in the cookie.) See RFC 8446, Section 4.4.1. 246 chHash := hs.transcript.Sum(nil) 247 hs.transcript.Reset() 248 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) 249 hs.transcript.Write(chHash) 250 if err := transcriptMsg(hs.serverHello, hs.transcript); err != nil { 251 return err 252 } 253 254 var isInnerHello bool 255 hello := hs.hello 256 if hs.echContext != nil { 257 chHash = hs.echContext.innerTranscript.Sum(nil) 258 hs.echContext.innerTranscript.Reset() 259 hs.echContext.innerTranscript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) 260 hs.echContext.innerTranscript.Write(chHash) 261 262 if hs.serverHello.encryptedClientHello != nil { 263 if len(hs.serverHello.encryptedClientHello) != 8 { 264 hs.c.sendAlert(alertDecodeError) 265 return errors.New("tls: malformed encrypted client hello extension") 266 } 267 268 confTranscript := cloneHash(hs.echContext.innerTranscript, hs.suite.hash) 269 hrrHello := make([]byte, len(hs.serverHello.original)) 270 copy(hrrHello, hs.serverHello.original) 271 hrrHello = bytes.Replace(hrrHello, hs.serverHello.encryptedClientHello, make([]byte, 8), 1) 272 confTranscript.Write(hrrHello) 273 acceptConfirmation := hs.suite.expandLabel( 274 hs.suite.extract(hs.echContext.innerHello.random, nil), 275 "hrr ech accept confirmation", 276 confTranscript.Sum(nil), 277 8, 278 ) 279 if subtle.ConstantTimeCompare(acceptConfirmation, hs.serverHello.encryptedClientHello) == 1 { 280 hello = hs.echContext.innerHello 281 c.serverName = c.config.ServerName 282 isInnerHello = true 283 c.echAccepted = true 284 } 285 } 286 287 if err := transcriptMsg(hs.serverHello, hs.echContext.innerTranscript); err != nil { 288 return err 289 } 290 } else if hs.serverHello.encryptedClientHello != nil { 291 // Unsolicited ECH extension should be rejected 292 c.sendAlert(alertUnsupportedExtension) 293 return errors.New("tls: unexpected ECH extension in serverHello") 294 } 295 296 // The only HelloRetryRequest extensions we support are key_share and 297 // cookie, and clients must abort the handshake if the HRR would not result 298 // in any change in the ClientHello. 299 if hs.serverHello.selectedGroup == 0 && hs.serverHello.cookie == nil { 300 c.sendAlert(alertIllegalParameter) 301 return errors.New("tls: server sent an unnecessary HelloRetryRequest message") 302 } 303 304 if hs.serverHello.cookie != nil { 305 hello.cookie = hs.serverHello.cookie 306 } 307 308 if hs.serverHello.serverShare.group != 0 { 309 c.sendAlert(alertDecodeError) 310 return errors.New("tls: received malformed key_share extension") 311 } 312 313 // If the server sent a key_share extension selecting a group, ensure it's 314 // a group we advertised but did not send a key share for, and send a key 315 // share for it this time. 316 if curveID := hs.serverHello.selectedGroup; curveID != 0 { 317 if !slices.Contains(hello.supportedCurves, curveID) { 318 c.sendAlert(alertIllegalParameter) 319 return errors.New("tls: server selected unsupported group") 320 } 321 if slices.ContainsFunc(hs.hello.keyShares, func(ks keyShare) bool { 322 return ks.group == curveID 323 }) { 324 c.sendAlert(alertIllegalParameter) 325 return errors.New("tls: server sent an unnecessary HelloRetryRequest key_share") 326 } 327 // Note: we don't support selecting X25519Kyber768Draft00 in a HRR, 328 // because we currently only support it at all when CurvePreferences is 329 // empty, which will cause us to also send a key share for it. 330 // 331 // This will have to change once we support selecting hybrid KEMs 332 // without sending key shares for them. 333 if _, ok := curveForCurveID(curveID); !ok { 334 c.sendAlert(alertInternalError) 335 return errors.New("tls: CurvePreferences includes unsupported curve") 336 } 337 key, err := generateECDHEKey(c.config.rand(), curveID) 338 if err != nil { 339 c.sendAlert(alertInternalError) 340 return err 341 } 342 hs.keyShareKeys = &keySharePrivateKeys{curveID: curveID, ecdhe: key} 343 hello.keyShares = []keyShare{{group: curveID, data: key.PublicKey().Bytes()}} 344 } 345 346 if len(hello.pskIdentities) > 0 { 347 pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite) 348 if pskSuite == nil { 349 return c.sendAlert(alertInternalError) 350 } 351 if pskSuite.hash == hs.suite.hash { 352 // Update binders and obfuscated_ticket_age. 353 ticketAge := c.config.time().Sub(time.Unix(int64(hs.session.createdAt), 0)) 354 hello.pskIdentities[0].obfuscatedTicketAge = uint32(ticketAge/time.Millisecond) + hs.session.ageAdd 355 356 transcript := hs.suite.hash.New() 357 transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) 358 transcript.Write(chHash) 359 if err := transcriptMsg(hs.serverHello, transcript); err != nil { 360 return err 361 } 362 363 if err := computeAndUpdatePSK(hello, hs.binderKey, transcript, hs.suite.finishedHash); err != nil { 364 return err 365 } 366 } else { 367 // Server selected a cipher suite incompatible with the PSK. 368 hello.pskIdentities = nil 369 hello.pskBinders = nil 370 } 371 } 372 373 if hello.earlyData { 374 hello.earlyData = false 375 c.quicRejectedEarlyData() 376 } 377 378 if isInnerHello { 379 // Any extensions which have changed in hello, but are mirrored in the 380 // outer hello and compressed, need to be copied to the outer hello, so 381 // they can be properly decompressed by the server. For now, the only 382 // extension which may have changed is keyShares. 383 hs.hello.keyShares = hello.keyShares 384 hs.echContext.innerHello = hello 385 if err := transcriptMsg(hs.echContext.innerHello, hs.echContext.innerTranscript); err != nil { 386 return err 387 } 388 389 if err := computeAndUpdateOuterECHExtension(hs.hello, hs.echContext.innerHello, hs.echContext, false); err != nil { 390 return err 391 } 392 } else { 393 hs.hello = hello 394 } 395 396 if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil { 397 return err 398 } 399 400 // serverHelloMsg is not included in the transcript 401 msg, err := c.readHandshake(nil) 402 if err != nil { 403 return err 404 } 405 406 serverHello, ok := msg.(*serverHelloMsg) 407 if !ok { 408 c.sendAlert(alertUnexpectedMessage) 409 return unexpectedMessageError(serverHello, msg) 410 } 411 hs.serverHello = serverHello 412 413 if err := hs.checkServerHelloOrHRR(); err != nil { 414 return err 415 } 416 417 c.didHRR = true 418 return nil 419} 420 421func (hs *clientHandshakeStateTLS13) processServerHello() error { 422 c := hs.c 423 424 if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) { 425 c.sendAlert(alertUnexpectedMessage) 426 return errors.New("tls: server sent two HelloRetryRequest messages") 427 } 428 429 if len(hs.serverHello.cookie) != 0 { 430 c.sendAlert(alertUnsupportedExtension) 431 return errors.New("tls: server sent a cookie in a normal ServerHello") 432 } 433 434 if hs.serverHello.selectedGroup != 0 { 435 c.sendAlert(alertDecodeError) 436 return errors.New("tls: malformed key_share extension") 437 } 438 439 if hs.serverHello.serverShare.group == 0 { 440 c.sendAlert(alertIllegalParameter) 441 return errors.New("tls: server did not send a key share") 442 } 443 if !slices.ContainsFunc(hs.hello.keyShares, func(ks keyShare) bool { 444 return ks.group == hs.serverHello.serverShare.group 445 }) { 446 c.sendAlert(alertIllegalParameter) 447 return errors.New("tls: server selected unsupported group") 448 } 449 450 if !hs.serverHello.selectedIdentityPresent { 451 return nil 452 } 453 454 if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) { 455 c.sendAlert(alertIllegalParameter) 456 return errors.New("tls: server selected an invalid PSK") 457 } 458 459 if len(hs.hello.pskIdentities) != 1 || hs.session == nil { 460 return c.sendAlert(alertInternalError) 461 } 462 pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite) 463 if pskSuite == nil { 464 return c.sendAlert(alertInternalError) 465 } 466 if pskSuite.hash != hs.suite.hash { 467 c.sendAlert(alertIllegalParameter) 468 return errors.New("tls: server selected an invalid PSK and cipher suite pair") 469 } 470 471 hs.usingPSK = true 472 c.didResume = true 473 c.peerCertificates = hs.session.peerCertificates 474 c.activeCertHandles = hs.session.activeCertHandles 475 c.verifiedChains = hs.session.verifiedChains 476 c.ocspResponse = hs.session.ocspResponse 477 c.scts = hs.session.scts 478 return nil 479} 480 481func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error { 482 c := hs.c 483 484 ecdhePeerData := hs.serverHello.serverShare.data 485 if hs.serverHello.serverShare.group == x25519Kyber768Draft00 { 486 if len(ecdhePeerData) != x25519PublicKeySize+mlkem768.CiphertextSize { 487 c.sendAlert(alertIllegalParameter) 488 return errors.New("tls: invalid server key share") 489 } 490 ecdhePeerData = hs.serverHello.serverShare.data[:x25519PublicKeySize] 491 } 492 peerKey, err := hs.keyShareKeys.ecdhe.Curve().NewPublicKey(ecdhePeerData) 493 if err != nil { 494 c.sendAlert(alertIllegalParameter) 495 return errors.New("tls: invalid server key share") 496 } 497 sharedKey, err := hs.keyShareKeys.ecdhe.ECDH(peerKey) 498 if err != nil { 499 c.sendAlert(alertIllegalParameter) 500 return errors.New("tls: invalid server key share") 501 } 502 if hs.serverHello.serverShare.group == x25519Kyber768Draft00 { 503 if hs.keyShareKeys.kyber == nil { 504 return c.sendAlert(alertInternalError) 505 } 506 ciphertext := hs.serverHello.serverShare.data[x25519PublicKeySize:] 507 kyberShared, err := kyberDecapsulate(hs.keyShareKeys.kyber, ciphertext) 508 if err != nil { 509 c.sendAlert(alertIllegalParameter) 510 return errors.New("tls: invalid Kyber server key share") 511 } 512 sharedKey = append(sharedKey, kyberShared...) 513 } 514 c.curveID = hs.serverHello.serverShare.group 515 516 earlySecret := hs.earlySecret 517 if !hs.usingPSK { 518 earlySecret = hs.suite.extract(nil, nil) 519 } 520 521 handshakeSecret := hs.suite.extract(sharedKey, 522 hs.suite.deriveSecret(earlySecret, "derived", nil)) 523 524 clientSecret := hs.suite.deriveSecret(handshakeSecret, 525 clientHandshakeTrafficLabel, hs.transcript) 526 c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, clientSecret) 527 serverSecret := hs.suite.deriveSecret(handshakeSecret, 528 serverHandshakeTrafficLabel, hs.transcript) 529 c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret) 530 531 if c.quic != nil { 532 if c.hand.Len() != 0 { 533 c.sendAlert(alertUnexpectedMessage) 534 } 535 c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, clientSecret) 536 c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret) 537 } 538 539 err = c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret) 540 if err != nil { 541 c.sendAlert(alertInternalError) 542 return err 543 } 544 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret) 545 if err != nil { 546 c.sendAlert(alertInternalError) 547 return err 548 } 549 550 hs.masterSecret = hs.suite.extract(nil, 551 hs.suite.deriveSecret(handshakeSecret, "derived", nil)) 552 553 return nil 554} 555 556func (hs *clientHandshakeStateTLS13) readServerParameters() error { 557 c := hs.c 558 559 msg, err := c.readHandshake(hs.transcript) 560 if err != nil { 561 return err 562 } 563 564 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg) 565 if !ok { 566 c.sendAlert(alertUnexpectedMessage) 567 return unexpectedMessageError(encryptedExtensions, msg) 568 } 569 570 if err := checkALPN(hs.hello.alpnProtocols, encryptedExtensions.alpnProtocol, c.quic != nil); err != nil { 571 // RFC 8446 specifies that no_application_protocol is sent by servers, but 572 // does not specify how clients handle the selection of an incompatible protocol. 573 // RFC 9001 Section 8.1 specifies that QUIC clients send no_application_protocol 574 // in this case. Always sending no_application_protocol seems reasonable. 575 c.sendAlert(alertNoApplicationProtocol) 576 return err 577 } 578 c.clientProtocol = encryptedExtensions.alpnProtocol 579 580 if c.quic != nil { 581 if encryptedExtensions.quicTransportParameters == nil { 582 // RFC 9001 Section 8.2. 583 c.sendAlert(alertMissingExtension) 584 return errors.New("tls: server did not send a quic_transport_parameters extension") 585 } 586 c.quicSetTransportParameters(encryptedExtensions.quicTransportParameters) 587 } else { 588 if encryptedExtensions.quicTransportParameters != nil { 589 c.sendAlert(alertUnsupportedExtension) 590 return errors.New("tls: server sent an unexpected quic_transport_parameters extension") 591 } 592 } 593 594 if !hs.hello.earlyData && encryptedExtensions.earlyData { 595 c.sendAlert(alertUnsupportedExtension) 596 return errors.New("tls: server sent an unexpected early_data extension") 597 } 598 if hs.hello.earlyData && !encryptedExtensions.earlyData { 599 c.quicRejectedEarlyData() 600 } 601 if encryptedExtensions.earlyData { 602 if hs.session.cipherSuite != c.cipherSuite { 603 c.sendAlert(alertHandshakeFailure) 604 return errors.New("tls: server accepted 0-RTT with the wrong cipher suite") 605 } 606 if hs.session.alpnProtocol != c.clientProtocol { 607 c.sendAlert(alertHandshakeFailure) 608 return errors.New("tls: server accepted 0-RTT with the wrong ALPN") 609 } 610 } 611 if hs.echContext != nil && !hs.echContext.echRejected && encryptedExtensions.echRetryConfigs != nil { 612 c.sendAlert(alertUnsupportedExtension) 613 return errors.New("tls: server sent ECH retry configs after accepting ECH") 614 } 615 616 return nil 617} 618 619func (hs *clientHandshakeStateTLS13) readServerCertificate() error { 620 c := hs.c 621 622 // Either a PSK or a certificate is always used, but not both. 623 // See RFC 8446, Section 4.1.1. 624 if hs.usingPSK { 625 // Make sure the connection is still being verified whether or not this 626 // is a resumption. Resumptions currently don't reverify certificates so 627 // they don't call verifyServerCertificate. See Issue 31641. 628 if c.config.VerifyConnection != nil { 629 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 630 c.sendAlert(alertBadCertificate) 631 return err 632 } 633 } 634 return nil 635 } 636 637 msg, err := c.readHandshake(hs.transcript) 638 if err != nil { 639 return err 640 } 641 642 certReq, ok := msg.(*certificateRequestMsgTLS13) 643 if ok { 644 hs.certReq = certReq 645 646 msg, err = c.readHandshake(hs.transcript) 647 if err != nil { 648 return err 649 } 650 } 651 652 certMsg, ok := msg.(*certificateMsgTLS13) 653 if !ok { 654 c.sendAlert(alertUnexpectedMessage) 655 return unexpectedMessageError(certMsg, msg) 656 } 657 if len(certMsg.certificate.Certificate) == 0 { 658 c.sendAlert(alertDecodeError) 659 return errors.New("tls: received empty certificates message") 660 } 661 662 c.scts = certMsg.certificate.SignedCertificateTimestamps 663 c.ocspResponse = certMsg.certificate.OCSPStaple 664 665 if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil { 666 return err 667 } 668 669 // certificateVerifyMsg is included in the transcript, but not until 670 // after we verify the handshake signature, since the state before 671 // this message was sent is used. 672 msg, err = c.readHandshake(nil) 673 if err != nil { 674 return err 675 } 676 677 certVerify, ok := msg.(*certificateVerifyMsg) 678 if !ok { 679 c.sendAlert(alertUnexpectedMessage) 680 return unexpectedMessageError(certVerify, msg) 681 } 682 683 // See RFC 8446, Section 4.4.3. 684 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) { 685 c.sendAlert(alertIllegalParameter) 686 return errors.New("tls: certificate used with invalid signature algorithm") 687 } 688 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm) 689 if err != nil { 690 return c.sendAlert(alertInternalError) 691 } 692 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 { 693 c.sendAlert(alertIllegalParameter) 694 return errors.New("tls: certificate used with invalid signature algorithm") 695 } 696 signed := signedMessage(sigHash, serverSignatureContext, hs.transcript) 697 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey, 698 sigHash, signed, certVerify.signature); err != nil { 699 c.sendAlert(alertDecryptError) 700 return errors.New("tls: invalid signature by the server certificate: " + err.Error()) 701 } 702 703 if err := transcriptMsg(certVerify, hs.transcript); err != nil { 704 return err 705 } 706 707 return nil 708} 709 710func (hs *clientHandshakeStateTLS13) readServerFinished() error { 711 c := hs.c 712 713 // finishedMsg is included in the transcript, but not until after we 714 // check the client version, since the state before this message was 715 // sent is used during verification. 716 msg, err := c.readHandshake(nil) 717 if err != nil { 718 return err 719 } 720 721 finished, ok := msg.(*finishedMsg) 722 if !ok { 723 c.sendAlert(alertUnexpectedMessage) 724 return unexpectedMessageError(finished, msg) 725 } 726 727 expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript) 728 if !hmac.Equal(expectedMAC, finished.verifyData) { 729 c.sendAlert(alertDecryptError) 730 return errors.New("tls: invalid server finished hash") 731 } 732 733 if err := transcriptMsg(finished, hs.transcript); err != nil { 734 return err 735 } 736 737 // Derive secrets that take context through the server Finished. 738 739 hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret, 740 clientApplicationTrafficLabel, hs.transcript) 741 serverSecret := hs.suite.deriveSecret(hs.masterSecret, 742 serverApplicationTrafficLabel, hs.transcript) 743 c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, serverSecret) 744 745 err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret) 746 if err != nil { 747 c.sendAlert(alertInternalError) 748 return err 749 } 750 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret) 751 if err != nil { 752 c.sendAlert(alertInternalError) 753 return err 754 } 755 756 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript) 757 758 return nil 759} 760 761func (hs *clientHandshakeStateTLS13) sendClientCertificate() error { 762 c := hs.c 763 764 if hs.certReq == nil { 765 return nil 766 } 767 768 if hs.echContext != nil && hs.echContext.echRejected { 769 if _, err := hs.c.writeHandshakeRecord(&certificateMsgTLS13{}, hs.transcript); err != nil { 770 return err 771 } 772 return nil 773 } 774 775 cert, err := c.getClientCertificate(&CertificateRequestInfo{ 776 AcceptableCAs: hs.certReq.certificateAuthorities, 777 SignatureSchemes: hs.certReq.supportedSignatureAlgorithms, 778 Version: c.vers, 779 ctx: hs.ctx, 780 }) 781 if err != nil { 782 return err 783 } 784 785 certMsg := new(certificateMsgTLS13) 786 787 certMsg.certificate = *cert 788 certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0 789 certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0 790 791 if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil { 792 return err 793 } 794 795 // If we sent an empty certificate message, skip the CertificateVerify. 796 if len(cert.Certificate) == 0 { 797 return nil 798 } 799 800 certVerifyMsg := new(certificateVerifyMsg) 801 certVerifyMsg.hasSignatureAlgorithm = true 802 803 certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms) 804 if err != nil { 805 // getClientCertificate returned a certificate incompatible with the 806 // CertificateRequestInfo supported signature algorithms. 807 c.sendAlert(alertHandshakeFailure) 808 return err 809 } 810 811 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm) 812 if err != nil { 813 return c.sendAlert(alertInternalError) 814 } 815 816 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript) 817 signOpts := crypto.SignerOpts(sigHash) 818 if sigType == signatureRSAPSS { 819 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash} 820 } 821 sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts) 822 if err != nil { 823 c.sendAlert(alertInternalError) 824 return errors.New("tls: failed to sign handshake: " + err.Error()) 825 } 826 certVerifyMsg.signature = sig 827 828 if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil { 829 return err 830 } 831 832 return nil 833} 834 835func (hs *clientHandshakeStateTLS13) sendClientFinished() error { 836 c := hs.c 837 838 finished := &finishedMsg{ 839 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript), 840 } 841 842 if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil { 843 return err 844 } 845 846 c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret) 847 848 if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil { 849 c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret, 850 resumptionLabel, hs.transcript) 851 } 852 853 if c.quic != nil { 854 if c.hand.Len() != 0 { 855 c.sendAlert(alertUnexpectedMessage) 856 } 857 c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, hs.trafficSecret) 858 } 859 860 return nil 861} 862 863func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error { 864 if !c.isClient { 865 c.sendAlert(alertUnexpectedMessage) 866 return errors.New("tls: received new session ticket from a client") 867 } 868 869 if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil { 870 return nil 871 } 872 873 // See RFC 8446, Section 4.6.1. 874 if msg.lifetime == 0 { 875 return nil 876 } 877 lifetime := time.Duration(msg.lifetime) * time.Second 878 if lifetime > maxSessionTicketLifetime { 879 c.sendAlert(alertIllegalParameter) 880 return errors.New("tls: received a session ticket with invalid lifetime") 881 } 882 883 // RFC 9001, Section 4.6.1 884 if c.quic != nil && msg.maxEarlyData != 0 && msg.maxEarlyData != 0xffffffff { 885 c.sendAlert(alertIllegalParameter) 886 return errors.New("tls: invalid early data for QUIC connection") 887 } 888 889 cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite) 890 if cipherSuite == nil || c.resumptionSecret == nil { 891 return c.sendAlert(alertInternalError) 892 } 893 894 psk := cipherSuite.expandLabel(c.resumptionSecret, "resumption", 895 msg.nonce, cipherSuite.hash.Size()) 896 897 session := c.sessionState() 898 session.secret = psk 899 session.useBy = uint64(c.config.time().Add(lifetime).Unix()) 900 session.ageAdd = msg.ageAdd 901 session.EarlyData = c.quic != nil && msg.maxEarlyData == 0xffffffff // RFC 9001, Section 4.6.1 902 session.ticket = msg.label 903 if c.quic != nil && c.quic.enableSessionEvents { 904 c.quicStoreSession(session) 905 return nil 906 } 907 cs := &ClientSessionState{session: session} 908 if cacheKey := c.clientSessionCacheKey(); cacheKey != "" { 909 c.config.ClientSessionCache.Put(cacheKey, cs) 910 } 911 912 return nil 913} 914