github.com/mangodowner/go-gm@v0.0.0-20180818020936-8baa2bd4408c/src/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 "container/list" 9 "crypto" 10 "crypto/internal/cipherhw" 11 "crypto/rand" 12 "crypto/sha512" 13 "errors" 14 "fmt" 15 "io" 16 "math/big" 17 "net" 18 "strings" 19 "sync" 20 "time" 21 "crypto/sm2" 22 ) 23 24 const ( 25 VersionSSL30 = 0x0300 26 VersionTLS10 = 0x0301 27 VersionTLS11 = 0x0302 28 VersionTLS12 = 0x0303 29 ) 30 31 const ( 32 maxPlaintext = 16384 // maximum plaintext payload length 33 maxCiphertext = 16384 + 2048 // maximum ciphertext payload length 34 recordHeaderLen = 5 // record header length 35 maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB) 36 37 minVersion = VersionTLS10 38 maxVersion = VersionTLS12 39 ) 40 41 // TLS record types. 42 type recordType uint8 43 44 const ( 45 recordTypeChangeCipherSpec recordType = 20 46 recordTypeAlert recordType = 21 47 recordTypeHandshake recordType = 22 48 recordTypeApplicationData recordType = 23 49 ) 50 51 // TLS handshake message types. 52 const ( 53 typeHelloRequest uint8 = 0 54 typeClientHello uint8 = 1 55 typeServerHello uint8 = 2 56 typeNewSessionTicket uint8 = 4 57 typeCertificate uint8 = 11 58 typeServerKeyExchange uint8 = 12 59 typeCertificateRequest uint8 = 13 60 typeServerHelloDone uint8 = 14 61 typeCertificateVerify uint8 = 15 62 typeClientKeyExchange uint8 = 16 63 typeFinished uint8 = 20 64 typeCertificateStatus uint8 = 22 65 typeNextProtocol uint8 = 67 // Not IANA assigned 66 ) 67 68 // TLS compression types. 69 const ( 70 compressionNone uint8 = 0 71 ) 72 73 // TLS extension numbers 74 const ( 75 extensionServerName uint16 = 0 76 extensionStatusRequest uint16 = 5 77 extensionSupportedCurves uint16 = 10 78 extensionSupportedPoints uint16 = 11 79 extensionSignatureAlgorithms uint16 = 13 80 extensionALPN uint16 = 16 81 extensionSCT uint16 = 18 // https://tools.ietf.org/html/rfc6962#section-6 82 extensionSessionTicket uint16 = 35 83 extensionNextProtoNeg uint16 = 13172 // not IANA assigned 84 extensionRenegotiationInfo uint16 = 0xff01 85 ) 86 87 // TLS signaling cipher suite values 88 const ( 89 scsvRenegotiation uint16 = 0x00ff 90 ) 91 92 // CurveID is the type of a TLS identifier for an elliptic curve. See 93 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8 94 type CurveID uint16 95 96 const ( 97 CurveP256 CurveID = 23 98 CurveP384 CurveID = 24 99 CurveP521 CurveID = 25 100 X25519 CurveID = 29 101 CureP256SM2 CurveID = 31 102 ) 103 104 // TLS Elliptic Curve Point Formats 105 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9 106 const ( 107 pointFormatUncompressed uint8 = 0 108 ) 109 110 // TLS CertificateStatusType (RFC 3546) 111 const ( 112 statusTypeOCSP uint8 = 1 113 ) 114 115 // Certificate types (for certificateRequestMsg) 116 const ( 117 certTypeRSASign = 1 // A certificate containing an RSA key 118 certTypeDSSSign = 2 // A certificate containing a DSA key 119 certTypeRSAFixedDH = 3 // A certificate containing a static DH key 120 certTypeDSSFixedDH = 4 // A certificate containing a static DH key 121 122 // See RFC 4492 sections 3 and 5.5. 123 certTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA. 124 certTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA. 125 certTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA. 126 127 // Rest of these are reserved by the TLS spec 128 ) 129 130 // Hash functions for TLS 1.2 (See RFC 5246, section A.4.1) 131 const ( 132 hashSHA1 uint8 = 2 133 hashSHA256 uint8 = 4 134 hashSHA384 uint8 = 5 135 ) 136 137 // Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1) 138 const ( 139 signatureRSA uint8 = 1 140 signatureECDSA uint8 = 3 141 ) 142 143 // signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See 144 // RFC 5246, section A.4.1. 145 type signatureAndHash struct { 146 hash, signature uint8 147 } 148 149 // supportedSignatureAlgorithms contains the signature and hash algorithms that 150 // the code advertises as supported in a TLS 1.2 ClientHello and in a TLS 1.2 151 // CertificateRequest. 152 var supportedSignatureAlgorithms = []signatureAndHash{ 153 {hashSHA256, signatureRSA}, 154 {hashSHA256, signatureECDSA}, 155 {hashSHA384, signatureRSA}, 156 {hashSHA384, signatureECDSA}, 157 {hashSHA1, signatureRSA}, 158 {hashSHA1, signatureECDSA}, 159 } 160 161 // ConnectionState records basic TLS details about the connection. 162 type ConnectionState struct { 163 Version uint16 // TLS version used by the connection (e.g. VersionTLS12) 164 HandshakeComplete bool // TLS handshake is complete 165 DidResume bool // connection resumes a previous TLS connection 166 CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...) 167 NegotiatedProtocol string // negotiated next protocol (not guaranteed to be from Config.NextProtos) 168 NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server (client side only) 169 ServerName string // server name requested by client, if any (server side only) 170 PeerCertificates []*sm2.Certificate // certificate chain presented by remote peer 171 VerifiedChains [][]*sm2.Certificate // verified chains built from PeerCertificates 172 SignedCertificateTimestamps [][]byte // SCTs from the server, if any 173 OCSPResponse []byte // stapled OCSP response from server, if any 174 175 // TLSUnique contains the "tls-unique" channel binding value (see RFC 176 // 5929, section 3). For resumed sessions this value will be nil 177 // because resumption does not include enough context (see 178 // https://mitls.org/pages/attacks/3SHAKE#channelbindings). This will 179 // change in future versions of Go once the TLS master-secret fix has 180 // been standardized and implemented. 181 TLSUnique []byte 182 } 183 184 // ClientAuthType declares the policy the server will follow for 185 // TLS Client Authentication. 186 type ClientAuthType int 187 188 const ( 189 NoClientCert ClientAuthType = iota 190 RequestClientCert 191 RequireAnyClientCert 192 VerifyClientCertIfGiven 193 RequireAndVerifyClientCert 194 ) 195 196 // ClientSessionState contains the state needed by clients to resume TLS 197 // sessions. 198 type ClientSessionState struct { 199 sessionTicket []uint8 // Encrypted ticket used for session resumption with server 200 vers uint16 // SSL/TLS version negotiated for the session 201 cipherSuite uint16 // Ciphersuite negotiated for the session 202 masterSecret []byte // MasterSecret generated by client on a full handshake 203 serverCertificates []*sm2.Certificate // Certificate chain presented by the server 204 verifiedChains [][]*sm2.Certificate // Certificate chains we built for verification 205 } 206 207 // ClientSessionCache is a cache of ClientSessionState objects that can be used 208 // by a client to resume a TLS session with a given server. ClientSessionCache 209 // implementations should expect to be called concurrently from different 210 // goroutines. Only ticket-based resumption is supported, not SessionID-based 211 // resumption. 212 type ClientSessionCache interface { 213 // Get searches for a ClientSessionState associated with the given key. 214 // On return, ok is true if one was found. 215 Get(sessionKey string) (session *ClientSessionState, ok bool) 216 217 // Put adds the ClientSessionState to the cache with the given key. 218 Put(sessionKey string, cs *ClientSessionState) 219 } 220 221 // SignatureScheme identifies a signature algorithm supported by TLS. See 222 // https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.3. 223 type SignatureScheme uint16 224 225 const ( 226 PKCS1WithSHA1 SignatureScheme = 0x0201 227 PKCS1WithSHA256 SignatureScheme = 0x0401 228 PKCS1WithSHA384 SignatureScheme = 0x0501 229 PKCS1WithSHA512 SignatureScheme = 0x0601 230 231 PSSWithSHA256 SignatureScheme = 0x0804 232 PSSWithSHA384 SignatureScheme = 0x0805 233 PSSWithSHA512 SignatureScheme = 0x0806 234 235 ECDSAWithP256AndSHA256 SignatureScheme = 0x0403 236 ECDSAWithP384AndSHA384 SignatureScheme = 0x0503 237 ECDSAWithP521AndSHA512 SignatureScheme = 0x0603 238 ) 239 240 // ClientHelloInfo contains information from a ClientHello message in order to 241 // guide certificate selection in the GetCertificate callback. 242 type ClientHelloInfo struct { 243 // CipherSuites lists the CipherSuites supported by the client (e.g. 244 // TLS_RSA_WITH_RC4_128_SHA). 245 CipherSuites []uint16 246 247 // ServerName indicates the name of the server requested by the client 248 // in order to support virtual hosting. ServerName is only set if the 249 // client is using SNI (see 250 // http://tools.ietf.org/html/rfc4366#section-3.1). 251 ServerName string 252 253 // SupportedCurves lists the elliptic curves supported by the client. 254 // SupportedCurves is set only if the Supported Elliptic Curves 255 // Extension is being used (see 256 // http://tools.ietf.org/html/rfc4492#section-5.1.1). 257 SupportedCurves []CurveID 258 259 // SupportedPoints lists the point formats supported by the client. 260 // SupportedPoints is set only if the Supported Point Formats Extension 261 // is being used (see 262 // http://tools.ietf.org/html/rfc4492#section-5.1.2). 263 SupportedPoints []uint8 264 265 // SignatureSchemes lists the signature and hash schemes that the client 266 // is willing to verify. SignatureSchemes is set only if the Signature 267 // Algorithms Extension is being used (see 268 // https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1). 269 SignatureSchemes []SignatureScheme 270 271 // SupportedProtos lists the application protocols supported by the client. 272 // SupportedProtos is set only if the Application-Layer Protocol 273 // Negotiation Extension is being used (see 274 // https://tools.ietf.org/html/rfc7301#section-3.1). 275 // 276 // Servers can select a protocol by setting Config.NextProtos in a 277 // GetConfigForClient return value. 278 SupportedProtos []string 279 280 // SupportedVersions lists the TLS versions supported by the client. 281 // For TLS versions less than 1.3, this is extrapolated from the max 282 // version advertised by the client, so values other than the greatest 283 // might be rejected if used. 284 SupportedVersions []uint16 285 286 // Conn is the underlying net.Conn for the connection. Do not read 287 // from, or write to, this connection; that will cause the TLS 288 // connection to fail. 289 Conn net.Conn 290 } 291 292 // CertificateRequestInfo contains information from a server's 293 // CertificateRequest message, which is used to demand a certificate and proof 294 // of control from a client. 295 type CertificateRequestInfo struct { 296 // AcceptableCAs contains zero or more, DER-encoded, X.501 297 // Distinguished Names. These are the names of root or intermediate CAs 298 // that the server wishes the returned certificate to be signed by. An 299 // empty slice indicates that the server has no preference. 300 AcceptableCAs [][]byte 301 302 // SignatureSchemes lists the signature schemes that the server is 303 // willing to verify. 304 SignatureSchemes []SignatureScheme 305 } 306 307 // RenegotiationSupport enumerates the different levels of support for TLS 308 // renegotiation. TLS renegotiation is the act of performing subsequent 309 // handshakes on a connection after the first. This significantly complicates 310 // the state machine and has been the source of numerous, subtle security 311 // issues. Initiating a renegotiation is not supported, but support for 312 // accepting renegotiation requests may be enabled. 313 // 314 // Even when enabled, the server may not change its identity between handshakes 315 // (i.e. the leaf certificate must be the same). Additionally, concurrent 316 // handshake and application data flow is not permitted so renegotiation can 317 // only be used with protocols that synchronise with the renegotiation, such as 318 // HTTPS. 319 type RenegotiationSupport int 320 321 const ( 322 // RenegotiateNever disables renegotiation. 323 RenegotiateNever RenegotiationSupport = iota 324 325 // RenegotiateOnceAsClient allows a remote server to request 326 // renegotiation once per connection. 327 RenegotiateOnceAsClient 328 329 // RenegotiateFreelyAsClient allows a remote server to repeatedly 330 // request renegotiation. 331 RenegotiateFreelyAsClient 332 ) 333 334 // A Config structure is used to configure a TLS client or server. 335 // After one has been passed to a TLS function it must not be 336 // modified. A Config may be reused; the tls package will also not 337 // modify it. 338 type Config struct { 339 // Rand provides the source of entropy for nonces and RSA blinding. 340 // If Rand is nil, TLS uses the cryptographic random reader in package 341 // crypto/rand. 342 // The Reader must be safe for use by multiple goroutines. 343 Rand io.Reader 344 345 // Time returns the current time as the number of seconds since the epoch. 346 // If Time is nil, TLS uses time.Now. 347 Time func() time.Time 348 349 // Certificates contains one or more certificate chains to present to 350 // the other side of the connection. Server configurations must include 351 // at least one certificate or else set GetCertificate. Clients doing 352 // client-authentication may set either Certificates or 353 // GetClientCertificate. 354 Certificates []Certificate 355 356 // NameToCertificate maps from a certificate name to an element of 357 // Certificates. Note that a certificate name can be of the form 358 // '*.example.com' and so doesn't have to be a domain name as such. 359 // See Config.BuildNameToCertificate 360 // The nil value causes the first element of Certificates to be used 361 // for all connections. 362 NameToCertificate map[string]*Certificate 363 364 // GetCertificate returns a Certificate based on the given 365 // ClientHelloInfo. It will only be called if the client supplies SNI 366 // information or if Certificates is empty. 367 // 368 // If GetCertificate is nil or returns nil, then the certificate is 369 // retrieved from NameToCertificate. If NameToCertificate is nil, the 370 // first element of Certificates will be used. 371 GetCertificate func(*ClientHelloInfo) (*Certificate, error) 372 373 // GetClientCertificate, if not nil, is called when a server requests a 374 // certificate from a client. If set, the contents of Certificates will 375 // be ignored. 376 // 377 // If GetClientCertificate returns an error, the handshake will be 378 // aborted and that error will be returned. Otherwise 379 // GetClientCertificate must return a non-nil Certificate. If 380 // Certificate.Certificate is empty then no certificate will be sent to 381 // the server. If this is unacceptable to the server then it may abort 382 // the handshake. 383 // 384 // GetClientCertificate may be called multiple times for the same 385 // connection if renegotiation occurs or if TLS 1.3 is in use. 386 GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error) 387 388 // GetConfigForClient, if not nil, is called after a ClientHello is 389 // received from a client. It may return a non-nil Config in order to 390 // change the Config that will be used to handle this connection. If 391 // the returned Config is nil, the original Config will be used. The 392 // Config returned by this callback may not be subsequently modified. 393 // 394 // If GetConfigForClient is nil, the Config passed to Server() will be 395 // used for all connections. 396 // 397 // Uniquely for the fields in the returned Config, session ticket keys 398 // will be duplicated from the original Config if not set. 399 // Specifically, if SetSessionTicketKeys was called on the original 400 // config but not on the returned config then the ticket keys from the 401 // original config will be copied into the new config before use. 402 // Otherwise, if SessionTicketKey was set in the original config but 403 // not in the returned config then it will be copied into the returned 404 // config before use. If neither of those cases applies then the key 405 // material from the returned config will be used for session tickets. 406 GetConfigForClient func(*ClientHelloInfo) (*Config, error) 407 408 // VerifyPeerCertificate, if not nil, is called after normal 409 // certificate verification by either a TLS client or server. It 410 // receives the raw ASN.1 certificates provided by the peer and also 411 // any verified chains that normal processing found. If it returns a 412 // non-nil error, the handshake is aborted and that error results. 413 // 414 // If normal verification fails then the handshake will abort before 415 // considering this callback. If normal verification is disabled by 416 // setting InsecureSkipVerify then this callback will be considered but 417 // the verifiedChains argument will always be nil. 418 VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*sm2.Certificate) error 419 420 // RootCAs defines the set of root certificate authorities 421 // that clients use when verifying server certificates. 422 // If RootCAs is nil, TLS uses the host's root CA set. 423 RootCAs *sm2.CertPool 424 425 // NextProtos is a list of supported, application level protocols. 426 NextProtos []string 427 428 // ServerName is used to verify the hostname on the returned 429 // certificates unless InsecureSkipVerify is given. It is also included 430 // in the client's handshake to support virtual hosting unless it is 431 // an IP address. 432 ServerName string 433 434 // ClientAuth determines the server's policy for 435 // TLS Client Authentication. The default is NoClientCert. 436 ClientAuth ClientAuthType 437 438 // ClientCAs defines the set of root certificate authorities 439 // that servers use if required to verify a client certificate 440 // by the policy in ClientAuth. 441 ClientCAs *sm2.CertPool 442 443 // InsecureSkipVerify controls whether a client verifies the 444 // server's certificate chain and host name. 445 // If InsecureSkipVerify is true, TLS accepts any certificate 446 // presented by the server and any host name in that certificate. 447 // In this mode, TLS is susceptible to man-in-the-middle attacks. 448 // This should be used only for testing. 449 InsecureSkipVerify bool 450 451 // CipherSuites is a list of supported cipher suites. If CipherSuites 452 // is nil, TLS uses a list of suites supported by the implementation. 453 CipherSuites []uint16 454 455 // PreferServerCipherSuites controls whether the server selects the 456 // client's most preferred ciphersuite, or the server's most preferred 457 // ciphersuite. If true then the server's preference, as expressed in 458 // the order of elements in CipherSuites, is used. 459 PreferServerCipherSuites bool 460 461 // SessionTicketsDisabled may be set to true to disable session ticket 462 // (resumption) support. 463 SessionTicketsDisabled bool 464 465 // SessionTicketKey is used by TLS servers to provide session 466 // resumption. See RFC 5077. If zero, it will be filled with 467 // random data before the first server handshake. 468 // 469 // If multiple servers are terminating connections for the same host 470 // they should all have the same SessionTicketKey. If the 471 // SessionTicketKey leaks, previously recorded and future TLS 472 // connections using that key are compromised. 473 SessionTicketKey [32]byte 474 475 // SessionCache is a cache of ClientSessionState entries for TLS session 476 // resumption. 477 ClientSessionCache ClientSessionCache 478 479 // MinVersion contains the minimum SSL/TLS version that is acceptable. 480 // If zero, then TLS 1.0 is taken as the minimum. 481 MinVersion uint16 482 483 // MaxVersion contains the maximum SSL/TLS version that is acceptable. 484 // If zero, then the maximum version supported by this package is used, 485 // which is currently TLS 1.2. 486 MaxVersion uint16 487 488 // CurvePreferences contains the elliptic curves that will be used in 489 // an ECDHE handshake, in preference order. If empty, the default will 490 // be used. 491 CurvePreferences []CurveID 492 493 // DynamicRecordSizingDisabled disables adaptive sizing of TLS records. 494 // When true, the largest possible TLS record size is always used. When 495 // false, the size of TLS records may be adjusted in an attempt to 496 // improve latency. 497 DynamicRecordSizingDisabled bool 498 499 // Renegotiation controls what types of renegotiation are supported. 500 // The default, none, is correct for the vast majority of applications. 501 Renegotiation RenegotiationSupport 502 503 // KeyLogWriter optionally specifies a destination for TLS master secrets 504 // in NSS key log format that can be used to allow external programs 505 // such as Wireshark to decrypt TLS connections. 506 // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format. 507 // Use of KeyLogWriter compromises security and should only be 508 // used for debugging. 509 KeyLogWriter io.Writer 510 511 serverInitOnce sync.Once // guards calling (*Config).serverInit 512 513 // mutex protects sessionTicketKeys. 514 mutex sync.RWMutex 515 // sessionTicketKeys contains zero or more ticket keys. If the length 516 // is zero, SessionTicketsDisabled must be true. The first key is used 517 // for new tickets and any subsequent keys can be used to decrypt old 518 // tickets. 519 sessionTicketKeys []ticketKey 520 } 521 522 // ticketKeyNameLen is the number of bytes of identifier that is prepended to 523 // an encrypted session ticket in order to identify the key used to encrypt it. 524 const ticketKeyNameLen = 16 525 526 // ticketKey is the internal representation of a session ticket key. 527 type ticketKey struct { 528 // keyName is an opaque byte string that serves to identify the session 529 // ticket key. It's exposed as plaintext in every session ticket. 530 keyName [ticketKeyNameLen]byte 531 aesKey [16]byte 532 hmacKey [16]byte 533 } 534 535 // ticketKeyFromBytes converts from the external representation of a session 536 // ticket key to a ticketKey. Externally, session ticket keys are 32 random 537 // bytes and this function expands that into sufficient name and key material. 538 func ticketKeyFromBytes(b [32]byte) (key ticketKey) { 539 hashed := sha512.Sum512(b[:]) 540 copy(key.keyName[:], hashed[:ticketKeyNameLen]) 541 copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16]) 542 copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32]) 543 return key 544 } 545 546 // Clone returns a shallow clone of c. It is safe to clone a Config that is 547 // being used concurrently by a TLS client or server. 548 func (c *Config) Clone() *Config { 549 // Running serverInit ensures that it's safe to read 550 // SessionTicketsDisabled. 551 c.serverInitOnce.Do(func() { c.serverInit(nil) }) 552 553 var sessionTicketKeys []ticketKey 554 c.mutex.RLock() 555 sessionTicketKeys = c.sessionTicketKeys 556 c.mutex.RUnlock() 557 558 return &Config{ 559 Rand: c.Rand, 560 Time: c.Time, 561 Certificates: c.Certificates, 562 NameToCertificate: c.NameToCertificate, 563 GetCertificate: c.GetCertificate, 564 GetClientCertificate: c.GetClientCertificate, 565 GetConfigForClient: c.GetConfigForClient, 566 VerifyPeerCertificate: c.VerifyPeerCertificate, 567 RootCAs: c.RootCAs, 568 NextProtos: c.NextProtos, 569 ServerName: c.ServerName, 570 ClientAuth: c.ClientAuth, 571 ClientCAs: c.ClientCAs, 572 InsecureSkipVerify: c.InsecureSkipVerify, 573 CipherSuites: c.CipherSuites, 574 PreferServerCipherSuites: c.PreferServerCipherSuites, 575 SessionTicketsDisabled: c.SessionTicketsDisabled, 576 SessionTicketKey: c.SessionTicketKey, 577 ClientSessionCache: c.ClientSessionCache, 578 MinVersion: c.MinVersion, 579 MaxVersion: c.MaxVersion, 580 CurvePreferences: c.CurvePreferences, 581 DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled, 582 Renegotiation: c.Renegotiation, 583 KeyLogWriter: c.KeyLogWriter, 584 sessionTicketKeys: sessionTicketKeys, 585 } 586 } 587 588 // serverInit is run under c.serverInitOnce to do initialization of c. If c was 589 // returned by a GetConfigForClient callback then the argument should be the 590 // Config that was passed to Server, otherwise it should be nil. 591 func (c *Config) serverInit(originalConfig *Config) { 592 if c.SessionTicketsDisabled || len(c.ticketKeys()) != 0 { 593 return 594 } 595 596 alreadySet := false 597 for _, b := range c.SessionTicketKey { 598 if b != 0 { 599 alreadySet = true 600 break 601 } 602 } 603 604 if !alreadySet { 605 if originalConfig != nil { 606 copy(c.SessionTicketKey[:], originalConfig.SessionTicketKey[:]) 607 } else if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil { 608 c.SessionTicketsDisabled = true 609 return 610 } 611 } 612 613 if originalConfig != nil { 614 originalConfig.mutex.RLock() 615 c.sessionTicketKeys = originalConfig.sessionTicketKeys 616 originalConfig.mutex.RUnlock() 617 } else { 618 c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)} 619 } 620 } 621 622 func (c *Config) ticketKeys() []ticketKey { 623 c.mutex.RLock() 624 // c.sessionTicketKeys is constant once created. SetSessionTicketKeys 625 // will only update it by replacing it with a new value. 626 ret := c.sessionTicketKeys 627 c.mutex.RUnlock() 628 return ret 629 } 630 631 // SetSessionTicketKeys updates the session ticket keys for a server. The first 632 // key will be used when creating new tickets, while all keys can be used for 633 // decrypting tickets. It is safe to call this function while the server is 634 // running in order to rotate the session ticket keys. The function will panic 635 // if keys is empty. 636 func (c *Config) SetSessionTicketKeys(keys [][32]byte) { 637 if len(keys) == 0 { 638 panic("tls: keys must have at least one key") 639 } 640 641 newKeys := make([]ticketKey, len(keys)) 642 for i, bytes := range keys { 643 newKeys[i] = ticketKeyFromBytes(bytes) 644 } 645 646 c.mutex.Lock() 647 c.sessionTicketKeys = newKeys 648 c.mutex.Unlock() 649 } 650 651 func (c *Config) rand() io.Reader { 652 r := c.Rand 653 if r == nil { 654 return rand.Reader 655 } 656 return r 657 } 658 659 func (c *Config) time() time.Time { 660 t := c.Time 661 if t == nil { 662 t = time.Now 663 } 664 return t() 665 } 666 667 func (c *Config) cipherSuites() []uint16 { 668 s := c.CipherSuites 669 if s == nil { 670 s = defaultCipherSuites() 671 } 672 return s 673 } 674 675 func (c *Config) minVersion() uint16 { 676 if c == nil || c.MinVersion == 0 { 677 return minVersion 678 } 679 return c.MinVersion 680 } 681 682 func (c *Config) maxVersion() uint16 { 683 if c == nil || c.MaxVersion == 0 { 684 return maxVersion 685 } 686 return c.MaxVersion 687 } 688 689 var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521} 690 691 func (c *Config) curvePreferences() []CurveID { 692 if c == nil || len(c.CurvePreferences) == 0 { 693 return defaultCurvePreferences 694 } 695 return c.CurvePreferences 696 } 697 698 // mutualVersion returns the protocol version to use given the advertised 699 // version of the peer. 700 func (c *Config) mutualVersion(vers uint16) (uint16, bool) { 701 minVersion := c.minVersion() 702 maxVersion := c.maxVersion() 703 704 if vers < minVersion { 705 return 0, false 706 } 707 if vers > maxVersion { 708 vers = maxVersion 709 } 710 return vers, true 711 } 712 713 // getCertificate returns the best certificate for the given ClientHelloInfo, 714 // defaulting to the first element of c.Certificates. 715 func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) { 716 if c.GetCertificate != nil && 717 (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) { 718 cert, err := c.GetCertificate(clientHello) 719 if cert != nil || err != nil { 720 return cert, err 721 } 722 } 723 724 if len(c.Certificates) == 0 { 725 return nil, errors.New("tls: no certificates configured") 726 } 727 728 if len(c.Certificates) == 1 || c.NameToCertificate == nil { 729 // There's only one choice, so no point doing any work. 730 return &c.Certificates[0], nil 731 } 732 733 name := strings.ToLower(clientHello.ServerName) 734 for len(name) > 0 && name[len(name)-1] == '.' { 735 name = name[:len(name)-1] 736 } 737 738 if cert, ok := c.NameToCertificate[name]; ok { 739 return cert, nil 740 } 741 742 // try replacing labels in the name with wildcards until we get a 743 // match. 744 labels := strings.Split(name, ".") 745 for i := range labels { 746 labels[i] = "*" 747 candidate := strings.Join(labels, ".") 748 if cert, ok := c.NameToCertificate[candidate]; ok { 749 return cert, nil 750 } 751 } 752 753 // If nothing matches, return the first certificate. 754 return &c.Certificates[0], nil 755 } 756 757 // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate 758 // from the CommonName and SubjectAlternateName fields of each of the leaf 759 // certificates. 760 func (c *Config) BuildNameToCertificate() { 761 c.NameToCertificate = make(map[string]*Certificate) 762 for i := range c.Certificates { 763 cert := &c.Certificates[i] 764 x509Cert, err := sm2.ParseCertificate(cert.Certificate[0]) 765 if err != nil { 766 continue 767 } 768 if len(x509Cert.Subject.CommonName) > 0 { 769 c.NameToCertificate[x509Cert.Subject.CommonName] = cert 770 } 771 for _, san := range x509Cert.DNSNames { 772 c.NameToCertificate[san] = cert 773 } 774 } 775 } 776 777 // writeKeyLog logs client random and master secret if logging was enabled by 778 // setting c.KeyLogWriter. 779 func (c *Config) writeKeyLog(clientRandom, masterSecret []byte) error { 780 if c.KeyLogWriter == nil { 781 return nil 782 } 783 784 logLine := []byte(fmt.Sprintf("CLIENT_RANDOM %x %x\n", clientRandom, masterSecret)) 785 786 writerMutex.Lock() 787 _, err := c.KeyLogWriter.Write(logLine) 788 writerMutex.Unlock() 789 790 return err 791 } 792 793 // writerMutex protects all KeyLogWriters globally. It is rarely enabled, 794 // and is only for debugging, so a global mutex saves space. 795 var writerMutex sync.Mutex 796 797 // A Certificate is a chain of one or more certificates, leaf first. 798 type Certificate struct { 799 Certificate [][]byte 800 // PrivateKey contains the private key corresponding to the public key 801 // in Leaf. For a server, this must implement crypto.Signer and/or 802 // crypto.Decrypter, with an RSA or ECDSA PublicKey. For a client 803 // (performing client authentication), this must be a crypto.Signer 804 // with an RSA or ECDSA PublicKey. 805 PrivateKey crypto.PrivateKey 806 // OCSPStaple contains an optional OCSP response which will be served 807 // to clients that request it. 808 OCSPStaple []byte 809 // SignedCertificateTimestamps contains an optional list of Signed 810 // Certificate Timestamps which will be served to clients that request it. 811 SignedCertificateTimestamps [][]byte 812 // Leaf is the parsed form of the leaf certificate, which may be 813 // initialized using x509.ParseCertificate to reduce per-handshake 814 // processing for TLS clients doing client authentication. If nil, the 815 // leaf certificate will be parsed as needed. 816 Leaf *sm2.Certificate 817 } 818 819 type handshakeMessage interface { 820 marshal() []byte 821 unmarshal([]byte) bool 822 } 823 824 // lruSessionCache is a ClientSessionCache implementation that uses an LRU 825 // caching strategy. 826 type lruSessionCache struct { 827 sync.Mutex 828 829 m map[string]*list.Element 830 q *list.List 831 capacity int 832 } 833 834 type lruSessionCacheEntry struct { 835 sessionKey string 836 state *ClientSessionState 837 } 838 839 // NewLRUClientSessionCache returns a ClientSessionCache with the given 840 // capacity that uses an LRU strategy. If capacity is < 1, a default capacity 841 // is used instead. 842 func NewLRUClientSessionCache(capacity int) ClientSessionCache { 843 const defaultSessionCacheCapacity = 64 844 845 if capacity < 1 { 846 capacity = defaultSessionCacheCapacity 847 } 848 return &lruSessionCache{ 849 m: make(map[string]*list.Element), 850 q: list.New(), 851 capacity: capacity, 852 } 853 } 854 855 // Put adds the provided (sessionKey, cs) pair to the cache. 856 func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) { 857 c.Lock() 858 defer c.Unlock() 859 860 if elem, ok := c.m[sessionKey]; ok { 861 entry := elem.Value.(*lruSessionCacheEntry) 862 entry.state = cs 863 c.q.MoveToFront(elem) 864 return 865 } 866 867 if c.q.Len() < c.capacity { 868 entry := &lruSessionCacheEntry{sessionKey, cs} 869 c.m[sessionKey] = c.q.PushFront(entry) 870 return 871 } 872 873 elem := c.q.Back() 874 entry := elem.Value.(*lruSessionCacheEntry) 875 delete(c.m, entry.sessionKey) 876 entry.sessionKey = sessionKey 877 entry.state = cs 878 c.q.MoveToFront(elem) 879 c.m[sessionKey] = elem 880 } 881 882 // Get returns the ClientSessionState value associated with a given key. It 883 // returns (nil, false) if no value is found. 884 func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) { 885 c.Lock() 886 defer c.Unlock() 887 888 if elem, ok := c.m[sessionKey]; ok { 889 c.q.MoveToFront(elem) 890 return elem.Value.(*lruSessionCacheEntry).state, true 891 } 892 return nil, false 893 } 894 895 // TODO(jsing): Make these available to both crypto/x509 and crypto/tls. 896 type dsaSignature struct { 897 R, S *big.Int 898 } 899 900 type ecdsaSignature dsaSignature 901 902 var emptyConfig Config 903 904 func defaultConfig() *Config { 905 return &emptyConfig 906 } 907 908 var ( 909 once sync.Once 910 varDefaultCipherSuites []uint16 911 ) 912 913 func defaultCipherSuites() []uint16 { 914 once.Do(initDefaultCipherSuites) 915 return varDefaultCipherSuites 916 } 917 918 func initDefaultCipherSuites() { 919 var topCipherSuites []uint16 920 if cipherhw.AESGCMSupport() { 921 // If AES-GCM hardware is provided then prioritise AES-GCM 922 // cipher suites. 923 topCipherSuites = []uint16{ 924 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 925 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 926 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 927 TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 928 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 929 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, 930 } 931 } else { 932 // Without AES-GCM hardware, we put the ChaCha20-Poly1305 933 // cipher suites first. 934 topCipherSuites = []uint16{ 935 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 936 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, 937 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 938 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 939 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 940 TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 941 } 942 } 943 944 varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites)) 945 varDefaultCipherSuites = append(varDefaultCipherSuites, topCipherSuites...) 946 947 NextCipherSuite: 948 for _, suite := range cipherSuites { 949 if suite.flags&suiteDefaultOff != 0 { 950 continue 951 } 952 for _, existing := range varDefaultCipherSuites { 953 if existing == suite.id { 954 continue NextCipherSuite 955 } 956 } 957 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id) 958 } 959 } 960 961 func unexpectedMessageError(wanted, got interface{}) error { 962 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted) 963 } 964 965 func isSupportedSignatureAndHash(sigHash signatureAndHash, sigHashes []signatureAndHash) bool { 966 for _, s := range sigHashes { 967 if s == sigHash { 968 return true 969 } 970 } 971 return false 972 }