Source file src/crypto/tls/common.go
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 "container/list" 10 "context" 11 "crypto" 12 "crypto/ecdsa" 13 "crypto/ed25519" 14 "crypto/elliptic" 15 "crypto/fips140" 16 "crypto/mldsa" 17 "crypto/rand" 18 "crypto/rsa" 19 "crypto/sha512" 20 "crypto/tls/internal/fips140tls" 21 "crypto/x509" 22 "errors" 23 "fmt" 24 "internal/godebug" 25 "io" 26 "net" 27 "runtime" 28 "slices" 29 "strings" 30 "sync" 31 "time" 32 _ "unsafe" // for linkname 33 ) 34 35 const ( 36 VersionTLS10 = 0x0301 37 VersionTLS11 = 0x0302 38 VersionTLS12 = 0x0303 39 VersionTLS13 = 0x0304 40 41 // Deprecated: SSLv3 is cryptographically broken, and is no longer 42 // supported by this package. See golang.org/issue/32716. 43 VersionSSL30 = 0x0300 44 ) 45 46 // VersionName returns the name for the provided TLS version number 47 // (e.g. "TLS 1.3"), or a fallback representation of the value if the 48 // version is not implemented by this package. 49 func VersionName(version uint16) string { 50 switch version { 51 case VersionSSL30: 52 return "SSLv3" 53 case VersionTLS10: 54 return "TLS 1.0" 55 case VersionTLS11: 56 return "TLS 1.1" 57 case VersionTLS12: 58 return "TLS 1.2" 59 case VersionTLS13: 60 return "TLS 1.3" 61 default: 62 return fmt.Sprintf("0x%04X", version) 63 } 64 } 65 66 const ( 67 maxPlaintext = 16384 // maximum plaintext payload length 68 maxCiphertext = 16384 + 2048 // maximum ciphertext payload length 69 maxCiphertextTLS13 = 16384 + 256 // maximum ciphertext length in TLS 1.3 70 recordHeaderLen = 5 // record header length 71 maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB) 72 maxHandshakeCertificateMsg = 262144 // maximum certificate message size (256 KiB) 73 maxUselessRecords = 16 // maximum number of consecutive non-advancing records 74 ) 75 76 // TLS record types. 77 type recordType uint8 78 79 const ( 80 recordTypeChangeCipherSpec recordType = 20 81 recordTypeAlert recordType = 21 82 recordTypeHandshake recordType = 22 83 recordTypeApplicationData recordType = 23 84 ) 85 86 // TLS handshake message types. 87 const ( 88 typeHelloRequest uint8 = 0 89 typeClientHello uint8 = 1 90 typeServerHello uint8 = 2 91 typeNewSessionTicket uint8 = 4 92 typeEndOfEarlyData uint8 = 5 93 typeEncryptedExtensions uint8 = 8 94 typeCertificate uint8 = 11 95 typeServerKeyExchange uint8 = 12 96 typeCertificateRequest uint8 = 13 97 typeServerHelloDone uint8 = 14 98 typeCertificateVerify uint8 = 15 99 typeClientKeyExchange uint8 = 16 100 typeFinished uint8 = 20 101 typeCertificateStatus uint8 = 22 102 typeKeyUpdate uint8 = 24 103 typeMessageHash uint8 = 254 // synthetic message 104 ) 105 106 // TLS compression types. 107 const ( 108 compressionNone uint8 = 0 109 ) 110 111 // TLS extension numbers 112 const ( 113 extensionServerName uint16 = 0 114 extensionStatusRequest uint16 = 5 115 extensionSupportedCurves uint16 = 10 // supported_groups in TLS 1.3, see RFC 8446, Section 4.2.7 116 extensionSupportedPoints uint16 = 11 117 extensionSignatureAlgorithms uint16 = 13 118 extensionALPN uint16 = 16 119 extensionSCT uint16 = 18 120 extensionExtendedMasterSecret uint16 = 23 121 extensionSessionTicket uint16 = 35 122 extensionPreSharedKey uint16 = 41 123 extensionEarlyData uint16 = 42 124 extensionSupportedVersions uint16 = 43 125 extensionCookie uint16 = 44 126 extensionPSKModes uint16 = 45 127 extensionCertificateAuthorities uint16 = 47 128 extensionSignatureAlgorithmsCert uint16 = 50 129 extensionKeyShare uint16 = 51 130 extensionQUICTransportParameters uint16 = 57 131 extensionRenegotiationInfo uint16 = 0xff01 132 extensionECHOuterExtensions uint16 = 0xfd00 133 extensionEncryptedClientHello uint16 = 0xfe0d 134 ) 135 136 // TLS signaling cipher suite values 137 const ( 138 scsvRenegotiation uint16 = 0x00ff 139 ) 140 141 // CurveID is the type of a TLS identifier for a key exchange mechanism. See 142 // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8. 143 // 144 // In TLS 1.2, this registry used to support only elliptic curves. In TLS 1.3, 145 // it was extended to other groups and renamed NamedGroup. See RFC 8446, Section 146 // 4.2.7. It was then also extended to other mechanisms, such as hybrid 147 // post-quantum KEMs. 148 type CurveID uint16 149 150 const ( 151 CurveP256 CurveID = 23 152 CurveP384 CurveID = 24 153 CurveP521 CurveID = 25 154 X25519 CurveID = 29 155 X25519MLKEM768 CurveID = 4588 156 SecP256r1MLKEM768 CurveID = 4587 157 SecP384r1MLKEM1024 CurveID = 4589 158 MLKEM1024 CurveID = 514 159 ) 160 161 func isTLS13OnlyKeyExchange(curve CurveID) bool { 162 switch curve { 163 case X25519MLKEM768, SecP256r1MLKEM768, SecP384r1MLKEM1024, MLKEM1024: 164 return true 165 default: 166 return false 167 } 168 } 169 170 func isPQKeyExchange(curve CurveID) bool { 171 switch curve { 172 case X25519MLKEM768, SecP256r1MLKEM768, SecP384r1MLKEM1024, MLKEM1024: 173 return true 174 default: 175 return false 176 } 177 } 178 179 // TLS 1.3 Key Share. See RFC 8446, Section 4.2.8. 180 type keyShare struct { 181 group CurveID 182 data []byte 183 } 184 185 // TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9. 186 const ( 187 pskModePlain uint8 = 0 188 pskModeDHE uint8 = 1 189 ) 190 191 // TLS 1.3 PSK Identity. Can be a Session Ticket, or a reference to a saved 192 // session. See RFC 8446, Section 4.2.11. 193 type pskIdentity struct { 194 label []byte 195 obfuscatedTicketAge uint32 196 } 197 198 // TLS Elliptic Curve Point Formats 199 // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9 200 const ( 201 pointFormatUncompressed uint8 = 0 202 ) 203 204 // TLS CertificateStatusType (RFC 3546) 205 const ( 206 statusTypeOCSP uint8 = 1 207 ) 208 209 // Certificate types (for certificateRequestMsg) 210 const ( 211 certTypeRSASign = 1 212 certTypeECDSASign = 64 // ECDSA or EdDSA keys, see RFC 8422, Section 3. 213 ) 214 215 // Signature algorithms (for internal signaling use). Starting at 225 to avoid overlap with 216 // TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do. 217 const ( 218 signaturePKCS1v15 uint8 = iota + 225 219 signatureRSAPSS 220 signatureECDSA 221 signatureEd25519 222 signatureMLDSA 223 ) 224 225 // directSigning is a standard Hash value that signals that no pre-hashing 226 // should be performed, and that the input should be signed directly. It is the 227 // hash function associated with the Ed25519 and ML-DSA signature schemes. 228 var directSigning crypto.Hash = 0 229 230 // helloRetryRequestRandom is set as the Random value of a ServerHello 231 // to signal that the message is actually a HelloRetryRequest. 232 var helloRetryRequestRandom = []byte{ // See RFC 8446, Section 4.1.3. 233 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11, 234 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91, 235 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E, 236 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C, 237 } 238 239 const ( 240 // downgradeCanaryTLS12 or downgradeCanaryTLS11 is embedded in the server 241 // random as a downgrade protection if the server would be capable of 242 // negotiating a higher version. See RFC 8446, Section 4.1.3. 243 downgradeCanaryTLS12 = "DOWNGRD\x01" 244 downgradeCanaryTLS11 = "DOWNGRD\x00" 245 ) 246 247 // testingOnlyForceDowngradeCanary is set in tests to force the server side to 248 // include downgrade canaries even if it's using its highers supported version. 249 var testingOnlyForceDowngradeCanary bool 250 251 // ConnectionState records basic TLS details about the connection. 252 type ConnectionState struct { 253 // Version is the TLS version used by the connection (e.g. VersionTLS12). 254 Version uint16 255 256 // HandshakeComplete is true if the handshake has concluded. 257 HandshakeComplete bool 258 259 // DidResume is true if this connection was successfully resumed from a 260 // previous session with a session ticket or similar mechanism. 261 DidResume bool 262 263 // CipherSuite is the cipher suite negotiated for the connection (e.g. 264 // TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256). 265 CipherSuite uint16 266 267 // CurveID is the key exchange mechanism used for the connection. The name 268 // refers to elliptic curves for legacy reasons, see [CurveID]. If a legacy 269 // RSA key exchange is used, this value is zero. 270 CurveID CurveID 271 272 // NegotiatedProtocol is the application protocol negotiated with ALPN. 273 NegotiatedProtocol string 274 275 // NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation. 276 // 277 // Deprecated: this value is always true. 278 NegotiatedProtocolIsMutual bool 279 280 // ServerName is the value of the Server Name Indication extension sent by 281 // the client. It's available both on the server and on the client side. 282 ServerName string 283 284 // PeerCertificates are the parsed certificates sent by the peer, in the 285 // order in which they were sent. The first element is the leaf certificate 286 // that the connection is verified against. 287 // 288 // On the client side, it can't be empty. On the server side, it can be 289 // empty if Config.ClientAuth is not RequireAnyClientCert or 290 // RequireAndVerifyClientCert. 291 // 292 // PeerCertificates and its contents should not be modified. 293 PeerCertificates []*x509.Certificate 294 295 // VerifiedChains is a list of one or more chains where the first element is 296 // PeerCertificates[0] and the last element is from Config.RootCAs (on the 297 // client side) or Config.ClientCAs (on the server side). 298 // 299 // On the client side, it's set if Config.InsecureSkipVerify is false. On 300 // the server side, it's set if Config.ClientAuth is VerifyClientCertIfGiven 301 // (and the peer provided a certificate) or RequireAndVerifyClientCert. 302 // 303 // VerifiedChains and its contents should not be modified. 304 VerifiedChains [][]*x509.Certificate 305 306 // SignedCertificateTimestamps is a list of SCTs provided by the peer 307 // through the TLS handshake for the leaf certificate, if any. 308 SignedCertificateTimestamps [][]byte 309 310 // OCSPResponse is a stapled Online Certificate Status Protocol (OCSP) 311 // response provided by the peer for the leaf certificate, if any. 312 OCSPResponse []byte 313 314 // TLSUnique contains the "tls-unique" channel binding value (see RFC 5929, 315 // Section 3). This value will be nil for TLS 1.3 connections and for 316 // resumed connections that don't support Extended Master Secret (RFC 7627). 317 TLSUnique []byte 318 319 // ECHAccepted indicates if Encrypted Client Hello was offered by the client 320 // and accepted by the server. Currently, ECH is supported only on the 321 // client side. 322 ECHAccepted bool 323 324 // HelloRetryRequest indicates whether we sent a HelloRetryRequest if we 325 // are a server, or if we received a HelloRetryRequest if we are a client. 326 HelloRetryRequest bool 327 328 // LocalCertificate is the certificate chain presented to the peer, if any, 329 // during the handshake. This field is only populated for connections which 330 // are not resumed (DidResume is false). 331 LocalCertificate [][]byte 332 333 // ekm is a closure exposed via ExportKeyingMaterial. 334 ekm func(label string, context []byte, length int) ([]byte, error) 335 336 // testingOnlyPeerSignatureAlgorithm is the signature algorithm used by the 337 // peer to sign the handshake. It is not set for resumed connections. 338 testingOnlyPeerSignatureAlgorithm SignatureScheme 339 } 340 341 // ExportKeyingMaterial returns length bytes of exported key material in a new 342 // slice as defined in RFC 5705. If context is nil, it is not used as part of 343 // the seed. If the connection was set to allow renegotiation via 344 // Config.Renegotiation, or if the connections supports neither TLS 1.3 nor 345 // Extended Master Secret, this function will return an error. 346 func (cs *ConnectionState) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error) { 347 return cs.ekm(label, context, length) 348 } 349 350 // ClientAuthType declares the policy the server will follow for 351 // TLS Client Authentication. 352 type ClientAuthType int 353 354 const ( 355 // NoClientCert indicates that no client certificate should be requested 356 // during the handshake, and if any certificates are sent they will not 357 // be verified. 358 NoClientCert ClientAuthType = iota 359 // RequestClientCert indicates that a client certificate should be requested 360 // during the handshake, but does not require that the client send any 361 // certificates. 362 RequestClientCert 363 // RequireAnyClientCert indicates that a client certificate should be requested 364 // during the handshake, and that at least one certificate is required to be 365 // sent by the client, but that certificate is not required to be valid. 366 RequireAnyClientCert 367 // VerifyClientCertIfGiven indicates that a client certificate should be requested 368 // during the handshake, but does not require that the client sends a 369 // certificate. If the client does send a certificate it is required to be 370 // valid. 371 VerifyClientCertIfGiven 372 // RequireAndVerifyClientCert indicates that a client certificate should be requested 373 // during the handshake, and that at least one valid certificate is required 374 // to be sent by the client. 375 RequireAndVerifyClientCert 376 ) 377 378 // requiresClientCert reports whether the ClientAuthType requires a client 379 // certificate to be provided. 380 func requiresClientCert(c ClientAuthType) bool { 381 switch c { 382 case RequireAnyClientCert, RequireAndVerifyClientCert: 383 return true 384 default: 385 return false 386 } 387 } 388 389 // ClientSessionCache is a cache of ClientSessionState objects that can be used 390 // by a client to resume a TLS session with a given server. ClientSessionCache 391 // implementations should expect to be called concurrently from different 392 // goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not 393 // SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which 394 // are supported via this interface. 395 type ClientSessionCache interface { 396 // Get searches for a ClientSessionState associated with the given key. 397 // On return, ok is true if one was found. 398 Get(sessionKey string) (session *ClientSessionState, ok bool) 399 400 // Put adds the ClientSessionState to the cache with the given key. It might 401 // get called multiple times in a connection if a TLS 1.3 server provides 402 // more than one session ticket. If called with a nil *ClientSessionState, 403 // it should remove the cache entry. 404 Put(sessionKey string, cs *ClientSessionState) 405 } 406 407 //go:generate stringer -linecomment -type=SignatureScheme,CurveID,ClientAuthType -output=common_string.go 408 409 // SignatureScheme identifies a signature algorithm supported by TLS. See 410 // RFC 8446, Section 4.2.3. 411 type SignatureScheme uint16 412 413 const ( 414 // RSASSA-PKCS1-v1_5 algorithms. 415 PKCS1WithSHA256 SignatureScheme = 0x0401 416 PKCS1WithSHA384 SignatureScheme = 0x0501 417 PKCS1WithSHA512 SignatureScheme = 0x0601 418 419 // RSASSA-PSS algorithms with public key OID rsaEncryption. 420 PSSWithSHA256 SignatureScheme = 0x0804 421 PSSWithSHA384 SignatureScheme = 0x0805 422 PSSWithSHA512 SignatureScheme = 0x0806 423 424 // ECDSA algorithms. Only constrained to a specific curve in TLS 1.3. 425 ECDSAWithP256AndSHA256 SignatureScheme = 0x0403 426 ECDSAWithP384AndSHA384 SignatureScheme = 0x0503 427 ECDSAWithP521AndSHA512 SignatureScheme = 0x0603 428 429 // EdDSA algorithms. 430 Ed25519 SignatureScheme = 0x0807 431 432 // ML-DSA algorithms. 433 MLDSA44 SignatureScheme = 0x0904 434 MLDSA65 SignatureScheme = 0x0905 435 MLDSA87 SignatureScheme = 0x0906 436 437 // Legacy signature and hash algorithms for TLS 1.2. 438 PKCS1WithSHA1 SignatureScheme = 0x0201 439 ECDSAWithSHA1 SignatureScheme = 0x0203 440 ) 441 442 // ClientHelloInfo contains information from a ClientHello message in order to 443 // guide application logic in the GetCertificate and GetConfigForClient callbacks. 444 type ClientHelloInfo struct { 445 // CipherSuites lists the CipherSuites supported by the client (e.g. 446 // TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256). 447 CipherSuites []uint16 448 449 // ServerName indicates the name of the server requested by the client 450 // in order to support virtual hosting. ServerName is only set if the 451 // client is using SNI (see RFC 4366, Section 3.1). 452 ServerName string 453 454 // SupportedCurves lists the key exchange mechanisms supported by the 455 // client. It was renamed to "supported groups" in TLS 1.3, see RFC 8446, 456 // Section 4.2.7 and [CurveID]. 457 // 458 // SupportedCurves may be nil in TLS 1.2 and lower if the Supported Elliptic 459 // Curves Extension is not being used (see RFC 4492, Section 5.1.1). 460 SupportedCurves []CurveID 461 462 // SupportedPoints lists the point formats supported by the client. 463 // SupportedPoints is set only if the Supported Point Formats Extension 464 // is being used (see RFC 4492, Section 5.1.2). 465 SupportedPoints []uint8 466 467 // SignatureSchemes lists the signature and hash schemes that the client 468 // is willing to verify. SignatureSchemes is set only if the Signature 469 // Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1). 470 SignatureSchemes []SignatureScheme 471 472 // SupportedProtos lists the application protocols supported by the client. 473 // SupportedProtos is set only if the Application-Layer Protocol 474 // Negotiation Extension is being used (see RFC 7301, Section 3.1). 475 // 476 // Servers can select a protocol by setting Config.NextProtos in a 477 // GetConfigForClient return value. 478 SupportedProtos []string 479 480 // SupportedVersions lists the TLS versions supported by the client. 481 // For TLS versions less than 1.3, this is extrapolated from the max 482 // version advertised by the client, so values other than the greatest 483 // might be rejected if used. 484 SupportedVersions []uint16 485 486 // Extensions lists the IDs of the extensions presented by the client 487 // in the ClientHello. 488 Extensions []uint16 489 490 // Conn is the underlying net.Conn for the connection. Do not read 491 // from, or write to, this connection; that will cause the TLS 492 // connection to fail. 493 Conn net.Conn 494 495 // HelloRetryRequest indicates whether the ClientHello was sent in response 496 // to a HelloRetryRequest message. 497 HelloRetryRequest bool 498 499 // config is embedded by the GetCertificate or GetConfigForClient caller, 500 // for use with SupportsCertificate. 501 config *Config 502 503 // isQUIC indicates whether the connection is a QUIC connection. 504 isQUIC bool 505 506 // ctx is the context of the handshake that is in progress. 507 ctx context.Context 508 } 509 510 // Context returns the context of the handshake that is in progress. 511 // This context is a child of the context passed to HandshakeContext, 512 // if any, and is canceled when the handshake concludes. 513 func (c *ClientHelloInfo) Context() context.Context { 514 return c.ctx 515 } 516 517 // CertificateRequestInfo contains information from a server's 518 // CertificateRequest message, which is used to demand a certificate and proof 519 // of control from a client. 520 type CertificateRequestInfo struct { 521 // AcceptableCAs contains zero or more, DER-encoded, X.501 522 // Distinguished Names. These are the names of root or intermediate CAs 523 // that the server wishes the returned certificate to be signed by. An 524 // empty slice indicates that the server has no preference. 525 AcceptableCAs [][]byte 526 527 // SignatureSchemes lists the signature schemes that the server is 528 // willing to verify. 529 SignatureSchemes []SignatureScheme 530 531 // Version is the TLS version that was negotiated for this connection. 532 Version uint16 533 534 // ctx is the context of the handshake that is in progress. 535 ctx context.Context 536 } 537 538 // Context returns the context of the handshake that is in progress. 539 // This context is a child of the context passed to HandshakeContext, 540 // if any, and is canceled when the handshake concludes. 541 func (c *CertificateRequestInfo) Context() context.Context { 542 return c.ctx 543 } 544 545 // RenegotiationSupport enumerates the different levels of support for TLS 546 // renegotiation. TLS renegotiation is the act of performing subsequent 547 // handshakes on a connection after the first. This significantly complicates 548 // the state machine and has been the source of numerous, subtle security 549 // issues. Initiating a renegotiation is not supported, but support for 550 // accepting renegotiation requests may be enabled. 551 // 552 // Even when enabled, the server may not change its identity between handshakes 553 // (i.e. the leaf certificate must be the same). Additionally, concurrent 554 // handshake and application data flow is not permitted so renegotiation can 555 // only be used with protocols that synchronise with the renegotiation, such as 556 // HTTPS. 557 // 558 // Renegotiation is not defined in TLS 1.3. 559 type RenegotiationSupport int 560 561 const ( 562 // RenegotiateNever disables renegotiation. 563 RenegotiateNever RenegotiationSupport = iota 564 565 // RenegotiateOnceAsClient allows a remote server to request 566 // renegotiation once per connection. 567 RenegotiateOnceAsClient 568 569 // RenegotiateFreelyAsClient allows a remote server to repeatedly 570 // request renegotiation. 571 RenegotiateFreelyAsClient 572 ) 573 574 // A Config structure is used to configure a TLS client or server. 575 // After one has been passed to a TLS function it must not be 576 // modified. A Config may be reused; the tls package will also not 577 // modify it. 578 type Config struct { 579 // Rand provides the source of entropy for the connection. 580 // If Rand is nil, TLS uses the cryptographic random reader in package 581 // crypto/rand. The Reader must be safe for use by multiple goroutines. 582 // 583 // Deprecated: this should be left nil in production. Not all TLS 584 // configurations are guaranteed to use Rand. Test code can use 585 // [testing/cryptotest.SetGlobalRandom] instead. 586 Rand io.Reader 587 588 // Time returns the current time as the number of seconds since the epoch. 589 // If Time is nil, TLS uses time.Now. 590 Time func() time.Time 591 592 // Certificates contains one or more certificate chains to present to the 593 // other side of the connection. The first certificate compatible with the 594 // peer's requirements is selected automatically. 595 // 596 // Server configurations must set one of Certificates, GetCertificate or 597 // GetConfigForClient. Clients doing client-authentication may set either 598 // Certificates or GetClientCertificate. 599 // 600 // Note: if there are multiple Certificates, and they don't have the 601 // optional field Leaf set, certificate selection will incur a significant 602 // per-handshake performance cost. 603 Certificates []Certificate 604 605 // NameToCertificate maps from a certificate name to an element of 606 // Certificates. Note that a certificate name can be of the form 607 // '*.example.com' and so doesn't have to be a domain name as such. 608 // 609 // Deprecated: NameToCertificate only allows associating a single 610 // certificate with a given name. Leave this field nil to let the library 611 // select the first compatible chain from Certificates. 612 NameToCertificate map[string]*Certificate 613 614 // GetCertificate returns a Certificate based on the given 615 // ClientHelloInfo. It will only be called if the client supplies SNI 616 // information or if Certificates is empty. 617 // 618 // If GetCertificate is nil or returns nil, then the certificate is 619 // retrieved from NameToCertificate. If NameToCertificate is nil, the 620 // best element of Certificates will be used. 621 // 622 // Once a Certificate is returned it should not be modified. 623 GetCertificate func(*ClientHelloInfo) (*Certificate, error) 624 625 // GetClientCertificate, if not nil, is called when a server requests a 626 // certificate from a client. If set, the contents of Certificates will 627 // be ignored. 628 // 629 // If GetClientCertificate returns an error, the handshake will be 630 // aborted and that error will be returned. Otherwise 631 // GetClientCertificate must return a non-nil Certificate. If 632 // Certificate.Certificate is empty then no certificate will be sent to 633 // the server. If this is unacceptable to the server then it may abort 634 // the handshake. 635 // 636 // GetClientCertificate may be called multiple times for the same 637 // connection if renegotiation occurs or if TLS 1.3 is in use. 638 // 639 // Once a Certificate is returned it should not be modified. 640 GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error) 641 642 // GetConfigForClient, if not nil, is called after a ClientHello is 643 // received from a client. It may return a non-nil Config in order to 644 // change the Config that will be used to handle this connection. If 645 // the returned Config is nil, the original Config will be used. The 646 // Config returned by this callback may not be subsequently modified. 647 // 648 // If GetConfigForClient is nil, the Config passed to Server() will be 649 // used for all connections. 650 // 651 // If SessionTicketKey is explicitly set on the returned Config, or if 652 // SetSessionTicketKeys is called on the returned Config, those keys will 653 // be used. Otherwise, the original Config keys will be used (and possibly 654 // rotated if they are automatically managed). WARNING: this allows session 655 // resumption of connections originally established with the parent (or a 656 // sibling) Config, which may bypass the [Config.VerifyPeerCertificate] 657 // value of the returned Config. 658 GetConfigForClient func(*ClientHelloInfo) (*Config, error) 659 660 // VerifyPeerCertificate, if not nil, is called after normal 661 // certificate verification by either a TLS client or server. It 662 // receives the raw ASN.1 certificates provided by the peer and also 663 // any verified chains that normal processing found. If it returns a 664 // non-nil error, the handshake is aborted and that error results. 665 // 666 // If normal verification fails then the handshake will abort before 667 // considering this callback. If normal verification is disabled (on the 668 // client when InsecureSkipVerify is set, or on a server when ClientAuth is 669 // RequestClientCert or RequireAnyClientCert), then this callback will be 670 // considered but the verifiedChains argument will always be nil. When 671 // ClientAuth is NoClientCert, this callback is not called on the server. 672 // rawCerts may be empty on the server if ClientAuth is RequestClientCert or 673 // VerifyClientCertIfGiven. 674 // 675 // This callback is not invoked on resumed connections. WARNING: this 676 // includes connections resumed across Configs returned by [Config.Clone] or 677 // [Config.GetConfigForClient] and their parents. If that is not intended, 678 // use [Config.VerifyConnection] instead, or set [Config.SessionTicketsDisabled]. 679 // 680 // verifiedChains and its contents should not be modified. 681 VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error 682 683 // VerifyConnection, if not nil, is called after normal certificate 684 // verification and after VerifyPeerCertificate by either a TLS client 685 // or server. If it returns a non-nil error, the handshake is aborted 686 // and that error results. 687 // 688 // If normal verification fails then the handshake will abort before 689 // considering this callback. This callback will run for all connections, 690 // including resumptions, regardless of InsecureSkipVerify or ClientAuth 691 // settings. 692 VerifyConnection func(ConnectionState) error 693 694 // RootCAs defines the set of root certificate authorities 695 // that clients use when verifying server certificates. 696 // If RootCAs is nil, TLS uses the host's root CA set. 697 RootCAs *x509.CertPool 698 699 // NextProtos is a list of supported application level protocols, in 700 // order of preference. If both peers support ALPN, the selected 701 // protocol will be one from this list, and the connection will fail 702 // if there is no mutually supported protocol. If NextProtos is empty 703 // or the peer doesn't support ALPN, the connection will succeed and 704 // ConnectionState.NegotiatedProtocol will be empty. 705 NextProtos []string 706 707 // ServerName is used to verify the hostname on the returned 708 // certificates unless InsecureSkipVerify is given. It is also included 709 // in the client's handshake to support virtual hosting unless it is 710 // an IP address. 711 ServerName string 712 713 // ClientAuth determines the server's policy for 714 // TLS Client Authentication. The default is NoClientCert. 715 ClientAuth ClientAuthType 716 717 // ClientCAs defines the set of root certificate authorities 718 // that servers use if required to verify a client certificate 719 // by the policy in ClientAuth. 720 ClientCAs *x509.CertPool 721 722 // InsecureSkipVerify controls whether a client verifies the server's 723 // certificate chain and host name. If InsecureSkipVerify is true, crypto/tls 724 // accepts any certificate presented by the server and any host name in that 725 // certificate. In this mode, TLS is susceptible to machine-in-the-middle 726 // attacks unless custom verification is used. This should be used only for 727 // testing or in combination with VerifyConnection or VerifyPeerCertificate. 728 InsecureSkipVerify bool 729 730 // CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of 731 // the list is ignored. Note that TLS 1.3 ciphersuites are not configurable. 732 // 733 // If CipherSuites is nil, a safe default list is used. The default cipher 734 // suites might change over time. 735 CipherSuites []uint16 736 737 // PreferServerCipherSuites is a legacy field and has no effect. 738 // 739 // It used to control whether the server would follow the client's or the 740 // server's preference. Servers now select the best mutually supported 741 // cipher suite based on logic that takes into account inferred client 742 // hardware, server hardware, and security. 743 // 744 // Deprecated: PreferServerCipherSuites is ignored. 745 PreferServerCipherSuites bool 746 747 // SessionTicketsDisabled may be set to true to disable session ticket and 748 // PSK (resumption) support. Note that on clients, session ticket support is 749 // also disabled if ClientSessionCache is nil. 750 SessionTicketsDisabled bool 751 752 // SessionTicketKey is used by TLS servers to provide session resumption. 753 // See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled 754 // with random data before the first server handshake. 755 // 756 // Deprecated: if this field is left at zero, session ticket keys will be 757 // automatically rotated every day and dropped after seven days. For 758 // customizing the rotation schedule or synchronizing servers that are 759 // terminating connections for the same host, use SetSessionTicketKeys. 760 SessionTicketKey [32]byte 761 762 // ClientSessionCache is a cache of ClientSessionState entries for TLS 763 // session resumption. It is only used by clients. 764 ClientSessionCache ClientSessionCache 765 766 // UnwrapSession is called on the server to turn a ticket/identity 767 // previously produced by [WrapSession] into a usable session. 768 // 769 // UnwrapSession will usually either decrypt a session state in the ticket 770 // (for example with [Config.EncryptTicket]), or use the ticket as a handle 771 // to recover a previously stored state. It must use [ParseSessionState] to 772 // deserialize the session state. 773 // 774 // If UnwrapSession returns an error, the connection is terminated. If it 775 // returns (nil, nil), the session is ignored. crypto/tls may still choose 776 // not to resume the returned session. 777 UnwrapSession func(identity []byte, cs ConnectionState) (*SessionState, error) 778 779 // WrapSession is called on the server to produce a session ticket/identity. 780 // 781 // WrapSession must serialize the session state with [SessionState.Bytes]. 782 // It may then encrypt the serialized state (for example with 783 // [Config.DecryptTicket]) and use it as the ticket, or store the state and 784 // return a handle for it. 785 // 786 // If WrapSession returns an error, the connection is terminated. 787 // 788 // Warning: the return value will be exposed on the wire and to clients in 789 // plaintext. The application is in charge of encrypting and authenticating 790 // it (and rotating keys) or returning high-entropy identifiers. Failing to 791 // do so correctly can compromise current, previous, and future connections 792 // depending on the protocol version. 793 WrapSession func(ConnectionState, *SessionState) ([]byte, error) 794 795 // MinVersion contains the minimum TLS version that is acceptable. 796 // 797 // By default, TLS 1.2 is currently used as the minimum. TLS 1.0 is the 798 // minimum supported by this package. 799 MinVersion uint16 800 801 // MaxVersion contains the maximum TLS version that is acceptable. 802 // 803 // By default, the maximum version supported by this package is used, 804 // which is currently TLS 1.3. 805 MaxVersion uint16 806 807 // CurvePreferences contains a set of supported key exchange mechanisms. 808 // The name refers to elliptic curves for legacy reasons, see [CurveID]. 809 // The order of the list is ignored, and key exchange mechanisms are chosen 810 // from this list using an internal preference order. If empty, the default 811 // will be used. 812 // 813 // From Go 1.24, the default includes the [X25519MLKEM768] hybrid 814 // post-quantum key exchange. To disable it, set CurvePreferences explicitly 815 // or use the GODEBUG=tlsmlkem=0 environment variable. 816 // 817 // From Go 1.26, the default includes the [SecP256r1MLKEM768] and 818 // [SecP384r1MLKEM1024] hybrid post-quantum key exchanges, too. To disable 819 // them, set CurvePreferences explicitly or use either the 820 // GODEBUG=tlsmlkem=0 or the GODEBUG=tlssecpmlkem=0 environment variable. 821 CurvePreferences []CurveID 822 823 // DynamicRecordSizingDisabled disables adaptive sizing of TLS records. 824 // When true, the largest possible TLS record size is always used. When 825 // false, the size of TLS records may be adjusted in an attempt to 826 // improve latency. 827 DynamicRecordSizingDisabled bool 828 829 // Renegotiation controls what types of renegotiation are supported. 830 // The default, none, is correct for the vast majority of applications. 831 Renegotiation RenegotiationSupport 832 833 // KeyLogWriter optionally specifies a destination for TLS master secrets 834 // in NSS key log format that can be used to allow external programs 835 // such as Wireshark to decrypt TLS connections. 836 // See https://datatracker.ietf.org/doc/draft-ietf-tls-keylogfile/. 837 // Use of KeyLogWriter compromises security and should only be 838 // used for debugging. 839 KeyLogWriter io.Writer 840 841 // EncryptedClientHelloConfigList is a serialized ECHConfigList. If 842 // provided, clients will attempt to connect to servers using Encrypted 843 // Client Hello (ECH) using one of the provided ECHConfigs. 844 // 845 // Servers do not use this field. In order to configure ECH for servers, see 846 // the EncryptedClientHelloKeys field. 847 // 848 // If the list contains no valid ECH configs, the handshake will fail 849 // and return an error. 850 // 851 // If EncryptedClientHelloConfigList is set, MinVersion, if set, must 852 // be VersionTLS13. 853 // 854 // When EncryptedClientHelloConfigList is set, the handshake will only 855 // succeed if ECH is successfully negotiated. If the server rejects ECH, 856 // an ECHRejectionError error will be returned, which may contain a new 857 // ECHConfigList that the server suggests using. 858 // 859 // How this field is parsed may change in future Go versions, if the 860 // encoding described in the final Encrypted Client Hello RFC changes. 861 EncryptedClientHelloConfigList []byte 862 863 // EncryptedClientHelloRejectionVerify, if not nil, is called when ECH is 864 // rejected by the remote server, in order to verify the ECH provider 865 // certificate in the outer ClientHello. If it returns a non-nil error, the 866 // handshake is aborted and that error results. 867 // 868 // On the server side this field is not used. 869 // 870 // Unlike VerifyPeerCertificate and VerifyConnection, normal certificate 871 // verification will not be performed before calling 872 // EncryptedClientHelloRejectionVerify. 873 // 874 // If EncryptedClientHelloRejectionVerify is nil and ECH is rejected, the 875 // roots in RootCAs will be used to verify the ECH providers public 876 // certificate. VerifyPeerCertificate and VerifyConnection are not called 877 // when ECH is rejected, even if set, and InsecureSkipVerify is ignored. 878 EncryptedClientHelloRejectionVerify func(ConnectionState) error 879 880 // GetEncryptedClientHelloKeys, if not nil, is called when by a server when 881 // a client attempts ECH. 882 // 883 // If GetEncryptedClientHelloKeys is not nil, [EncryptedClientHelloKeys] is 884 // ignored. 885 // 886 // If GetEncryptedClientHelloKeys returns an error, the handshake will be 887 // aborted and the error will be returned. Otherwise, 888 // GetEncryptedClientHelloKeys must return a non-nil slice of 889 // [EncryptedClientHelloKey] that represents the acceptable ECH keys. 890 // 891 // For further details, see [EncryptedClientHelloKeys]. 892 GetEncryptedClientHelloKeys func(*ClientHelloInfo) ([]EncryptedClientHelloKey, error) 893 894 // EncryptedClientHelloKeys are the ECH keys to use when a client 895 // attempts ECH. 896 // 897 // If EncryptedClientHelloKeys is set, MinVersion, if set, must be 898 // VersionTLS13. 899 // 900 // If a client attempts ECH, but it is rejected by the server, the server 901 // will send a list of configs to retry based on the set of 902 // EncryptedClientHelloKeys which have the SendAsRetry field set. 903 // 904 // If GetEncryptedClientHelloKeys is non-nil, EncryptedClientHelloKeys is 905 // ignored. 906 // 907 // On the client side, this field is ignored. In order to configure ECH for 908 // clients, see the EncryptedClientHelloConfigList field. 909 EncryptedClientHelloKeys []EncryptedClientHelloKey 910 911 // mutex protects sessionTicketKeys and autoSessionTicketKeys. 912 mutex sync.RWMutex 913 // sessionTicketKeys contains zero or more ticket keys. If set, it means 914 // the keys were set with SessionTicketKey or SetSessionTicketKeys. The 915 // first key is used for new tickets and any subsequent keys can be used to 916 // decrypt old tickets. The slice contents are not protected by the mutex 917 // and are immutable. 918 sessionTicketKeys []ticketKey 919 // autoSessionTicketKeys is like sessionTicketKeys but is owned by the 920 // auto-rotation logic. See Config.ticketKeys. 921 autoSessionTicketKeys []ticketKey 922 } 923 924 // EncryptedClientHelloKey holds a private key that is associated 925 // with a specific ECH config known to a client. 926 type EncryptedClientHelloKey struct { 927 // Config should be a marshalled ECHConfig associated with PrivateKey. This 928 // must match the config provided to clients byte-for-byte. The config must 929 // use as KEM one of 930 // 931 // - DHKEM(P-256, HKDF-SHA256) (0x0010) 932 // - DHKEM(P-384, HKDF-SHA384) (0x0011) 933 // - DHKEM(P-521, HKDF-SHA512) (0x0012) 934 // - DHKEM(X25519, HKDF-SHA256) (0x0020) 935 // - ML-KEM-768 (0x0041) 936 // - ML-KEM-1024 (0x0042) 937 // - MLKEM768-P256 (0x0050) 938 // - MLKEM1024-P384 (0x0051) 939 // - MLKEM768-X25519 (0x647a) 940 // 941 // and as KDF one of 942 // 943 // - HKDF-SHA256 (0x0001) 944 // - HKDF-SHA384 (0x0002) 945 // - HKDF-SHA512 (0x0003) 946 // 947 // and as AEAD one of 948 // 949 // - AES-128-GCM (0x0001) 950 // - AES-256-GCM (0x0002) 951 // - ChaCha20Poly1305 (0x0003) 952 // 953 Config []byte 954 // PrivateKey should be a marshalled private key, in the format expected by 955 // HPKE's DeserializePrivateKey (see RFC 9180), for the KEM used in Config. 956 PrivateKey []byte 957 // SendAsRetry indicates if Config should be sent as part of the list of 958 // retry configs when ECH is requested by the client but rejected by the 959 // server. 960 SendAsRetry bool 961 } 962 963 const ( 964 // ticketKeyLifetime is how long a ticket key remains valid and can be used to 965 // resume a client connection. 966 ticketKeyLifetime = 7 * 24 * time.Hour // 7 days 967 968 // ticketKeyRotation is how often the server should rotate the session ticket key 969 // that is used for new tickets. 970 ticketKeyRotation = 24 * time.Hour 971 ) 972 973 // ticketKey is the internal representation of a session ticket key. 974 type ticketKey struct { 975 aesKey [16]byte 976 hmacKey [16]byte 977 // created is the time at which this ticket key was created. See Config.ticketKeys. 978 created time.Time 979 } 980 981 // ticketKeyFromBytes converts from the external representation of a session 982 // ticket key to a ticketKey. Externally, session ticket keys are 32 random 983 // bytes and this function expands that into sufficient name and key material. 984 func (c *Config) ticketKeyFromBytes(b [32]byte) (key ticketKey) { 985 hashed := sha512.Sum512(b[:]) 986 // The first 16 bytes of the hash used to be exposed on the wire as a ticket 987 // prefix. They MUST NOT be used as a secret. In the future, it would make 988 // sense to use a proper KDF here, like HKDF with a fixed salt. 989 const legacyTicketKeyNameLen = 16 990 copy(key.aesKey[:], hashed[legacyTicketKeyNameLen:]) 991 copy(key.hmacKey[:], hashed[legacyTicketKeyNameLen+len(key.aesKey):]) 992 key.created = c.time() 993 return key 994 } 995 996 // maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session 997 // ticket, and the lifetime we set for all tickets we send. 998 const maxSessionTicketLifetime = 7 * 24 * time.Hour 999 1000 // Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a 1001 // [Config] that is being used concurrently by a TLS client or server. 1002 // 1003 // The returned Config can share session ticket keys with the original Config, 1004 // which means connections could be resumed across the two Configs. WARNING: 1005 // [Config.VerifyPeerCertificate] does not get called on resumed connections, 1006 // including connections that were originally established on the parent Config. 1007 // If that is not intended, use [Config.VerifyConnection] instead, or set 1008 // [Config.SessionTicketsDisabled]. 1009 func (c *Config) Clone() *Config { 1010 if c == nil { 1011 return nil 1012 } 1013 c.mutex.RLock() 1014 defer c.mutex.RUnlock() 1015 return &Config{ 1016 Rand: c.Rand, 1017 Time: c.Time, 1018 Certificates: c.Certificates, 1019 NameToCertificate: c.NameToCertificate, 1020 GetCertificate: c.GetCertificate, 1021 GetClientCertificate: c.GetClientCertificate, 1022 GetConfigForClient: c.GetConfigForClient, 1023 GetEncryptedClientHelloKeys: c.GetEncryptedClientHelloKeys, 1024 VerifyPeerCertificate: c.VerifyPeerCertificate, 1025 VerifyConnection: c.VerifyConnection, 1026 RootCAs: c.RootCAs, 1027 NextProtos: c.NextProtos, 1028 ServerName: c.ServerName, 1029 ClientAuth: c.ClientAuth, 1030 ClientCAs: c.ClientCAs, 1031 InsecureSkipVerify: c.InsecureSkipVerify, 1032 CipherSuites: c.CipherSuites, 1033 PreferServerCipherSuites: c.PreferServerCipherSuites, 1034 SessionTicketsDisabled: c.SessionTicketsDisabled, 1035 SessionTicketKey: c.SessionTicketKey, 1036 ClientSessionCache: c.ClientSessionCache, 1037 UnwrapSession: c.UnwrapSession, 1038 WrapSession: c.WrapSession, 1039 MinVersion: c.MinVersion, 1040 MaxVersion: c.MaxVersion, 1041 CurvePreferences: c.CurvePreferences, 1042 DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled, 1043 Renegotiation: c.Renegotiation, 1044 KeyLogWriter: c.KeyLogWriter, 1045 EncryptedClientHelloConfigList: c.EncryptedClientHelloConfigList, 1046 EncryptedClientHelloRejectionVerify: c.EncryptedClientHelloRejectionVerify, 1047 EncryptedClientHelloKeys: c.EncryptedClientHelloKeys, 1048 sessionTicketKeys: c.sessionTicketKeys, 1049 autoSessionTicketKeys: c.autoSessionTicketKeys, 1050 } 1051 } 1052 1053 // deprecatedSessionTicketKey is set as the prefix of SessionTicketKey if it was 1054 // randomized for backwards compatibility but is not in use. 1055 var deprecatedSessionTicketKey = []byte("DEPRECATED") 1056 1057 // initLegacySessionTicketKeyRLocked ensures the legacy SessionTicketKey field is 1058 // randomized if empty, and that sessionTicketKeys is populated from it otherwise. 1059 func (c *Config) initLegacySessionTicketKeyRLocked() { 1060 // Don't write if SessionTicketKey is already defined as our deprecated string, 1061 // or if it is defined by the user but sessionTicketKeys is already set. 1062 if c.SessionTicketKey != [32]byte{} && 1063 (bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) || len(c.sessionTicketKeys) > 0) { 1064 return 1065 } 1066 1067 // We need to write some data, so get an exclusive lock and re-check any conditions. 1068 c.mutex.RUnlock() 1069 defer c.mutex.RLock() 1070 c.mutex.Lock() 1071 defer c.mutex.Unlock() 1072 if c.SessionTicketKey == [32]byte{} { 1073 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil { 1074 panic(fmt.Sprintf("tls: unable to generate random session ticket key: %v", err)) 1075 } 1076 // Write the deprecated prefix at the beginning so we know we created 1077 // it. This key with the DEPRECATED prefix isn't used as an actual 1078 // session ticket key, and is only randomized in case the application 1079 // reuses it for some reason. 1080 copy(c.SessionTicketKey[:], deprecatedSessionTicketKey) 1081 } else if !bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) && len(c.sessionTicketKeys) == 0 { 1082 c.sessionTicketKeys = []ticketKey{c.ticketKeyFromBytes(c.SessionTicketKey)} 1083 } 1084 } 1085 1086 // ticketKeys returns the ticketKeys for this connection. 1087 // If configForClient has explicitly set keys, those will 1088 // be returned. Otherwise, the keys on c will be used and 1089 // may be rotated if auto-managed. 1090 // During rotation, any expired session ticket keys are deleted from 1091 // c.sessionTicketKeys. If the session ticket key that is currently 1092 // encrypting tickets (ie. the first ticketKey in c.sessionTicketKeys) 1093 // is not fresh, then a new session ticket key will be 1094 // created and prepended to c.sessionTicketKeys. 1095 func (c *Config) ticketKeys(configForClient *Config) []ticketKey { 1096 // If the ConfigForClient callback returned a Config with explicitly set 1097 // keys, use those, otherwise just use the original Config. 1098 if configForClient != nil { 1099 configForClient.mutex.RLock() 1100 if configForClient.SessionTicketsDisabled { 1101 configForClient.mutex.RUnlock() 1102 return nil 1103 } 1104 configForClient.initLegacySessionTicketKeyRLocked() 1105 if len(configForClient.sessionTicketKeys) != 0 { 1106 ret := configForClient.sessionTicketKeys 1107 configForClient.mutex.RUnlock() 1108 return ret 1109 } 1110 configForClient.mutex.RUnlock() 1111 } 1112 1113 c.mutex.RLock() 1114 defer c.mutex.RUnlock() 1115 if c.SessionTicketsDisabled { 1116 return nil 1117 } 1118 c.initLegacySessionTicketKeyRLocked() 1119 if len(c.sessionTicketKeys) != 0 { 1120 return c.sessionTicketKeys 1121 } 1122 // Fast path for the common case where the key is fresh enough. 1123 if len(c.autoSessionTicketKeys) > 0 && c.time().Sub(c.autoSessionTicketKeys[0].created) < ticketKeyRotation { 1124 return c.autoSessionTicketKeys 1125 } 1126 1127 // autoSessionTicketKeys are managed by auto-rotation. 1128 c.mutex.RUnlock() 1129 defer c.mutex.RLock() 1130 c.mutex.Lock() 1131 defer c.mutex.Unlock() 1132 // Re-check the condition in case it changed since obtaining the new lock. 1133 if len(c.autoSessionTicketKeys) == 0 || c.time().Sub(c.autoSessionTicketKeys[0].created) >= ticketKeyRotation { 1134 var newKey [32]byte 1135 if _, err := io.ReadFull(c.rand(), newKey[:]); err != nil { 1136 panic(fmt.Sprintf("unable to generate random session ticket key: %v", err)) 1137 } 1138 valid := make([]ticketKey, 0, len(c.autoSessionTicketKeys)+1) 1139 valid = append(valid, c.ticketKeyFromBytes(newKey)) 1140 for _, k := range c.autoSessionTicketKeys { 1141 // While rotating the current key, also remove any expired ones. 1142 if c.time().Sub(k.created) < ticketKeyLifetime { 1143 valid = append(valid, k) 1144 } 1145 } 1146 c.autoSessionTicketKeys = valid 1147 } 1148 return c.autoSessionTicketKeys 1149 } 1150 1151 // SetSessionTicketKeys updates the session ticket keys for a server. 1152 // 1153 // The first key will be used when creating new tickets, while all keys can be 1154 // used for decrypting tickets. It is safe to call this function while the 1155 // server is running in order to rotate the session ticket keys. The function 1156 // will panic if keys is empty. 1157 // 1158 // Calling this function will turn off automatic session ticket key rotation. 1159 // 1160 // If multiple servers are terminating connections for the same host they should 1161 // all have the same session ticket keys. If the session ticket keys leaks, 1162 // previously recorded and future TLS connections using those keys might be 1163 // compromised. 1164 func (c *Config) SetSessionTicketKeys(keys [][32]byte) { 1165 if len(keys) == 0 { 1166 panic("tls: keys must have at least one key") 1167 } 1168 1169 newKeys := make([]ticketKey, len(keys)) 1170 for i, bytes := range keys { 1171 newKeys[i] = c.ticketKeyFromBytes(bytes) 1172 } 1173 1174 c.mutex.Lock() 1175 c.sessionTicketKeys = newKeys 1176 c.mutex.Unlock() 1177 } 1178 1179 func (c *Config) rand() io.Reader { 1180 r := c.Rand 1181 if r == nil { 1182 return rand.Reader 1183 } 1184 return r 1185 } 1186 1187 func (c *Config) time() time.Time { 1188 t := c.Time 1189 if t == nil { 1190 t = time.Now 1191 } 1192 return t() 1193 } 1194 1195 func (c *Config) cipherSuites(aesGCMPreferred bool) []uint16 { 1196 var cipherSuites []uint16 1197 if c.CipherSuites == nil { 1198 cipherSuites = defaultCipherSuites(aesGCMPreferred) 1199 } else { 1200 cipherSuites = supportedCipherSuites(aesGCMPreferred) 1201 cipherSuites = slices.DeleteFunc(cipherSuites, func(id uint16) bool { 1202 return !slices.Contains(c.CipherSuites, id) 1203 }) 1204 } 1205 if fips140tls.Required() { 1206 cipherSuites = slices.DeleteFunc(cipherSuites, func(id uint16) bool { 1207 return !slices.Contains(allowedCipherSuitesFIPS, id) 1208 }) 1209 } 1210 return cipherSuites 1211 } 1212 1213 // supportedCipherSuites returns the supported TLS 1.0–1.2 cipher suites in an 1214 // undefined order. For preference ordering, use [Config.cipherSuites]. 1215 func (c *Config) supportedCipherSuites() []uint16 { 1216 return c.cipherSuites(false) 1217 } 1218 1219 var supportedVersions = []uint16{ 1220 VersionTLS13, 1221 VersionTLS12, 1222 VersionTLS11, 1223 VersionTLS10, 1224 } 1225 1226 // roleClient and roleServer are meant to call supportedVersions and parents 1227 // with more readability at the callsite. 1228 const roleClient = true 1229 const roleServer = false 1230 1231 // supportedVersions returns the list of supported TLS versions, sorted from 1232 // highest to lowest (and hence also in preference order). 1233 func (c *Config) supportedVersions(isClient, isQUIC bool) []uint16 { 1234 versions := make([]uint16, 0, len(supportedVersions)) 1235 for _, v := range supportedVersions { 1236 if fips140tls.Required() && !slices.Contains(allowedSupportedVersionsFIPS, v) { 1237 continue 1238 } 1239 if (c == nil || c.MinVersion == 0) && v < VersionTLS12 { 1240 continue 1241 } 1242 if isClient && c.EncryptedClientHelloConfigList != nil && v < VersionTLS13 { 1243 continue 1244 } 1245 if c != nil && c.MinVersion != 0 && v < c.MinVersion { 1246 continue 1247 } 1248 if c != nil && c.MaxVersion != 0 && v > c.MaxVersion { 1249 continue 1250 } 1251 if isQUIC && v < VersionTLS13 { 1252 continue 1253 } 1254 versions = append(versions, v) 1255 } 1256 return versions 1257 } 1258 1259 func (c *Config) maxSupportedVersion(isClient, isQUIC bool) uint16 { 1260 supportedVersions := c.supportedVersions(isClient, isQUIC) 1261 if len(supportedVersions) == 0 { 1262 return 0 1263 } 1264 return supportedVersions[0] 1265 } 1266 1267 // supportedVersionsFromMax returns a list of supported versions derived from a 1268 // legacy maximum version value. Note that only versions supported by this 1269 // library are returned. Any newer peer will use supportedVersions anyway. 1270 func supportedVersionsFromMax(maxVersion uint16) []uint16 { 1271 versions := make([]uint16, 0, len(supportedVersions)) 1272 for _, v := range supportedVersions { 1273 if v > maxVersion { 1274 continue 1275 } 1276 versions = append(versions, v) 1277 } 1278 return versions 1279 } 1280 1281 func (c *Config) curvePreferences(version uint16) []CurveID { 1282 return slices.DeleteFunc(curvePreferenceOrder(), func(x CurveID) bool { 1283 return !c.supportsCurve(version, x) 1284 }) 1285 } 1286 1287 func (c *Config) supportsCurve(version uint16, x CurveID) bool { 1288 if c != nil && len(c.CurvePreferences) != 0 { 1289 if !slices.Contains(c.CurvePreferences, x) { 1290 return false 1291 } 1292 // Ignore unimplemented entries in c.CurvePreferences. 1293 if !slices.Contains(curvePreferenceOrder(), x) { 1294 return false 1295 } 1296 } else { 1297 if !defaultCurveEnabled(x) { 1298 return false 1299 } 1300 } 1301 if fips140tls.Required() && !slices.Contains(allowedCurvePreferencesFIPS, x) { 1302 return false 1303 } 1304 if version < VersionTLS13 && isTLS13OnlyKeyExchange(x) { 1305 return false 1306 } 1307 return true 1308 } 1309 1310 // mutualVersion returns the protocol version to use given the advertised 1311 // versions of the peer. The highest supported version is preferred. 1312 func (c *Config) mutualVersion(isClient, isQUIC bool, peerVersions []uint16) (uint16, bool) { 1313 supportedVersions := c.supportedVersions(isClient, isQUIC) 1314 for _, v := range supportedVersions { 1315 if slices.Contains(peerVersions, v) { 1316 return v, true 1317 } 1318 } 1319 return 0, false 1320 } 1321 1322 // errNoCertificates should be an internal detail, 1323 // but widely used packages access it using linkname. 1324 // Notable members of the hall of shame include: 1325 // - github.com/xtls/xray-core 1326 // 1327 // Do not remove or change the type signature. 1328 // See go.dev/issue/67401. 1329 // 1330 //go:linkname errNoCertificates 1331 var errNoCertificates = errors.New("tls: no certificates configured") 1332 1333 // getCertificate returns the best certificate for the given ClientHelloInfo, 1334 // defaulting to the first element of c.Certificates. 1335 func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) { 1336 if c.GetCertificate != nil && 1337 (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) { 1338 cert, err := c.GetCertificate(clientHello) 1339 if cert != nil || err != nil { 1340 return cert, err 1341 } 1342 } 1343 1344 if len(c.Certificates) == 0 { 1345 return nil, errNoCertificates 1346 } 1347 1348 if len(c.Certificates) == 1 { 1349 // There's only one choice, so no point doing any work. 1350 return &c.Certificates[0], nil 1351 } 1352 1353 if c.NameToCertificate != nil { 1354 name := strings.ToLower(clientHello.ServerName) 1355 if cert, ok := c.NameToCertificate[name]; ok { 1356 return cert, nil 1357 } 1358 if len(name) > 0 { 1359 labels := strings.Split(name, ".") 1360 labels[0] = "*" 1361 wildcardName := strings.Join(labels, ".") 1362 if cert, ok := c.NameToCertificate[wildcardName]; ok { 1363 return cert, nil 1364 } 1365 } 1366 } 1367 1368 for _, cert := range c.Certificates { 1369 if err := clientHello.SupportsCertificate(&cert); err == nil { 1370 return &cert, nil 1371 } 1372 } 1373 1374 // If nothing matches, return the first certificate. 1375 return &c.Certificates[0], nil 1376 } 1377 1378 // SupportsCertificate returns nil if the provided certificate is supported by 1379 // the client that sent the ClientHello. Otherwise, it returns an error 1380 // describing the reason for the incompatibility. 1381 // 1382 // If this [ClientHelloInfo] was passed to a GetConfigForClient or GetCertificate 1383 // callback, this method will take into account the associated [Config]. Note that 1384 // if GetConfigForClient returns a different [Config], the change can't be 1385 // accounted for by this method. 1386 // 1387 // This function will call x509.ParseCertificate unless c.Leaf is set, which can 1388 // incur a significant performance cost. 1389 func (chi *ClientHelloInfo) SupportsCertificate(c *Certificate) error { 1390 // Note we don't currently support certificate_authorities nor 1391 // signature_algorithms_cert, and don't check the algorithms of the 1392 // signatures on the chain (which anyway are a SHOULD, see RFC 8446, 1393 // Section 4.4.2.2). 1394 1395 config := chi.config 1396 if config == nil { 1397 config = &Config{} 1398 } 1399 vers, ok := config.mutualVersion(roleServer, chi.isQUIC, chi.SupportedVersions) 1400 if !ok { 1401 return errors.New("no mutually supported protocol versions") 1402 } 1403 1404 // If the client specified the name they are trying to connect to, the 1405 // certificate needs to be valid for it. 1406 if chi.ServerName != "" { 1407 x509Cert, err := c.leaf() 1408 if err != nil { 1409 return fmt.Errorf("failed to parse certificate: %w", err) 1410 } 1411 if err := x509Cert.VerifyHostname(chi.ServerName); err != nil { 1412 return fmt.Errorf("certificate is not valid for requested server name: %w", err) 1413 } 1414 } 1415 1416 // supportsRSAFallback returns nil if the certificate and connection support 1417 // the static RSA key exchange, and unsupported otherwise. The logic for 1418 // supporting static RSA is completely disjoint from the logic for 1419 // supporting signed key exchanges, so we just check it as a fallback. 1420 supportsRSAFallback := func(unsupported error) error { 1421 // TLS 1.3 dropped support for the static RSA key exchange. 1422 if vers == VersionTLS13 { 1423 return unsupported 1424 } 1425 // The static RSA key exchange works by decrypting a challenge with the 1426 // RSA private key, not by signing, so check the PrivateKey implements 1427 // crypto.Decrypter, like *rsa.PrivateKey does. 1428 if priv, ok := c.PrivateKey.(crypto.Decrypter); ok { 1429 if _, ok := priv.Public().(*rsa.PublicKey); !ok { 1430 return unsupported 1431 } 1432 } else { 1433 return unsupported 1434 } 1435 // Finally, there needs to be a mutual cipher suite that uses the static 1436 // RSA key exchange instead of ECDHE. 1437 rsaCipherSuite := selectCipherSuite(chi.CipherSuites, config.supportedCipherSuites(), func(c *cipherSuite) bool { 1438 if c.flags&suiteECDHE != 0 { 1439 return false 1440 } 1441 if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 { 1442 return false 1443 } 1444 return true 1445 }) 1446 if rsaCipherSuite == nil { 1447 return unsupported 1448 } 1449 return nil 1450 } 1451 1452 // If the client sent the signature_algorithms extension, ensure it supports 1453 // schemes we can use with this certificate and TLS version. 1454 if len(chi.SignatureSchemes) > 0 { 1455 if _, err := selectSignatureScheme(vers, c, chi.SignatureSchemes); err != nil { 1456 return supportsRSAFallback(err) 1457 } 1458 } 1459 1460 // In TLS 1.3 we are done because supported_groups is only relevant to the 1461 // ECDHE computation, point format negotiation is removed, cipher suites are 1462 // only relevant to the AEAD choice, and static RSA does not exist. 1463 if vers == VersionTLS13 { 1464 return nil 1465 } 1466 1467 // The only signed key exchange we support is ECDHE. 1468 ecdheSupported, err := supportsECDHE(config, vers, chi.SupportedCurves, chi.SupportedPoints) 1469 if err != nil { 1470 return err 1471 } 1472 if !ecdheSupported { 1473 return supportsRSAFallback(errors.New("client doesn't support ECDHE, can only use legacy RSA key exchange")) 1474 } 1475 1476 var ecdsaCipherSuite bool 1477 if priv, ok := c.PrivateKey.(crypto.Signer); ok { 1478 switch pub := priv.Public().(type) { 1479 case *ecdsa.PublicKey: 1480 var curve CurveID 1481 switch pub.Curve { 1482 case elliptic.P256(): 1483 curve = CurveP256 1484 case elliptic.P384(): 1485 curve = CurveP384 1486 case elliptic.P521(): 1487 curve = CurveP521 1488 default: 1489 return supportsRSAFallback(unsupportedCertificateError(c)) 1490 } 1491 var curveOk bool 1492 for _, c := range chi.SupportedCurves { 1493 if c == curve && config.supportsCurve(vers, c) { 1494 curveOk = true 1495 break 1496 } 1497 } 1498 if !curveOk { 1499 return errors.New("client doesn't support certificate curve") 1500 } 1501 ecdsaCipherSuite = true 1502 case ed25519.PublicKey: 1503 if vers < VersionTLS12 || len(chi.SignatureSchemes) == 0 { 1504 return errors.New("connection doesn't support Ed25519") 1505 } 1506 ecdsaCipherSuite = true 1507 case *mldsa.PublicKey: 1508 // ML-DSA requires TLS 1.3, which we already excluded above. 1509 return errors.New("connection doesn't support ML-DSA") 1510 case *rsa.PublicKey: 1511 default: 1512 return supportsRSAFallback(unsupportedCertificateError(c)) 1513 } 1514 } else { 1515 return supportsRSAFallback(unsupportedCertificateError(c)) 1516 } 1517 1518 // Make sure that there is a mutually supported cipher suite that works with 1519 // this certificate. Cipher suite selection will then apply the logic in 1520 // reverse to pick it. See also serverHandshakeState.cipherSuiteOk. 1521 cipherSuite := selectCipherSuite(chi.CipherSuites, config.supportedCipherSuites(), func(c *cipherSuite) bool { 1522 if c.flags&suiteECDHE == 0 { 1523 return false 1524 } 1525 if c.flags&suiteECSign != 0 { 1526 if !ecdsaCipherSuite { 1527 return false 1528 } 1529 } else { 1530 if ecdsaCipherSuite { 1531 return false 1532 } 1533 } 1534 if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 { 1535 return false 1536 } 1537 return true 1538 }) 1539 if cipherSuite == nil { 1540 return supportsRSAFallback(errors.New("client doesn't support any cipher suites compatible with the certificate")) 1541 } 1542 1543 return nil 1544 } 1545 1546 // SupportsCertificate returns nil if the provided certificate is supported by 1547 // the server that sent the CertificateRequest. Otherwise, it returns an error 1548 // describing the reason for the incompatibility. 1549 func (cri *CertificateRequestInfo) SupportsCertificate(c *Certificate) error { 1550 if _, err := selectSignatureScheme(cri.Version, c, cri.SignatureSchemes); err != nil { 1551 return err 1552 } 1553 1554 if len(cri.AcceptableCAs) == 0 { 1555 return nil 1556 } 1557 1558 for j, cert := range c.Certificate { 1559 x509Cert := c.Leaf 1560 // Parse the certificate if this isn't the leaf node, or if 1561 // chain.Leaf was nil. 1562 if j != 0 || x509Cert == nil { 1563 var err error 1564 if x509Cert, err = x509.ParseCertificate(cert); err != nil { 1565 return fmt.Errorf("failed to parse certificate #%d in the chain: %w", j, err) 1566 } 1567 } 1568 1569 for _, ca := range cri.AcceptableCAs { 1570 if bytes.Equal(x509Cert.RawIssuer, ca) { 1571 return nil 1572 } 1573 } 1574 } 1575 return errors.New("chain is not signed by an acceptable CA") 1576 } 1577 1578 // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate 1579 // from the CommonName and SubjectAlternateName fields of each of the leaf 1580 // certificates. 1581 // 1582 // Deprecated: NameToCertificate only allows associating a single certificate 1583 // with a given name. Leave that field nil to let the library select the first 1584 // compatible chain from Certificates. 1585 func (c *Config) BuildNameToCertificate() { 1586 c.NameToCertificate = make(map[string]*Certificate) 1587 for i := range c.Certificates { 1588 cert := &c.Certificates[i] 1589 x509Cert, err := cert.leaf() 1590 if err != nil { 1591 continue 1592 } 1593 // If SANs are *not* present, some clients will consider the certificate 1594 // valid for the name in the Common Name. 1595 if x509Cert.Subject.CommonName != "" && len(x509Cert.DNSNames) == 0 { 1596 c.NameToCertificate[x509Cert.Subject.CommonName] = cert 1597 } 1598 for _, san := range x509Cert.DNSNames { 1599 c.NameToCertificate[san] = cert 1600 } 1601 } 1602 } 1603 1604 const ( 1605 keyLogLabelTLS12 = "CLIENT_RANDOM" 1606 keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET" 1607 keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET" 1608 keyLogLabelClientTraffic = "CLIENT_TRAFFIC_SECRET_0" 1609 keyLogLabelServerTraffic = "SERVER_TRAFFIC_SECRET_0" 1610 ) 1611 1612 func (c *Config) writeKeyLog(label string, clientRandom, secret []byte) error { 1613 if c.KeyLogWriter == nil { 1614 return nil 1615 } 1616 1617 logLine := fmt.Appendf(nil, "%s %x %x\n", label, clientRandom, secret) 1618 1619 writerMutex.Lock() 1620 _, err := c.KeyLogWriter.Write(logLine) 1621 writerMutex.Unlock() 1622 1623 if err != nil { 1624 return fmt.Errorf("tls: KeyLogWriter: %w", err) 1625 } 1626 return nil 1627 } 1628 1629 // writerMutex protects all KeyLogWriters globally. It is rarely enabled, 1630 // and is only for debugging, so a global mutex saves space. 1631 var writerMutex sync.Mutex 1632 1633 // A Certificate is a chain of one or more certificates, leaf first. 1634 type Certificate struct { 1635 Certificate [][]byte 1636 // PrivateKey contains the private key corresponding to the public key in 1637 // Leaf. This must implement [crypto.Signer] with an RSA, ECDSA, Ed25519 1638 // (TLS 1.2+), or ML-DSA (TLS 1.3) PublicKey. 1639 // 1640 // For a server up to TLS 1.2, it can also implement crypto.Decrypter with 1641 // an RSA PublicKey. 1642 // 1643 // If it implements [crypto.MessageSigner], SignMessage will be used instead 1644 // of Sign for TLS 1.2 and later. 1645 PrivateKey crypto.PrivateKey 1646 // SupportedSignatureAlgorithms is an optional list restricting what 1647 // signature algorithms the PrivateKey can be used for. 1648 SupportedSignatureAlgorithms []SignatureScheme 1649 // OCSPStaple contains an optional OCSP response which will be served 1650 // to clients that request it. 1651 OCSPStaple []byte 1652 // SignedCertificateTimestamps contains an optional list of Signed 1653 // Certificate Timestamps which will be served to clients that request it. 1654 SignedCertificateTimestamps [][]byte 1655 // Leaf is the parsed form of the leaf certificate, which may be initialized 1656 // using x509.ParseCertificate to reduce per-handshake processing. If nil, 1657 // the leaf certificate will be parsed as needed. 1658 Leaf *x509.Certificate 1659 } 1660 1661 // leaf returns the parsed leaf certificate, either from c.Leaf or by parsing 1662 // the corresponding c.Certificate[0]. 1663 func (c *Certificate) leaf() (*x509.Certificate, error) { 1664 if c.Leaf != nil { 1665 return c.Leaf, nil 1666 } 1667 return x509.ParseCertificate(c.Certificate[0]) 1668 } 1669 1670 type handshakeMessage interface { 1671 marshal() ([]byte, error) 1672 unmarshal([]byte) bool 1673 } 1674 1675 type handshakeMessageWithOriginalBytes interface { 1676 handshakeMessage 1677 1678 // originalBytes should return the original bytes that were passed to 1679 // unmarshal to create the message. If the message was not produced by 1680 // unmarshal, it should return nil. 1681 originalBytes() []byte 1682 } 1683 1684 // lruSessionCache is a ClientSessionCache implementation that uses an LRU 1685 // caching strategy. 1686 type lruSessionCache struct { 1687 sync.Mutex 1688 1689 m map[string]*list.Element 1690 q *list.List 1691 capacity int 1692 } 1693 1694 type lruSessionCacheEntry struct { 1695 sessionKey string 1696 state *ClientSessionState 1697 } 1698 1699 // NewLRUClientSessionCache returns a [ClientSessionCache] with the given 1700 // capacity that uses an LRU strategy. If capacity is < 1, a default capacity 1701 // is used instead. 1702 func NewLRUClientSessionCache(capacity int) ClientSessionCache { 1703 const defaultSessionCacheCapacity = 64 1704 1705 if capacity < 1 { 1706 capacity = defaultSessionCacheCapacity 1707 } 1708 return &lruSessionCache{ 1709 m: make(map[string]*list.Element), 1710 q: list.New(), 1711 capacity: capacity, 1712 } 1713 } 1714 1715 // Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry 1716 // corresponding to sessionKey is removed from the cache instead. 1717 func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) { 1718 c.Lock() 1719 defer c.Unlock() 1720 1721 if elem, ok := c.m[sessionKey]; ok { 1722 if cs == nil { 1723 c.q.Remove(elem) 1724 delete(c.m, sessionKey) 1725 } else { 1726 entry := elem.Value.(*lruSessionCacheEntry) 1727 entry.state = cs 1728 c.q.MoveToFront(elem) 1729 } 1730 return 1731 } 1732 1733 if c.q.Len() < c.capacity { 1734 entry := &lruSessionCacheEntry{sessionKey, cs} 1735 c.m[sessionKey] = c.q.PushFront(entry) 1736 return 1737 } 1738 1739 elem := c.q.Back() 1740 entry := elem.Value.(*lruSessionCacheEntry) 1741 delete(c.m, entry.sessionKey) 1742 entry.sessionKey = sessionKey 1743 entry.state = cs 1744 c.q.MoveToFront(elem) 1745 c.m[sessionKey] = elem 1746 } 1747 1748 // Get returns the [ClientSessionState] value associated with a given key. It 1749 // returns (nil, false) if no value is found. 1750 func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) { 1751 c.Lock() 1752 defer c.Unlock() 1753 1754 if elem, ok := c.m[sessionKey]; ok { 1755 c.q.MoveToFront(elem) 1756 return elem.Value.(*lruSessionCacheEntry).state, true 1757 } 1758 return nil, false 1759 } 1760 1761 var emptyConfig Config 1762 1763 func defaultConfig() *Config { 1764 return &emptyConfig 1765 } 1766 1767 func unexpectedMessageError(wanted, got any) error { 1768 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted) 1769 } 1770 1771 var testingOnlySupportedSignatureAlgorithms []SignatureScheme 1772 1773 // supportedSignatureAlgorithms returns the supported signature algorithms for 1774 // the given range of TLS versions, to advertise in ClientHello and 1775 // CertificateRequest messages. An algorithm is included if it is enabled at any 1776 // version in the range. 1777 func supportedSignatureAlgorithms(minVers, maxVers uint16) []SignatureScheme { 1778 sigAlgs := defaultSupportedSignatureAlgorithms() 1779 if testingOnlySupportedSignatureAlgorithms != nil { 1780 sigAlgs = slices.Clone(testingOnlySupportedSignatureAlgorithms) 1781 } 1782 return slices.DeleteFunc(sigAlgs, func(s SignatureScheme) bool { 1783 for v := minVers; v <= maxVers; v++ { 1784 if !isDisabledSignatureAlgorithm(v, s, false) { 1785 return false 1786 } 1787 } 1788 return true 1789 }) 1790 } 1791 1792 var tlssha1 = godebug.New("tlssha1") 1793 1794 func isDisabledSignatureAlgorithm(version uint16, s SignatureScheme, isCert bool) bool { 1795 if fips140tls.Required() && !slices.Contains(allowedSignatureAlgorithmsFIPS, s) { 1796 return true 1797 } 1798 1799 switch s { 1800 case MLDSA44, MLDSA65, MLDSA87: 1801 // ML-DSA is not available in FIPS 140-3 module v1.0.0. 1802 if fips140.Version() == "v1.0.0" { 1803 return true 1804 } 1805 // ML-DSA codepoints are only defined for TLS 1.3. 1806 if version < VersionTLS13 { 1807 return true 1808 } 1809 } 1810 1811 // For the _cert extension we include all algorithms, including SHA-1 and 1812 // PKCS#1 v1.5, because it's more likely that something on our side will be 1813 // willing to accept a *-with-SHA1 certificate (e.g. with a custom 1814 // VerifyConnection or by a direct match with the CertPool), than that the 1815 // peer would have a better certificate but is just choosing not to send it. 1816 // crypto/x509 will refuse to verify important SHA-1 signatures anyway. 1817 if isCert { 1818 return false 1819 } 1820 1821 // TLS 1.3 removed support for PKCS#1 v1.5 and SHA-1 signatures, 1822 // and Go 1.25 removed support for SHA-1 signatures in TLS 1.2. 1823 if version > VersionTLS12 { 1824 sigType, sigHash, _ := typeAndHashFromSignatureScheme(s) 1825 if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 { 1826 return true 1827 } 1828 } else if tlssha1.Value() != "1" { 1829 _, sigHash, _ := typeAndHashFromSignatureScheme(s) 1830 if sigHash == crypto.SHA1 { 1831 return true 1832 } 1833 } 1834 1835 return false 1836 } 1837 1838 // supportedSignatureAlgorithmsCert returns the supported algorithms for 1839 // signatures in certificates. 1840 func supportedSignatureAlgorithmsCert(minVers, maxVers uint16) []SignatureScheme { 1841 sigAlgs := defaultSupportedSignatureAlgorithms() 1842 return slices.DeleteFunc(sigAlgs, func(s SignatureScheme) bool { 1843 for v := minVers; v <= maxVers; v++ { 1844 if !isDisabledSignatureAlgorithm(v, s, true) { 1845 return false 1846 } 1847 } 1848 return true 1849 }) 1850 } 1851 1852 func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool { 1853 return slices.Contains(supportedSignatureAlgorithms, sigAlg) 1854 } 1855 1856 // CertificateVerificationError is returned when certificate verification fails during the handshake. 1857 type CertificateVerificationError struct { 1858 // UnverifiedCertificates and its contents should not be modified. 1859 UnverifiedCertificates []*x509.Certificate 1860 Err error 1861 } 1862 1863 func (e *CertificateVerificationError) Error() string { 1864 return fmt.Sprintf("tls: failed to verify certificate: %s", e.Err) 1865 } 1866 1867 func (e *CertificateVerificationError) Unwrap() error { 1868 return e.Err 1869 } 1870 1871 // fipsAllowedChains returns chains that are allowed to be used in a TLS connection 1872 // based on the current fips140tls enforcement setting. 1873 // 1874 // If fips140tls is not required, the chains are returned as-is with no processing. 1875 // Otherwise, the returned chains are filtered to only those allowed by FIPS 140-3. 1876 // If this results in no chains it returns an error. 1877 func fipsAllowedChains(chains [][]*x509.Certificate) ([][]*x509.Certificate, error) { 1878 if !fips140tls.Required() { 1879 return chains, nil 1880 } 1881 1882 permittedChains := make([][]*x509.Certificate, 0, len(chains)) 1883 for _, chain := range chains { 1884 if fipsAllowChain(chain) { 1885 permittedChains = append(permittedChains, chain) 1886 } 1887 } 1888 1889 if len(permittedChains) == 0 { 1890 return nil, errors.New("tls: no FIPS compatible certificate chains found") 1891 } 1892 1893 return permittedChains, nil 1894 } 1895 1896 func fipsAllowChain(chain []*x509.Certificate) bool { 1897 if len(chain) == 0 { 1898 return false 1899 } 1900 1901 for _, cert := range chain { 1902 if !isCertificateAllowedFIPS(cert) { 1903 return false 1904 } 1905 } 1906 1907 return true 1908 } 1909 1910 // anyValidVerifiedChain reports if at least one of the chains in verifiedChains 1911 // is valid, as indicated by none of the certificates being expired and the root 1912 // being in opts.Roots (or in the system root pool if opts.Roots is nil). If 1913 // verifiedChains is empty, it returns false. 1914 func anyValidVerifiedChain(verifiedChains [][]*x509.Certificate, opts x509.VerifyOptions) bool { 1915 for _, chain := range verifiedChains { 1916 if len(chain) == 0 { 1917 continue 1918 } 1919 if slices.ContainsFunc(chain, func(cert *x509.Certificate) bool { 1920 return opts.CurrentTime.Before(cert.NotBefore) || opts.CurrentTime.After(cert.NotAfter) 1921 }) { 1922 continue 1923 } 1924 // Since we already validated the chain, we only care that it is rooted 1925 // in a CA in opts.Roots. On platforms where we control chain validation 1926 // (e.g. not Windows or macOS) this is a simple lookup in the CertPool 1927 // internal hash map, which we can simulate by running Verify on the 1928 // root. On other platforms, we have to do full verification again, 1929 // because EKU handling might differ. We will want to replace this with 1930 // CertPool.Contains if/once that is available. See go.dev/issue/77376. 1931 if runtime.GOOS == "windows" || runtime.GOOS == "darwin" || runtime.GOOS == "ios" { 1932 opts.Intermediates = x509.NewCertPool() 1933 for _, cert := range chain[1:max(1, len(chain)-1)] { 1934 opts.Intermediates.AddCert(cert) 1935 } 1936 leaf := chain[0] 1937 if _, err := leaf.Verify(opts); err == nil { 1938 return true 1939 } 1940 } else { 1941 root := chain[len(chain)-1] 1942 if _, err := root.Verify(opts); err == nil { 1943 return true 1944 } 1945 } 1946 } 1947 return false 1948 } 1949