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