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