git.prognetwork.ru/x0r/utls@v1.3.3/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/hmac" 12 "crypto/rsa" 13 "errors" 14 "fmt" 15 "hash" 16 "sync/atomic" 17 "time" 18 ) 19 20 // [uTLS SECTION START] 21 type KeySharesEcdheParameters map[CurveID]ecdheParameters 22 23 func (keymap KeySharesEcdheParameters) AddEcdheParams(curveID CurveID, params ecdheParameters) { 24 keymap[curveID] = params 25 } 26 func (keymap KeySharesEcdheParameters) GetEcdheParams(curveID CurveID) (params ecdheParameters, ok bool) { 27 params, ok = keymap[curveID] 28 return 29 } 30 func (keymap KeySharesEcdheParameters) GetPublicEcdheParams(curveID CurveID) (params EcdheParameters, 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 ecdheParams ecdheParameters 43 keySharesEcdheParams KeySharesEcdheParameters // [uTLS] 44 45 session *ClientSessionState 46 earlySecret []byte 47 binderKey []byte 48 49 certReq *certificateRequestMsgTLS13 50 usingPSK bool 51 sentDummyCCS bool 52 suite *cipherSuiteTLS13 53 transcript hash.Hash 54 masterSecret []byte 55 trafficSecret []byte // client_application_traffic_secret_0 56 57 uconn *UConn // [uTLS] 58 } 59 60 // handshake requires hs.c, hs.hello, hs.serverHello, hs.ecdheParams, and, 61 // optionally, hs.session, hs.earlySecret and hs.binderKey to be set. 62 func (hs *clientHandshakeStateTLS13) handshake() error { 63 c := hs.c 64 65 if needFIPS() { 66 return errors.New("tls: internal error: TLS 1.3 reached in FIPS mode") 67 } 68 69 // The server must not select TLS 1.3 in a renegotiation. See RFC 8446, 70 // sections 4.1.2 and 4.1.3. 71 if c.handshakes > 0 { 72 c.sendAlert(alertProtocolVersion) 73 return errors.New("tls: server selected TLS 1.3 in a renegotiation") 74 } 75 76 // [uTLS SECTION START] 77 78 // set echdheParams to what we received from server 79 if ecdheParams, ok := hs.keySharesEcdheParams.GetEcdheParams(hs.serverHello.serverShare.group); ok { 80 hs.ecdheParams = ecdheParams 81 } 82 // [uTLS SECTION END] 83 84 // Consistency check on the presence of a keyShare and its parameters. 85 if hs.ecdheParams == nil || len(hs.hello.keyShares) < 1 { // [uTLS] 86 // keyshares "< 1" instead of "!= 1", as uTLS may send multiple 87 return c.sendAlert(alertInternalError) 88 } 89 90 if err := hs.checkServerHelloOrHRR(); err != nil { 91 return err 92 } 93 94 hs.transcript = hs.suite.hash.New() 95 96 if err := transcriptMsg(hs.hello, hs.transcript); err != nil { 97 return err 98 } 99 100 if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) { 101 if err := hs.sendDummyChangeCipherSpec(); err != nil { 102 return err 103 } 104 if err := hs.processHelloRetryRequest(); err != nil { 105 return err 106 } 107 } 108 109 if err := transcriptMsg(hs.serverHello, hs.transcript); err != nil { 110 return err 111 } 112 113 c.buffering = true 114 if err := hs.processServerHello(); err != nil { 115 return err 116 } 117 if err := hs.sendDummyChangeCipherSpec(); err != nil { 118 return err 119 } 120 if err := hs.establishHandshakeKeys(); err != nil { 121 return err 122 } 123 if err := hs.readServerParameters(); err != nil { 124 return err 125 } 126 if err := hs.readServerCertificate(); err != nil { 127 return err 128 } 129 if err := hs.readServerFinished(); err != nil { 130 return err 131 } 132 // [UTLS SECTION START] 133 if err := hs.serverFinishedReceived(); err != nil { 134 return err 135 } 136 // [UTLS SECTION END] 137 if err := hs.sendClientCertificate(); err != nil { 138 return err 139 } 140 if err := hs.sendClientFinished(); err != nil { 141 return err 142 } 143 if _, err := c.flush(); err != nil { 144 return err 145 } 146 147 atomic.StoreUint32(&c.handshakeStatus, 1) 148 149 return nil 150 } 151 152 // checkServerHelloOrHRR does validity checks that apply to both ServerHello and 153 // HelloRetryRequest messages. It sets hs.suite. 154 func (hs *clientHandshakeStateTLS13) checkServerHelloOrHRR() error { 155 c := hs.c 156 157 if hs.serverHello.supportedVersion == 0 { 158 c.sendAlert(alertMissingExtension) 159 return errors.New("tls: server selected TLS 1.3 using the legacy version field") 160 } 161 162 if hs.serverHello.supportedVersion != VersionTLS13 { 163 c.sendAlert(alertIllegalParameter) 164 return errors.New("tls: server selected an invalid version after a HelloRetryRequest") 165 } 166 167 if hs.serverHello.vers != VersionTLS12 { 168 c.sendAlert(alertIllegalParameter) 169 return errors.New("tls: server sent an incorrect legacy version") 170 } 171 172 if hs.serverHello.ocspStapling || 173 hs.serverHello.ticketSupported || 174 hs.serverHello.secureRenegotiationSupported || 175 len(hs.serverHello.secureRenegotiation) != 0 || 176 len(hs.serverHello.alpnProtocol) != 0 || 177 len(hs.serverHello.scts) != 0 { 178 c.sendAlert(alertUnsupportedExtension) 179 return errors.New("tls: server sent a ServerHello extension forbidden in TLS 1.3") 180 } 181 182 if !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) { 183 c.sendAlert(alertIllegalParameter) 184 return errors.New("tls: server did not echo the legacy session ID") 185 } 186 187 if hs.serverHello.compressionMethod != compressionNone { 188 c.sendAlert(alertIllegalParameter) 189 return errors.New("tls: server selected unsupported compression format") 190 } 191 192 selectedSuite := mutualCipherSuiteTLS13(hs.hello.cipherSuites, hs.serverHello.cipherSuite) 193 if hs.suite != nil && selectedSuite != hs.suite { 194 c.sendAlert(alertIllegalParameter) 195 return errors.New("tls: server changed cipher suite after a HelloRetryRequest") 196 } 197 if selectedSuite == nil { 198 c.sendAlert(alertIllegalParameter) 199 return errors.New("tls: server chose an unconfigured cipher suite") 200 } 201 hs.suite = selectedSuite 202 c.cipherSuite = hs.suite.id 203 204 return nil 205 } 206 207 // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility 208 // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4. 209 func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error { 210 if hs.sentDummyCCS { 211 return nil 212 } 213 hs.sentDummyCCS = true 214 215 return hs.c.writeChangeCipherRecord() 216 } 217 218 // processHelloRetryRequest handles the HRR in hs.serverHello, modifies and 219 // resends hs.hello, and reads the new ServerHello into hs.serverHello. 220 func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error { 221 c := hs.c 222 223 // The first ClientHello gets double-hashed into the transcript upon a 224 // HelloRetryRequest. (The idea is that the server might offload transcript 225 // storage to the client in the cookie.) See RFC 8446, Section 4.4.1. 226 chHash := hs.transcript.Sum(nil) 227 hs.transcript.Reset() 228 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) 229 hs.transcript.Write(chHash) 230 if err := transcriptMsg(hs.serverHello, hs.transcript); err != nil { 231 return err 232 } 233 234 // The only HelloRetryRequest extensions we support are key_share and 235 // cookie, and clients must abort the handshake if the HRR would not result 236 // in any change in the ClientHello. 237 if hs.serverHello.selectedGroup == 0 && hs.serverHello.cookie == nil { 238 c.sendAlert(alertIllegalParameter) 239 return errors.New("tls: server sent an unnecessary HelloRetryRequest message") 240 } 241 242 if hs.serverHello.cookie != nil { 243 hs.hello.cookie = hs.serverHello.cookie 244 } 245 246 // The only HelloRetryRequest extensions we support are key_share and 247 // cookie, and clients must abort the handshake if the HRR would not result 248 // in any change in the ClientHello. 249 if hs.serverHello.selectedGroup == 0 && hs.serverHello.cookie == nil { 250 c.sendAlert(alertIllegalParameter) 251 return errors.New("tls: server sent an unnecessary HelloRetryRequest message") 252 } 253 254 if hs.serverHello.cookie != nil { 255 hs.hello.cookie = hs.serverHello.cookie 256 } 257 258 if hs.serverHello.serverShare.group != 0 { 259 c.sendAlert(alertDecodeError) 260 return errors.New("tls: received malformed key_share extension") 261 } 262 263 // If the server sent a key_share extension selecting a group, ensure it's 264 // a group we advertised but did not send a key share for, and send a key 265 // share for it this time. 266 if curveID := hs.serverHello.selectedGroup; curveID != 0 { 267 curveOK := false 268 for _, id := range hs.hello.supportedCurves { 269 if id == curveID { 270 curveOK = true 271 break 272 } 273 } 274 if !curveOK { 275 c.sendAlert(alertIllegalParameter) 276 return errors.New("tls: server selected unsupported group") 277 } 278 if hs.ecdheParams.CurveID() == curveID { 279 c.sendAlert(alertIllegalParameter) 280 return errors.New("tls: server sent an unnecessary HelloRetryRequest key_share") 281 } 282 if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok { 283 c.sendAlert(alertInternalError) 284 return errors.New("tls: CurvePreferences includes unsupported curve") 285 } 286 params, err := generateECDHEParameters(c.config.rand(), curveID) 287 if err != nil { 288 c.sendAlert(alertInternalError) 289 return err 290 } 291 hs.ecdheParams = params 292 hs.hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}} 293 } 294 295 hs.hello.raw = nil 296 if len(hs.hello.pskIdentities) > 0 { 297 pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite) 298 if pskSuite == nil { 299 return c.sendAlert(alertInternalError) 300 } 301 if pskSuite.hash == hs.suite.hash { 302 // Update binders and obfuscated_ticket_age. 303 ticketAge := uint32(c.config.time().Sub(hs.session.receivedAt) / time.Millisecond) 304 hs.hello.pskIdentities[0].obfuscatedTicketAge = ticketAge + hs.session.ageAdd 305 306 transcript := hs.suite.hash.New() 307 transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) 308 transcript.Write(chHash) 309 if err := transcriptMsg(hs.serverHello, hs.transcript); err != nil { 310 return err 311 } 312 helloBytes, err := hs.hello.marshalWithoutBinders() 313 if err != nil { 314 return err 315 } 316 transcript.Write(helloBytes) 317 pskBinders := [][]byte{hs.suite.finishedHash(hs.binderKey, transcript)} 318 if err := hs.hello.updateBinders(pskBinders); err != nil { 319 return err 320 } 321 } else { 322 // Server selected a cipher suite incompatible with the PSK. 323 hs.hello.pskIdentities = nil 324 hs.hello.pskBinders = nil 325 } 326 } 327 328 // [uTLS SECTION BEGINS] 329 // crypto/tls code above this point had changed crypto/tls structures in accordance with HRR, and is about 330 // to call default marshaller. 331 // Instead, we fill uTLS-specific structs and call uTLS marshaller. 332 // Only extensionCookie, extensionPreSharedKey, extensionKeyShare, extensionEarlyData, extensionSupportedVersions, 333 // and utlsExtensionPadding are supposed to change 334 if hs.uconn != nil { 335 if hs.uconn.ClientHelloID != HelloGolang { 336 if len(hs.hello.pskIdentities) > 0 { 337 // TODO: wait for someone who cares about PSK to implement 338 return errors.New("uTLS does not support reprocessing of PSK key triggered by HelloRetryRequest") 339 } 340 341 keyShareExtFound := false 342 for _, ext := range hs.uconn.Extensions { 343 // new ks seems to be generated either way 344 if ks, ok := ext.(*KeyShareExtension); ok { 345 ks.KeyShares = keyShares(hs.hello.keyShares).ToPublic() 346 keyShareExtFound = true 347 } 348 } 349 if !keyShareExtFound { 350 return errors.New("uTLS: received HelloRetryRequest, but keyshare not found among client's " + 351 "uconn.Extensions") 352 } 353 354 if len(hs.serverHello.cookie) > 0 { 355 // serverHello specified a cookie, let's echo it 356 cookieFound := false 357 for _, ext := range hs.uconn.Extensions { 358 if ks, ok := ext.(*CookieExtension); ok { 359 ks.Cookie = hs.serverHello.cookie 360 cookieFound = true 361 } 362 } 363 364 if !cookieFound { 365 // pick a random index where to add cookieExtension 366 // -2 instead of -1 is a lazy way to ensure that PSK is still a last extension 367 p, err := newPRNG() 368 if err != nil { 369 return err 370 } 371 cookieIndex := p.Intn(len(hs.uconn.Extensions) - 2) 372 if cookieIndex >= len(hs.uconn.Extensions) { 373 // this check is for empty hs.uconn.Extensions 374 return fmt.Errorf("cookieIndex >= len(hs.uconn.Extensions): %v >= %v", 375 cookieIndex, len(hs.uconn.Extensions)) 376 } 377 hs.uconn.Extensions = append(hs.uconn.Extensions[:cookieIndex], 378 append([]TLSExtension{&CookieExtension{Cookie: hs.serverHello.cookie}}, 379 hs.uconn.Extensions[cookieIndex:]...)...) 380 } 381 } 382 if err := hs.uconn.MarshalClientHello(); err != nil { 383 return err 384 } 385 hs.hello.raw = hs.uconn.HandshakeState.Hello.Raw 386 } 387 } 388 // [uTLS SECTION ENDS] 389 390 if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil { 391 return err 392 } 393 394 // serverHelloMsg is not included in the transcript 395 msg, err := c.readHandshake(nil) 396 if err != nil { 397 return err 398 } 399 400 serverHello, ok := msg.(*serverHelloMsg) 401 if !ok { 402 c.sendAlert(alertUnexpectedMessage) 403 return unexpectedMessageError(serverHello, msg) 404 } 405 hs.serverHello = serverHello 406 407 if err := hs.checkServerHelloOrHRR(); err != nil { 408 return err 409 } 410 411 return nil 412 } 413 414 func (hs *clientHandshakeStateTLS13) processServerHello() error { 415 c := hs.c 416 417 if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) { 418 c.sendAlert(alertUnexpectedMessage) 419 return errors.New("tls: server sent two HelloRetryRequest messages") 420 } 421 422 if len(hs.serverHello.cookie) != 0 { 423 c.sendAlert(alertUnsupportedExtension) 424 return errors.New("tls: server sent a cookie in a normal ServerHello") 425 } 426 427 if hs.serverHello.selectedGroup != 0 { 428 c.sendAlert(alertDecodeError) 429 return errors.New("tls: malformed key_share extension") 430 } 431 432 if hs.serverHello.serverShare.group == 0 { 433 c.sendAlert(alertIllegalParameter) 434 return errors.New("tls: server did not send a key share") 435 } 436 if hs.serverHello.serverShare.group != hs.ecdheParams.CurveID() { 437 c.sendAlert(alertIllegalParameter) 438 return errors.New("tls: server selected unsupported group") 439 } 440 441 if !hs.serverHello.selectedIdentityPresent { 442 return nil 443 } 444 445 if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) { 446 c.sendAlert(alertIllegalParameter) 447 return errors.New("tls: server selected an invalid PSK") 448 } 449 450 if len(hs.hello.pskIdentities) != 1 || hs.session == nil { 451 return c.sendAlert(alertInternalError) 452 } 453 pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite) 454 if pskSuite == nil { 455 return c.sendAlert(alertInternalError) 456 } 457 if pskSuite.hash != hs.suite.hash { 458 c.sendAlert(alertIllegalParameter) 459 return errors.New("tls: server selected an invalid PSK and cipher suite pair") 460 } 461 462 hs.usingPSK = true 463 c.didResume = true 464 c.peerCertificates = hs.session.serverCertificates 465 c.verifiedChains = hs.session.verifiedChains 466 c.ocspResponse = hs.session.ocspResponse 467 c.scts = hs.session.scts 468 return nil 469 } 470 471 func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error { 472 c := hs.c 473 474 sharedKey := hs.ecdheParams.SharedKey(hs.serverHello.serverShare.data) 475 if sharedKey == nil { 476 c.sendAlert(alertIllegalParameter) 477 return errors.New("tls: invalid server key share") 478 } 479 480 earlySecret := hs.earlySecret 481 if !hs.usingPSK { 482 earlySecret = hs.suite.extract(nil, nil) 483 } 484 485 handshakeSecret := hs.suite.extract(sharedKey, 486 hs.suite.deriveSecret(earlySecret, "derived", nil)) 487 488 clientSecret := hs.suite.deriveSecret(handshakeSecret, 489 clientHandshakeTrafficLabel, hs.transcript) 490 c.out.setTrafficSecret(hs.suite, clientSecret) 491 serverSecret := hs.suite.deriveSecret(handshakeSecret, 492 serverHandshakeTrafficLabel, hs.transcript) 493 c.in.setTrafficSecret(hs.suite, serverSecret) 494 495 err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret) 496 if err != nil { 497 c.sendAlert(alertInternalError) 498 return err 499 } 500 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret) 501 if err != nil { 502 c.sendAlert(alertInternalError) 503 return err 504 } 505 506 hs.masterSecret = hs.suite.extract(nil, 507 hs.suite.deriveSecret(handshakeSecret, "derived", nil)) 508 509 return nil 510 } 511 512 func (hs *clientHandshakeStateTLS13) readServerParameters() error { 513 c := hs.c 514 515 msg, err := c.readHandshake(hs.transcript) 516 if err != nil { 517 return err 518 } 519 520 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg) 521 if !ok { 522 c.sendAlert(alertUnexpectedMessage) 523 return unexpectedMessageError(encryptedExtensions, msg) 524 } 525 526 if err := checkALPN(hs.hello.alpnProtocols, encryptedExtensions.alpnProtocol); err != nil { 527 c.sendAlert(alertUnsupportedExtension) 528 return err 529 } 530 c.clientProtocol = encryptedExtensions.alpnProtocol 531 532 // [UTLS SECTION STARTS] 533 if hs.uconn != nil { 534 err = hs.utlsReadServerParameters(encryptedExtensions) 535 if err != nil { 536 c.sendAlert(alertUnsupportedExtension) 537 return err 538 } 539 } 540 // [UTLS SECTION ENDS] 541 return nil 542 } 543 544 func (hs *clientHandshakeStateTLS13) readServerCertificate() error { 545 c := hs.c 546 547 // Either a PSK or a certificate is always used, but not both. 548 // See RFC 8446, Section 4.1.1. 549 if hs.usingPSK { 550 // Make sure the connection is still being verified whether or not this 551 // is a resumption. Resumptions currently don't reverify certificates so 552 // they don't call verifyServerCertificate. See Issue 31641. 553 if c.config.VerifyConnection != nil { 554 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 555 c.sendAlert(alertBadCertificate) 556 return err 557 } 558 } 559 return nil 560 } 561 562 // [UTLS SECTION BEGINS] 563 // msg, err := c.readHandshake(hs.transcript) 564 msg, err := c.readHandshake(nil) // hold writing to transcript until we know it is not compressed cert 565 // [UTLS SECTION ENDS] 566 if err != nil { 567 return err 568 } 569 570 certReq, ok := msg.(*certificateRequestMsgTLS13) 571 if ok { 572 hs.certReq = certReq 573 transcriptMsg(certReq, hs.transcript) // [UTLS] if it is certReq (not compressedCert), write to transcript 574 575 // msg, err = c.readHandshake(hs.transcript) 576 msg, err = c.readHandshake(nil) // [UTLS] we don't write to transcript until make sure it is not compressed cert 577 if err != nil { 578 return err 579 } 580 } 581 582 // [UTLS SECTION BEGINS] 583 var skipWritingCertToTranscript bool = false 584 if hs.uconn != nil { 585 processedMsg, err := hs.utlsReadServerCertificate(msg) 586 if err != nil { 587 return err 588 } 589 if processedMsg != nil { 590 skipWritingCertToTranscript = true 591 msg = processedMsg // msg is now a processed-by-extension certificateMsg 592 } 593 } 594 // [UTLS SECTION ENDS] 595 596 certMsg, ok := msg.(*certificateMsgTLS13) 597 if !ok { 598 c.sendAlert(alertUnexpectedMessage) 599 return unexpectedMessageError(certMsg, msg) 600 } 601 if len(certMsg.certificate.Certificate) == 0 { 602 c.sendAlert(alertDecodeError) 603 return errors.New("tls: received empty certificates message") 604 } 605 // [UTLS SECTION BEGINS] 606 if !skipWritingCertToTranscript { // write to transcript only if it is not compressedCert (i.e. if not processed by extension) 607 if err = transcriptMsg(certMsg, hs.transcript); err != nil { 608 return err 609 } 610 } 611 // [UTLS SECTION ENDS] 612 613 c.scts = certMsg.certificate.SignedCertificateTimestamps 614 c.ocspResponse = certMsg.certificate.OCSPStaple 615 616 if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil { 617 return err 618 } 619 620 // certificateVerifyMsg is included in the transcript, but not until 621 // after we verify the handshake signature, since the state before 622 // this message was sent is used. 623 msg, err = c.readHandshake(nil) 624 if err != nil { 625 return err 626 } 627 628 certVerify, ok := msg.(*certificateVerifyMsg) 629 if !ok { 630 c.sendAlert(alertUnexpectedMessage) 631 return unexpectedMessageError(certVerify, msg) 632 } 633 634 // See RFC 8446, Section 4.4.3. 635 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) { 636 c.sendAlert(alertIllegalParameter) 637 return errors.New("tls: certificate used with invalid signature algorithm") 638 } 639 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm) 640 if err != nil { 641 return c.sendAlert(alertInternalError) 642 } 643 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 { 644 c.sendAlert(alertIllegalParameter) 645 return errors.New("tls: certificate used with invalid signature algorithm") 646 } 647 signed := signedMessage(sigHash, serverSignatureContext, hs.transcript) 648 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey, 649 sigHash, signed, certVerify.signature); err != nil { 650 c.sendAlert(alertDecryptError) 651 return errors.New("tls: invalid signature by the server certificate: " + err.Error()) 652 } 653 654 if err := transcriptMsg(certVerify, hs.transcript); err != nil { 655 return err 656 } 657 658 return nil 659 } 660 661 func (hs *clientHandshakeStateTLS13) readServerFinished() error { 662 c := hs.c 663 664 // finishedMsg is included in the transcript, but not until after we 665 // check the client version, since the state before this message was 666 // sent is used during verification. 667 msg, err := c.readHandshake(nil) 668 if err != nil { 669 return err 670 } 671 672 finished, ok := msg.(*finishedMsg) 673 if !ok { 674 c.sendAlert(alertUnexpectedMessage) 675 return unexpectedMessageError(finished, msg) 676 } 677 678 expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript) 679 if !hmac.Equal(expectedMAC, finished.verifyData) { 680 c.sendAlert(alertDecryptError) 681 return errors.New("tls: invalid server finished hash") 682 } 683 684 if err := transcriptMsg(finished, hs.transcript); err != nil { 685 return err 686 } 687 688 // Derive secrets that take context through the server Finished. 689 690 hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret, 691 clientApplicationTrafficLabel, hs.transcript) 692 serverSecret := hs.suite.deriveSecret(hs.masterSecret, 693 serverApplicationTrafficLabel, hs.transcript) 694 c.in.setTrafficSecret(hs.suite, serverSecret) 695 696 err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret) 697 if err != nil { 698 c.sendAlert(alertInternalError) 699 return err 700 } 701 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret) 702 if err != nil { 703 c.sendAlert(alertInternalError) 704 return err 705 } 706 707 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript) 708 709 return nil 710 } 711 712 func (hs *clientHandshakeStateTLS13) sendClientCertificate() error { 713 c := hs.c 714 715 if hs.certReq == nil { 716 return nil 717 } 718 719 cert, err := c.getClientCertificate(&CertificateRequestInfo{ 720 AcceptableCAs: hs.certReq.certificateAuthorities, 721 SignatureSchemes: hs.certReq.supportedSignatureAlgorithms, 722 Version: c.vers, 723 ctx: hs.ctx, 724 }) 725 if err != nil { 726 return err 727 } 728 729 certMsg := new(certificateMsgTLS13) 730 731 certMsg.certificate = *cert 732 certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0 733 certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0 734 735 if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil { 736 return err 737 } 738 739 // If we sent an empty certificate message, skip the CertificateVerify. 740 if len(cert.Certificate) == 0 { 741 return nil 742 } 743 744 certVerifyMsg := new(certificateVerifyMsg) 745 certVerifyMsg.hasSignatureAlgorithm = true 746 747 certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms) 748 if err != nil { 749 // getClientCertificate returned a certificate incompatible with the 750 // CertificateRequestInfo supported signature algorithms. 751 c.sendAlert(alertHandshakeFailure) 752 return err 753 } 754 755 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm) 756 if err != nil { 757 return c.sendAlert(alertInternalError) 758 } 759 760 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript) 761 signOpts := crypto.SignerOpts(sigHash) 762 if sigType == signatureRSAPSS { 763 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash} 764 } 765 sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts) 766 if err != nil { 767 c.sendAlert(alertInternalError) 768 return errors.New("tls: failed to sign handshake: " + err.Error()) 769 } 770 certVerifyMsg.signature = sig 771 772 if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil { 773 return err 774 } 775 776 return nil 777 } 778 779 func (hs *clientHandshakeStateTLS13) sendClientFinished() error { 780 c := hs.c 781 782 finished := &finishedMsg{ 783 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript), 784 } 785 786 if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil { 787 return err 788 } 789 790 c.out.setTrafficSecret(hs.suite, hs.trafficSecret) 791 792 if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil { 793 c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret, 794 resumptionLabel, hs.transcript) 795 } 796 797 return nil 798 } 799 800 func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error { 801 if !c.isClient { 802 c.sendAlert(alertUnexpectedMessage) 803 return errors.New("tls: received new session ticket from a client") 804 } 805 806 if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil { 807 return nil 808 } 809 810 // See RFC 8446, Section 4.6.1. 811 if msg.lifetime == 0 { 812 return nil 813 } 814 lifetime := time.Duration(msg.lifetime) * time.Second 815 if lifetime > maxSessionTicketLifetime { 816 c.sendAlert(alertIllegalParameter) 817 return errors.New("tls: received a session ticket with invalid lifetime") 818 } 819 820 cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite) 821 if cipherSuite == nil || c.resumptionSecret == nil { 822 return c.sendAlert(alertInternalError) 823 } 824 825 // Save the resumption_master_secret and nonce instead of deriving the PSK 826 // to do the least amount of work on NewSessionTicket messages before we 827 // know if the ticket will be used. Forward secrecy of resumed connections 828 // is guaranteed by the requirement for pskModeDHE. 829 session := &ClientSessionState{ 830 sessionTicket: msg.label, 831 vers: c.vers, 832 cipherSuite: c.cipherSuite, 833 masterSecret: c.resumptionSecret, 834 serverCertificates: c.peerCertificates, 835 verifiedChains: c.verifiedChains, 836 receivedAt: c.config.time(), 837 nonce: msg.nonce, 838 useBy: c.config.time().Add(lifetime), 839 ageAdd: msg.ageAdd, 840 ocspResponse: c.ocspResponse, 841 scts: c.scts, 842 } 843 844 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config) 845 c.config.ClientSessionCache.Put(cacheKey, session) 846 847 return nil 848 }