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