| 1 |
// Copyright 2009 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/ecdsa" |
| 12 |
"crypto/ed25519" |
| 13 |
"crypto/internal/fips140/mlkem" |
| 14 |
"crypto/internal/fips140/tls13" |
| 15 |
"crypto/internal/hpke" |
| 16 |
"crypto/rsa" |
| 17 |
"crypto/subtle" |
| 18 |
"crypto/tls/internal/fips140tls" |
| 19 |
"crypto/x509" |
| 20 |
"errors" |
| 21 |
"fmt" |
| 22 |
"hash" |
| 23 |
"internal/godebug" |
| 24 |
"io" |
| 25 |
"net" |
| 26 |
"slices" |
| 27 |
"strconv" |
| 28 |
"strings" |
| 29 |
"time" |
| 30 |
) |
| 31 |
|
| 32 |
type clientHandshakeState struct { |
| 33 |
c *Conn |
| 34 |
ctx context.Context |
| 35 |
serverHello *serverHelloMsg |
| 36 |
hello *clientHelloMsg |
| 37 |
suite *cipherSuite |
| 38 |
finishedHash finishedHash |
| 39 |
masterSecret []byte |
| 40 |
session *SessionState // the session being resumed |
| 41 |
ticket []byte // a fresh ticket received during this handshake |
| 42 |
} |
| 43 |
|
| 44 |
func (c *Conn) makeClientHello() (*clientHelloMsg, *keySharePrivateKeys, *echClientContext, error) { |
| 45 |
config := c.config |
| 46 |
if len(config.ServerName) == 0 && !config.InsecureSkipVerify { |
| 47 |
return nil, nil, nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config") |
| 48 |
} |
| 49 |
|
| 50 |
nextProtosLength := 0 |
| 51 |
for _, proto := range config.NextProtos { |
| 52 |
if l := len(proto); l == 0 || l > 255 { |
| 53 |
return nil, nil, nil, errors.New("tls: invalid NextProtos value") |
| 54 |
} else { |
| 55 |
nextProtosLength += 1 + l |
| 56 |
} |
| 57 |
} |
| 58 |
if nextProtosLength > 0xffff { |
| 59 |
return nil, nil, nil, errors.New("tls: NextProtos values too large") |
| 60 |
} |
| 61 |
|
| 62 |
supportedVersions := config.supportedVersions(roleClient) |
| 63 |
if len(supportedVersions) == 0 { |
| 64 |
return nil, nil, nil, errors.New("tls: no supported versions satisfy MinVersion and MaxVersion") |
| 65 |
} |
| 66 |
// Since supportedVersions is sorted in descending order, the first element |
| 67 |
// is the maximum version and the last element is the minimum version. |
| 68 |
maxVersion := supportedVersions[0] |
| 69 |
minVersion := supportedVersions[len(supportedVersions)-1] |
| 70 |
|
| 71 |
hello := &clientHelloMsg{ |
| 72 |
vers: maxVersion, |
| 73 |
compressionMethods: []uint8{compressionNone}, |
| 74 |
random: make([]byte, 32), |
| 75 |
extendedMasterSecret: true, |
| 76 |
ocspStapling: true, |
| 77 |
scts: true, |
| 78 |
serverName: hostnameInSNI(config.ServerName), |
| 79 |
supportedCurves: config.curvePreferences(maxVersion), |
| 80 |
supportedPoints: []uint8{pointFormatUncompressed}, |
| 81 |
secureRenegotiationSupported: true, |
| 82 |
alpnProtocols: config.NextProtos, |
| 83 |
supportedVersions: supportedVersions, |
| 84 |
} |
| 85 |
|
| 86 |
// The version at the beginning of the ClientHello was capped at TLS 1.2 |
| 87 |
// for compatibility reasons. The supported_versions extension is used |
| 88 |
// to negotiate versions now. See RFC 8446, Section 4.2.1. |
| 89 |
if hello.vers > VersionTLS12 { |
| 90 |
hello.vers = VersionTLS12 |
| 91 |
} |
| 92 |
|
| 93 |
if c.handshakes > 0 { |
| 94 |
hello.secureRenegotiation = c.clientFinished[:] |
| 95 |
} |
| 96 |
|
| 97 |
hello.cipherSuites = config.cipherSuites(hasAESGCMHardwareSupport) |
| 98 |
// Don't advertise TLS 1.2-only cipher suites unless we're attempting TLS 1.2. |
| 99 |
if maxVersion < VersionTLS12 { |
| 100 |
hello.cipherSuites = slices.DeleteFunc(hello.cipherSuites, func(id uint16) bool { |
| 101 |
return cipherSuiteByID(id).flags&suiteTLS12 != 0 |
| 102 |
}) |
| 103 |
} |
| 104 |
|
| 105 |
_, err := io.ReadFull(config.rand(), hello.random) |
| 106 |
if err != nil { |
| 107 |
return nil, nil, nil, errors.New("tls: short read from Rand: " + err.Error()) |
| 108 |
} |
| 109 |
|
| 110 |
// A random session ID is used to detect when the server accepted a ticket |
| 111 |
// and is resuming a session (see RFC 5077). In TLS 1.3, it's always set as |
| 112 |
// a compatibility measure (see RFC 8446, Section 4.1.2). |
| 113 |
// |
| 114 |
// The session ID is not set for QUIC connections (see RFC 9001, Section 8.4). |
| 115 |
if c.quic == nil { |
| 116 |
hello.sessionId = make([]byte, 32) |
| 117 |
if _, err := io.ReadFull(config.rand(), hello.sessionId); err != nil { |
| 118 |
return nil, nil, nil, errors.New("tls: short read from Rand: " + err.Error()) |
| 119 |
} |
| 120 |
} |
| 121 |
|
| 122 |
if maxVersion >= VersionTLS12 { |
| 123 |
hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms(minVersion) |
| 124 |
hello.supportedSignatureAlgorithmsCert = supportedSignatureAlgorithmsCert() |
| 125 |
} |
| 126 |
|
| 127 |
var keyShareKeys *keySharePrivateKeys |
| 128 |
if maxVersion >= VersionTLS13 { |
| 129 |
// Reset the list of ciphers when the client only supports TLS 1.3. |
| 130 |
if minVersion >= VersionTLS13 { |
| 131 |
hello.cipherSuites = nil |
| 132 |
} |
| 133 |
|
| 134 |
if fips140tls.Required() { |
| 135 |
hello.cipherSuites = append(hello.cipherSuites, allowedCipherSuitesTLS13FIPS...) |
| 136 |
} else if hasAESGCMHardwareSupport { |
| 137 |
hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13...) |
| 138 |
} else { |
| 139 |
hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13NoAES...) |
| 140 |
} |
| 141 |
|
| 142 |
if len(hello.supportedCurves) == 0 { |
| 143 |
return nil, nil, nil, errors.New("tls: no supported elliptic curves for ECDHE") |
| 144 |
} |
| 145 |
curveID := hello.supportedCurves[0] |
| 146 |
keyShareKeys = &keySharePrivateKeys{curveID: curveID} |
| 147 |
// Note that if X25519MLKEM768 is supported, it will be first because |
| 148 |
// the preference order is fixed. |
| 149 |
if curveID == X25519MLKEM768 { |
| 150 |
keyShareKeys.ecdhe, err = generateECDHEKey(config.rand(), X25519) |
| 151 |
if err != nil { |
| 152 |
return nil, nil, nil, err |
| 153 |
} |
| 154 |
seed := make([]byte, mlkem.SeedSize) |
| 155 |
if _, err := io.ReadFull(config.rand(), seed); err != nil { |
| 156 |
return nil, nil, nil, err |
| 157 |
} |
| 158 |
keyShareKeys.mlkem, err = mlkem.NewDecapsulationKey768(seed) |
| 159 |
if err != nil { |
| 160 |
return nil, nil, nil, err |
| 161 |
} |
| 162 |
mlkemEncapsulationKey := keyShareKeys.mlkem.EncapsulationKey().Bytes() |
| 163 |
x25519EphemeralKey := keyShareKeys.ecdhe.PublicKey().Bytes() |
| 164 |
hello.keyShares = []keyShare{ |
| 165 |
{group: X25519MLKEM768, data: append(mlkemEncapsulationKey, x25519EphemeralKey...)}, |
| 166 |
} |
| 167 |
// If both X25519MLKEM768 and X25519 are supported, we send both key |
| 168 |
// shares (as a fallback) and we reuse the same X25519 ephemeral |
| 169 |
// key, as allowed by draft-ietf-tls-hybrid-design-09, Section 3.2. |
| 170 |
if slices.Contains(hello.supportedCurves, X25519) { |
| 171 |
hello.keyShares = append(hello.keyShares, keyShare{group: X25519, data: x25519EphemeralKey}) |
| 172 |
} |
| 173 |
} else { |
| 174 |
if _, ok := curveForCurveID(curveID); !ok { |
| 175 |
return nil, nil, nil, errors.New("tls: CurvePreferences includes unsupported curve") |
| 176 |
} |
| 177 |
keyShareKeys.ecdhe, err = generateECDHEKey(config.rand(), curveID) |
| 178 |
if err != nil { |
| 179 |
return nil, nil, nil, err |
| 180 |
} |
| 181 |
hello.keyShares = []keyShare{{group: curveID, data: keyShareKeys.ecdhe.PublicKey().Bytes()}} |
| 182 |
} |
| 183 |
} |
| 184 |
|
| 185 |
if c.quic != nil { |
| 186 |
p, err := c.quicGetTransportParameters() |
| 187 |
if err != nil { |
| 188 |
return nil, nil, nil, err |
| 189 |
} |
| 190 |
if p == nil { |
| 191 |
p = []byte{} |
| 192 |
} |
| 193 |
hello.quicTransportParameters = p |
| 194 |
} |
| 195 |
|
| 196 |
var ech *echClientContext |
| 197 |
if c.config.EncryptedClientHelloConfigList != nil { |
| 198 |
if c.config.MinVersion != 0 && c.config.MinVersion < VersionTLS13 { |
| 199 |
return nil, nil, nil, errors.New("tls: MinVersion must be >= VersionTLS13 if EncryptedClientHelloConfigList is populated") |
| 200 |
} |
| 201 |
if c.config.MaxVersion != 0 && c.config.MaxVersion <= VersionTLS12 { |
| 202 |
return nil, nil, nil, errors.New("tls: MaxVersion must be >= VersionTLS13 if EncryptedClientHelloConfigList is populated") |
| 203 |
} |
| 204 |
echConfigs, err := parseECHConfigList(c.config.EncryptedClientHelloConfigList) |
| 205 |
if err != nil { |
| 206 |
return nil, nil, nil, err |
| 207 |
} |
| 208 |
echConfig := pickECHConfig(echConfigs) |
| 209 |
if echConfig == nil { |
| 210 |
return nil, nil, nil, errors.New("tls: EncryptedClientHelloConfigList contains no valid configs") |
| 211 |
} |
| 212 |
ech = &echClientContext{config: echConfig} |
| 213 |
hello.encryptedClientHello = []byte{1} // indicate inner hello |
| 214 |
// We need to explicitly set these 1.2 fields to nil, as we do not |
| 215 |
// marshal them when encoding the inner hello, otherwise transcripts |
| 216 |
// will later mismatch. |
| 217 |
hello.supportedPoints = nil |
| 218 |
hello.ticketSupported = false |
| 219 |
hello.secureRenegotiationSupported = false |
| 220 |
hello.extendedMasterSecret = false |
| 221 |
|
| 222 |
echPK, err := hpke.ParseHPKEPublicKey(ech.config.KemID, ech.config.PublicKey) |
| 223 |
if err != nil { |
| 224 |
return nil, nil, nil, err |
| 225 |
} |
| 226 |
suite, err := pickECHCipherSuite(ech.config.SymmetricCipherSuite) |
| 227 |
if err != nil { |
| 228 |
return nil, nil, nil, err |
| 229 |
} |
| 230 |
ech.kdfID, ech.aeadID = suite.KDFID, suite.AEADID |
| 231 |
info := append([]byte("tls ech\x00"), ech.config.raw...) |
| 232 |
ech.encapsulatedKey, ech.hpkeContext, err = hpke.SetupSender(ech.config.KemID, suite.KDFID, suite.AEADID, echPK, info) |
| 233 |
if err != nil { |
| 234 |
return nil, nil, nil, err |
| 235 |
} |
| 236 |
} |
| 237 |
|
| 238 |
return hello, keyShareKeys, ech, nil |
| 239 |
} |
| 240 |
|
| 241 |
type echClientContext struct { |
| 242 |
config *echConfig |
| 243 |
hpkeContext *hpke.Sender |
| 244 |
encapsulatedKey []byte |
| 245 |
innerHello *clientHelloMsg |
| 246 |
innerTranscript hash.Hash |
| 247 |
kdfID uint16 |
| 248 |
aeadID uint16 |
| 249 |
echRejected bool |
| 250 |
retryConfigs []byte |
| 251 |
} |
| 252 |
|
| 253 |
func (c *Conn) clientHandshake(ctx context.Context) (err error) { |
| 254 |
if c.config == nil { |
| 255 |
c.config = defaultConfig() |
| 256 |
} |
| 257 |
|
| 258 |
// This may be a renegotiation handshake, in which case some fields |
| 259 |
// need to be reset. |
| 260 |
c.didResume = false |
| 261 |
c.curveID = 0 |
| 262 |
|
| 263 |
hello, keyShareKeys, ech, err := c.makeClientHello() |
| 264 |
if err != nil { |
| 265 |
return err |
| 266 |
} |
| 267 |
|
| 268 |
session, earlySecret, binderKey, err := c.loadSession(hello) |
| 269 |
if err != nil { |
| 270 |
return err |
| 271 |
} |
| 272 |
if session != nil { |
| 273 |
defer func() { |
| 274 |
// If we got a handshake failure when resuming a session, throw away |
| 275 |
// the session ticket. See RFC 5077, Section 3.2. |
| 276 |
// |
| 277 |
// RFC 8446 makes no mention of dropping tickets on failure, but it |
| 278 |
// does require servers to abort on invalid binders, so we need to |
| 279 |
// delete tickets to recover from a corrupted PSK. |
| 280 |
if err != nil { |
| 281 |
if cacheKey := c.clientSessionCacheKey(); cacheKey != "" { |
| 282 |
c.config.ClientSessionCache.Put(cacheKey, nil) |
| 283 |
} |
| 284 |
} |
| 285 |
}() |
| 286 |
} |
| 287 |
|
| 288 |
if ech != nil { |
| 289 |
// Split hello into inner and outer |
| 290 |
ech.innerHello = hello.clone() |
| 291 |
|
| 292 |
// Overwrite the server name in the outer hello with the public facing |
| 293 |
// name. |
| 294 |
hello.serverName = string(ech.config.PublicName) |
| 295 |
// Generate a new random for the outer hello. |
| 296 |
hello.random = make([]byte, 32) |
| 297 |
_, err = io.ReadFull(c.config.rand(), hello.random) |
| 298 |
if err != nil { |
| 299 |
return errors.New("tls: short read from Rand: " + err.Error()) |
| 300 |
} |
| 301 |
|
| 302 |
// NOTE: we don't do PSK GREASE, in line with boringssl, it's meant to |
| 303 |
// work around _possibly_ broken middleboxes, but there is little-to-no |
| 304 |
// evidence that this is actually a problem. |
| 305 |
|
| 306 |
if err := computeAndUpdateOuterECHExtension(hello, ech.innerHello, ech, true); err != nil { |
| 307 |
return err |
| 308 |
} |
| 309 |
} |
| 310 |
|
| 311 |
c.serverName = hello.serverName |
| 312 |
|
| 313 |
if _, err := c.writeHandshakeRecord(hello, nil); err != nil { |
| 314 |
return err |
| 315 |
} |
| 316 |
|
| 317 |
if hello.earlyData { |
| 318 |
suite := cipherSuiteTLS13ByID(session.cipherSuite) |
| 319 |
transcript := suite.hash.New() |
| 320 |
transcriptHello := hello |
| 321 |
if ech != nil { |
| 322 |
transcriptHello = ech.innerHello |
| 323 |
} |
| 324 |
if err := transcriptMsg(transcriptHello, transcript); err != nil { |
| 325 |
return err |
| 326 |
} |
| 327 |
earlyTrafficSecret := earlySecret.ClientEarlyTrafficSecret(transcript) |
| 328 |
c.quicSetWriteSecret(QUICEncryptionLevelEarly, suite.id, earlyTrafficSecret) |
| 329 |
} |
| 330 |
|
| 331 |
// serverHelloMsg is not included in the transcript |
| 332 |
msg, err := c.readHandshake(nil) |
| 333 |
if err != nil { |
| 334 |
return err |
| 335 |
} |
| 336 |
|
| 337 |
serverHello, ok := msg.(*serverHelloMsg) |
| 338 |
if !ok { |
| 339 |
c.sendAlert(alertUnexpectedMessage) |
| 340 |
return unexpectedMessageError(serverHello, msg) |
| 341 |
} |
| 342 |
|
| 343 |
if err := c.pickTLSVersion(serverHello); err != nil { |
| 344 |
return err |
| 345 |
} |
| 346 |
|
| 347 |
// If we are negotiating a protocol version that's lower than what we |
| 348 |
// support, check for the server downgrade canaries. |
| 349 |
// See RFC 8446, Section 4.1.3. |
| 350 |
maxVers := c.config.maxSupportedVersion(roleClient) |
| 351 |
tls12Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS12 |
| 352 |
tls11Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS11 |
| 353 |
if maxVers == VersionTLS13 && c.vers <= VersionTLS12 && (tls12Downgrade || tls11Downgrade) || |
| 354 |
maxVers == VersionTLS12 && c.vers <= VersionTLS11 && tls11Downgrade { |
| 355 |
c.sendAlert(alertIllegalParameter) |
| 356 |
return errors.New("tls: downgrade attempt detected, possibly due to a MitM attack or a broken middlebox") |
| 357 |
} |
| 358 |
|
| 359 |
if c.vers == VersionTLS13 { |
| 360 |
hs := &clientHandshakeStateTLS13{ |
| 361 |
c: c, |
| 362 |
ctx: ctx, |
| 363 |
serverHello: serverHello, |
| 364 |
hello: hello, |
| 365 |
keyShareKeys: keyShareKeys, |
| 366 |
session: session, |
| 367 |
earlySecret: earlySecret, |
| 368 |
binderKey: binderKey, |
| 369 |
echContext: ech, |
| 370 |
} |
| 371 |
return hs.handshake() |
| 372 |
} |
| 373 |
|
| 374 |
hs := &clientHandshakeState{ |
| 375 |
c: c, |
| 376 |
ctx: ctx, |
| 377 |
serverHello: serverHello, |
| 378 |
hello: hello, |
| 379 |
session: session, |
| 380 |
} |
| 381 |
return hs.handshake() |
| 382 |
} |
| 383 |
|
| 384 |
// fips140ems is a GODEBUG variable that can be set to 0 to disable the |
| 385 |
// enforcement of Extended Master Secret in FIPS 140-3 mode. |
| 386 |
var fips140ems = godebug.New("fips140ems") |
| 387 |
|
| 388 |
func (c *Conn) loadSession(hello *clientHelloMsg) ( |
| 389 |
session *SessionState, earlySecret *tls13.EarlySecret, binderKey []byte, err error) { |
| 390 |
if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil { |
| 391 |
return nil, nil, nil, nil |
| 392 |
} |
| 393 |
|
| 394 |
echInner := bytes.Equal(hello.encryptedClientHello, []byte{1}) |
| 395 |
|
| 396 |
// ticketSupported is a TLS 1.2 extension (as TLS 1.3 replaced tickets with PSK |
| 397 |
// identities) and ECH requires and forces TLS 1.3. |
| 398 |
hello.ticketSupported = true && !echInner |
| 399 |
|
| 400 |
if hello.supportedVersions[0] == VersionTLS13 { |
| 401 |
// Require DHE on resumption as it guarantees forward secrecy against |
| 402 |
// compromise of the session ticket key. See RFC 8446, Section 4.2.9. |
| 403 |
hello.pskModes = []uint8{pskModeDHE} |
| 404 |
} |
| 405 |
|
| 406 |
// Session resumption is not allowed if renegotiating because |
| 407 |
// renegotiation is primarily used to allow a client to send a client |
| 408 |
// certificate, which would be skipped if session resumption occurred. |
| 409 |
if c.handshakes != 0 { |
| 410 |
return nil, nil, nil, nil |
| 411 |
} |
| 412 |
|
| 413 |
// Try to resume a previously negotiated TLS session, if available. |
| 414 |
cacheKey := c.clientSessionCacheKey() |
| 415 |
if cacheKey == "" { |
| 416 |
return nil, nil, nil, nil |
| 417 |
} |
| 418 |
cs, ok := c.config.ClientSessionCache.Get(cacheKey) |
| 419 |
if !ok || cs == nil { |
| 420 |
return nil, nil, nil, nil |
| 421 |
} |
| 422 |
session = cs.session |
| 423 |
|
| 424 |
// Check that version used for the previous session is still valid. |
| 425 |
versOk := false |
| 426 |
for _, v := range hello.supportedVersions { |
| 427 |
if v == session.version { |
| 428 |
versOk = true |
| 429 |
break |
| 430 |
} |
| 431 |
} |
| 432 |
if !versOk { |
| 433 |
return nil, nil, nil, nil |
| 434 |
} |
| 435 |
|
| 436 |
if c.config.time().After(session.peerCertificates[0].NotAfter) { |
| 437 |
// Expired certificate, delete the entry. |
| 438 |
c.config.ClientSessionCache.Put(cacheKey, nil) |
| 439 |
return nil, nil, nil, nil |
| 440 |
} |
| 441 |
if !c.config.InsecureSkipVerify { |
| 442 |
if len(session.verifiedChains) == 0 { |
| 443 |
// The original connection had InsecureSkipVerify, while this doesn't. |
| 444 |
return nil, nil, nil, nil |
| 445 |
} |
| 446 |
if err := session.peerCertificates[0].VerifyHostname(c.config.ServerName); err != nil { |
| 447 |
// This should be ensured by the cache key, but protect the |
| 448 |
// application from a faulty ClientSessionCache implementation. |
| 449 |
return nil, nil, nil, nil |
| 450 |
} |
| 451 |
opts := x509.VerifyOptions{ |
| 452 |
CurrentTime: c.config.time(), |
| 453 |
Roots: c.config.RootCAs, |
| 454 |
KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, |
| 455 |
} |
| 456 |
if !anyValidVerifiedChain(session.verifiedChains, opts) { |
| 457 |
// No valid chains, delete the entry. |
| 458 |
c.config.ClientSessionCache.Put(cacheKey, nil) |
| 459 |
return nil, nil, nil, nil |
| 460 |
} |
| 461 |
} |
| 462 |
|
| 463 |
if session.version != VersionTLS13 { |
| 464 |
// In TLS 1.2 the cipher suite must match the resumed session. Ensure we |
| 465 |
// are still offering it. |
| 466 |
if mutualCipherSuite(hello.cipherSuites, session.cipherSuite) == nil { |
| 467 |
return nil, nil, nil, nil |
| 468 |
} |
| 469 |
|
| 470 |
// FIPS 140-3 requires the use of Extended Master Secret. |
| 471 |
if !session.extMasterSecret && fips140tls.Required() { |
| 472 |
if fips140ems.Value() != "0" { |
| 473 |
return nil, nil, nil, nil |
| 474 |
} |
| 475 |
fips140ems.IncNonDefault() |
| 476 |
} |
| 477 |
|
| 478 |
hello.sessionTicket = session.ticket |
| 479 |
return |
| 480 |
} |
| 481 |
|
| 482 |
// Check that the session ticket is not expired. |
| 483 |
if c.config.time().After(time.Unix(int64(session.useBy), 0)) { |
| 484 |
c.config.ClientSessionCache.Put(cacheKey, nil) |
| 485 |
return nil, nil, nil, nil |
| 486 |
} |
| 487 |
|
| 488 |
// In TLS 1.3 the KDF hash must match the resumed session. Ensure we |
| 489 |
// offer at least one cipher suite with that hash. |
| 490 |
cipherSuite := cipherSuiteTLS13ByID(session.cipherSuite) |
| 491 |
if cipherSuite == nil { |
| 492 |
return nil, nil, nil, nil |
| 493 |
} |
| 494 |
cipherSuiteOk := false |
| 495 |
for _, offeredID := range hello.cipherSuites { |
| 496 |
offeredSuite := cipherSuiteTLS13ByID(offeredID) |
| 497 |
if offeredSuite != nil && offeredSuite.hash == cipherSuite.hash { |
| 498 |
cipherSuiteOk = true |
| 499 |
break |
| 500 |
} |
| 501 |
} |
| 502 |
if !cipherSuiteOk { |
| 503 |
return nil, nil, nil, nil |
| 504 |
} |
| 505 |
|
| 506 |
if c.quic != nil { |
| 507 |
if c.quic.enableSessionEvents { |
| 508 |
c.quicResumeSession(session) |
| 509 |
} |
| 510 |
|
| 511 |
// For 0-RTT, the cipher suite has to match exactly, and we need to be |
| 512 |
// offering the same ALPN. |
| 513 |
if session.EarlyData && mutualCipherSuiteTLS13(hello.cipherSuites, session.cipherSuite) != nil { |
| 514 |
for _, alpn := range hello.alpnProtocols { |
| 515 |
if alpn == session.alpnProtocol { |
| 516 |
hello.earlyData = true |
| 517 |
break |
| 518 |
} |
| 519 |
} |
| 520 |
} |
| 521 |
} |
| 522 |
|
| 523 |
// Set the pre_shared_key extension. See RFC 8446, Section 4.2.11.1. |
| 524 |
ticketAge := c.config.time().Sub(time.Unix(int64(session.createdAt), 0)) |
| 525 |
identity := pskIdentity{ |
| 526 |
label: session.ticket, |
| 527 |
obfuscatedTicketAge: uint32(ticketAge/time.Millisecond) + session.ageAdd, |
| 528 |
} |
| 529 |
hello.pskIdentities = []pskIdentity{identity} |
| 530 |
hello.pskBinders = [][]byte{make([]byte, cipherSuite.hash.Size())} |
| 531 |
|
| 532 |
// Compute the PSK binders. See RFC 8446, Section 4.2.11.2. |
| 533 |
earlySecret = tls13.NewEarlySecret(cipherSuite.hash.New, session.secret) |
| 534 |
binderKey = earlySecret.ResumptionBinderKey() |
| 535 |
transcript := cipherSuite.hash.New() |
| 536 |
if err := computeAndUpdatePSK(hello, binderKey, transcript, cipherSuite.finishedHash); err != nil { |
| 537 |
return nil, nil, nil, err |
| 538 |
} |
| 539 |
|
| 540 |
return |
| 541 |
} |
| 542 |
|
| 543 |
func (c *Conn) pickTLSVersion(serverHello *serverHelloMsg) error { |
| 544 |
peerVersion := serverHello.vers |
| 545 |
if serverHello.supportedVersion != 0 { |
| 546 |
peerVersion = serverHello.supportedVersion |
| 547 |
} |
| 548 |
|
| 549 |
vers, ok := c.config.mutualVersion(roleClient, []uint16{peerVersion}) |
| 550 |
if !ok { |
| 551 |
c.sendAlert(alertProtocolVersion) |
| 552 |
return fmt.Errorf("tls: server selected unsupported protocol version %x", peerVersion) |
| 553 |
} |
| 554 |
|
| 555 |
c.vers = vers |
| 556 |
c.haveVers = true |
| 557 |
c.in.version = vers |
| 558 |
c.out.version = vers |
| 559 |
|
| 560 |
return nil |
| 561 |
} |
| 562 |
|
| 563 |
// Does the handshake, either a full one or resumes old session. Requires hs.c, |
| 564 |
// hs.hello, hs.serverHello, and, optionally, hs.session to be set. |
| 565 |
func (hs *clientHandshakeState) handshake() error { |
| 566 |
c := hs.c |
| 567 |
|
| 568 |
// If we did not load a session (hs.session == nil), but we did set a |
| 569 |
// session ID in the transmitted client hello (hs.hello.sessionId != nil), |
| 570 |
// it means we tried to negotiate TLS 1.3 and sent a random session ID as a |
| 571 |
// compatibility measure (see RFC 8446, Section 4.1.2). |
| 572 |
// |
| 573 |
// Since we're now handshaking for TLS 1.2, if the server echoed the |
| 574 |
// transmitted ID back to us, we know mischief is afoot: the session ID |
| 575 |
// was random and can't possibly be recognized by the server. |
| 576 |
if hs.session == nil && hs.hello.sessionId != nil && bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) { |
| 577 |
c.sendAlert(alertIllegalParameter) |
| 578 |
return errors.New("tls: server echoed TLS 1.3 compatibility session ID in TLS 1.2") |
| 579 |
} |
| 580 |
|
| 581 |
isResume, err := hs.processServerHello() |
| 582 |
if err != nil { |
| 583 |
return err |
| 584 |
} |
| 585 |
|
| 586 |
hs.finishedHash = newFinishedHash(c.vers, hs.suite) |
| 587 |
|
| 588 |
// No signatures of the handshake are needed in a resumption. |
| 589 |
// Otherwise, in a full handshake, if we don't have any certificates |
| 590 |
// configured then we will never send a CertificateVerify message and |
| 591 |
// thus no signatures are needed in that case either. |
| 592 |
if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) { |
| 593 |
hs.finishedHash.discardHandshakeBuffer() |
| 594 |
} |
| 595 |
|
| 596 |
if err := transcriptMsg(hs.hello, &hs.finishedHash); err != nil { |
| 597 |
return err |
| 598 |
} |
| 599 |
if err := transcriptMsg(hs.serverHello, &hs.finishedHash); err != nil { |
| 600 |
return err |
| 601 |
} |
| 602 |
|
| 603 |
c.buffering = true |
| 604 |
c.didResume = isResume |
| 605 |
if isResume { |
| 606 |
if err := hs.establishKeys(); err != nil { |
| 607 |
return err |
| 608 |
} |
| 609 |
if err := hs.readSessionTicket(); err != nil { |
| 610 |
return err |
| 611 |
} |
| 612 |
if err := hs.readFinished(c.serverFinished[:]); err != nil { |
| 613 |
return err |
| 614 |
} |
| 615 |
c.clientFinishedIsFirst = false |
| 616 |
// Make sure the connection is still being verified whether or not this |
| 617 |
// is a resumption. Resumptions currently don't reverify certificates so |
| 618 |
// they don't call verifyServerCertificate. See Issue 31641. |
| 619 |
if c.config.VerifyConnection != nil { |
| 620 |
if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { |
| 621 |
c.sendAlert(alertBadCertificate) |
| 622 |
return err |
| 623 |
} |
| 624 |
} |
| 625 |
if err := hs.sendFinished(c.clientFinished[:]); err != nil { |
| 626 |
return err |
| 627 |
} |
| 628 |
if _, err := c.flush(); err != nil { |
| 629 |
return err |
| 630 |
} |
| 631 |
} else { |
| 632 |
if err := hs.doFullHandshake(); err != nil { |
| 633 |
return err |
| 634 |
} |
| 635 |
if err := hs.establishKeys(); err != nil { |
| 636 |
return err |
| 637 |
} |
| 638 |
if err := hs.sendFinished(c.clientFinished[:]); err != nil { |
| 639 |
return err |
| 640 |
} |
| 641 |
if _, err := c.flush(); err != nil { |
| 642 |
return err |
| 643 |
} |
| 644 |
c.clientFinishedIsFirst = true |
| 645 |
if err := hs.readSessionTicket(); err != nil { |
| 646 |
return err |
| 647 |
} |
| 648 |
if err := hs.readFinished(c.serverFinished[:]); err != nil { |
| 649 |
return err |
| 650 |
} |
| 651 |
} |
| 652 |
if err := hs.saveSessionTicket(); err != nil { |
| 653 |
return err |
| 654 |
} |
| 655 |
|
| 656 |
c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random) |
| 657 |
c.isHandshakeComplete.Store(true) |
| 658 |
|
| 659 |
return nil |
| 660 |
} |
| 661 |
|
| 662 |
func (hs *clientHandshakeState) pickCipherSuite() error { |
| 663 |
if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil { |
| 664 |
hs.c.sendAlert(alertHandshakeFailure) |
| 665 |
return errors.New("tls: server chose an unconfigured cipher suite") |
| 666 |
} |
| 667 |
|
| 668 |
if hs.c.config.CipherSuites == nil && !fips140tls.Required() && rsaKexCiphers[hs.suite.id] { |
| 669 |
tlsrsakex.Value() // ensure godebug is initialized |
| 670 |
tlsrsakex.IncNonDefault() |
| 671 |
} |
| 672 |
if hs.c.config.CipherSuites == nil && !fips140tls.Required() && tdesCiphers[hs.suite.id] { |
| 673 |
tls3des.Value() // ensure godebug is initialized |
| 674 |
tls3des.IncNonDefault() |
| 675 |
} |
| 676 |
|
| 677 |
hs.c.cipherSuite = hs.suite.id |
| 678 |
return nil |
| 679 |
} |
| 680 |
|
| 681 |
func (hs *clientHandshakeState) doFullHandshake() error { |
| 682 |
c := hs.c |
| 683 |
|
| 684 |
msg, err := c.readHandshake(&hs.finishedHash) |
| 685 |
if err != nil { |
| 686 |
return err |
| 687 |
} |
| 688 |
certMsg, ok := msg.(*certificateMsg) |
| 689 |
if !ok || len(certMsg.certificates) == 0 { |
| 690 |
c.sendAlert(alertUnexpectedMessage) |
| 691 |
return unexpectedMessageError(certMsg, msg) |
| 692 |
} |
| 693 |
|
| 694 |
msg, err = c.readHandshake(&hs.finishedHash) |
| 695 |
if err != nil { |
| 696 |
return err |
| 697 |
} |
| 698 |
|
| 699 |
cs, ok := msg.(*certificateStatusMsg) |
| 700 |
if ok { |
| 701 |
// RFC4366 on Certificate Status Request: |
| 702 |
// The server MAY return a "certificate_status" message. |
| 703 |
|
| 704 |
if !hs.serverHello.ocspStapling { |
| 705 |
// If a server returns a "CertificateStatus" message, then the |
| 706 |
// server MUST have included an extension of type "status_request" |
| 707 |
// with empty "extension_data" in the extended server hello. |
| 708 |
|
| 709 |
c.sendAlert(alertUnexpectedMessage) |
| 710 |
return errors.New("tls: received unexpected CertificateStatus message") |
| 711 |
} |
| 712 |
|
| 713 |
c.ocspResponse = cs.response |
| 714 |
|
| 715 |
msg, err = c.readHandshake(&hs.finishedHash) |
| 716 |
if err != nil { |
| 717 |
return err |
| 718 |
} |
| 719 |
} |
| 720 |
|
| 721 |
if c.handshakes == 0 { |
| 722 |
// If this is the first handshake on a connection, process and |
| 723 |
// (optionally) verify the server's certificates. |
| 724 |
if err := c.verifyServerCertificate(certMsg.certificates); err != nil { |
| 725 |
return err |
| 726 |
} |
| 727 |
} else { |
| 728 |
// This is a renegotiation handshake. We require that the |
| 729 |
// server's identity (i.e. leaf certificate) is unchanged and |
| 730 |
// thus any previous trust decision is still valid. |
| 731 |
// |
| 732 |
// See https://mitls.org/pages/attacks/3SHAKE for the |
| 733 |
// motivation behind this requirement. |
| 734 |
if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) { |
| 735 |
c.sendAlert(alertBadCertificate) |
| 736 |
return errors.New("tls: server's identity changed during renegotiation") |
| 737 |
} |
| 738 |
} |
| 739 |
|
| 740 |
keyAgreement := hs.suite.ka(c.vers) |
| 741 |
|
| 742 |
skx, ok := msg.(*serverKeyExchangeMsg) |
| 743 |
if ok { |
| 744 |
err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx) |
| 745 |
if err != nil { |
| 746 |
c.sendAlert(alertIllegalParameter) |
| 747 |
return err |
| 748 |
} |
| 749 |
if keyAgreement, ok := keyAgreement.(*ecdheKeyAgreement); ok { |
| 750 |
c.curveID = keyAgreement.curveID |
| 751 |
c.peerSigAlg = keyAgreement.signatureAlgorithm |
| 752 |
} |
| 753 |
|
| 754 |
msg, err = c.readHandshake(&hs.finishedHash) |
| 755 |
if err != nil { |
| 756 |
return err |
| 757 |
} |
| 758 |
} |
| 759 |
|
| 760 |
var chainToSend *Certificate |
| 761 |
var certRequested bool |
| 762 |
certReq, ok := msg.(*certificateRequestMsg) |
| 763 |
if ok { |
| 764 |
certRequested = true |
| 765 |
|
| 766 |
cri := certificateRequestInfoFromMsg(hs.ctx, c.vers, certReq) |
| 767 |
if chainToSend, err = c.getClientCertificate(cri); err != nil { |
| 768 |
c.sendAlert(alertInternalError) |
| 769 |
return err |
| 770 |
} |
| 771 |
|
| 772 |
msg, err = c.readHandshake(&hs.finishedHash) |
| 773 |
if err != nil { |
| 774 |
return err |
| 775 |
} |
| 776 |
} |
| 777 |
|
| 778 |
shd, ok := msg.(*serverHelloDoneMsg) |
| 779 |
if !ok { |
| 780 |
c.sendAlert(alertUnexpectedMessage) |
| 781 |
return unexpectedMessageError(shd, msg) |
| 782 |
} |
| 783 |
|
| 784 |
// If the server requested a certificate then we have to send a |
| 785 |
// Certificate message, even if it's empty because we don't have a |
| 786 |
// certificate to send. |
| 787 |
if certRequested { |
| 788 |
certMsg = new(certificateMsg) |
| 789 |
certMsg.certificates = chainToSend.Certificate |
| 790 |
if _, err := hs.c.writeHandshakeRecord(certMsg, &hs.finishedHash); err != nil { |
| 791 |
return err |
| 792 |
} |
| 793 |
} |
| 794 |
|
| 795 |
preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0]) |
| 796 |
if err != nil { |
| 797 |
c.sendAlert(alertInternalError) |
| 798 |
return err |
| 799 |
} |
| 800 |
if ckx != nil { |
| 801 |
if _, err := hs.c.writeHandshakeRecord(ckx, &hs.finishedHash); err != nil { |
| 802 |
return err |
| 803 |
} |
| 804 |
} |
| 805 |
|
| 806 |
if hs.serverHello.extendedMasterSecret { |
| 807 |
c.extMasterSecret = true |
| 808 |
hs.masterSecret = extMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, |
| 809 |
hs.finishedHash.Sum()) |
| 810 |
} else { |
| 811 |
if fips140tls.Required() { |
| 812 |
if fips140ems.Value() != "0" { |
| 813 |
c.sendAlert(alertHandshakeFailure) |
| 814 |
return errors.New("tls: FIPS 140-3 requires the use of Extended Master Secret") |
| 815 |
} |
| 816 |
fips140ems.IncNonDefault() |
| 817 |
} |
| 818 |
hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, |
| 819 |
hs.hello.random, hs.serverHello.random) |
| 820 |
} |
| 821 |
if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.hello.random, hs.masterSecret); err != nil { |
| 822 |
c.sendAlert(alertInternalError) |
| 823 |
return errors.New("tls: failed to write to key log: " + err.Error()) |
| 824 |
} |
| 825 |
|
| 826 |
if chainToSend != nil && len(chainToSend.Certificate) > 0 { |
| 827 |
certVerify := &certificateVerifyMsg{} |
| 828 |
|
| 829 |
key, ok := chainToSend.PrivateKey.(crypto.Signer) |
| 830 |
if !ok { |
| 831 |
c.sendAlert(alertInternalError) |
| 832 |
return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey) |
| 833 |
} |
| 834 |
|
| 835 |
var sigType uint8 |
| 836 |
var sigHash crypto.Hash |
| 837 |
if c.vers >= VersionTLS12 { |
| 838 |
signatureAlgorithm, err := selectSignatureScheme(c.vers, chainToSend, certReq.supportedSignatureAlgorithms) |
| 839 |
if err != nil { |
| 840 |
c.sendAlert(alertHandshakeFailure) |
| 841 |
return err |
| 842 |
} |
| 843 |
sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm) |
| 844 |
if err != nil { |
| 845 |
return c.sendAlert(alertInternalError) |
| 846 |
} |
| 847 |
certVerify.hasSignatureAlgorithm = true |
| 848 |
certVerify.signatureAlgorithm = signatureAlgorithm |
| 849 |
if sigHash == crypto.SHA1 { |
| 850 |
tlssha1.Value() // ensure godebug is initialized |
| 851 |
tlssha1.IncNonDefault() |
| 852 |
} |
| 853 |
} else { |
| 854 |
sigType, sigHash, err = legacyTypeAndHashFromPublicKey(key.Public()) |
| 855 |
if err != nil { |
| 856 |
c.sendAlert(alertIllegalParameter) |
| 857 |
return err |
| 858 |
} |
| 859 |
} |
| 860 |
|
| 861 |
signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash) |
| 862 |
signOpts := crypto.SignerOpts(sigHash) |
| 863 |
if sigType == signatureRSAPSS { |
| 864 |
signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash} |
| 865 |
} |
| 866 |
certVerify.signature, err = key.Sign(c.config.rand(), signed, signOpts) |
| 867 |
if err != nil { |
| 868 |
c.sendAlert(alertInternalError) |
| 869 |
return err |
| 870 |
} |
| 871 |
|
| 872 |
if _, err := hs.c.writeHandshakeRecord(certVerify, &hs.finishedHash); err != nil { |
| 873 |
return err |
| 874 |
} |
| 875 |
} |
| 876 |
|
| 877 |
hs.finishedHash.discardHandshakeBuffer() |
| 878 |
|
| 879 |
return nil |
| 880 |
} |
| 881 |
|
| 882 |
func (hs *clientHandshakeState) establishKeys() error { |
| 883 |
c := hs.c |
| 884 |
|
| 885 |
clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV := |
| 886 |
keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen) |
| 887 |
var clientCipher, serverCipher any |
| 888 |
var clientHash, serverHash hash.Hash |
| 889 |
if hs.suite.cipher != nil { |
| 890 |
clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */) |
| 891 |
clientHash = hs.suite.mac(clientMAC) |
| 892 |
serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */) |
| 893 |
serverHash = hs.suite.mac(serverMAC) |
| 894 |
} else { |
| 895 |
clientCipher = hs.suite.aead(clientKey, clientIV) |
| 896 |
serverCipher = hs.suite.aead(serverKey, serverIV) |
| 897 |
} |
| 898 |
|
| 899 |
c.in.prepareCipherSpec(c.vers, serverCipher, serverHash) |
| 900 |
c.out.prepareCipherSpec(c.vers, clientCipher, clientHash) |
| 901 |
return nil |
| 902 |
} |
| 903 |
|
| 904 |
func (hs *clientHandshakeState) serverResumedSession() bool { |
| 905 |
// If the server responded with the same sessionId then it means the |
| 906 |
// sessionTicket is being used to resume a TLS session. |
| 907 |
return hs.session != nil && hs.hello.sessionId != nil && |
| 908 |
bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId) |
| 909 |
} |
| 910 |
|
| 911 |
func (hs *clientHandshakeState) processServerHello() (bool, error) { |
| 912 |
c := hs.c |
| 913 |
|
| 914 |
if err := hs.pickCipherSuite(); err != nil { |
| 915 |
return false, err |
| 916 |
} |
| 917 |
|
| 918 |
if hs.serverHello.compressionMethod != compressionNone { |
| 919 |
c.sendAlert(alertIllegalParameter) |
| 920 |
return false, errors.New("tls: server selected unsupported compression format") |
| 921 |
} |
| 922 |
|
| 923 |
supportsPointFormat := false |
| 924 |
offeredNonCompressedFormat := false |
| 925 |
for _, format := range hs.serverHello.supportedPoints { |
| 926 |
if format == pointFormatUncompressed { |
| 927 |
supportsPointFormat = true |
| 928 |
} else { |
| 929 |
offeredNonCompressedFormat = true |
| 930 |
} |
| 931 |
} |
| 932 |
if !supportsPointFormat && offeredNonCompressedFormat { |
| 933 |
return false, errors.New("tls: server offered only incompatible point formats") |
| 934 |
} |
| 935 |
|
| 936 |
if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported { |
| 937 |
c.secureRenegotiation = true |
| 938 |
if len(hs.serverHello.secureRenegotiation) != 0 { |
| 939 |
c.sendAlert(alertHandshakeFailure) |
| 940 |
return false, errors.New("tls: initial handshake had non-empty renegotiation extension") |
| 941 |
} |
| 942 |
} |
| 943 |
|
| 944 |
if c.handshakes > 0 && c.secureRenegotiation { |
| 945 |
var expectedSecureRenegotiation [24]byte |
| 946 |
copy(expectedSecureRenegotiation[:], c.clientFinished[:]) |
| 947 |
copy(expectedSecureRenegotiation[12:], c.serverFinished[:]) |
| 948 |
if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) { |
| 949 |
c.sendAlert(alertHandshakeFailure) |
| 950 |
return false, errors.New("tls: incorrect renegotiation extension contents") |
| 951 |
} |
| 952 |
} |
| 953 |
|
| 954 |
if err := checkALPN(hs.hello.alpnProtocols, hs.serverHello.alpnProtocol, false); err != nil { |
| 955 |
c.sendAlert(alertUnsupportedExtension) |
| 956 |
return false, err |
| 957 |
} |
| 958 |
c.clientProtocol = hs.serverHello.alpnProtocol |
| 959 |
|
| 960 |
c.scts = hs.serverHello.scts |
| 961 |
|
| 962 |
if !hs.serverResumedSession() { |
| 963 |
return false, nil |
| 964 |
} |
| 965 |
|
| 966 |
if hs.session.version != c.vers { |
| 967 |
c.sendAlert(alertHandshakeFailure) |
| 968 |
return false, errors.New("tls: server resumed a session with a different version") |
| 969 |
} |
| 970 |
|
| 971 |
if hs.session.cipherSuite != hs.suite.id { |
| 972 |
c.sendAlert(alertHandshakeFailure) |
| 973 |
return false, errors.New("tls: server resumed a session with a different cipher suite") |
| 974 |
} |
| 975 |
|
| 976 |
// RFC 7627, Section 5.3 |
| 977 |
if hs.session.extMasterSecret != hs.serverHello.extendedMasterSecret { |
| 978 |
c.sendAlert(alertHandshakeFailure) |
| 979 |
return false, errors.New("tls: server resumed a session with a different EMS extension") |
| 980 |
} |
| 981 |
|
| 982 |
// Restore master secret and certificates from previous state |
| 983 |
hs.masterSecret = hs.session.secret |
| 984 |
c.extMasterSecret = hs.session.extMasterSecret |
| 985 |
c.peerCertificates = hs.session.peerCertificates |
| 986 |
c.verifiedChains = hs.session.verifiedChains |
| 987 |
c.ocspResponse = hs.session.ocspResponse |
| 988 |
// Let the ServerHello SCTs override the session SCTs from the original |
| 989 |
// connection, if any are provided. |
| 990 |
if len(c.scts) == 0 && len(hs.session.scts) != 0 { |
| 991 |
c.scts = hs.session.scts |
| 992 |
} |
| 993 |
c.curveID = hs.session.curveID |
| 994 |
|
| 995 |
return true, nil |
| 996 |
} |
| 997 |
|
| 998 |
// checkALPN ensure that the server's choice of ALPN protocol is compatible with |
| 999 |
// the protocols that we advertised in the ClientHello. |
| 1000 |
func checkALPN(clientProtos []string, serverProto string, quic bool) error { |
| 1001 |
if serverProto == "" { |
| 1002 |
if quic && len(clientProtos) > 0 { |
| 1003 |
// RFC 9001, Section 8.1 |
| 1004 |
return errors.New("tls: server did not select an ALPN protocol") |
| 1005 |
} |
| 1006 |
return nil |
| 1007 |
} |
| 1008 |
if len(clientProtos) == 0 { |
| 1009 |
return errors.New("tls: server advertised unrequested ALPN extension") |
| 1010 |
} |
| 1011 |
for _, proto := range clientProtos { |
| 1012 |
if proto == serverProto { |
| 1013 |
return nil |
| 1014 |
} |
| 1015 |
} |
| 1016 |
return errors.New("tls: server selected unadvertised ALPN protocol") |
| 1017 |
} |
| 1018 |
|
| 1019 |
func (hs *clientHandshakeState) readFinished(out []byte) error { |
| 1020 |
c := hs.c |
| 1021 |
|
| 1022 |
if err := c.readChangeCipherSpec(); err != nil { |
| 1023 |
return err |
| 1024 |
} |
| 1025 |
|
| 1026 |
// finishedMsg is included in the transcript, but not until after we |
| 1027 |
// check the client version, since the state before this message was |
| 1028 |
// sent is used during verification. |
| 1029 |
msg, err := c.readHandshake(nil) |
| 1030 |
if err != nil { |
| 1031 |
return err |
| 1032 |
} |
| 1033 |
serverFinished, ok := msg.(*finishedMsg) |
| 1034 |
if !ok { |
| 1035 |
c.sendAlert(alertUnexpectedMessage) |
| 1036 |
return unexpectedMessageError(serverFinished, msg) |
| 1037 |
} |
| 1038 |
|
| 1039 |
verify := hs.finishedHash.serverSum(hs.masterSecret) |
| 1040 |
if len(verify) != len(serverFinished.verifyData) || |
| 1041 |
subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 { |
| 1042 |
c.sendAlert(alertHandshakeFailure) |
| 1043 |
return errors.New("tls: server's Finished message was incorrect") |
| 1044 |
} |
| 1045 |
|
| 1046 |
if err := transcriptMsg(serverFinished, &hs.finishedHash); err != nil { |
| 1047 |
return err |
| 1048 |
} |
| 1049 |
|
| 1050 |
copy(out, verify) |
| 1051 |
return nil |
| 1052 |
} |
| 1053 |
|
| 1054 |
func (hs *clientHandshakeState) readSessionTicket() error { |
| 1055 |
if !hs.serverHello.ticketSupported { |
| 1056 |
return nil |
| 1057 |
} |
| 1058 |
c := hs.c |
| 1059 |
|
| 1060 |
if !hs.hello.ticketSupported { |
| 1061 |
c.sendAlert(alertIllegalParameter) |
| 1062 |
return errors.New("tls: server sent unrequested session ticket") |
| 1063 |
} |
| 1064 |
|
| 1065 |
msg, err := c.readHandshake(&hs.finishedHash) |
| 1066 |
if err != nil { |
| 1067 |
return err |
| 1068 |
} |
| 1069 |
sessionTicketMsg, ok := msg.(*newSessionTicketMsg) |
| 1070 |
if !ok { |
| 1071 |
c.sendAlert(alertUnexpectedMessage) |
| 1072 |
return unexpectedMessageError(sessionTicketMsg, msg) |
| 1073 |
} |
| 1074 |
|
| 1075 |
hs.ticket = sessionTicketMsg.ticket |
| 1076 |
return nil |
| 1077 |
} |
| 1078 |
|
| 1079 |
func (hs *clientHandshakeState) saveSessionTicket() error { |
| 1080 |
if hs.ticket == nil { |
| 1081 |
return nil |
| 1082 |
} |
| 1083 |
c := hs.c |
| 1084 |
|
| 1085 |
cacheKey := c.clientSessionCacheKey() |
| 1086 |
if cacheKey == "" { |
| 1087 |
return nil |
| 1088 |
} |
| 1089 |
|
| 1090 |
session := c.sessionState() |
| 1091 |
session.secret = hs.masterSecret |
| 1092 |
session.ticket = hs.ticket |
| 1093 |
|
| 1094 |
cs := &ClientSessionState{session: session} |
| 1095 |
c.config.ClientSessionCache.Put(cacheKey, cs) |
| 1096 |
return nil |
| 1097 |
} |
| 1098 |
|
| 1099 |
func (hs *clientHandshakeState) sendFinished(out []byte) error { |
| 1100 |
c := hs.c |
| 1101 |
|
| 1102 |
if err := c.writeChangeCipherRecord(); err != nil { |
| 1103 |
return err |
| 1104 |
} |
| 1105 |
|
| 1106 |
finished := new(finishedMsg) |
| 1107 |
finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret) |
| 1108 |
if _, err := hs.c.writeHandshakeRecord(finished, &hs.finishedHash); err != nil { |
| 1109 |
return err |
| 1110 |
} |
| 1111 |
copy(out, finished.verifyData) |
| 1112 |
return nil |
| 1113 |
} |
| 1114 |
|
| 1115 |
// defaultMaxRSAKeySize is the maximum RSA key size in bits that we are willing |
| 1116 |
// to verify the signatures of during a TLS handshake. |
| 1117 |
const defaultMaxRSAKeySize = 8192 |
| 1118 |
|
| 1119 |
var tlsmaxrsasize = godebug.New("tlsmaxrsasize") |
| 1120 |
|
| 1121 |
func checkKeySize(n int) (max int, ok bool) { |
| 1122 |
if v := tlsmaxrsasize.Value(); v != "" { |
| 1123 |
if max, err := strconv.Atoi(v); err == nil { |
| 1124 |
if (n <= max) != (n <= defaultMaxRSAKeySize) { |
| 1125 |
tlsmaxrsasize.IncNonDefault() |
| 1126 |
} |
| 1127 |
return max, n <= max |
| 1128 |
} |
| 1129 |
} |
| 1130 |
return defaultMaxRSAKeySize, n <= defaultMaxRSAKeySize |
| 1131 |
} |
| 1132 |
|
| 1133 |
// verifyServerCertificate parses and verifies the provided chain, setting |
| 1134 |
// c.verifiedChains and c.peerCertificates or sending the appropriate alert. |
| 1135 |
func (c *Conn) verifyServerCertificate(certificates [][]byte) error { |
| 1136 |
certs := make([]*x509.Certificate, len(certificates)) |
| 1137 |
for i, asn1Data := range certificates { |
| 1138 |
cert, err := globalCertCache.newCert(asn1Data) |
| 1139 |
if err != nil { |
| 1140 |
c.sendAlert(alertDecodeError) |
| 1141 |
return errors.New("tls: failed to parse certificate from server: " + err.Error()) |
| 1142 |
} |
| 1143 |
if cert.PublicKeyAlgorithm == x509.RSA { |
| 1144 |
n := cert.PublicKey.(*rsa.PublicKey).N.BitLen() |
| 1145 |
if max, ok := checkKeySize(n); !ok { |
| 1146 |
c.sendAlert(alertBadCertificate) |
| 1147 |
return fmt.Errorf("tls: server sent certificate containing RSA key larger than %d bits", max) |
| 1148 |
} |
| 1149 |
} |
| 1150 |
certs[i] = cert |
| 1151 |
} |
| 1152 |
|
| 1153 |
echRejected := c.config.EncryptedClientHelloConfigList != nil && !c.echAccepted |
| 1154 |
if echRejected { |
| 1155 |
if c.config.EncryptedClientHelloRejectionVerify != nil { |
| 1156 |
if err := c.config.EncryptedClientHelloRejectionVerify(c.connectionStateLocked()); err != nil { |
| 1157 |
c.sendAlert(alertBadCertificate) |
| 1158 |
return err |
| 1159 |
} |
| 1160 |
} else { |
| 1161 |
opts := x509.VerifyOptions{ |
| 1162 |
Roots: c.config.RootCAs, |
| 1163 |
CurrentTime: c.config.time(), |
| 1164 |
DNSName: c.serverName, |
| 1165 |
Intermediates: x509.NewCertPool(), |
| 1166 |
} |
| 1167 |
|
| 1168 |
for _, cert := range certs[1:] { |
| 1169 |
opts.Intermediates.AddCert(cert) |
| 1170 |
} |
| 1171 |
chains, err := certs[0].Verify(opts) |
| 1172 |
if err != nil { |
| 1173 |
c.sendAlert(alertBadCertificate) |
| 1174 |
return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err} |
| 1175 |
} |
| 1176 |
|
| 1177 |
c.verifiedChains, err = fipsAllowedChains(chains) |
| 1178 |
if err != nil { |
| 1179 |
c.sendAlert(alertBadCertificate) |
| 1180 |
return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err} |
| 1181 |
} |
| 1182 |
} |
| 1183 |
} else if !c.config.InsecureSkipVerify { |
| 1184 |
opts := x509.VerifyOptions{ |
| 1185 |
Roots: c.config.RootCAs, |
| 1186 |
CurrentTime: c.config.time(), |
| 1187 |
DNSName: c.config.ServerName, |
| 1188 |
Intermediates: x509.NewCertPool(), |
| 1189 |
} |
| 1190 |
|
| 1191 |
for _, cert := range certs[1:] { |
| 1192 |
opts.Intermediates.AddCert(cert) |
| 1193 |
} |
| 1194 |
chains, err := certs[0].Verify(opts) |
| 1195 |
if err != nil { |
| 1196 |
c.sendAlert(alertBadCertificate) |
| 1197 |
return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err} |
| 1198 |
} |
| 1199 |
|
| 1200 |
c.verifiedChains, err = fipsAllowedChains(chains) |
| 1201 |
if err != nil { |
| 1202 |
c.sendAlert(alertBadCertificate) |
| 1203 |
return &CertificateVerificationError{UnverifiedCertificates: certs, Err: err} |
| 1204 |
} |
| 1205 |
} |
| 1206 |
|
| 1207 |
switch certs[0].PublicKey.(type) { |
| 1208 |
case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey: |
| 1209 |
break |
| 1210 |
default: |
| 1211 |
c.sendAlert(alertUnsupportedCertificate) |
| 1212 |
return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey) |
| 1213 |
} |
| 1214 |
|
| 1215 |
c.peerCertificates = certs |
| 1216 |
|
| 1217 |
if c.config.VerifyPeerCertificate != nil && !echRejected { |
| 1218 |
if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil { |
| 1219 |
c.sendAlert(alertBadCertificate) |
| 1220 |
return err |
| 1221 |
} |
| 1222 |
} |
| 1223 |
|
| 1224 |
if c.config.VerifyConnection != nil && !echRejected { |
| 1225 |
if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { |
| 1226 |
c.sendAlert(alertBadCertificate) |
| 1227 |
return err |
| 1228 |
} |
| 1229 |
} |
| 1230 |
|
| 1231 |
return nil |
| 1232 |
} |
| 1233 |
|
| 1234 |
// certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS |
| 1235 |
// <= 1.2 CertificateRequest, making an effort to fill in missing information. |
| 1236 |
func certificateRequestInfoFromMsg(ctx context.Context, vers uint16, certReq *certificateRequestMsg) *CertificateRequestInfo { |
| 1237 |
cri := &CertificateRequestInfo{ |
| 1238 |
AcceptableCAs: certReq.certificateAuthorities, |
| 1239 |
Version: vers, |
| 1240 |
ctx: ctx, |
| 1241 |
} |
| 1242 |
|
| 1243 |
var rsaAvail, ecAvail bool |
| 1244 |
for _, certType := range certReq.certificateTypes { |
| 1245 |
switch certType { |
| 1246 |
case certTypeRSASign: |
| 1247 |
rsaAvail = true |
| 1248 |
case certTypeECDSASign: |
| 1249 |
ecAvail = true |
| 1250 |
} |
| 1251 |
} |
| 1252 |
|
| 1253 |
if !certReq.hasSignatureAlgorithm { |
| 1254 |
// Prior to TLS 1.2, signature schemes did not exist. In this case we |
| 1255 |
// make up a list based on the acceptable certificate types, to help |
| 1256 |
// GetClientCertificate and SupportsCertificate select the right certificate. |
| 1257 |
// The hash part of the SignatureScheme is a lie here, because |
| 1258 |
// TLS 1.0 and 1.1 always use MD5+SHA1 for RSA and SHA1 for ECDSA. |
| 1259 |
switch { |
| 1260 |
case rsaAvail && ecAvail: |
| 1261 |
cri.SignatureSchemes = []SignatureScheme{ |
| 1262 |
ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, |
| 1263 |
PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1, |
| 1264 |
} |
| 1265 |
case rsaAvail: |
| 1266 |
cri.SignatureSchemes = []SignatureScheme{ |
| 1267 |
PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1, |
| 1268 |
} |
| 1269 |
case ecAvail: |
| 1270 |
cri.SignatureSchemes = []SignatureScheme{ |
| 1271 |
ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, |
| 1272 |
} |
| 1273 |
} |
| 1274 |
return cri |
| 1275 |
} |
| 1276 |
|
| 1277 |
// Filter the signature schemes based on the certificate types. |
| 1278 |
// See RFC 5246, Section 7.4.4 (where it calls this "somewhat complicated"). |
| 1279 |
cri.SignatureSchemes = make([]SignatureScheme, 0, len(certReq.supportedSignatureAlgorithms)) |
| 1280 |
for _, sigScheme := range certReq.supportedSignatureAlgorithms { |
| 1281 |
sigType, _, err := typeAndHashFromSignatureScheme(sigScheme) |
| 1282 |
if err != nil { |
| 1283 |
continue |
| 1284 |
} |
| 1285 |
switch sigType { |
| 1286 |
case signatureECDSA, signatureEd25519: |
| 1287 |
if ecAvail { |
| 1288 |
cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme) |
| 1289 |
} |
| 1290 |
case signatureRSAPSS, signaturePKCS1v15: |
| 1291 |
if rsaAvail { |
| 1292 |
cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme) |
| 1293 |
} |
| 1294 |
} |
| 1295 |
} |
| 1296 |
|
| 1297 |
return cri |
| 1298 |
} |
| 1299 |
|
| 1300 |
func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error) { |
| 1301 |
if c.config.GetClientCertificate != nil { |
| 1302 |
return c.config.GetClientCertificate(cri) |
| 1303 |
} |
| 1304 |
|
| 1305 |
for _, chain := range c.config.Certificates { |
| 1306 |
if err := cri.SupportsCertificate(&chain); err != nil { |
| 1307 |
continue |
| 1308 |
} |
| 1309 |
return &chain, nil |
| 1310 |
} |
| 1311 |
|
| 1312 |
// No acceptable certificate found. Don't send a certificate. |
| 1313 |
return new(Certificate), nil |
| 1314 |
} |
| 1315 |
|
| 1316 |
// clientSessionCacheKey returns a key used to cache sessionTickets that could |
| 1317 |
// be used to resume previously negotiated TLS sessions with a server. |
| 1318 |
func (c *Conn) clientSessionCacheKey() string { |
| 1319 |
if len(c.config.ServerName) > 0 { |
| 1320 |
return c.config.ServerName |
| 1321 |
} |
| 1322 |
if c.conn != nil { |
| 1323 |
return c.conn.RemoteAddr().String() |
| 1324 |
} |
| 1325 |
return "" |
| 1326 |
} |
| 1327 |
|
| 1328 |
// hostnameInSNI converts name into an appropriate hostname for SNI. |
| 1329 |
// Literal IP addresses and absolute FQDNs are not permitted as SNI values. |
| 1330 |
// See RFC 6066, Section 3. |
| 1331 |
func hostnameInSNI(name string) string { |
| 1332 |
host := name |
| 1333 |
if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' { |
| 1334 |
host = host[1 : len(host)-1] |
| 1335 |
} |
| 1336 |
if i := strings.LastIndex(host, "%"); i > 0 { |
| 1337 |
host = host[:i] |
| 1338 |
} |
| 1339 |
if net.ParseIP(host) != nil { |
| 1340 |
return "" |
| 1341 |
} |
| 1342 |
for len(name) > 0 && name[len(name)-1] == '.' { |
| 1343 |
name = name[:len(name)-1] |
| 1344 |
} |
| 1345 |
return name |
| 1346 |
} |
| 1347 |
|
| 1348 |
func computeAndUpdatePSK(m *clientHelloMsg, binderKey []byte, transcript hash.Hash, finishedHash func([]byte, hash.Hash) []byte) error { |
| 1349 |
helloBytes, err := m.marshalWithoutBinders() |
| 1350 |
if err != nil { |
| 1351 |
return err |
| 1352 |
} |
| 1353 |
transcript.Write(helloBytes) |
| 1354 |
pskBinders := [][]byte{finishedHash(binderKey, transcript)} |
| 1355 |
return m.updateBinders(pskBinders) |
| 1356 |
} |