git.prognetwork.ru/x0r/utls@v1.3.3/handshake_server_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 "encoding/binary" 14 "errors" 15 "hash" 16 "io" 17 "sync/atomic" 18 "time" 19 ) 20 21 // maxClientPSKIdentities is the number of client PSK identities the server will 22 // attempt to validate. It will ignore the rest not to let cheap ClientHello 23 // messages cause too much work in session ticket decryption attempts. 24 const maxClientPSKIdentities = 5 25 26 type serverHandshakeStateTLS13 struct { 27 c *Conn 28 ctx context.Context 29 clientHello *clientHelloMsg 30 hello *serverHelloMsg 31 sentDummyCCS bool 32 usingPSK bool 33 suite *cipherSuiteTLS13 34 cert *Certificate 35 sigAlg SignatureScheme 36 earlySecret []byte 37 sharedKey []byte 38 handshakeSecret []byte 39 masterSecret []byte 40 trafficSecret []byte // client_application_traffic_secret_0 41 transcript hash.Hash 42 clientFinished []byte 43 } 44 45 func (hs *serverHandshakeStateTLS13) 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 // For an overview of the TLS 1.3 handshake, see RFC 8446, Section 2. 53 if err := hs.processClientHello(); err != nil { 54 return err 55 } 56 if err := hs.checkForResumption(); err != nil { 57 return err 58 } 59 if err := hs.pickCertificate(); err != nil { 60 return err 61 } 62 c.buffering = true 63 if err := hs.sendServerParameters(); err != nil { 64 return err 65 } 66 if err := hs.sendServerCertificate(); err != nil { 67 return err 68 } 69 if err := hs.sendServerFinished(); err != nil { 70 return err 71 } 72 // Note that at this point we could start sending application data without 73 // waiting for the client's second flight, but the application might not 74 // expect the lack of replay protection of the ClientHello parameters. 75 if _, err := c.flush(); err != nil { 76 return err 77 } 78 if err := hs.readClientCertificate(); err != nil { 79 return err 80 } 81 if err := hs.readClientFinished(); err != nil { 82 return err 83 } 84 85 atomic.StoreUint32(&c.handshakeStatus, 1) 86 87 return nil 88 } 89 90 func (hs *serverHandshakeStateTLS13) processClientHello() error { 91 c := hs.c 92 93 hs.hello = new(serverHelloMsg) 94 95 // TLS 1.3 froze the ServerHello.legacy_version field, and uses 96 // supported_versions instead. See RFC 8446, sections 4.1.3 and 4.2.1. 97 hs.hello.vers = VersionTLS12 98 hs.hello.supportedVersion = c.vers 99 100 if len(hs.clientHello.supportedVersions) == 0 { 101 c.sendAlert(alertIllegalParameter) 102 return errors.New("tls: client used the legacy version field to negotiate TLS 1.3") 103 } 104 105 // Abort if the client is doing a fallback and landing lower than what we 106 // support. See RFC 7507, which however does not specify the interaction 107 // with supported_versions. The only difference is that with 108 // supported_versions a client has a chance to attempt a [TLS 1.2, TLS 1.4] 109 // handshake in case TLS 1.3 is broken but 1.2 is not. Alas, in that case, 110 // it will have to drop the TLS_FALLBACK_SCSV protection if it falls back to 111 // TLS 1.2, because a TLS 1.3 server would abort here. The situation before 112 // supported_versions was not better because there was just no way to do a 113 // TLS 1.4 handshake without risking the server selecting TLS 1.3. 114 for _, id := range hs.clientHello.cipherSuites { 115 if id == TLS_FALLBACK_SCSV { 116 // Use c.vers instead of max(supported_versions) because an attacker 117 // could defeat this by adding an arbitrary high version otherwise. 118 if c.vers < c.config.maxSupportedVersion(roleServer) { 119 c.sendAlert(alertInappropriateFallback) 120 return errors.New("tls: client using inappropriate protocol fallback") 121 } 122 break 123 } 124 } 125 126 if len(hs.clientHello.compressionMethods) != 1 || 127 hs.clientHello.compressionMethods[0] != compressionNone { 128 c.sendAlert(alertIllegalParameter) 129 return errors.New("tls: TLS 1.3 client supports illegal compression methods") 130 } 131 132 hs.hello.random = make([]byte, 32) 133 if _, err := io.ReadFull(c.config.rand(), hs.hello.random); err != nil { 134 c.sendAlert(alertInternalError) 135 return err 136 } 137 138 if len(hs.clientHello.secureRenegotiation) != 0 { 139 c.sendAlert(alertHandshakeFailure) 140 return errors.New("tls: initial handshake had non-empty renegotiation extension") 141 } 142 143 if hs.clientHello.earlyData { 144 // See RFC 8446, Section 4.2.10 for the complicated behavior required 145 // here. The scenario is that a different server at our address offered 146 // to accept early data in the past, which we can't handle. For now, all 147 // 0-RTT enabled session tickets need to expire before a Go server can 148 // replace a server or join a pool. That's the same requirement that 149 // applies to mixing or replacing with any TLS 1.2 server. 150 c.sendAlert(alertUnsupportedExtension) 151 return errors.New("tls: client sent unexpected early data") 152 } 153 154 hs.hello.sessionId = hs.clientHello.sessionId 155 hs.hello.compressionMethod = compressionNone 156 157 preferenceList := defaultCipherSuitesTLS13 158 if !hasAESGCMHardwareSupport || !aesgcmPreferred(hs.clientHello.cipherSuites) { 159 preferenceList = defaultCipherSuitesTLS13NoAES 160 } 161 for _, suiteID := range preferenceList { 162 hs.suite = mutualCipherSuiteTLS13(hs.clientHello.cipherSuites, suiteID) 163 if hs.suite != nil { 164 break 165 } 166 } 167 if hs.suite == nil { 168 c.sendAlert(alertHandshakeFailure) 169 return errors.New("tls: no cipher suite supported by both client and server") 170 } 171 c.cipherSuite = hs.suite.id 172 hs.hello.cipherSuite = hs.suite.id 173 hs.transcript = hs.suite.hash.New() 174 175 // Pick the ECDHE group in server preference order, but give priority to 176 // groups with a key share, to avoid a HelloRetryRequest round-trip. 177 var selectedGroup CurveID 178 var clientKeyShare *keyShare 179 GroupSelection: 180 for _, preferredGroup := range c.config.curvePreferences() { 181 for _, ks := range hs.clientHello.keyShares { 182 if ks.group == preferredGroup { 183 selectedGroup = ks.group 184 clientKeyShare = &ks 185 break GroupSelection 186 } 187 } 188 if selectedGroup != 0 { 189 continue 190 } 191 for _, group := range hs.clientHello.supportedCurves { 192 if group == preferredGroup { 193 selectedGroup = group 194 break 195 } 196 } 197 } 198 if selectedGroup == 0 { 199 c.sendAlert(alertHandshakeFailure) 200 return errors.New("tls: no ECDHE curve supported by both client and server") 201 } 202 if clientKeyShare == nil { 203 if err := hs.doHelloRetryRequest(selectedGroup); err != nil { 204 return err 205 } 206 clientKeyShare = &hs.clientHello.keyShares[0] 207 } 208 209 if _, ok := curveForCurveID(selectedGroup); selectedGroup != X25519 && !ok { 210 c.sendAlert(alertInternalError) 211 return errors.New("tls: CurvePreferences includes unsupported curve") 212 } 213 params, err := generateECDHEParameters(c.config.rand(), selectedGroup) 214 if err != nil { 215 c.sendAlert(alertInternalError) 216 return err 217 } 218 hs.hello.serverShare = keyShare{group: selectedGroup, data: params.PublicKey()} 219 hs.sharedKey = params.SharedKey(clientKeyShare.data) 220 if hs.sharedKey == nil { 221 c.sendAlert(alertIllegalParameter) 222 return errors.New("tls: invalid client key share") 223 } 224 225 c.serverName = hs.clientHello.serverName 226 return nil 227 } 228 229 func (hs *serverHandshakeStateTLS13) checkForResumption() error { 230 c := hs.c 231 232 if c.config.SessionTicketsDisabled { 233 return nil 234 } 235 236 modeOK := false 237 for _, mode := range hs.clientHello.pskModes { 238 if mode == pskModeDHE { 239 modeOK = true 240 break 241 } 242 } 243 if !modeOK { 244 return nil 245 } 246 247 if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) { 248 c.sendAlert(alertIllegalParameter) 249 return errors.New("tls: invalid or missing PSK binders") 250 } 251 if len(hs.clientHello.pskIdentities) == 0 { 252 return nil 253 } 254 255 for i, identity := range hs.clientHello.pskIdentities { 256 if i >= maxClientPSKIdentities { 257 break 258 } 259 260 plaintext, _ := c.decryptTicket(identity.label) 261 if plaintext == nil { 262 continue 263 } 264 sessionState := new(sessionStateTLS13) 265 if ok := sessionState.unmarshal(plaintext); !ok { 266 continue 267 } 268 269 createdAt := time.Unix(int64(sessionState.createdAt), 0) 270 if c.config.time().Sub(createdAt) > maxSessionTicketLifetime { 271 continue 272 } 273 274 // We don't check the obfuscated ticket age because it's affected by 275 // clock skew and it's only a freshness signal useful for shrinking the 276 // window for replay attacks, which don't affect us as we don't do 0-RTT. 277 278 pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite) 279 if pskSuite == nil || pskSuite.hash != hs.suite.hash { 280 continue 281 } 282 283 // PSK connections don't re-establish client certificates, but carry 284 // them over in the session ticket. Ensure the presence of client certs 285 // in the ticket is consistent with the configured requirements. 286 sessionHasClientCerts := len(sessionState.certificate.Certificate) != 0 287 needClientCerts := requiresClientCert(c.config.ClientAuth) 288 if needClientCerts && !sessionHasClientCerts { 289 continue 290 } 291 if sessionHasClientCerts && c.config.ClientAuth == NoClientCert { 292 continue 293 } 294 295 psk := hs.suite.expandLabel(sessionState.resumptionSecret, "resumption", 296 nil, hs.suite.hash.Size()) 297 hs.earlySecret = hs.suite.extract(psk, nil) 298 binderKey := hs.suite.deriveSecret(hs.earlySecret, resumptionBinderLabel, nil) 299 // Clone the transcript in case a HelloRetryRequest was recorded. 300 transcript := cloneHash(hs.transcript, hs.suite.hash) 301 if transcript == nil { 302 c.sendAlert(alertInternalError) 303 return errors.New("tls: internal error: failed to clone hash") 304 } 305 clientHelloBytes, err := hs.clientHello.marshalWithoutBinders() 306 if err != nil { 307 c.sendAlert(alertInternalError) 308 return err 309 } 310 transcript.Write(clientHelloBytes) 311 pskBinder := hs.suite.finishedHash(binderKey, transcript) 312 if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) { 313 c.sendAlert(alertDecryptError) 314 return errors.New("tls: invalid PSK binder") 315 } 316 317 c.didResume = true 318 if err := c.processCertsFromClient(sessionState.certificate); err != nil { 319 return err 320 } 321 322 hs.hello.selectedIdentityPresent = true 323 hs.hello.selectedIdentity = uint16(i) 324 hs.usingPSK = true 325 return nil 326 } 327 328 return nil 329 } 330 331 // cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler 332 // interfaces implemented by standard library hashes to clone the state of in 333 // to a new instance of h. It returns nil if the operation fails. 334 func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash { 335 // Recreate the interface to avoid importing encoding. 336 type binaryMarshaler interface { 337 MarshalBinary() (data []byte, err error) 338 UnmarshalBinary(data []byte) error 339 } 340 marshaler, ok := in.(binaryMarshaler) 341 if !ok { 342 return nil 343 } 344 state, err := marshaler.MarshalBinary() 345 if err != nil { 346 return nil 347 } 348 out := h.New() 349 unmarshaler, ok := out.(binaryMarshaler) 350 if !ok { 351 return nil 352 } 353 if err := unmarshaler.UnmarshalBinary(state); err != nil { 354 return nil 355 } 356 return out 357 } 358 359 func (hs *serverHandshakeStateTLS13) pickCertificate() error { 360 c := hs.c 361 362 // Only one of PSK and certificates are used at a time. 363 if hs.usingPSK { 364 return nil 365 } 366 367 // signature_algorithms is required in TLS 1.3. See RFC 8446, Section 4.2.3. 368 if len(hs.clientHello.supportedSignatureAlgorithms) == 0 { 369 return c.sendAlert(alertMissingExtension) 370 } 371 372 certificate, err := c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello)) 373 if err != nil { 374 if err == errNoCertificates { 375 c.sendAlert(alertUnrecognizedName) 376 } else { 377 c.sendAlert(alertInternalError) 378 } 379 return err 380 } 381 hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms) 382 if err != nil { 383 // getCertificate returned a certificate that is unsupported or 384 // incompatible with the client's signature algorithms. 385 c.sendAlert(alertHandshakeFailure) 386 return err 387 } 388 hs.cert = certificate 389 390 return nil 391 } 392 393 // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility 394 // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4. 395 func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error { 396 if hs.sentDummyCCS { 397 return nil 398 } 399 hs.sentDummyCCS = true 400 401 return hs.c.writeChangeCipherRecord() 402 } 403 404 func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) error { 405 c := hs.c 406 407 // The first ClientHello gets double-hashed into the transcript upon a 408 // HelloRetryRequest. See RFC 8446, Section 4.4.1. 409 if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil { 410 return err 411 } 412 chHash := hs.transcript.Sum(nil) 413 hs.transcript.Reset() 414 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) 415 hs.transcript.Write(chHash) 416 417 helloRetryRequest := &serverHelloMsg{ 418 vers: hs.hello.vers, 419 random: helloRetryRequestRandom, 420 sessionId: hs.hello.sessionId, 421 cipherSuite: hs.hello.cipherSuite, 422 compressionMethod: hs.hello.compressionMethod, 423 supportedVersion: hs.hello.supportedVersion, 424 selectedGroup: selectedGroup, 425 } 426 427 if _, err := hs.c.writeHandshakeRecord(helloRetryRequest, hs.transcript); err != nil { 428 return err 429 } 430 431 if err := hs.sendDummyChangeCipherSpec(); err != nil { 432 return err 433 } 434 435 // clientHelloMsg is not included in the transcript. 436 msg, err := c.readHandshake(nil) 437 if err != nil { 438 return err 439 } 440 441 clientHello, ok := msg.(*clientHelloMsg) 442 if !ok { 443 c.sendAlert(alertUnexpectedMessage) 444 return unexpectedMessageError(clientHello, msg) 445 } 446 447 if len(clientHello.keyShares) != 1 || clientHello.keyShares[0].group != selectedGroup { 448 c.sendAlert(alertIllegalParameter) 449 return errors.New("tls: client sent invalid key share in second ClientHello") 450 } 451 452 if clientHello.earlyData { 453 c.sendAlert(alertIllegalParameter) 454 return errors.New("tls: client indicated early data in second ClientHello") 455 } 456 457 if illegalClientHelloChange(clientHello, hs.clientHello) { 458 c.sendAlert(alertIllegalParameter) 459 return errors.New("tls: client illegally modified second ClientHello") 460 } 461 462 hs.clientHello = clientHello 463 return nil 464 } 465 466 // illegalClientHelloChange reports whether the two ClientHello messages are 467 // different, with the exception of the changes allowed before and after a 468 // HelloRetryRequest. See RFC 8446, Section 4.1.2. 469 func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool { 470 if len(ch.supportedVersions) != len(ch1.supportedVersions) || 471 len(ch.cipherSuites) != len(ch1.cipherSuites) || 472 len(ch.supportedCurves) != len(ch1.supportedCurves) || 473 len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) || 474 len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) || 475 len(ch.alpnProtocols) != len(ch1.alpnProtocols) { 476 return true 477 } 478 for i := range ch.supportedVersions { 479 if ch.supportedVersions[i] != ch1.supportedVersions[i] { 480 return true 481 } 482 } 483 for i := range ch.cipherSuites { 484 if ch.cipherSuites[i] != ch1.cipherSuites[i] { 485 return true 486 } 487 } 488 for i := range ch.supportedCurves { 489 if ch.supportedCurves[i] != ch1.supportedCurves[i] { 490 return true 491 } 492 } 493 for i := range ch.supportedSignatureAlgorithms { 494 if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] { 495 return true 496 } 497 } 498 for i := range ch.supportedSignatureAlgorithmsCert { 499 if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] { 500 return true 501 } 502 } 503 for i := range ch.alpnProtocols { 504 if ch.alpnProtocols[i] != ch1.alpnProtocols[i] { 505 return true 506 } 507 } 508 return ch.vers != ch1.vers || 509 !bytes.Equal(ch.random, ch1.random) || 510 !bytes.Equal(ch.sessionId, ch1.sessionId) || 511 !bytes.Equal(ch.compressionMethods, ch1.compressionMethods) || 512 ch.serverName != ch1.serverName || 513 ch.ocspStapling != ch1.ocspStapling || 514 !bytes.Equal(ch.supportedPoints, ch1.supportedPoints) || 515 ch.ticketSupported != ch1.ticketSupported || 516 !bytes.Equal(ch.sessionTicket, ch1.sessionTicket) || 517 ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported || 518 !bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) || 519 ch.scts != ch1.scts || 520 !bytes.Equal(ch.cookie, ch1.cookie) || 521 !bytes.Equal(ch.pskModes, ch1.pskModes) 522 } 523 524 func (hs *serverHandshakeStateTLS13) sendServerParameters() error { 525 c := hs.c 526 527 if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil { 528 return err 529 } 530 if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil { 531 return err 532 } 533 534 if err := hs.sendDummyChangeCipherSpec(); err != nil { 535 return err 536 } 537 538 earlySecret := hs.earlySecret 539 if earlySecret == nil { 540 earlySecret = hs.suite.extract(nil, nil) 541 } 542 hs.handshakeSecret = hs.suite.extract(hs.sharedKey, 543 hs.suite.deriveSecret(earlySecret, "derived", nil)) 544 545 clientSecret := hs.suite.deriveSecret(hs.handshakeSecret, 546 clientHandshakeTrafficLabel, hs.transcript) 547 c.in.setTrafficSecret(hs.suite, clientSecret) 548 serverSecret := hs.suite.deriveSecret(hs.handshakeSecret, 549 serverHandshakeTrafficLabel, hs.transcript) 550 c.out.setTrafficSecret(hs.suite, serverSecret) 551 552 err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret) 553 if err != nil { 554 c.sendAlert(alertInternalError) 555 return err 556 } 557 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret) 558 if err != nil { 559 c.sendAlert(alertInternalError) 560 return err 561 } 562 563 encryptedExtensions := new(encryptedExtensionsMsg) 564 565 selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols) 566 if err != nil { 567 c.sendAlert(alertNoApplicationProtocol) 568 return err 569 } 570 encryptedExtensions.alpnProtocol = selectedProto 571 c.clientProtocol = selectedProto 572 573 if _, err := hs.c.writeHandshakeRecord(encryptedExtensions, hs.transcript); err != nil { 574 return err 575 } 576 577 return nil 578 } 579 580 func (hs *serverHandshakeStateTLS13) requestClientCert() bool { 581 return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK 582 } 583 584 func (hs *serverHandshakeStateTLS13) sendServerCertificate() error { 585 c := hs.c 586 587 // Only one of PSK and certificates are used at a time. 588 if hs.usingPSK { 589 return nil 590 } 591 592 if hs.requestClientCert() { 593 // Request a client certificate 594 certReq := new(certificateRequestMsgTLS13) 595 certReq.ocspStapling = true 596 certReq.scts = true 597 certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms() 598 if c.config.ClientCAs != nil { 599 certReq.certificateAuthorities = c.config.ClientCAs.Subjects() 600 } 601 602 if _, err := hs.c.writeHandshakeRecord(certReq, hs.transcript); err != nil { 603 return err 604 } 605 } 606 607 certMsg := new(certificateMsgTLS13) 608 609 certMsg.certificate = *hs.cert 610 certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0 611 certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 612 613 if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil { 614 return err 615 } 616 617 certVerifyMsg := new(certificateVerifyMsg) 618 certVerifyMsg.hasSignatureAlgorithm = true 619 certVerifyMsg.signatureAlgorithm = hs.sigAlg 620 621 sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg) 622 if err != nil { 623 return c.sendAlert(alertInternalError) 624 } 625 626 signed := signedMessage(sigHash, serverSignatureContext, hs.transcript) 627 signOpts := crypto.SignerOpts(sigHash) 628 if sigType == signatureRSAPSS { 629 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash} 630 } 631 sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts) 632 if err != nil { 633 public := hs.cert.PrivateKey.(crypto.Signer).Public() 634 if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS && 635 rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 { // key too small for RSA-PSS 636 c.sendAlert(alertHandshakeFailure) 637 } else { 638 c.sendAlert(alertInternalError) 639 } 640 return errors.New("tls: failed to sign handshake: " + err.Error()) 641 } 642 certVerifyMsg.signature = sig 643 644 if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil { 645 return err 646 } 647 648 return nil 649 } 650 651 func (hs *serverHandshakeStateTLS13) sendServerFinished() error { 652 c := hs.c 653 654 finished := &finishedMsg{ 655 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript), 656 } 657 658 if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil { 659 return err 660 } 661 662 // Derive secrets that take context through the server Finished. 663 664 hs.masterSecret = hs.suite.extract(nil, 665 hs.suite.deriveSecret(hs.handshakeSecret, "derived", nil)) 666 667 hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret, 668 clientApplicationTrafficLabel, hs.transcript) 669 serverSecret := hs.suite.deriveSecret(hs.masterSecret, 670 serverApplicationTrafficLabel, hs.transcript) 671 c.out.setTrafficSecret(hs.suite, serverSecret) 672 673 err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret) 674 if err != nil { 675 c.sendAlert(alertInternalError) 676 return err 677 } 678 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret) 679 if err != nil { 680 c.sendAlert(alertInternalError) 681 return err 682 } 683 684 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript) 685 686 // If we did not request client certificates, at this point we can 687 // precompute the client finished and roll the transcript forward to send 688 // session tickets in our first flight. 689 if !hs.requestClientCert() { 690 if err := hs.sendSessionTickets(); err != nil { 691 return err 692 } 693 } 694 695 return nil 696 } 697 698 func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool { 699 if hs.c.config.SessionTicketsDisabled { 700 return false 701 } 702 703 // Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9. 704 for _, pskMode := range hs.clientHello.pskModes { 705 if pskMode == pskModeDHE { 706 return true 707 } 708 } 709 return false 710 } 711 712 func (hs *serverHandshakeStateTLS13) sendSessionTickets() error { 713 c := hs.c 714 715 hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript) 716 finishedMsg := &finishedMsg{ 717 verifyData: hs.clientFinished, 718 } 719 if err := transcriptMsg(finishedMsg, hs.transcript); err != nil { 720 return err 721 } 722 723 if !hs.shouldSendSessionTickets() { 724 return nil 725 } 726 727 resumptionSecret := hs.suite.deriveSecret(hs.masterSecret, 728 resumptionLabel, hs.transcript) 729 730 m := new(newSessionTicketMsgTLS13) 731 732 var certsFromClient [][]byte 733 for _, cert := range c.peerCertificates { 734 certsFromClient = append(certsFromClient, cert.Raw) 735 } 736 state := sessionStateTLS13{ 737 cipherSuite: hs.suite.id, 738 createdAt: uint64(c.config.time().Unix()), 739 resumptionSecret: resumptionSecret, 740 certificate: Certificate{ 741 Certificate: certsFromClient, 742 OCSPStaple: c.ocspResponse, 743 SignedCertificateTimestamps: c.scts, 744 }, 745 } 746 stateBytes, err := state.marshal() 747 if err != nil { 748 c.sendAlert(alertInternalError) 749 return err 750 } 751 m.label, err = c.encryptTicket(stateBytes) 752 if err != nil { 753 return err 754 } 755 m.lifetime = uint32(maxSessionTicketLifetime / time.Second) 756 757 // ticket_age_add is a random 32-bit value. See RFC 8446, section 4.6.1 758 // The value is not stored anywhere; we never need to check the ticket age 759 // because 0-RTT is not supported. 760 ageAdd := make([]byte, 4) 761 _, err = hs.c.config.rand().Read(ageAdd) 762 if err != nil { 763 return err 764 } 765 m.ageAdd = binary.LittleEndian.Uint32(ageAdd) 766 767 // ticket_nonce, which must be unique per connection, is always left at 768 // zero because we only ever send one ticket per connection. 769 770 if _, err := c.writeHandshakeRecord(m, nil); err != nil { 771 return err 772 } 773 774 return nil 775 } 776 777 func (hs *serverHandshakeStateTLS13) readClientCertificate() error { 778 c := hs.c 779 780 if !hs.requestClientCert() { 781 // Make sure the connection is still being verified whether or not 782 // the server requested a client certificate. 783 if c.config.VerifyConnection != nil { 784 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 785 c.sendAlert(alertBadCertificate) 786 return err 787 } 788 } 789 return nil 790 } 791 792 // If we requested a client certificate, then the client must send a 793 // certificate message. If it's empty, no CertificateVerify is sent. 794 795 msg, err := c.readHandshake(hs.transcript) 796 if err != nil { 797 return err 798 } 799 800 certMsg, ok := msg.(*certificateMsgTLS13) 801 if !ok { 802 c.sendAlert(alertUnexpectedMessage) 803 return unexpectedMessageError(certMsg, msg) 804 } 805 806 if err := c.processCertsFromClient(certMsg.certificate); err != nil { 807 return err 808 } 809 810 if c.config.VerifyConnection != nil { 811 if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 812 c.sendAlert(alertBadCertificate) 813 return err 814 } 815 } 816 817 if len(certMsg.certificate.Certificate) != 0 { 818 // certificateVerifyMsg is included in the transcript, but not until 819 // after we verify the handshake signature, since the state before 820 // this message was sent is used. 821 msg, err = c.readHandshake(nil) 822 if err != nil { 823 return err 824 } 825 826 certVerify, ok := msg.(*certificateVerifyMsg) 827 if !ok { 828 c.sendAlert(alertUnexpectedMessage) 829 return unexpectedMessageError(certVerify, msg) 830 } 831 832 // See RFC 8446, Section 4.4.3. 833 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) { 834 c.sendAlert(alertIllegalParameter) 835 return errors.New("tls: client certificate used with invalid signature algorithm") 836 } 837 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm) 838 if err != nil { 839 return c.sendAlert(alertInternalError) 840 } 841 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 { 842 c.sendAlert(alertIllegalParameter) 843 return errors.New("tls: client certificate used with invalid signature algorithm") 844 } 845 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript) 846 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey, 847 sigHash, signed, certVerify.signature); err != nil { 848 c.sendAlert(alertDecryptError) 849 return errors.New("tls: invalid signature by the client certificate: " + err.Error()) 850 } 851 852 if err := transcriptMsg(certVerify, hs.transcript); err != nil { 853 return err 854 } 855 } 856 857 // If we waited until the client certificates to send session tickets, we 858 // are ready to do it now. 859 if err := hs.sendSessionTickets(); err != nil { 860 return err 861 } 862 863 return nil 864 } 865 866 func (hs *serverHandshakeStateTLS13) readClientFinished() error { 867 c := hs.c 868 869 // finishedMsg is not included in the transcript. 870 msg, err := c.readHandshake(nil) 871 if err != nil { 872 return err 873 } 874 875 finished, ok := msg.(*finishedMsg) 876 if !ok { 877 c.sendAlert(alertUnexpectedMessage) 878 return unexpectedMessageError(finished, msg) 879 } 880 881 if !hmac.Equal(hs.clientFinished, finished.verifyData) { 882 c.sendAlert(alertDecryptError) 883 return errors.New("tls: invalid client finished hash") 884 } 885 886 c.in.setTrafficSecret(hs.suite, hs.trafficSecret) 887 888 return nil 889 }