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