github.com/3andne/restls-client-go@v0.1.6/handshake_client_tls13.go (about) 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 5 package tls 6 7 import ( 8 "bytes" 9 "context" 10 "crypto" 11 "crypto/ecdh" 12 "crypto/hmac" 13 "crypto/rsa" 14 "errors" 15 "fmt" 16 "hash" 17 "time" 18 ) 19 20 // [uTLS SECTION START] 21 type KeySharesEcdheParameters map[CurveID]*ecdh.PrivateKey 22 23 func (keymap KeySharesEcdheParameters) AddEcdheParams(curveID CurveID, ecdheKey *ecdh.PrivateKey) { 24 keymap[curveID] = ecdheKey 25 } 26 func (keymap KeySharesEcdheParameters) GetEcdheParams(curveID CurveID) (ecdheKey *ecdh.PrivateKey, ok bool) { 27 ecdheKey, ok = keymap[curveID] 28 return 29 } 30 func (keymap KeySharesEcdheParameters) GetPublicEcdheParams(curveID CurveID) (params *ecdh.PrivateKey, ok bool) { 31 params, ok = keymap[curveID] 32 return 33 } 34 35 // [uTLS SECTION END] 36 37 type clientHandshakeStateTLS13 struct { 38 c *Conn 39 ctx context.Context 40 serverHello *serverHelloMsg 41 hello *clientHelloMsg 42 ecdheKey *ecdh.PrivateKey 43 44 keySharesEcdheParams KeySharesEcdheParameters // [uTLS] 45 46 session *SessionState 47 earlySecret []byte 48 binderKey []byte 49 50 certReq *certificateRequestMsgTLS13 51 usingPSK bool 52 sentDummyCCS bool 53 suite *cipherSuiteTLS13 54 transcript hash.Hash 55 masterSecret []byte 56 trafficSecret []byte // client_application_traffic_secret_0 57 58 uconn *UConn // [uTLS] 59 } 60 61 // handshake requires hs.c, hs.hello, hs.serverHello, hs.ecdheKey, and, 62 // optionally, hs.session, hs.earlySecret and hs.binderKey to be set. 63 func (hs *clientHandshakeStateTLS13) handshake() error { 64 c := hs.c 65 66 if needFIPS() { 67 return errors.New("tls: internal error: TLS 1.3 reached in FIPS mode") 68 } 69 70 // The server must not select TLS 1.3 in a renegotiation. See RFC 8446, 71 // sections 4.1.2 and 4.1.3. 72 if c.handshakes > 0 { 73 c.sendAlert(alertProtocolVersion) 74 return errors.New("tls: server selected TLS 1.3 in a renegotiation") 75 } 76 77 // [uTLS SECTION START] 78 79 // set echdheParams to what we received from server 80 if ecdheKey, ok := hs.keySharesEcdheParams.GetEcdheParams(hs.serverHello.serverShare.group); ok { 81 hs.ecdheKey = ecdheKey 82 } 83 // [uTLS SECTION END] 84 85 // Consistency check on the presence of a keyShare and its parameters. 86 if hs.ecdheKey == nil || len(hs.hello.keyShares) < 1 { // [uTLS] 87 // keyshares "< 1" instead of "!= 1", as uTLS may send multiple 88 return c.sendAlert(alertInternalError) 89 } 90 91 if err := hs.checkServerHelloOrHRR(); err != nil { 92 return err 93 } 94 95 hs.transcript = hs.suite.hash.New() 96 97 if err := transcriptMsg(hs.hello, hs.transcript); err != nil { 98 return err 99 } 100 101 if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) { 102 if err := hs.sendDummyChangeCipherSpec(); err != nil { 103 return err 104 } 105 if err := hs.processHelloRetryRequest(); err != nil { 106 return err 107 } 108 } 109 110 if err := transcriptMsg(hs.serverHello, hs.transcript); err != nil { 111 return err 112 } 113 114 c.buffering = true 115 if err := hs.processServerHello(); err != nil { 116 return err 117 } 118 if err := hs.sendDummyChangeCipherSpec(); err != nil { 119 return err 120 } 121 if err := hs.establishHandshakeKeys(); err != nil { 122 return err 123 } 124 if err := hs.readServerParameters(); err != nil { 125 return err 126 } 127 if err := hs.readServerCertificate(); err != nil { 128 return err 129 } 130 if err := hs.readServerFinished(); err != nil { 131 return err 132 } 133 // [UTLS SECTION START] 134 if err := hs.serverFinishedReceived(); err != nil { 135 return err 136 } 137 // [UTLS SECTION END] 138 if err := hs.sendClientCertificate(); err != nil { 139 return err 140 } 141 if err := hs.sendClientFinished(); err != nil { 142 return err 143 } 144 if _, err := c.flush(); err != nil { 145 return err 146 } 147 148 c.isHandshakeComplete.Store(true) 149 150 return nil 151 } 152 153 // checkServerHelloOrHRR does validity checks that apply to both ServerHello and 154 // HelloRetryRequest messages. It sets hs.suite. 155 func (hs *clientHandshakeStateTLS13) checkServerHelloOrHRR() error { 156 c := hs.c 157 158 if hs.serverHello.supportedVersion == 0 { 159 c.sendAlert(alertMissingExtension) 160 return errors.New("tls: server selected TLS 1.3 using the legacy version field") 161 } 162 163 if hs.serverHello.supportedVersion != VersionTLS13 { 164 c.sendAlert(alertIllegalParameter) 165 return errors.New("tls: server selected an invalid version after a HelloRetryRequest") 166 } 167 168 if hs.serverHello.vers != VersionTLS12 { 169 c.sendAlert(alertIllegalParameter) 170 return errors.New("tls: server sent an incorrect legacy version") 171 } 172 173 if hs.serverHello.ocspStapling || 174 hs.serverHello.ticketSupported || 175 hs.serverHello.extendedMasterSecret || 176 hs.serverHello.secureRenegotiationSupported || 177 len(hs.serverHello.secureRenegotiation) != 0 || 178 len(hs.serverHello.alpnProtocol) != 0 || 179 len(hs.serverHello.scts) != 0 { 180 c.sendAlert(alertUnsupportedExtension) 181 return errors.New("tls: server sent a ServerHello extension forbidden in TLS 1.3") 182 } 183 184 if !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) { 185 c.sendAlert(alertIllegalParameter) 186 return errors.New("tls: server did not echo the legacy session ID") 187 } 188 189 if hs.serverHello.compressionMethod != compressionNone { 190 c.sendAlert(alertIllegalParameter) 191 return errors.New("tls: server selected unsupported compression format") 192 } 193 194 selectedSuite := mutualCipherSuiteTLS13(hs.hello.cipherSuites, hs.serverHello.cipherSuite) 195 if hs.suite != nil && selectedSuite != hs.suite { 196 c.sendAlert(alertIllegalParameter) 197 return errors.New("tls: server changed cipher suite after a HelloRetryRequest") 198 } 199 if selectedSuite == nil { 200 c.sendAlert(alertIllegalParameter) 201 return errors.New("tls: server chose an unconfigured cipher suite") 202 } 203 hs.suite = selectedSuite 204 c.cipherSuite = hs.suite.id 205 206 return nil 207 } 208 209 // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility 210 // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4. 211 func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error { 212 if hs.c.quic != nil { 213 return nil 214 } 215 if hs.sentDummyCCS { 216 return nil 217 } 218 hs.sentDummyCCS = true 219 220 return hs.c.writeChangeCipherRecord() 221 } 222 223 // processHelloRetryRequest handles the HRR in hs.serverHello, modifies and 224 // resends hs.hello, and reads the new ServerHello into hs.serverHello. 225 func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error { 226 c := hs.c 227 228 // The first ClientHello gets double-hashed into the transcript upon a 229 // HelloRetryRequest. (The idea is that the server might offload transcript 230 // storage to the client in the cookie.) See RFC 8446, Section 4.4.1. 231 chHash := hs.transcript.Sum(nil) 232 hs.transcript.Reset() 233 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) 234 hs.transcript.Write(chHash) 235 if err := transcriptMsg(hs.serverHello, hs.transcript); err != nil { 236 return err 237 } 238 239 // The only HelloRetryRequest extensions we support are key_share and 240 // cookie, and clients must abort the handshake if the HRR would not result 241 // in any change in the ClientHello. 242 if hs.serverHello.selectedGroup == 0 && hs.serverHello.cookie == nil { 243 c.sendAlert(alertIllegalParameter) 244 return errors.New("tls: server sent an unnecessary HelloRetryRequest message") 245 } 246 247 if hs.serverHello.cookie != nil { 248 hs.hello.cookie = hs.serverHello.cookie 249 } 250 251 if hs.serverHello.serverShare.group != 0 { 252 c.sendAlert(alertDecodeError) 253 return errors.New("tls: received malformed key_share extension") 254 } 255 256 // If the server sent a key_share extension selecting a group, ensure it's 257 // a group we advertised but did not send a key share for, and send a key 258 // share for it this time. 259 if curveID := hs.serverHello.selectedGroup; curveID != 0 { 260 curveOK := false 261 for _, id := range hs.hello.supportedCurves { 262 if id == curveID { 263 curveOK = true 264 break 265 } 266 } 267 if !curveOK { 268 c.sendAlert(alertIllegalParameter) 269 return errors.New("tls: server selected unsupported group") 270 } 271 if sentID, _ := curveIDForCurve(hs.ecdheKey.Curve()); sentID == curveID { 272 c.sendAlert(alertIllegalParameter) 273 return errors.New("tls: server sent an unnecessary HelloRetryRequest key_share") 274 } 275 if _, ok := curveForCurveID(curveID); !ok { 276 c.sendAlert(alertInternalError) 277 return errors.New("tls: CurvePreferences includes unsupported curve") 278 } 279 key, err := generateECDHEKey(c.config.rand(), curveID) 280 if err != nil { 281 c.sendAlert(alertInternalError) 282 return err 283 } 284 hs.ecdheKey = key 285 hs.hello.keyShares = []keyShare{{group: curveID, data: key.PublicKey().Bytes()}} 286 } 287 288 hs.hello.raw = nil 289 if len(hs.hello.pskIdentities) > 0 { 290 pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite) 291 if pskSuite == nil { 292 return c.sendAlert(alertInternalError) 293 } 294 if pskSuite.hash == hs.suite.hash { 295 // Update binders and obfuscated_ticket_age. 296 ticketAge := c.config.time().Sub(time.Unix(int64(hs.session.createdAt), 0)) 297 hs.hello.pskIdentities[0].obfuscatedTicketAge = uint32(ticketAge/time.Millisecond) + hs.session.ageAdd 298 299 transcript := hs.suite.hash.New() 300 transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) 301 transcript.Write(chHash) 302 if err := transcriptMsg(hs.serverHello, transcript); err != nil { 303 return err 304 } 305 helloBytes, err := hs.hello.marshalWithoutBinders() 306 if err != nil { 307 return err 308 } 309 transcript.Write(helloBytes) 310 pskBinders := [][]byte{hs.suite.finishedHash(hs.binderKey, transcript)} 311 if err := hs.hello.updateBinders(pskBinders); err != nil { 312 return err 313 } 314 } else { 315 // Server selected a cipher suite incompatible with the PSK. 316 hs.hello.pskIdentities = nil 317 hs.hello.pskBinders = nil 318 } 319 } 320 321 // [uTLS SECTION BEGINS] 322 // crypto/tls code above this point had changed crypto/tls structures in accordance with HRR, and is about 323 // to call default marshaller. 324 // Instead, we fill uTLS-specific structs and call uTLS marshaller. 325 // Only extensionCookie, extensionPreSharedKey, extensionKeyShare, extensionEarlyData, extensionSupportedVersions, 326 // and utlsExtensionPadding are supposed to change 327 if hs.uconn != nil { 328 if hs.uconn.ClientHelloID != HelloGolang { 329 if len(hs.hello.pskIdentities) > 0 { 330 // TODO: wait for someone who cares about PSK to implement 331 return errors.New("uTLS does not support reprocessing of PSK key triggered by HelloRetryRequest") 332 } 333 334 keyShareExtFound := false 335 for _, ext := range hs.uconn.Extensions { 336 // new ks seems to be generated either way 337 if ks, ok := ext.(*KeyShareExtension); ok { 338 ks.KeyShares = keyShares(hs.hello.keyShares).ToPublic() 339 keyShareExtFound = true 340 } 341 } 342 if !keyShareExtFound { 343 return errors.New("uTLS: received HelloRetryRequest, but keyshare not found among client's " + 344 "uconn.Extensions") 345 } 346 347 if len(hs.serverHello.cookie) > 0 { 348 // serverHello specified a cookie, let's echo it 349 cookieFound := false 350 for _, ext := range hs.uconn.Extensions { 351 if ks, ok := ext.(*CookieExtension); ok { 352 ks.Cookie = hs.serverHello.cookie 353 cookieFound = true 354 } 355 } 356 357 if !cookieFound { 358 // pick a random index where to add cookieExtension 359 // -2 instead of -1 is a lazy way to ensure that PSK is still a last extension 360 p, err := newPRNG() 361 if err != nil { 362 return err 363 } 364 cookieIndex := p.Intn(len(hs.uconn.Extensions) - 2) 365 if cookieIndex >= len(hs.uconn.Extensions) { 366 // this check is for empty hs.uconn.Extensions 367 return fmt.Errorf("cookieIndex >= len(hs.uconn.Extensions): %v >= %v", 368 cookieIndex, len(hs.uconn.Extensions)) 369 } 370 hs.uconn.Extensions = append(hs.uconn.Extensions[:cookieIndex], 371 append([]TLSExtension{&CookieExtension{Cookie: hs.serverHello.cookie}}, 372 hs.uconn.Extensions[cookieIndex:]...)...) 373 } 374 } 375 if err := hs.uconn.MarshalClientHello(); err != nil { 376 return err 377 } 378 hs.hello.raw = hs.uconn.HandshakeState.Hello.Raw 379 } 380 } 381 // [uTLS SECTION ENDS] 382 if hs.hello.earlyData { 383 hs.hello.earlyData = false 384 c.quicRejectedEarlyData() 385 } 386 387 if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil { 388 return err 389 } 390 391 // serverHelloMsg is not included in the transcript 392 msg, err := c.readHandshake(nil) 393 if err != nil { 394 return err 395 } 396 397 serverHello, ok := msg.(*serverHelloMsg) 398 if !ok { 399 c.sendAlert(alertUnexpectedMessage) 400 return unexpectedMessageError(serverHello, msg) 401 } 402 hs.serverHello = serverHello 403 404 if err := hs.checkServerHelloOrHRR(); err != nil { 405 return err 406 } 407 408 return nil 409 } 410 411 func (hs *clientHandshakeStateTLS13) processServerHello() error { 412 c := hs.c 413 414 if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) { 415 c.sendAlert(alertUnexpectedMessage) 416 return errors.New("tls: server sent two HelloRetryRequest messages") 417 } 418 419 if len(hs.serverHello.cookie) != 0 { 420 c.sendAlert(alertUnsupportedExtension) 421 return errors.New("tls: server sent a cookie in a normal ServerHello") 422 } 423 424 if hs.serverHello.selectedGroup != 0 { 425 c.sendAlert(alertDecodeError) 426 return errors.New("tls: malformed key_share extension") 427 } 428 429 if hs.serverHello.serverShare.group == 0 { 430 c.sendAlert(alertIllegalParameter) 431 return errors.New("tls: server did not send a key share") 432 } 433 if sentID, _ := curveIDForCurve(hs.ecdheKey.Curve()); hs.serverHello.serverShare.group != sentID { 434 c.sendAlert(alertIllegalParameter) 435 return errors.New("tls: server selected unsupported group") 436 } 437 438 if !hs.serverHello.selectedIdentityPresent { 439 return nil 440 } 441 442 if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) { 443 c.sendAlert(alertIllegalParameter) 444 return errors.New("tls: server selected an invalid PSK") 445 } 446 447 if len(hs.hello.pskIdentities) != 1 || hs.session == nil { 448 return c.sendAlert(alertInternalError) 449 } 450 pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite) 451 if pskSuite == nil { 452 return c.sendAlert(alertInternalError) 453 } 454 if pskSuite.hash != hs.suite.hash { 455 c.sendAlert(alertIllegalParameter) 456 return errors.New("tls: server selected an invalid PSK and cipher suite pair") 457 } 458 459 hs.usingPSK = true 460 c.didResume = true 461 debugf(hs.uconn.Conn, "hs.usingPSK, c.didResume\n") // #Restls# 462 c.peerCertificates = hs.session.peerCertificates 463 c.activeCertHandles = hs.session.activeCertHandles 464 c.verifiedChains = hs.session.verifiedChains 465 c.ocspResponse = hs.session.ocspResponse 466 c.scts = hs.session.scts 467 return nil 468 } 469 470 func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error { 471 c := hs.c 472 473 peerKey, err := hs.ecdheKey.Curve().NewPublicKey(hs.serverHello.serverShare.data) 474 if err != nil { 475 c.sendAlert(alertIllegalParameter) 476 return errors.New("tls: invalid server key share") 477 } 478 sharedKey, err := hs.ecdheKey.ECDH(peerKey) 479 if err != nil { 480 c.sendAlert(alertIllegalParameter) 481 return errors.New("tls: invalid server key share") 482 } 483 484 earlySecret := hs.earlySecret 485 if !hs.usingPSK { 486 earlySecret = hs.suite.extract(nil, nil) 487 } 488 489 handshakeSecret := hs.suite.extract(sharedKey, 490 hs.suite.deriveSecret(earlySecret, "derived", nil)) 491 492 clientSecret := hs.suite.deriveSecret(handshakeSecret, 493 clientHandshakeTrafficLabel, hs.transcript) 494 c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, clientSecret) 495 serverSecret := hs.suite.deriveSecret(handshakeSecret, 496 serverHandshakeTrafficLabel, hs.transcript) 497 c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret) 498 499 if c.quic != nil { 500 if c.hand.Len() != 0 { 501 c.sendAlert(alertUnexpectedMessage) 502 } 503 c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, clientSecret) 504 c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret) 505 } 506 507 err = c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret) 508 if err != nil { 509 c.sendAlert(alertInternalError) 510 return err 511 } 512 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret) 513 if err != nil { 514 c.sendAlert(alertInternalError) 515 return err 516 } 517 518 hs.masterSecret = hs.suite.extract(nil, 519 hs.suite.deriveSecret(handshakeSecret, "derived", nil)) 520 521 return nil 522 } 523 524 func (hs *clientHandshakeStateTLS13) readServerParameters() error { 525 c := hs.c 526 527 msg, err := c.readHandshake(hs.transcript) 528 if err != nil { 529 return err 530 } 531 532 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg) 533 if !ok { 534 c.sendAlert(alertUnexpectedMessage) 535 return unexpectedMessageError(encryptedExtensions, msg) 536 } 537 538 if err := checkALPN(hs.hello.alpnProtocols, encryptedExtensions.alpnProtocol, c.quic != nil); err != nil { 539 // RFC 8446 specifies that no_application_protocol is sent by servers, but 540 // does not specify how clients handle the selection of an incompatible protocol. 541 // RFC 9001 Section 8.1 specifies that QUIC clients send no_application_protocol 542 // in this case. Always sending no_application_protocol seems reasonable. 543 c.sendAlert(alertNoApplicationProtocol) 544 return err 545 } 546 c.clientProtocol = encryptedExtensions.alpnProtocol 547 548 // [UTLS SECTION STARTS] 549 if hs.uconn != nil { 550 err = hs.utlsReadServerParameters(encryptedExtensions) 551 if err != nil { 552 c.sendAlert(alertUnsupportedExtension) 553 return err 554 } 555 } 556 // [UTLS SECTION ENDS] 557 558 if c.quic != nil { 559 if encryptedExtensions.quicTransportParameters == nil { 560 // RFC 9001 Section 8.2. 561 c.sendAlert(alertMissingExtension) 562 return errors.New("tls: server did not send a quic_transport_parameters extension") 563 } 564 c.quicSetTransportParameters(encryptedExtensions.quicTransportParameters) 565 } else { 566 if encryptedExtensions.quicTransportParameters != nil { 567 c.sendAlert(alertUnsupportedExtension) 568 return errors.New("tls: server sent an unexpected quic_transport_parameters extension") 569 } 570 } 571 572 if !hs.hello.earlyData && encryptedExtensions.earlyData { 573 c.sendAlert(alertUnsupportedExtension) 574 return errors.New("tls: server sent an unexpected early_data extension") 575 } 576 if hs.hello.earlyData && !encryptedExtensions.earlyData { 577 c.quicRejectedEarlyData() 578 } 579 if encryptedExtensions.earlyData { 580 if hs.session.cipherSuite != c.cipherSuite { 581 c.sendAlert(alertHandshakeFailure) 582 return errors.New("tls: server accepted 0-RTT with the wrong cipher suite") 583 } 584 if hs.session.alpnProtocol != c.clientProtocol { 585 c.sendAlert(alertHandshakeFailure) 586 return errors.New("tls: server accepted 0-RTT with the wrong ALPN") 587 } 588 } 589 590 return nil 591 } 592 593 func (hs *clientHandshakeStateTLS13) readServerCertificate() error { 594 c := hs.c 595 596 // Either a PSK or a certificate is always used, but not both. 597 // See RFC 8446, Section 4.1.1. 598 if hs.usingPSK { 599 // Make sure the connection is still being verified whether or not this 600 // is a resumption. Resumptions currently don't reverify certificates so 601 // they don't call verifyServerCertificate. See Issue 31641. 602 if c.config.VerifyConnection != nil { 603 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 604 c.sendAlert(alertBadCertificate) 605 return err 606 } 607 } 608 return nil 609 } 610 611 // [UTLS SECTION BEGINS] 612 // msg, err := c.readHandshake(hs.transcript) 613 msg, err := c.readHandshake(nil) // hold writing to transcript until we know it is not compressed cert 614 // [UTLS SECTION ENDS] 615 if err != nil { 616 return err 617 } 618 619 certReq, ok := msg.(*certificateRequestMsgTLS13) 620 if ok { 621 hs.certReq = certReq 622 transcriptMsg(certReq, hs.transcript) // [UTLS] if it is certReq (not compressedCert), write to transcript 623 624 // msg, err = c.readHandshake(hs.transcript) 625 msg, err = c.readHandshake(nil) // [UTLS] we don't write to transcript until make sure it is not compressed cert 626 if err != nil { 627 return err 628 } 629 } 630 631 // [UTLS SECTION BEGINS] 632 var skipWritingCertToTranscript bool = false 633 if hs.uconn != nil { 634 processedMsg, err := hs.utlsReadServerCertificate(msg) 635 if err != nil { 636 return err 637 } 638 if processedMsg != nil { 639 skipWritingCertToTranscript = true 640 msg = processedMsg // msg is now a processed-by-extension certificateMsg 641 } 642 } 643 // [UTLS SECTION ENDS] 644 645 certMsg, ok := msg.(*certificateMsgTLS13) 646 if !ok { 647 c.sendAlert(alertUnexpectedMessage) 648 return unexpectedMessageError(certMsg, msg) 649 } 650 if len(certMsg.certificate.Certificate) == 0 { 651 c.sendAlert(alertDecodeError) 652 return errors.New("tls: received empty certificates message") 653 } 654 // [UTLS SECTION BEGINS] 655 if !skipWritingCertToTranscript { // write to transcript only if it is not compressedCert (i.e. if not processed by extension) 656 if err = transcriptMsg(certMsg, hs.transcript); err != nil { 657 return err 658 } 659 } 660 // [UTLS SECTION ENDS] 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 710 func (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 761 func (hs *clientHandshakeStateTLS13) sendClientCertificate() error { 762 c := hs.c 763 764 if hs.certReq == nil { 765 return nil 766 } 767 768 cert, err := c.getClientCertificate(&CertificateRequestInfo{ 769 AcceptableCAs: hs.certReq.certificateAuthorities, 770 SignatureSchemes: hs.certReq.supportedSignatureAlgorithms, 771 Version: c.vers, 772 ctx: hs.ctx, 773 }) 774 if err != nil { 775 return err 776 } 777 778 certMsg := new(certificateMsgTLS13) 779 780 certMsg.certificate = *cert 781 certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0 782 certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0 783 784 if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil { 785 return err 786 } 787 788 // If we sent an empty certificate message, skip the CertificateVerify. 789 if len(cert.Certificate) == 0 { 790 return nil 791 } 792 793 certVerifyMsg := new(certificateVerifyMsg) 794 certVerifyMsg.hasSignatureAlgorithm = true 795 796 certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms) 797 if err != nil { 798 // getClientCertificate returned a certificate incompatible with the 799 // CertificateRequestInfo supported signature algorithms. 800 c.sendAlert(alertHandshakeFailure) 801 return err 802 } 803 804 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm) 805 if err != nil { 806 return c.sendAlert(alertInternalError) 807 } 808 809 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript) 810 signOpts := crypto.SignerOpts(sigHash) 811 if sigType == signatureRSAPSS { 812 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash} 813 } 814 sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts) 815 if err != nil { 816 c.sendAlert(alertInternalError) 817 return errors.New("tls: failed to sign handshake: " + err.Error()) 818 } 819 certVerifyMsg.signature = sig 820 821 if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil { 822 return err 823 } 824 825 return nil 826 } 827 828 func (hs *clientHandshakeStateTLS13) sendClientFinished() error { 829 c := hs.c 830 831 finished := &finishedMsg{ 832 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript), 833 } 834 835 c.out.restlsPlugin.WritingClientFinished() // #Restls# 836 if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil { 837 return err 838 } 839 840 c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret) 841 842 if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil { 843 c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret, 844 resumptionLabel, hs.transcript) 845 } 846 847 if c.quic != nil { 848 if c.hand.Len() != 0 { 849 c.sendAlert(alertUnexpectedMessage) 850 } 851 c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, hs.trafficSecret) 852 } 853 854 return nil 855 } 856 857 func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error { 858 if !c.isClient { 859 c.sendAlert(alertUnexpectedMessage) 860 return errors.New("tls: received new session ticket from a client") 861 } 862 863 debugf(c, "c.config.SessionTicketsDisabled %v || c.config.ClientSessionCache == nil %v\n", c.config.SessionTicketsDisabled, c.config.ClientSessionCache == nil) // #Restls# 864 865 if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil { 866 return nil 867 } 868 869 // See RFC 8446, Section 4.6.1. 870 if msg.lifetime == 0 { 871 return nil 872 } 873 lifetime := time.Duration(msg.lifetime) * time.Second 874 if lifetime > maxSessionTicketLifetime { 875 c.sendAlert(alertIllegalParameter) 876 return errors.New("tls: received a session ticket with invalid lifetime") 877 } 878 879 // RFC 9001, Section 4.6.1 880 if c.quic != nil && msg.maxEarlyData != 0 && msg.maxEarlyData != 0xffffffff { 881 c.sendAlert(alertIllegalParameter) 882 return errors.New("tls: invalid early data for QUIC connection") 883 } 884 885 cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite) 886 if cipherSuite == nil || c.resumptionSecret == nil { 887 return c.sendAlert(alertInternalError) 888 } 889 890 psk := cipherSuite.expandLabel(c.resumptionSecret, "resumption", 891 msg.nonce, cipherSuite.hash.Size()) 892 893 session, err := c.sessionState() 894 if err != nil { 895 c.sendAlert(alertInternalError) 896 return err 897 } 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 cs := &ClientSessionState{ticket: msg.label, session: session} 903 904 if cacheKey := c.clientSessionCacheKey(); cacheKey != "" { 905 debugf(c, "tls 1.3 add new session") // #Restls# 906 c.config.ClientSessionCache.Put(cacheKey, cs) 907 } 908 909 return nil 910 }