| 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/hkdf" |
| 12 |
"crypto/hmac" |
| 13 |
"crypto/internal/fips140/mlkem" |
| 14 |
"crypto/internal/fips140/tls13" |
| 15 |
"crypto/internal/hpke" |
| 16 |
"crypto/rsa" |
| 17 |
"crypto/tls/internal/fips140tls" |
| 18 |
"crypto/x509" |
| 19 |
"errors" |
| 20 |
"fmt" |
| 21 |
"hash" |
| 22 |
"internal/byteorder" |
| 23 |
"io" |
| 24 |
"slices" |
| 25 |
"sort" |
| 26 |
"time" |
| 27 |
) |
| 28 |
|
| 29 |
// maxClientPSKIdentities is the number of client PSK identities the server will |
| 30 |
// attempt to validate. It will ignore the rest not to let cheap ClientHello |
| 31 |
// messages cause too much work in session ticket decryption attempts. |
| 32 |
const maxClientPSKIdentities = 5 |
| 33 |
|
| 34 |
type echServerContext struct { |
| 35 |
hpkeContext *hpke.Recipient |
| 36 |
configID uint8 |
| 37 |
ciphersuite echCipher |
| 38 |
transcript hash.Hash |
| 39 |
// inner indicates that the initial client_hello we recieved contained an |
| 40 |
// encrypted_client_hello extension that indicated it was an "inner" hello. |
| 41 |
// We don't do any additional processing of the hello in this case, so all |
| 42 |
// fields above are unset. |
| 43 |
inner bool |
| 44 |
} |
| 45 |
|
| 46 |
type serverHandshakeStateTLS13 struct { |
| 47 |
c *Conn |
| 48 |
ctx context.Context |
| 49 |
clientHello *clientHelloMsg |
| 50 |
hello *serverHelloMsg |
| 51 |
sentDummyCCS bool |
| 52 |
usingPSK bool |
| 53 |
earlyData bool |
| 54 |
suite *cipherSuiteTLS13 |
| 55 |
cert *Certificate |
| 56 |
sigAlg SignatureScheme |
| 57 |
earlySecret *tls13.EarlySecret |
| 58 |
sharedKey []byte |
| 59 |
handshakeSecret *tls13.HandshakeSecret |
| 60 |
masterSecret *tls13.MasterSecret |
| 61 |
trafficSecret []byte // client_application_traffic_secret_0 |
| 62 |
transcript hash.Hash |
| 63 |
clientFinished []byte |
| 64 |
echContext *echServerContext |
| 65 |
} |
| 66 |
|
| 67 |
func (hs *serverHandshakeStateTLS13) handshake() error { |
| 68 |
c := hs.c |
| 69 |
|
| 70 |
// For an overview of the TLS 1.3 handshake, see RFC 8446, Section 2. |
| 71 |
if err := hs.processClientHello(); err != nil { |
| 72 |
return err |
| 73 |
} |
| 74 |
if err := hs.checkForResumption(); err != nil { |
| 75 |
return err |
| 76 |
} |
| 77 |
if err := hs.pickCertificate(); err != nil { |
| 78 |
return err |
| 79 |
} |
| 80 |
c.buffering = true |
| 81 |
if err := hs.sendServerParameters(); err != nil { |
| 82 |
return err |
| 83 |
} |
| 84 |
if err := hs.sendServerCertificate(); err != nil { |
| 85 |
return err |
| 86 |
} |
| 87 |
if err := hs.sendServerFinished(); err != nil { |
| 88 |
return err |
| 89 |
} |
| 90 |
// Note that at this point we could start sending application data without |
| 91 |
// waiting for the client's second flight, but the application might not |
| 92 |
// expect the lack of replay protection of the ClientHello parameters. |
| 93 |
if _, err := c.flush(); err != nil { |
| 94 |
return err |
| 95 |
} |
| 96 |
if err := hs.readClientCertificate(); err != nil { |
| 97 |
return err |
| 98 |
} |
| 99 |
if err := hs.readClientFinished(); err != nil { |
| 100 |
return err |
| 101 |
} |
| 102 |
|
| 103 |
c.isHandshakeComplete.Store(true) |
| 104 |
|
| 105 |
return nil |
| 106 |
} |
| 107 |
|
| 108 |
func (hs *serverHandshakeStateTLS13) processClientHello() error { |
| 109 |
c := hs.c |
| 110 |
|
| 111 |
hs.hello = new(serverHelloMsg) |
| 112 |
|
| 113 |
// TLS 1.3 froze the ServerHello.legacy_version field, and uses |
| 114 |
// supported_versions instead. See RFC 8446, sections 4.1.3 and 4.2.1. |
| 115 |
hs.hello.vers = VersionTLS12 |
| 116 |
hs.hello.supportedVersion = c.vers |
| 117 |
|
| 118 |
if len(hs.clientHello.supportedVersions) == 0 { |
| 119 |
c.sendAlert(alertIllegalParameter) |
| 120 |
return errors.New("tls: client used the legacy version field to negotiate TLS 1.3") |
| 121 |
} |
| 122 |
|
| 123 |
// Abort if the client is doing a fallback and landing lower than what we |
| 124 |
// support. See RFC 7507, which however does not specify the interaction |
| 125 |
// with supported_versions. The only difference is that with |
| 126 |
// supported_versions a client has a chance to attempt a [TLS 1.2, TLS 1.4] |
| 127 |
// handshake in case TLS 1.3 is broken but 1.2 is not. Alas, in that case, |
| 128 |
// it will have to drop the TLS_FALLBACK_SCSV protection if it falls back to |
| 129 |
// TLS 1.2, because a TLS 1.3 server would abort here. The situation before |
| 130 |
// supported_versions was not better because there was just no way to do a |
| 131 |
// TLS 1.4 handshake without risking the server selecting TLS 1.3. |
| 132 |
for _, id := range hs.clientHello.cipherSuites { |
| 133 |
if id == TLS_FALLBACK_SCSV { |
| 134 |
// Use c.vers instead of max(supported_versions) because an attacker |
| 135 |
// could defeat this by adding an arbitrary high version otherwise. |
| 136 |
if c.vers < c.config.maxSupportedVersion(roleServer) { |
| 137 |
c.sendAlert(alertInappropriateFallback) |
| 138 |
return errors.New("tls: client using inappropriate protocol fallback") |
| 139 |
} |
| 140 |
break |
| 141 |
} |
| 142 |
} |
| 143 |
|
| 144 |
if len(hs.clientHello.compressionMethods) != 1 || |
| 145 |
hs.clientHello.compressionMethods[0] != compressionNone { |
| 146 |
c.sendAlert(alertIllegalParameter) |
| 147 |
return errors.New("tls: TLS 1.3 client supports illegal compression methods") |
| 148 |
} |
| 149 |
|
| 150 |
hs.hello.random = make([]byte, 32) |
| 151 |
if _, err := io.ReadFull(c.config.rand(), hs.hello.random); err != nil { |
| 152 |
c.sendAlert(alertInternalError) |
| 153 |
return err |
| 154 |
} |
| 155 |
|
| 156 |
if len(hs.clientHello.secureRenegotiation) != 0 { |
| 157 |
c.sendAlert(alertHandshakeFailure) |
| 158 |
return errors.New("tls: initial handshake had non-empty renegotiation extension") |
| 159 |
} |
| 160 |
|
| 161 |
if hs.clientHello.earlyData && c.quic != nil { |
| 162 |
if len(hs.clientHello.pskIdentities) == 0 { |
| 163 |
c.sendAlert(alertIllegalParameter) |
| 164 |
return errors.New("tls: early_data without pre_shared_key") |
| 165 |
} |
| 166 |
} else if hs.clientHello.earlyData { |
| 167 |
// See RFC 8446, Section 4.2.10 for the complicated behavior required |
| 168 |
// here. The scenario is that a different server at our address offered |
| 169 |
// to accept early data in the past, which we can't handle. For now, all |
| 170 |
// 0-RTT enabled session tickets need to expire before a Go server can |
| 171 |
// replace a server or join a pool. That's the same requirement that |
| 172 |
// applies to mixing or replacing with any TLS 1.2 server. |
| 173 |
c.sendAlert(alertUnsupportedExtension) |
| 174 |
return errors.New("tls: client sent unexpected early data") |
| 175 |
} |
| 176 |
|
| 177 |
hs.hello.sessionId = hs.clientHello.sessionId |
| 178 |
hs.hello.compressionMethod = compressionNone |
| 179 |
|
| 180 |
preferenceList := defaultCipherSuitesTLS13 |
| 181 |
if !hasAESGCMHardwareSupport || !isAESGCMPreferred(hs.clientHello.cipherSuites) { |
| 182 |
preferenceList = defaultCipherSuitesTLS13NoAES |
| 183 |
} |
| 184 |
if fips140tls.Required() { |
| 185 |
preferenceList = allowedCipherSuitesTLS13FIPS |
| 186 |
} |
| 187 |
for _, suiteID := range preferenceList { |
| 188 |
hs.suite = mutualCipherSuiteTLS13(hs.clientHello.cipherSuites, suiteID) |
| 189 |
if hs.suite != nil { |
| 190 |
break |
| 191 |
} |
| 192 |
} |
| 193 |
if hs.suite == nil { |
| 194 |
c.sendAlert(alertHandshakeFailure) |
| 195 |
return fmt.Errorf("tls: no cipher suite supported by both client and server; client offered: %x", |
| 196 |
hs.clientHello.cipherSuites) |
| 197 |
} |
| 198 |
c.cipherSuite = hs.suite.id |
| 199 |
hs.hello.cipherSuite = hs.suite.id |
| 200 |
hs.transcript = hs.suite.hash.New() |
| 201 |
|
| 202 |
// First, if a post-quantum key exchange is available, use one. See |
| 203 |
// draft-ietf-tls-key-share-prediction-01, Section 4 for why this must be |
| 204 |
// first. |
| 205 |
// |
| 206 |
// Second, if the client sent a key share for a group we support, use that, |
| 207 |
// to avoid a HelloRetryRequest round-trip. |
| 208 |
// |
| 209 |
// Finally, pick in our fixed preference order. |
| 210 |
preferredGroups := c.config.curvePreferences(c.vers) |
| 211 |
preferredGroups = slices.DeleteFunc(preferredGroups, func(group CurveID) bool { |
| 212 |
return !slices.Contains(hs.clientHello.supportedCurves, group) |
| 213 |
}) |
| 214 |
if len(preferredGroups) == 0 { |
| 215 |
c.sendAlert(alertHandshakeFailure) |
| 216 |
return errors.New("tls: no key exchanges supported by both client and server") |
| 217 |
} |
| 218 |
hasKeyShare := func(group CurveID) bool { |
| 219 |
for _, ks := range hs.clientHello.keyShares { |
| 220 |
if ks.group == group { |
| 221 |
return true |
| 222 |
} |
| 223 |
} |
| 224 |
return false |
| 225 |
} |
| 226 |
sort.SliceStable(preferredGroups, func(i, j int) bool { |
| 227 |
return hasKeyShare(preferredGroups[i]) && !hasKeyShare(preferredGroups[j]) |
| 228 |
}) |
| 229 |
sort.SliceStable(preferredGroups, func(i, j int) bool { |
| 230 |
return isPQKeyExchange(preferredGroups[i]) && !isPQKeyExchange(preferredGroups[j]) |
| 231 |
}) |
| 232 |
selectedGroup := preferredGroups[0] |
| 233 |
|
| 234 |
var clientKeyShare *keyShare |
| 235 |
for _, ks := range hs.clientHello.keyShares { |
| 236 |
if ks.group == selectedGroup { |
| 237 |
clientKeyShare = &ks |
| 238 |
break |
| 239 |
} |
| 240 |
} |
| 241 |
if clientKeyShare == nil { |
| 242 |
ks, err := hs.doHelloRetryRequest(selectedGroup) |
| 243 |
if err != nil { |
| 244 |
return err |
| 245 |
} |
| 246 |
clientKeyShare = ks |
| 247 |
} |
| 248 |
c.curveID = selectedGroup |
| 249 |
|
| 250 |
ecdhGroup := selectedGroup |
| 251 |
ecdhData := clientKeyShare.data |
| 252 |
if selectedGroup == X25519MLKEM768 { |
| 253 |
ecdhGroup = X25519 |
| 254 |
if len(ecdhData) != mlkem.EncapsulationKeySize768+x25519PublicKeySize { |
| 255 |
c.sendAlert(alertIllegalParameter) |
| 256 |
return errors.New("tls: invalid X25519MLKEM768 client key share") |
| 257 |
} |
| 258 |
ecdhData = ecdhData[mlkem.EncapsulationKeySize768:] |
| 259 |
} |
| 260 |
if _, ok := curveForCurveID(ecdhGroup); !ok { |
| 261 |
c.sendAlert(alertInternalError) |
| 262 |
return errors.New("tls: CurvePreferences includes unsupported curve") |
| 263 |
} |
| 264 |
key, err := generateECDHEKey(c.config.rand(), ecdhGroup) |
| 265 |
if err != nil { |
| 266 |
c.sendAlert(alertInternalError) |
| 267 |
return err |
| 268 |
} |
| 269 |
hs.hello.serverShare = keyShare{group: selectedGroup, data: key.PublicKey().Bytes()} |
| 270 |
peerKey, err := key.Curve().NewPublicKey(ecdhData) |
| 271 |
if err != nil { |
| 272 |
c.sendAlert(alertIllegalParameter) |
| 273 |
return errors.New("tls: invalid client key share") |
| 274 |
} |
| 275 |
hs.sharedKey, err = key.ECDH(peerKey) |
| 276 |
if err != nil { |
| 277 |
c.sendAlert(alertIllegalParameter) |
| 278 |
return errors.New("tls: invalid client key share") |
| 279 |
} |
| 280 |
if selectedGroup == X25519MLKEM768 { |
| 281 |
k, err := mlkem.NewEncapsulationKey768(clientKeyShare.data[:mlkem.EncapsulationKeySize768]) |
| 282 |
if err != nil { |
| 283 |
c.sendAlert(alertIllegalParameter) |
| 284 |
return errors.New("tls: invalid X25519MLKEM768 client key share") |
| 285 |
} |
| 286 |
mlkemSharedSecret, ciphertext := k.Encapsulate() |
| 287 |
// draft-kwiatkowski-tls-ecdhe-mlkem-02, Section 3.1.3: "For |
| 288 |
// X25519MLKEM768, the shared secret is the concatenation of the ML-KEM |
| 289 |
// shared secret and the X25519 shared secret. The shared secret is 64 |
| 290 |
// bytes (32 bytes for each part)." |
| 291 |
hs.sharedKey = append(mlkemSharedSecret, hs.sharedKey...) |
| 292 |
// draft-kwiatkowski-tls-ecdhe-mlkem-02, Section 3.1.2: "When the |
| 293 |
// X25519MLKEM768 group is negotiated, the server's key exchange value |
| 294 |
// is the concatenation of an ML-KEM ciphertext returned from |
| 295 |
// encapsulation to the client's encapsulation key, and the server's |
| 296 |
// ephemeral X25519 share." |
| 297 |
hs.hello.serverShare.data = append(ciphertext, hs.hello.serverShare.data...) |
| 298 |
} |
| 299 |
|
| 300 |
selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols, c.quic != nil) |
| 301 |
if err != nil { |
| 302 |
c.sendAlert(alertNoApplicationProtocol) |
| 303 |
return err |
| 304 |
} |
| 305 |
c.clientProtocol = selectedProto |
| 306 |
|
| 307 |
if c.quic != nil { |
| 308 |
// RFC 9001 Section 4.2: Clients MUST NOT offer TLS versions older than 1.3. |
| 309 |
for _, v := range hs.clientHello.supportedVersions { |
| 310 |
if v < VersionTLS13 { |
| 311 |
c.sendAlert(alertProtocolVersion) |
| 312 |
return errors.New("tls: client offered TLS version older than TLS 1.3") |
| 313 |
} |
| 314 |
} |
| 315 |
// RFC 9001 Section 8.2. |
| 316 |
if hs.clientHello.quicTransportParameters == nil { |
| 317 |
c.sendAlert(alertMissingExtension) |
| 318 |
return errors.New("tls: client did not send a quic_transport_parameters extension") |
| 319 |
} |
| 320 |
c.quicSetTransportParameters(hs.clientHello.quicTransportParameters) |
| 321 |
} else { |
| 322 |
if hs.clientHello.quicTransportParameters != nil { |
| 323 |
c.sendAlert(alertUnsupportedExtension) |
| 324 |
return errors.New("tls: client sent an unexpected quic_transport_parameters extension") |
| 325 |
} |
| 326 |
} |
| 327 |
|
| 328 |
c.serverName = hs.clientHello.serverName |
| 329 |
return nil |
| 330 |
} |
| 331 |
|
| 332 |
func (hs *serverHandshakeStateTLS13) checkForResumption() error { |
| 333 |
c := hs.c |
| 334 |
|
| 335 |
if c.config.SessionTicketsDisabled { |
| 336 |
return nil |
| 337 |
} |
| 338 |
|
| 339 |
modeOK := false |
| 340 |
for _, mode := range hs.clientHello.pskModes { |
| 341 |
if mode == pskModeDHE { |
| 342 |
modeOK = true |
| 343 |
break |
| 344 |
} |
| 345 |
} |
| 346 |
if !modeOK { |
| 347 |
return nil |
| 348 |
} |
| 349 |
|
| 350 |
if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) { |
| 351 |
c.sendAlert(alertIllegalParameter) |
| 352 |
return errors.New("tls: invalid or missing PSK binders") |
| 353 |
} |
| 354 |
if len(hs.clientHello.pskIdentities) == 0 { |
| 355 |
return nil |
| 356 |
} |
| 357 |
|
| 358 |
for i, identity := range hs.clientHello.pskIdentities { |
| 359 |
if i >= maxClientPSKIdentities { |
| 360 |
break |
| 361 |
} |
| 362 |
|
| 363 |
var sessionState *SessionState |
| 364 |
if c.config.UnwrapSession != nil { |
| 365 |
var err error |
| 366 |
sessionState, err = c.config.UnwrapSession(identity.label, c.connectionStateLocked()) |
| 367 |
if err != nil { |
| 368 |
return err |
| 369 |
} |
| 370 |
if sessionState == nil { |
| 371 |
continue |
| 372 |
} |
| 373 |
} else { |
| 374 |
plaintext := c.config.decryptTicket(identity.label, c.ticketKeys) |
| 375 |
if plaintext == nil { |
| 376 |
continue |
| 377 |
} |
| 378 |
var err error |
| 379 |
sessionState, err = ParseSessionState(plaintext) |
| 380 |
if err != nil { |
| 381 |
continue |
| 382 |
} |
| 383 |
} |
| 384 |
|
| 385 |
if sessionState.version != VersionTLS13 { |
| 386 |
continue |
| 387 |
} |
| 388 |
|
| 389 |
createdAt := time.Unix(int64(sessionState.createdAt), 0) |
| 390 |
if c.config.time().Sub(createdAt) > maxSessionTicketLifetime { |
| 391 |
continue |
| 392 |
} |
| 393 |
|
| 394 |
pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite) |
| 395 |
if pskSuite == nil || pskSuite.hash != hs.suite.hash { |
| 396 |
continue |
| 397 |
} |
| 398 |
|
| 399 |
// PSK connections don't re-establish client certificates, but carry |
| 400 |
// them over in the session ticket. Ensure the presence of client certs |
| 401 |
// in the ticket is consistent with the configured requirements. |
| 402 |
sessionHasClientCerts := len(sessionState.peerCertificates) != 0 |
| 403 |
needClientCerts := requiresClientCert(c.config.ClientAuth) |
| 404 |
if needClientCerts && !sessionHasClientCerts { |
| 405 |
continue |
| 406 |
} |
| 407 |
if sessionHasClientCerts && c.config.ClientAuth == NoClientCert { |
| 408 |
continue |
| 409 |
} |
| 410 |
if sessionHasClientCerts && c.config.time().After(sessionState.peerCertificates[0].NotAfter) { |
| 411 |
continue |
| 412 |
} |
| 413 |
opts := x509.VerifyOptions{ |
| 414 |
CurrentTime: c.config.time(), |
| 415 |
Roots: c.config.ClientCAs, |
| 416 |
KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, |
| 417 |
} |
| 418 |
if sessionHasClientCerts && c.config.ClientAuth >= VerifyClientCertIfGiven && |
| 419 |
!anyValidVerifiedChain(sessionState.verifiedChains, opts) { |
| 420 |
continue |
| 421 |
} |
| 422 |
|
| 423 |
if c.quic != nil && c.quic.enableSessionEvents { |
| 424 |
if err := c.quicResumeSession(sessionState); err != nil { |
| 425 |
return err |
| 426 |
} |
| 427 |
} |
| 428 |
|
| 429 |
hs.earlySecret = tls13.NewEarlySecret(hs.suite.hash.New, sessionState.secret) |
| 430 |
binderKey := hs.earlySecret.ResumptionBinderKey() |
| 431 |
// Clone the transcript in case a HelloRetryRequest was recorded. |
| 432 |
transcript := cloneHash(hs.transcript, hs.suite.hash) |
| 433 |
if transcript == nil { |
| 434 |
c.sendAlert(alertInternalError) |
| 435 |
return errors.New("tls: internal error: failed to clone hash") |
| 436 |
} |
| 437 |
clientHelloBytes, err := hs.clientHello.marshalWithoutBinders() |
| 438 |
if err != nil { |
| 439 |
c.sendAlert(alertInternalError) |
| 440 |
return err |
| 441 |
} |
| 442 |
transcript.Write(clientHelloBytes) |
| 443 |
pskBinder := hs.suite.finishedHash(binderKey, transcript) |
| 444 |
if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) { |
| 445 |
c.sendAlert(alertDecryptError) |
| 446 |
return errors.New("tls: invalid PSK binder") |
| 447 |
} |
| 448 |
|
| 449 |
if c.quic != nil && hs.clientHello.earlyData && i == 0 && |
| 450 |
sessionState.EarlyData && sessionState.cipherSuite == hs.suite.id && |
| 451 |
sessionState.alpnProtocol == c.clientProtocol { |
| 452 |
hs.earlyData = true |
| 453 |
|
| 454 |
transcript := hs.suite.hash.New() |
| 455 |
if err := transcriptMsg(hs.clientHello, transcript); err != nil { |
| 456 |
return err |
| 457 |
} |
| 458 |
earlyTrafficSecret := hs.earlySecret.ClientEarlyTrafficSecret(transcript) |
| 459 |
if err := c.quicSetReadSecret(QUICEncryptionLevelEarly, hs.suite.id, earlyTrafficSecret); err != nil { |
| 460 |
return err |
| 461 |
} |
| 462 |
} |
| 463 |
|
| 464 |
c.didResume = true |
| 465 |
c.peerCertificates = sessionState.peerCertificates |
| 466 |
c.ocspResponse = sessionState.ocspResponse |
| 467 |
c.scts = sessionState.scts |
| 468 |
c.verifiedChains = sessionState.verifiedChains |
| 469 |
|
| 470 |
hs.hello.selectedIdentityPresent = true |
| 471 |
hs.hello.selectedIdentity = uint16(i) |
| 472 |
hs.usingPSK = true |
| 473 |
return nil |
| 474 |
} |
| 475 |
|
| 476 |
return nil |
| 477 |
} |
| 478 |
|
| 479 |
// cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler |
| 480 |
// interfaces implemented by standard library hashes to clone the state of in |
| 481 |
// to a new instance of h. It returns nil if the operation fails. |
| 482 |
func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash { |
| 483 |
// Recreate the interface to avoid importing encoding. |
| 484 |
type binaryMarshaler interface { |
| 485 |
MarshalBinary() (data []byte, err error) |
| 486 |
UnmarshalBinary(data []byte) error |
| 487 |
} |
| 488 |
marshaler, ok := in.(binaryMarshaler) |
| 489 |
if !ok { |
| 490 |
return nil |
| 491 |
} |
| 492 |
state, err := marshaler.MarshalBinary() |
| 493 |
if err != nil { |
| 494 |
return nil |
| 495 |
} |
| 496 |
out := h.New() |
| 497 |
unmarshaler, ok := out.(binaryMarshaler) |
| 498 |
if !ok { |
| 499 |
return nil |
| 500 |
} |
| 501 |
if err := unmarshaler.UnmarshalBinary(state); err != nil { |
| 502 |
return nil |
| 503 |
} |
| 504 |
return out |
| 505 |
} |
| 506 |
|
| 507 |
func (hs *serverHandshakeStateTLS13) pickCertificate() error { |
| 508 |
c := hs.c |
| 509 |
|
| 510 |
// Only one of PSK and certificates are used at a time. |
| 511 |
if hs.usingPSK { |
| 512 |
return nil |
| 513 |
} |
| 514 |
|
| 515 |
// signature_algorithms is required in TLS 1.3. See RFC 8446, Section 4.2.3. |
| 516 |
if len(hs.clientHello.supportedSignatureAlgorithms) == 0 { |
| 517 |
return c.sendAlert(alertMissingExtension) |
| 518 |
} |
| 519 |
|
| 520 |
certificate, err := c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello)) |
| 521 |
if err != nil { |
| 522 |
if err == errNoCertificates { |
| 523 |
c.sendAlert(alertUnrecognizedName) |
| 524 |
} else { |
| 525 |
c.sendAlert(alertInternalError) |
| 526 |
} |
| 527 |
return err |
| 528 |
} |
| 529 |
hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms) |
| 530 |
if err != nil { |
| 531 |
// getCertificate returned a certificate that is unsupported or |
| 532 |
// incompatible with the client's signature algorithms. |
| 533 |
c.sendAlert(alertHandshakeFailure) |
| 534 |
return err |
| 535 |
} |
| 536 |
hs.cert = certificate |
| 537 |
|
| 538 |
return nil |
| 539 |
} |
| 540 |
|
| 541 |
// sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility |
| 542 |
// with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4. |
| 543 |
func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error { |
| 544 |
if hs.c.quic != nil { |
| 545 |
return nil |
| 546 |
} |
| 547 |
if hs.sentDummyCCS { |
| 548 |
return nil |
| 549 |
} |
| 550 |
hs.sentDummyCCS = true |
| 551 |
|
| 552 |
return hs.c.writeChangeCipherRecord() |
| 553 |
} |
| 554 |
|
| 555 |
func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) (*keyShare, error) { |
| 556 |
c := hs.c |
| 557 |
|
| 558 |
// Make sure the client didn't send extra handshake messages alongside |
| 559 |
// their initial client_hello. If they sent two client_hello messages, |
| 560 |
// we will consume the second before they respond to the server_hello. |
| 561 |
if c.hand.Len() != 0 { |
| 562 |
c.sendAlert(alertUnexpectedMessage) |
| 563 |
return nil, errors.New("tls: handshake buffer not empty before HelloRetryRequest") |
| 564 |
} |
| 565 |
|
| 566 |
// The first ClientHello gets double-hashed into the transcript upon a |
| 567 |
// HelloRetryRequest. See RFC 8446, Section 4.4.1. |
| 568 |
if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil { |
| 569 |
return nil, err |
| 570 |
} |
| 571 |
chHash := hs.transcript.Sum(nil) |
| 572 |
hs.transcript.Reset() |
| 573 |
hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) |
| 574 |
hs.transcript.Write(chHash) |
| 575 |
|
| 576 |
helloRetryRequest := &serverHelloMsg{ |
| 577 |
vers: hs.hello.vers, |
| 578 |
random: helloRetryRequestRandom, |
| 579 |
sessionId: hs.hello.sessionId, |
| 580 |
cipherSuite: hs.hello.cipherSuite, |
| 581 |
compressionMethod: hs.hello.compressionMethod, |
| 582 |
supportedVersion: hs.hello.supportedVersion, |
| 583 |
selectedGroup: selectedGroup, |
| 584 |
} |
| 585 |
|
| 586 |
if hs.echContext != nil { |
| 587 |
// Compute the acceptance message. |
| 588 |
helloRetryRequest.encryptedClientHello = make([]byte, 8) |
| 589 |
confTranscript := cloneHash(hs.transcript, hs.suite.hash) |
| 590 |
if err := transcriptMsg(helloRetryRequest, confTranscript); err != nil { |
| 591 |
return nil, err |
| 592 |
} |
| 593 |
h := hs.suite.hash.New |
| 594 |
prf, err := hkdf.Extract(h, hs.clientHello.random, nil) |
| 595 |
if err != nil { |
| 596 |
c.sendAlert(alertInternalError) |
| 597 |
return nil, err |
| 598 |
} |
| 599 |
acceptConfirmation := tls13.ExpandLabel(h, prf, "hrr ech accept confirmation", confTranscript.Sum(nil), 8) |
| 600 |
helloRetryRequest.encryptedClientHello = acceptConfirmation |
| 601 |
} |
| 602 |
|
| 603 |
if _, err := hs.c.writeHandshakeRecord(helloRetryRequest, hs.transcript); err != nil { |
| 604 |
return nil, err |
| 605 |
} |
| 606 |
|
| 607 |
if err := hs.sendDummyChangeCipherSpec(); err != nil { |
| 608 |
return nil, err |
| 609 |
} |
| 610 |
|
| 611 |
// clientHelloMsg is not included in the transcript. |
| 612 |
msg, err := c.readHandshake(nil) |
| 613 |
if err != nil { |
| 614 |
return nil, err |
| 615 |
} |
| 616 |
|
| 617 |
clientHello, ok := msg.(*clientHelloMsg) |
| 618 |
if !ok { |
| 619 |
c.sendAlert(alertUnexpectedMessage) |
| 620 |
return nil, unexpectedMessageError(clientHello, msg) |
| 621 |
} |
| 622 |
|
| 623 |
if hs.echContext != nil { |
| 624 |
if len(clientHello.encryptedClientHello) == 0 { |
| 625 |
c.sendAlert(alertMissingExtension) |
| 626 |
return nil, errors.New("tls: second client hello missing encrypted client hello extension") |
| 627 |
} |
| 628 |
|
| 629 |
echType, echCiphersuite, configID, encap, payload, err := parseECHExt(clientHello.encryptedClientHello) |
| 630 |
if err != nil { |
| 631 |
c.sendAlert(alertDecodeError) |
| 632 |
return nil, errors.New("tls: client sent invalid encrypted client hello extension") |
| 633 |
} |
| 634 |
|
| 635 |
if echType == outerECHExt && hs.echContext.inner || echType == innerECHExt && !hs.echContext.inner { |
| 636 |
c.sendAlert(alertDecodeError) |
| 637 |
return nil, errors.New("tls: unexpected switch in encrypted client hello extension type") |
| 638 |
} |
| 639 |
|
| 640 |
if echType == outerECHExt { |
| 641 |
if echCiphersuite != hs.echContext.ciphersuite || configID != hs.echContext.configID || len(encap) != 0 { |
| 642 |
c.sendAlert(alertIllegalParameter) |
| 643 |
return nil, errors.New("tls: second client hello encrypted client hello extension does not match") |
| 644 |
} |
| 645 |
|
| 646 |
encodedInner, err := decryptECHPayload(hs.echContext.hpkeContext, clientHello.original, payload) |
| 647 |
if err != nil { |
| 648 |
c.sendAlert(alertDecryptError) |
| 649 |
return nil, errors.New("tls: failed to decrypt second client hello encrypted client hello extension payload") |
| 650 |
} |
| 651 |
|
| 652 |
echInner, err := decodeInnerClientHello(clientHello, encodedInner) |
| 653 |
if err != nil { |
| 654 |
c.sendAlert(alertIllegalParameter) |
| 655 |
return nil, errors.New("tls: client sent invalid encrypted client hello extension") |
| 656 |
} |
| 657 |
|
| 658 |
clientHello = echInner |
| 659 |
} |
| 660 |
} |
| 661 |
|
| 662 |
if len(clientHello.keyShares) != 1 { |
| 663 |
c.sendAlert(alertIllegalParameter) |
| 664 |
return nil, errors.New("tls: client didn't send one key share in second ClientHello") |
| 665 |
} |
| 666 |
ks := &clientHello.keyShares[0] |
| 667 |
|
| 668 |
if ks.group != selectedGroup { |
| 669 |
c.sendAlert(alertIllegalParameter) |
| 670 |
return nil, errors.New("tls: client sent unexpected key share in second ClientHello") |
| 671 |
} |
| 672 |
|
| 673 |
if clientHello.earlyData { |
| 674 |
c.sendAlert(alertIllegalParameter) |
| 675 |
return nil, errors.New("tls: client indicated early data in second ClientHello") |
| 676 |
} |
| 677 |
|
| 678 |
if illegalClientHelloChange(clientHello, hs.clientHello) { |
| 679 |
c.sendAlert(alertIllegalParameter) |
| 680 |
return nil, errors.New("tls: client illegally modified second ClientHello") |
| 681 |
} |
| 682 |
|
| 683 |
c.didHRR = true |
| 684 |
hs.clientHello = clientHello |
| 685 |
return ks, nil |
| 686 |
} |
| 687 |
|
| 688 |
// illegalClientHelloChange reports whether the two ClientHello messages are |
| 689 |
// different, with the exception of the changes allowed before and after a |
| 690 |
// HelloRetryRequest. See RFC 8446, Section 4.1.2. |
| 691 |
func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool { |
| 692 |
if len(ch.supportedVersions) != len(ch1.supportedVersions) || |
| 693 |
len(ch.cipherSuites) != len(ch1.cipherSuites) || |
| 694 |
len(ch.supportedCurves) != len(ch1.supportedCurves) || |
| 695 |
len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) || |
| 696 |
len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) || |
| 697 |
len(ch.alpnProtocols) != len(ch1.alpnProtocols) { |
| 698 |
return true |
| 699 |
} |
| 700 |
for i := range ch.supportedVersions { |
| 701 |
if ch.supportedVersions[i] != ch1.supportedVersions[i] { |
| 702 |
return true |
| 703 |
} |
| 704 |
} |
| 705 |
for i := range ch.cipherSuites { |
| 706 |
if ch.cipherSuites[i] != ch1.cipherSuites[i] { |
| 707 |
return true |
| 708 |
} |
| 709 |
} |
| 710 |
for i := range ch.supportedCurves { |
| 711 |
if ch.supportedCurves[i] != ch1.supportedCurves[i] { |
| 712 |
return true |
| 713 |
} |
| 714 |
} |
| 715 |
for i := range ch.supportedSignatureAlgorithms { |
| 716 |
if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] { |
| 717 |
return true |
| 718 |
} |
| 719 |
} |
| 720 |
for i := range ch.supportedSignatureAlgorithmsCert { |
| 721 |
if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] { |
| 722 |
return true |
| 723 |
} |
| 724 |
} |
| 725 |
for i := range ch.alpnProtocols { |
| 726 |
if ch.alpnProtocols[i] != ch1.alpnProtocols[i] { |
| 727 |
return true |
| 728 |
} |
| 729 |
} |
| 730 |
return ch.vers != ch1.vers || |
| 731 |
!bytes.Equal(ch.random, ch1.random) || |
| 732 |
!bytes.Equal(ch.sessionId, ch1.sessionId) || |
| 733 |
!bytes.Equal(ch.compressionMethods, ch1.compressionMethods) || |
| 734 |
ch.serverName != ch1.serverName || |
| 735 |
ch.ocspStapling != ch1.ocspStapling || |
| 736 |
!bytes.Equal(ch.supportedPoints, ch1.supportedPoints) || |
| 737 |
ch.ticketSupported != ch1.ticketSupported || |
| 738 |
!bytes.Equal(ch.sessionTicket, ch1.sessionTicket) || |
| 739 |
ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported || |
| 740 |
!bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) || |
| 741 |
ch.scts != ch1.scts || |
| 742 |
!bytes.Equal(ch.cookie, ch1.cookie) || |
| 743 |
!bytes.Equal(ch.pskModes, ch1.pskModes) |
| 744 |
} |
| 745 |
|
| 746 |
func (hs *serverHandshakeStateTLS13) sendServerParameters() error { |
| 747 |
c := hs.c |
| 748 |
|
| 749 |
if hs.echContext != nil { |
| 750 |
copy(hs.hello.random[32-8:], make([]byte, 8)) |
| 751 |
echTranscript := cloneHash(hs.transcript, hs.suite.hash) |
| 752 |
echTranscript.Write(hs.clientHello.original) |
| 753 |
if err := transcriptMsg(hs.hello, echTranscript); err != nil { |
| 754 |
return err |
| 755 |
} |
| 756 |
// compute the acceptance message |
| 757 |
h := hs.suite.hash.New |
| 758 |
prk, err := hkdf.Extract(h, hs.clientHello.random, nil) |
| 759 |
if err != nil { |
| 760 |
c.sendAlert(alertInternalError) |
| 761 |
return err |
| 762 |
} |
| 763 |
acceptConfirmation := tls13.ExpandLabel(h, prk, "ech accept confirmation", echTranscript.Sum(nil), 8) |
| 764 |
copy(hs.hello.random[32-8:], acceptConfirmation) |
| 765 |
} |
| 766 |
|
| 767 |
if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil { |
| 768 |
return err |
| 769 |
} |
| 770 |
|
| 771 |
if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil { |
| 772 |
return err |
| 773 |
} |
| 774 |
|
| 775 |
if err := hs.sendDummyChangeCipherSpec(); err != nil { |
| 776 |
return err |
| 777 |
} |
| 778 |
|
| 779 |
earlySecret := hs.earlySecret |
| 780 |
if earlySecret == nil { |
| 781 |
earlySecret = tls13.NewEarlySecret(hs.suite.hash.New, nil) |
| 782 |
} |
| 783 |
hs.handshakeSecret = earlySecret.HandshakeSecret(hs.sharedKey) |
| 784 |
|
| 785 |
serverSecret := hs.handshakeSecret.ServerHandshakeTrafficSecret(hs.transcript) |
| 786 |
c.setWriteTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret) |
| 787 |
clientSecret := hs.handshakeSecret.ClientHandshakeTrafficSecret(hs.transcript) |
| 788 |
if err := c.setReadTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, clientSecret, false); err != nil { |
| 789 |
return err |
| 790 |
} |
| 791 |
|
| 792 |
if c.quic != nil { |
| 793 |
c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret) |
| 794 |
if err := c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, clientSecret); err != nil { |
| 795 |
return err |
| 796 |
} |
| 797 |
} |
| 798 |
|
| 799 |
err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret) |
| 800 |
if err != nil { |
| 801 |
c.sendAlert(alertInternalError) |
| 802 |
return err |
| 803 |
} |
| 804 |
err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret) |
| 805 |
if err != nil { |
| 806 |
c.sendAlert(alertInternalError) |
| 807 |
return err |
| 808 |
} |
| 809 |
|
| 810 |
encryptedExtensions := new(encryptedExtensionsMsg) |
| 811 |
encryptedExtensions.alpnProtocol = c.clientProtocol |
| 812 |
|
| 813 |
if c.quic != nil { |
| 814 |
p, err := c.quicGetTransportParameters() |
| 815 |
if err != nil { |
| 816 |
return err |
| 817 |
} |
| 818 |
encryptedExtensions.quicTransportParameters = p |
| 819 |
encryptedExtensions.earlyData = hs.earlyData |
| 820 |
} |
| 821 |
|
| 822 |
if !hs.c.didResume && hs.clientHello.serverName != "" { |
| 823 |
encryptedExtensions.serverNameAck = true |
| 824 |
} |
| 825 |
|
| 826 |
// If client sent ECH extension, but we didn't accept it, |
| 827 |
// send retry configs, if available. |
| 828 |
echKeys := hs.c.config.EncryptedClientHelloKeys |
| 829 |
if hs.c.config.GetEncryptedClientHelloKeys != nil { |
| 830 |
echKeys, err = hs.c.config.GetEncryptedClientHelloKeys(clientHelloInfo(hs.ctx, c, hs.clientHello)) |
| 831 |
if err != nil { |
| 832 |
c.sendAlert(alertInternalError) |
| 833 |
return err |
| 834 |
} |
| 835 |
} |
| 836 |
if len(echKeys) > 0 && len(hs.clientHello.encryptedClientHello) > 0 && hs.echContext == nil { |
| 837 |
encryptedExtensions.echRetryConfigs, err = buildRetryConfigList(echKeys) |
| 838 |
if err != nil { |
| 839 |
c.sendAlert(alertInternalError) |
| 840 |
return err |
| 841 |
} |
| 842 |
} |
| 843 |
|
| 844 |
if _, err := hs.c.writeHandshakeRecord(encryptedExtensions, hs.transcript); err != nil { |
| 845 |
return err |
| 846 |
} |
| 847 |
|
| 848 |
return nil |
| 849 |
} |
| 850 |
|
| 851 |
func (hs *serverHandshakeStateTLS13) requestClientCert() bool { |
| 852 |
return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK |
| 853 |
} |
| 854 |
|
| 855 |
func (hs *serverHandshakeStateTLS13) sendServerCertificate() error { |
| 856 |
c := hs.c |
| 857 |
|
| 858 |
// Only one of PSK and certificates are used at a time. |
| 859 |
if hs.usingPSK { |
| 860 |
return nil |
| 861 |
} |
| 862 |
|
| 863 |
if hs.requestClientCert() { |
| 864 |
// Request a client certificate |
| 865 |
certReq := new(certificateRequestMsgTLS13) |
| 866 |
certReq.ocspStapling = true |
| 867 |
certReq.scts = true |
| 868 |
certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms(c.vers) |
| 869 |
certReq.supportedSignatureAlgorithmsCert = supportedSignatureAlgorithmsCert() |
| 870 |
if c.config.ClientCAs != nil { |
| 871 |
certReq.certificateAuthorities = c.config.ClientCAs.Subjects() |
| 872 |
} |
| 873 |
|
| 874 |
if _, err := hs.c.writeHandshakeRecord(certReq, hs.transcript); err != nil { |
| 875 |
return err |
| 876 |
} |
| 877 |
} |
| 878 |
|
| 879 |
certMsg := new(certificateMsgTLS13) |
| 880 |
|
| 881 |
certMsg.certificate = *hs.cert |
| 882 |
certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0 |
| 883 |
certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 |
| 884 |
|
| 885 |
if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil { |
| 886 |
return err |
| 887 |
} |
| 888 |
|
| 889 |
certVerifyMsg := new(certificateVerifyMsg) |
| 890 |
certVerifyMsg.hasSignatureAlgorithm = true |
| 891 |
certVerifyMsg.signatureAlgorithm = hs.sigAlg |
| 892 |
|
| 893 |
sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg) |
| 894 |
if err != nil { |
| 895 |
return c.sendAlert(alertInternalError) |
| 896 |
} |
| 897 |
|
| 898 |
signed := signedMessage(sigHash, serverSignatureContext, hs.transcript) |
| 899 |
signOpts := crypto.SignerOpts(sigHash) |
| 900 |
if sigType == signatureRSAPSS { |
| 901 |
signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash} |
| 902 |
} |
| 903 |
sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts) |
| 904 |
if err != nil { |
| 905 |
public := hs.cert.PrivateKey.(crypto.Signer).Public() |
| 906 |
if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS && |
| 907 |
rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 { // key too small for RSA-PSS |
| 908 |
c.sendAlert(alertHandshakeFailure) |
| 909 |
} else { |
| 910 |
c.sendAlert(alertInternalError) |
| 911 |
} |
| 912 |
return errors.New("tls: failed to sign handshake: " + err.Error()) |
| 913 |
} |
| 914 |
certVerifyMsg.signature = sig |
| 915 |
|
| 916 |
if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil { |
| 917 |
return err |
| 918 |
} |
| 919 |
|
| 920 |
return nil |
| 921 |
} |
| 922 |
|
| 923 |
func (hs *serverHandshakeStateTLS13) sendServerFinished() error { |
| 924 |
c := hs.c |
| 925 |
|
| 926 |
finished := &finishedMsg{ |
| 927 |
verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript), |
| 928 |
} |
| 929 |
|
| 930 |
if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil { |
| 931 |
return err |
| 932 |
} |
| 933 |
|
| 934 |
// Derive secrets that take context through the server Finished. |
| 935 |
|
| 936 |
hs.masterSecret = hs.handshakeSecret.MasterSecret() |
| 937 |
|
| 938 |
hs.trafficSecret = hs.masterSecret.ClientApplicationTrafficSecret(hs.transcript) |
| 939 |
serverSecret := hs.masterSecret.ServerApplicationTrafficSecret(hs.transcript) |
| 940 |
c.setWriteTrafficSecret(hs.suite, QUICEncryptionLevelApplication, serverSecret) |
| 941 |
|
| 942 |
if c.quic != nil { |
| 943 |
c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, serverSecret) |
| 944 |
} |
| 945 |
|
| 946 |
err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret) |
| 947 |
if err != nil { |
| 948 |
c.sendAlert(alertInternalError) |
| 949 |
return err |
| 950 |
} |
| 951 |
err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret) |
| 952 |
if err != nil { |
| 953 |
c.sendAlert(alertInternalError) |
| 954 |
return err |
| 955 |
} |
| 956 |
|
| 957 |
c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript) |
| 958 |
|
| 959 |
// If we did not request client certificates, at this point we can |
| 960 |
// precompute the client finished and roll the transcript forward to send |
| 961 |
// session tickets in our first flight. |
| 962 |
if !hs.requestClientCert() { |
| 963 |
if err := hs.sendSessionTickets(); err != nil { |
| 964 |
return err |
| 965 |
} |
| 966 |
} |
| 967 |
|
| 968 |
return nil |
| 969 |
} |
| 970 |
|
| 971 |
func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool { |
| 972 |
if hs.c.config.SessionTicketsDisabled { |
| 973 |
return false |
| 974 |
} |
| 975 |
|
| 976 |
// QUIC tickets are sent by QUICConn.SendSessionTicket, not automatically. |
| 977 |
if hs.c.quic != nil { |
| 978 |
return false |
| 979 |
} |
| 980 |
|
| 981 |
// Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9. |
| 982 |
return slices.Contains(hs.clientHello.pskModes, pskModeDHE) |
| 983 |
} |
| 984 |
|
| 985 |
func (hs *serverHandshakeStateTLS13) sendSessionTickets() error { |
| 986 |
c := hs.c |
| 987 |
|
| 988 |
hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript) |
| 989 |
finishedMsg := &finishedMsg{ |
| 990 |
verifyData: hs.clientFinished, |
| 991 |
} |
| 992 |
if err := transcriptMsg(finishedMsg, hs.transcript); err != nil { |
| 993 |
return err |
| 994 |
} |
| 995 |
|
| 996 |
c.resumptionSecret = hs.masterSecret.ResumptionMasterSecret(hs.transcript) |
| 997 |
|
| 998 |
if !hs.shouldSendSessionTickets() { |
| 999 |
return nil |
| 1000 |
} |
| 1001 |
return c.sendSessionTicket(false, nil) |
| 1002 |
} |
| 1003 |
|
| 1004 |
func (c *Conn) sendSessionTicket(earlyData bool, extra [][]byte) error { |
| 1005 |
suite := cipherSuiteTLS13ByID(c.cipherSuite) |
| 1006 |
if suite == nil { |
| 1007 |
return errors.New("tls: internal error: unknown cipher suite") |
| 1008 |
} |
| 1009 |
// ticket_nonce, which must be unique per connection, is always left at |
| 1010 |
// zero because we only ever send one ticket per connection. |
| 1011 |
psk := tls13.ExpandLabel(suite.hash.New, c.resumptionSecret, "resumption", |
| 1012 |
nil, suite.hash.Size()) |
| 1013 |
|
| 1014 |
m := new(newSessionTicketMsgTLS13) |
| 1015 |
|
| 1016 |
state := c.sessionState() |
| 1017 |
state.secret = psk |
| 1018 |
state.EarlyData = earlyData |
| 1019 |
state.Extra = extra |
| 1020 |
if c.config.WrapSession != nil { |
| 1021 |
var err error |
| 1022 |
m.label, err = c.config.WrapSession(c.connectionStateLocked(), state) |
| 1023 |
if err != nil { |
| 1024 |
return err |
| 1025 |
} |
| 1026 |
} else { |
| 1027 |
stateBytes, err := state.Bytes() |
| 1028 |
if err != nil { |
| 1029 |
c.sendAlert(alertInternalError) |
| 1030 |
return err |
| 1031 |
} |
| 1032 |
m.label, err = c.config.encryptTicket(stateBytes, c.ticketKeys) |
| 1033 |
if err != nil { |
| 1034 |
return err |
| 1035 |
} |
| 1036 |
} |
| 1037 |
m.lifetime = uint32(maxSessionTicketLifetime / time.Second) |
| 1038 |
|
| 1039 |
// ticket_age_add is a random 32-bit value. See RFC 8446, section 4.6.1 |
| 1040 |
// The value is not stored anywhere; we never need to check the ticket age |
| 1041 |
// because 0-RTT is not supported. |
| 1042 |
ageAdd := make([]byte, 4) |
| 1043 |
if _, err := c.config.rand().Read(ageAdd); err != nil { |
| 1044 |
return err |
| 1045 |
} |
| 1046 |
m.ageAdd = byteorder.LEUint32(ageAdd) |
| 1047 |
|
| 1048 |
if earlyData { |
| 1049 |
// RFC 9001, Section 4.6.1 |
| 1050 |
m.maxEarlyData = 0xffffffff |
| 1051 |
} |
| 1052 |
|
| 1053 |
if _, err := c.writeHandshakeRecord(m, nil); err != nil { |
| 1054 |
return err |
| 1055 |
} |
| 1056 |
|
| 1057 |
return nil |
| 1058 |
} |
| 1059 |
|
| 1060 |
func (hs *serverHandshakeStateTLS13) readClientCertificate() error { |
| 1061 |
c := hs.c |
| 1062 |
|
| 1063 |
if !hs.requestClientCert() { |
| 1064 |
// Make sure the connection is still being verified whether or not |
| 1065 |
// the server requested a client certificate. |
| 1066 |
if c.config.VerifyConnection != nil { |
| 1067 |
if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { |
| 1068 |
c.sendAlert(alertBadCertificate) |
| 1069 |
return err |
| 1070 |
} |
| 1071 |
} |
| 1072 |
return nil |
| 1073 |
} |
| 1074 |
|
| 1075 |
// If we requested a client certificate, then the client must send a |
| 1076 |
// certificate message. If it's empty, no CertificateVerify is sent. |
| 1077 |
|
| 1078 |
msg, err := c.readHandshake(hs.transcript) |
| 1079 |
if err != nil { |
| 1080 |
return err |
| 1081 |
} |
| 1082 |
|
| 1083 |
certMsg, ok := msg.(*certificateMsgTLS13) |
| 1084 |
if !ok { |
| 1085 |
c.sendAlert(alertUnexpectedMessage) |
| 1086 |
return unexpectedMessageError(certMsg, msg) |
| 1087 |
} |
| 1088 |
|
| 1089 |
if err := c.processCertsFromClient(certMsg.certificate); err != nil { |
| 1090 |
return err |
| 1091 |
} |
| 1092 |
|
| 1093 |
if c.config.VerifyConnection != nil { |
| 1094 |
if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { |
| 1095 |
c.sendAlert(alertBadCertificate) |
| 1096 |
return err |
| 1097 |
} |
| 1098 |
} |
| 1099 |
|
| 1100 |
if len(certMsg.certificate.Certificate) != 0 { |
| 1101 |
// certificateVerifyMsg is included in the transcript, but not until |
| 1102 |
// after we verify the handshake signature, since the state before |
| 1103 |
// this message was sent is used. |
| 1104 |
msg, err = c.readHandshake(nil) |
| 1105 |
if err != nil { |
| 1106 |
return err |
| 1107 |
} |
| 1108 |
|
| 1109 |
certVerify, ok := msg.(*certificateVerifyMsg) |
| 1110 |
if !ok { |
| 1111 |
c.sendAlert(alertUnexpectedMessage) |
| 1112 |
return unexpectedMessageError(certVerify, msg) |
| 1113 |
} |
| 1114 |
|
| 1115 |
// See RFC 8446, Section 4.4.3. |
| 1116 |
// We don't use certReq.supportedSignatureAlgorithms because it would |
| 1117 |
// require keeping the certificateRequestMsgTLS13 around in the hs. |
| 1118 |
if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms(c.vers)) || |
| 1119 |
!isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, signatureSchemesForPublicKey(c.vers, c.peerCertificates[0].PublicKey)) { |
| 1120 |
c.sendAlert(alertIllegalParameter) |
| 1121 |
return errors.New("tls: client certificate used with invalid signature algorithm") |
| 1122 |
} |
| 1123 |
sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm) |
| 1124 |
if err != nil { |
| 1125 |
return c.sendAlert(alertInternalError) |
| 1126 |
} |
| 1127 |
if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 { |
| 1128 |
return c.sendAlert(alertInternalError) |
| 1129 |
} |
| 1130 |
signed := signedMessage(sigHash, clientSignatureContext, hs.transcript) |
| 1131 |
if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey, |
| 1132 |
sigHash, signed, certVerify.signature); err != nil { |
| 1133 |
c.sendAlert(alertDecryptError) |
| 1134 |
return errors.New("tls: invalid signature by the client certificate: " + err.Error()) |
| 1135 |
} |
| 1136 |
c.peerSigAlg = certVerify.signatureAlgorithm |
| 1137 |
|
| 1138 |
if err := transcriptMsg(certVerify, hs.transcript); err != nil { |
| 1139 |
return err |
| 1140 |
} |
| 1141 |
} |
| 1142 |
|
| 1143 |
// If we waited until the client certificates to send session tickets, we |
| 1144 |
// are ready to do it now. |
| 1145 |
if err := hs.sendSessionTickets(); err != nil { |
| 1146 |
return err |
| 1147 |
} |
| 1148 |
|
| 1149 |
return nil |
| 1150 |
} |
| 1151 |
|
| 1152 |
func (hs *serverHandshakeStateTLS13) readClientFinished() error { |
| 1153 |
c := hs.c |
| 1154 |
|
| 1155 |
// finishedMsg is not included in the transcript. |
| 1156 |
msg, err := c.readHandshake(nil) |
| 1157 |
if err != nil { |
| 1158 |
return err |
| 1159 |
} |
| 1160 |
|
| 1161 |
finished, ok := msg.(*finishedMsg) |
| 1162 |
if !ok { |
| 1163 |
c.sendAlert(alertUnexpectedMessage) |
| 1164 |
return unexpectedMessageError(finished, msg) |
| 1165 |
} |
| 1166 |
|
| 1167 |
if !hmac.Equal(hs.clientFinished, finished.verifyData) { |
| 1168 |
c.sendAlert(alertDecryptError) |
| 1169 |
return errors.New("tls: invalid client finished hash") |
| 1170 |
} |
| 1171 |
|
| 1172 |
if err := c.setReadTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret, false); err != nil { |
| 1173 |
return err |
| 1174 |
} |
| 1175 |
|
| 1176 |
return nil |
| 1177 |
} |