gitee.com/lh-her-team/common@v1.5.1/crypto/tls/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 "crypto" 10 "crypto/hmac" 11 "crypto/rsa" 12 "errors" 13 "hash" 14 "sync/atomic" 15 "time" 16 ) 17 18 type clientHandshakeStateTLS13 struct { 19 c *Conn 20 serverHello *serverHelloMsg 21 hello *clientHelloMsg 22 ecdheParams ecdheParameters 23 session *ClientSessionState 24 earlySecret []byte 25 binderKey []byte 26 certReq *certificateRequestMsgTLS13 27 usingPSK bool 28 sentDummyCCS bool 29 suite *cipherSuiteTLS13 30 transcript hash.Hash 31 masterSecret []byte 32 trafficSecret []byte // client_application_traffic_secret_0 33 } 34 35 // handshake requires hs.c, hs.hello, hs.serverHello, hs.ecdheParams, and, 36 // optionally, hs.session, hs.earlySecret and hs.binderKey to be set. 37 func (hs *clientHandshakeStateTLS13) handshake() error { 38 c := hs.c 39 // The server must not select TLS 1.3 in a renegotiation. See RFC 8446, 40 // sections 4.1.2 and 4.1.3. 41 if c.handshakes > 0 { 42 c.sendAlert(alertProtocolVersion) 43 return errors.New("tls: server selected TLS 1.3 in a renegotiation") 44 } 45 // Consistency check on the presence of a keyShare and its parameters. 46 if hs.ecdheParams == nil || len(hs.hello.keyShares) != 1 { 47 return c.sendAlert(alertInternalError) 48 } 49 if err := hs.checkServerHelloOrHRR(); err != nil { 50 return err 51 } 52 hs.transcript = hs.suite.hash.New() 53 hs.transcript.Write(hs.hello.marshal()) 54 if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) { 55 if err := hs.sendDummyChangeCipherSpec(); err != nil { 56 return err 57 } 58 if err := hs.processHelloRetryRequest(); err != nil { 59 return err 60 } 61 } 62 hs.transcript.Write(hs.serverHello.marshal()) 63 c.buffering = true 64 if err := hs.processServerHello(); err != nil { 65 return err 66 } 67 if err := hs.sendDummyChangeCipherSpec(); err != nil { 68 return err 69 } 70 if err := hs.establishHandshakeKeys(); err != nil { 71 return err 72 } 73 if err := hs.readServerParameters(); err != nil { 74 return err 75 } 76 if err := hs.readServerCertificate(); err != nil { 77 return err 78 } 79 if err := hs.readServerFinished(); err != nil { 80 return err 81 } 82 if err := hs.sendClientCertificate(); err != nil { 83 return err 84 } 85 if err := hs.sendClientFinished(); err != nil { 86 return err 87 } 88 if _, err := c.flush(); err != nil { 89 return err 90 } 91 atomic.StoreUint32(&c.handshakeStatus, 1) 92 return nil 93 } 94 95 // checkServerHelloOrHRR does validity checks that apply to both ServerHello and 96 // HelloRetryRequest messages. It sets hs.suite. 97 func (hs *clientHandshakeStateTLS13) checkServerHelloOrHRR() error { 98 c := hs.c 99 if hs.serverHello.supportedVersion == 0 { 100 c.sendAlert(alertMissingExtension) 101 return errors.New("tls: server selected TLS 1.3 using the legacy version field") 102 } 103 if hs.serverHello.supportedVersion != VersionTLS13 { 104 c.sendAlert(alertIllegalParameter) 105 return errors.New("tls: server selected an invalid version after a HelloRetryRequest") 106 } 107 if hs.serverHello.vers != VersionTLS12 { 108 c.sendAlert(alertIllegalParameter) 109 return errors.New("tls: server sent an incorrect legacy version") 110 } 111 if hs.serverHello.ocspStapling || 112 hs.serverHello.ticketSupported || 113 hs.serverHello.secureRenegotiationSupported || 114 len(hs.serverHello.secureRenegotiation) != 0 || 115 len(hs.serverHello.alpnProtocol) != 0 || 116 len(hs.serverHello.scts) != 0 { 117 c.sendAlert(alertUnsupportedExtension) 118 return errors.New("tls: server sent a ServerHello extension forbidden in TLS 1.3") 119 } 120 if !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) { 121 c.sendAlert(alertIllegalParameter) 122 return errors.New("tls: server did not echo the legacy session ID") 123 } 124 if hs.serverHello.compressionMethod != compressionNone { 125 c.sendAlert(alertIllegalParameter) 126 return errors.New("tls: server selected unsupported compression format") 127 } 128 selectedSuite := mutualCipherSuiteTLS13(hs.hello.cipherSuites, hs.serverHello.cipherSuite) 129 if hs.suite != nil && selectedSuite != hs.suite { 130 c.sendAlert(alertIllegalParameter) 131 return errors.New("tls: server changed cipher suite after a HelloRetryRequest") 132 } 133 if selectedSuite == nil { 134 c.sendAlert(alertIllegalParameter) 135 return errors.New("tls: server chose an unconfigured cipher suite") 136 } 137 hs.suite = selectedSuite 138 c.cipherSuite = hs.suite.id 139 140 return nil 141 } 142 143 // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility 144 // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4. 145 func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error { 146 if hs.sentDummyCCS { 147 return nil 148 } 149 hs.sentDummyCCS = true 150 _, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) 151 return err 152 } 153 154 // processHelloRetryRequest handles the HRR in hs.serverHello, modifies and 155 // resends hs.hello, and reads the new ServerHello into hs.serverHello. 156 func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error { 157 c := hs.c 158 // The first ClientHello gets double-hashed into the transcript upon a 159 // HelloRetryRequest. See RFC 8446, Section 4.4.1. 160 chHash := hs.transcript.Sum(nil) 161 hs.transcript.Reset() 162 hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) 163 hs.transcript.Write(chHash) 164 hs.transcript.Write(hs.serverHello.marshal()) 165 if hs.serverHello.serverShare.group != 0 { 166 c.sendAlert(alertDecodeError) 167 return errors.New("tls: received malformed key_share extension") 168 } 169 curveID := hs.serverHello.selectedGroup 170 if curveID == 0 { 171 c.sendAlert(alertMissingExtension) 172 return errors.New("tls: received HelloRetryRequest without selected group") 173 } 174 curveOK := false 175 for _, id := range hs.hello.supportedCurves { 176 if id == curveID { 177 curveOK = true 178 break 179 } 180 } 181 if !curveOK { 182 c.sendAlert(alertIllegalParameter) 183 return errors.New("tls: server selected unsupported group") 184 } 185 if hs.ecdheParams.CurveID() == curveID { 186 c.sendAlert(alertIllegalParameter) 187 return errors.New("tls: server sent an unnecessary HelloRetryRequest message") 188 } 189 if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok { 190 c.sendAlert(alertInternalError) 191 return errors.New("tls: CurvePreferences includes unsupported curve") 192 } 193 params, err := generateECDHEParameters(c.config.rand(), curveID) 194 if err != nil { 195 c.sendAlert(alertInternalError) 196 return err 197 } 198 hs.ecdheParams = params 199 hs.hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}} 200 hs.hello.cookie = hs.serverHello.cookie 201 hs.hello.raw = nil 202 if len(hs.hello.pskIdentities) > 0 { 203 pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite) 204 if pskSuite == nil { 205 return c.sendAlert(alertInternalError) 206 } 207 if pskSuite.hash == hs.suite.hash { 208 // Update binders and obfuscated_ticket_age. 209 ticketAge := uint32(c.config.time().Sub(hs.session.receivedAt) / time.Millisecond) 210 hs.hello.pskIdentities[0].obfuscatedTicketAge = ticketAge + hs.session.ageAdd 211 transcript := hs.suite.hash.New() 212 transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) 213 transcript.Write(chHash) 214 transcript.Write(hs.serverHello.marshal()) 215 transcript.Write(hs.hello.marshalWithoutBinders()) 216 pskBinders := [][]byte{hs.suite.finishedHash(hs.binderKey, transcript)} 217 hs.hello.updateBinders(pskBinders) 218 } else { 219 // Server selected a cipher suite incompatible with the PSK. 220 hs.hello.pskIdentities = nil 221 hs.hello.pskBinders = nil 222 } 223 } 224 hs.transcript.Write(hs.hello.marshal()) 225 if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil { 226 return err 227 } 228 msg, err := c.readHandshake() 229 if err != nil { 230 return err 231 } 232 serverHello, ok := msg.(*serverHelloMsg) 233 if !ok { 234 c.sendAlert(alertUnexpectedMessage) 235 return unexpectedMessageError(serverHello, msg) 236 } 237 hs.serverHello = serverHello 238 if err := hs.checkServerHelloOrHRR(); err != nil { 239 return err 240 } 241 return nil 242 } 243 244 func (hs *clientHandshakeStateTLS13) processServerHello() error { 245 c := hs.c 246 if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) { 247 c.sendAlert(alertUnexpectedMessage) 248 return errors.New("tls: server sent two HelloRetryRequest messages") 249 } 250 if len(hs.serverHello.cookie) != 0 { 251 c.sendAlert(alertUnsupportedExtension) 252 return errors.New("tls: server sent a cookie in a normal ServerHello") 253 } 254 if hs.serverHello.selectedGroup != 0 { 255 c.sendAlert(alertDecodeError) 256 return errors.New("tls: malformed key_share extension") 257 } 258 if hs.serverHello.serverShare.group == 0 { 259 c.sendAlert(alertIllegalParameter) 260 return errors.New("tls: server did not send a key share") 261 } 262 if hs.serverHello.serverShare.group != hs.ecdheParams.CurveID() { 263 c.sendAlert(alertIllegalParameter) 264 return errors.New("tls: server selected unsupported group") 265 } 266 if !hs.serverHello.selectedIdentityPresent { 267 return nil 268 } 269 if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) { 270 c.sendAlert(alertIllegalParameter) 271 return errors.New("tls: server selected an invalid PSK") 272 } 273 if len(hs.hello.pskIdentities) != 1 || hs.session == nil { 274 return c.sendAlert(alertInternalError) 275 } 276 pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite) 277 if pskSuite == nil { 278 return c.sendAlert(alertInternalError) 279 } 280 if pskSuite.hash != hs.suite.hash { 281 c.sendAlert(alertIllegalParameter) 282 return errors.New("tls: server selected an invalid PSK and cipher suite pair") 283 } 284 hs.usingPSK = true 285 c.didResume = true 286 c.peerCertificates = hs.session.serverCertificates 287 c.verifiedChains = hs.session.verifiedChains 288 return nil 289 } 290 291 func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error { 292 c := hs.c 293 sharedKey := hs.ecdheParams.SharedKey(hs.serverHello.serverShare.data) 294 if sharedKey == nil { 295 c.sendAlert(alertIllegalParameter) 296 return errors.New("tls: invalid server key share") 297 } 298 earlySecret := hs.earlySecret 299 if !hs.usingPSK { 300 earlySecret = hs.suite.extract(nil, nil) 301 } 302 handshakeSecret := hs.suite.extract(sharedKey, 303 hs.suite.deriveSecret(earlySecret, "derived", nil)) 304 clientSecret := hs.suite.deriveSecret(handshakeSecret, 305 clientHandshakeTrafficLabel, hs.transcript) 306 c.out.setTrafficSecret(hs.suite, clientSecret) 307 serverSecret := hs.suite.deriveSecret(handshakeSecret, 308 serverHandshakeTrafficLabel, hs.transcript) 309 c.in.setTrafficSecret(hs.suite, serverSecret) 310 err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret) 311 if err != nil { 312 c.sendAlert(alertInternalError) 313 return err 314 } 315 err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret) 316 if err != nil { 317 c.sendAlert(alertInternalError) 318 return err 319 } 320 hs.masterSecret = hs.suite.extract(nil, 321 hs.suite.deriveSecret(handshakeSecret, "derived", nil)) 322 return nil 323 } 324 325 func (hs *clientHandshakeStateTLS13) readServerParameters() error { 326 c := hs.c 327 msg, err := c.readHandshake() 328 if err != nil { 329 return err 330 } 331 encryptedExtensions, ok := msg.(*encryptedExtensionsMsg) 332 if !ok { 333 c.sendAlert(alertUnexpectedMessage) 334 return unexpectedMessageError(encryptedExtensions, msg) 335 } 336 hs.transcript.Write(encryptedExtensions.marshal()) 337 if len(encryptedExtensions.alpnProtocol) != 0 && len(hs.hello.alpnProtocols) == 0 { 338 c.sendAlert(alertUnsupportedExtension) 339 return errors.New("tls: server advertised unrequested ALPN extension") 340 } 341 c.clientProtocol = encryptedExtensions.alpnProtocol 342 return nil 343 } 344 345 func (hs *clientHandshakeStateTLS13) readServerCertificate() error { 346 c := hs.c 347 // Either a PSK or a certificate is always used, but not both. 348 // See RFC 8446, Section 4.1.1. 349 if hs.usingPSK { 350 return nil 351 } 352 msg, err := c.readHandshake() 353 if err != nil { 354 return err 355 } 356 certReq, ok := msg.(*certificateRequestMsgTLS13) 357 if ok { 358 hs.transcript.Write(certReq.marshal()) 359 hs.certReq = certReq 360 msg, err = c.readHandshake() 361 if err != nil { 362 return err 363 } 364 } 365 certMsg, ok := msg.(*certificateMsgTLS13) 366 if !ok { 367 c.sendAlert(alertUnexpectedMessage) 368 return unexpectedMessageError(certMsg, msg) 369 } 370 if len(certMsg.certificate.Certificate) == 0 { 371 c.sendAlert(alertDecodeError) 372 return errors.New("tls: received empty certificates message") 373 } 374 hs.transcript.Write(certMsg.marshal()) 375 c.scts = certMsg.certificate.SignedCertificateTimestamps 376 c.ocspResponse = certMsg.certificate.OCSPStaple 377 if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil { 378 return err 379 } 380 msg, err = c.readHandshake() 381 if err != nil { 382 return err 383 } 384 certVerify, ok := msg.(*certificateVerifyMsg) 385 if !ok { 386 c.sendAlert(alertUnexpectedMessage) 387 return unexpectedMessageError(certVerify, msg) 388 } 389 // See RFC 8446, Section 4.4.3. 390 if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms) { 391 c.sendAlert(alertIllegalParameter) 392 return errors.New("tls: certificate used with invalid signature algorithm") 393 } 394 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm) 395 if err != nil { 396 return c.sendAlert(alertInternalError) 397 } 398 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 { 399 c.sendAlert(alertIllegalParameter) 400 return errors.New("tls: certificate used with invalid signature algorithm") 401 } 402 signed := signedMessage(sigHash, serverSignatureContext, hs.transcript) 403 if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey, 404 sigHash, signed, certVerify.signature); err != nil { 405 c.sendAlert(alertDecryptError) 406 return errors.New("tls: invalid signature by the server certificate: " + err.Error()) 407 } 408 hs.transcript.Write(certVerify.marshal()) 409 return nil 410 } 411 412 func (hs *clientHandshakeStateTLS13) readServerFinished() error { 413 c := hs.c 414 msg, err := c.readHandshake() 415 if err != nil { 416 return err 417 } 418 finished, ok := msg.(*finishedMsg) 419 if !ok { 420 c.sendAlert(alertUnexpectedMessage) 421 return unexpectedMessageError(finished, msg) 422 } 423 expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript) 424 if !hmac.Equal(expectedMAC, finished.verifyData) { 425 c.sendAlert(alertDecryptError) 426 return errors.New("tls: invalid server finished hash") 427 } 428 hs.transcript.Write(finished.marshal()) 429 // Derive secrets that take context through the server Finished. 430 hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret, 431 clientApplicationTrafficLabel, hs.transcript) 432 serverSecret := hs.suite.deriveSecret(hs.masterSecret, 433 serverApplicationTrafficLabel, hs.transcript) 434 c.in.setTrafficSecret(hs.suite, serverSecret) 435 err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret) 436 if err != nil { 437 c.sendAlert(alertInternalError) 438 return err 439 } 440 err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret) 441 if err != nil { 442 c.sendAlert(alertInternalError) 443 return err 444 } 445 c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript) 446 return nil 447 } 448 449 func (hs *clientHandshakeStateTLS13) sendClientCertificate() error { 450 c := hs.c 451 if hs.certReq == nil { 452 return nil 453 } 454 cert, err := c.getClientCertificate(&CertificateRequestInfo{ 455 AcceptableCAs: hs.certReq.certificateAuthorities, 456 SignatureSchemes: hs.certReq.supportedSignatureAlgorithms, 457 Version: c.vers, 458 }) 459 if err != nil { 460 return err 461 } 462 certMsg := new(certificateMsgTLS13) 463 certMsg.certificate = *cert 464 certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0 465 certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0 466 hs.transcript.Write(certMsg.marshal()) 467 if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil { 468 return err 469 } 470 // If we sent an empty certificate message, skip the CertificateVerify. 471 if len(cert.Certificate) == 0 { 472 return nil 473 } 474 certVerifyMsg := new(certificateVerifyMsg) 475 certVerifyMsg.hasSignatureAlgorithm = true 476 certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms) 477 if err != nil { 478 // getClientCertificate returned a certificate incompatible with the 479 // CertificateRequestInfo supported signature algorithms. 480 c.sendAlert(alertHandshakeFailure) 481 return err 482 } 483 sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm) 484 if err != nil { 485 return c.sendAlert(alertInternalError) 486 } 487 signed := signedMessage(sigHash, clientSignatureContext, hs.transcript) 488 signOpts := crypto.SignerOpts(sigHash) 489 if sigType == signatureRSAPSS { 490 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash} 491 } 492 sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts) 493 if err != nil { 494 c.sendAlert(alertInternalError) 495 return errors.New("tls: failed to sign handshake: " + err.Error()) 496 } 497 certVerifyMsg.signature = sig 498 hs.transcript.Write(certVerifyMsg.marshal()) 499 if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil { 500 return err 501 } 502 return nil 503 } 504 505 func (hs *clientHandshakeStateTLS13) sendClientFinished() error { 506 c := hs.c 507 finished := &finishedMsg{ 508 verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript), 509 } 510 hs.transcript.Write(finished.marshal()) 511 if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil { 512 return err 513 } 514 c.out.setTrafficSecret(hs.suite, hs.trafficSecret) 515 if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil { 516 c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret, 517 resumptionLabel, hs.transcript) 518 } 519 return nil 520 } 521 522 func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error { 523 if !c.isClient { 524 c.sendAlert(alertUnexpectedMessage) 525 return errors.New("tls: received new session ticket from a client") 526 } 527 if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil { 528 return nil 529 } 530 // See RFC 8446, Section 4.6.1. 531 if msg.lifetime == 0 { 532 return nil 533 } 534 lifetime := time.Duration(msg.lifetime) * time.Second 535 if lifetime > maxSessionTicketLifetime { 536 c.sendAlert(alertIllegalParameter) 537 return errors.New("tls: received a session ticket with invalid lifetime") 538 } 539 cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite) 540 if cipherSuite == nil || c.resumptionSecret == nil { 541 return c.sendAlert(alertInternalError) 542 } 543 // Save the resumption_master_secret and nonce instead of deriving the PSK 544 // to do the least amount of work on NewSessionTicket messages before we 545 // know if the ticket will be used. Forward secrecy of resumed connections 546 // is guaranteed by the requirement for pskModeDHE. 547 session := &ClientSessionState{ 548 sessionTicket: msg.label, 549 vers: c.vers, 550 cipherSuite: c.cipherSuite, 551 masterSecret: c.resumptionSecret, 552 serverCertificates: c.peerCertificates, 553 verifiedChains: c.verifiedChains, 554 receivedAt: c.config.time(), 555 nonce: msg.nonce, 556 useBy: c.config.time().Add(lifetime), 557 ageAdd: msg.ageAdd, 558 } 559 cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config) 560 c.config.ClientSessionCache.Put(cacheKey, session) 561 return nil 562 }