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