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