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