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