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