github.com/4ad/go@v0.0.0-20161219182952-69a12818b605/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/rand" 11 "crypto/sha512" 12 "crypto/x509" 13 "errors" 14 "fmt" 15 "io" 16 "math/big" 17 "strings" 18 "sync" 19 "time" 20 ) 21 22 const ( 23 VersionSSL30 = 0x0300 24 VersionTLS10 = 0x0301 25 VersionTLS11 = 0x0302 26 VersionTLS12 = 0x0303 27 ) 28 29 const ( 30 maxPlaintext = 16384 // maximum plaintext payload length 31 maxCiphertext = 16384 + 2048 // maximum ciphertext payload length 32 recordHeaderLen = 5 // record header length 33 maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB) 34 35 minVersion = VersionTLS10 36 maxVersion = VersionTLS12 37 ) 38 39 // TLS record types. 40 type recordType uint8 41 42 const ( 43 recordTypeChangeCipherSpec recordType = 20 44 recordTypeAlert recordType = 21 45 recordTypeHandshake recordType = 22 46 recordTypeApplicationData recordType = 23 47 ) 48 49 // TLS handshake message types. 50 const ( 51 typeHelloRequest uint8 = 0 52 typeClientHello uint8 = 1 53 typeServerHello uint8 = 2 54 typeNewSessionTicket uint8 = 4 55 typeCertificate uint8 = 11 56 typeServerKeyExchange uint8 = 12 57 typeCertificateRequest uint8 = 13 58 typeServerHelloDone uint8 = 14 59 typeCertificateVerify uint8 = 15 60 typeClientKeyExchange uint8 = 16 61 typeFinished uint8 = 20 62 typeCertificateStatus uint8 = 22 63 typeNextProtocol uint8 = 67 // Not IANA assigned 64 ) 65 66 // TLS compression types. 67 const ( 68 compressionNone uint8 = 0 69 ) 70 71 // TLS extension numbers 72 const ( 73 extensionServerName uint16 = 0 74 extensionStatusRequest uint16 = 5 75 extensionSupportedCurves uint16 = 10 76 extensionSupportedPoints uint16 = 11 77 extensionSignatureAlgorithms uint16 = 13 78 extensionALPN uint16 = 16 79 extensionSCT uint16 = 18 // https://tools.ietf.org/html/rfc6962#section-6 80 extensionSessionTicket uint16 = 35 81 extensionNextProtoNeg uint16 = 13172 // not IANA assigned 82 extensionRenegotiationInfo uint16 = 0xff01 83 ) 84 85 // TLS signaling cipher suite values 86 const ( 87 scsvRenegotiation uint16 = 0x00ff 88 ) 89 90 // CurveID is the type of a TLS identifier for an elliptic curve. See 91 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8 92 type CurveID uint16 93 94 const ( 95 CurveP256 CurveID = 23 96 CurveP384 CurveID = 24 97 CurveP521 CurveID = 25 98 ) 99 100 // TLS Elliptic Curve Point Formats 101 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9 102 const ( 103 pointFormatUncompressed uint8 = 0 104 ) 105 106 // TLS CertificateStatusType (RFC 3546) 107 const ( 108 statusTypeOCSP uint8 = 1 109 ) 110 111 // Certificate types (for certificateRequestMsg) 112 const ( 113 certTypeRSASign = 1 // A certificate containing an RSA key 114 certTypeDSSSign = 2 // A certificate containing a DSA key 115 certTypeRSAFixedDH = 3 // A certificate containing a static DH key 116 certTypeDSSFixedDH = 4 // A certificate containing a static DH key 117 118 // See RFC 4492 sections 3 and 5.5. 119 certTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA. 120 certTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA. 121 certTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA. 122 123 // Rest of these are reserved by the TLS spec 124 ) 125 126 // Hash functions for TLS 1.2 (See RFC 5246, section A.4.1) 127 const ( 128 hashSHA1 uint8 = 2 129 hashSHA256 uint8 = 4 130 hashSHA384 uint8 = 5 131 ) 132 133 // Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1) 134 const ( 135 signatureRSA uint8 = 1 136 signatureECDSA uint8 = 3 137 ) 138 139 // signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See 140 // RFC 5246, section A.4.1. 141 type signatureAndHash struct { 142 hash, signature uint8 143 } 144 145 // supportedSignatureAlgorithms contains the signature and hash algorithms that 146 // the code advertises as supported in a TLS 1.2 ClientHello and in a TLS 1.2 147 // CertificateRequest. 148 var supportedSignatureAlgorithms = []signatureAndHash{ 149 {hashSHA256, signatureRSA}, 150 {hashSHA256, signatureECDSA}, 151 {hashSHA384, signatureRSA}, 152 {hashSHA384, signatureECDSA}, 153 {hashSHA1, signatureRSA}, 154 {hashSHA1, signatureECDSA}, 155 } 156 157 // ConnectionState records basic TLS details about the connection. 158 type ConnectionState struct { 159 Version uint16 // TLS version used by the connection (e.g. VersionTLS12) 160 HandshakeComplete bool // TLS handshake is complete 161 DidResume bool // connection resumes a previous TLS connection 162 CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...) 163 NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos) 164 NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server 165 ServerName string // server name requested by client, if any (server side only) 166 PeerCertificates []*x509.Certificate // certificate chain presented by remote peer 167 VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates 168 SignedCertificateTimestamps [][]byte // SCTs from the server, if any 169 OCSPResponse []byte // stapled OCSP response from server, if any 170 171 // TLSUnique contains the "tls-unique" channel binding value (see RFC 172 // 5929, section 3). For resumed sessions this value will be nil 173 // because resumption does not include enough context (see 174 // https://secure-resumption.com/#channelbindings). This will change in 175 // future versions of Go once the TLS master-secret fix has been 176 // standardized and implemented. 177 TLSUnique []byte 178 } 179 180 // ClientAuthType declares the policy the server will follow for 181 // TLS Client Authentication. 182 type ClientAuthType int 183 184 const ( 185 NoClientCert ClientAuthType = iota 186 RequestClientCert 187 RequireAnyClientCert 188 VerifyClientCertIfGiven 189 RequireAndVerifyClientCert 190 ) 191 192 // ClientSessionState contains the state needed by clients to resume TLS 193 // sessions. 194 type ClientSessionState struct { 195 sessionTicket []uint8 // Encrypted ticket used for session resumption with server 196 vers uint16 // SSL/TLS version negotiated for the session 197 cipherSuite uint16 // Ciphersuite negotiated for the session 198 masterSecret []byte // MasterSecret generated by client on a full handshake 199 serverCertificates []*x509.Certificate // Certificate chain presented by the server 200 verifiedChains [][]*x509.Certificate // Certificate chains we built for verification 201 } 202 203 // ClientSessionCache is a cache of ClientSessionState objects that can be used 204 // by a client to resume a TLS session with a given server. ClientSessionCache 205 // implementations should expect to be called concurrently from different 206 // goroutines. 207 type ClientSessionCache interface { 208 // Get searches for a ClientSessionState associated with the given key. 209 // On return, ok is true if one was found. 210 Get(sessionKey string) (session *ClientSessionState, ok bool) 211 212 // Put adds the ClientSessionState to the cache with the given key. 213 Put(sessionKey string, cs *ClientSessionState) 214 } 215 216 // ClientHelloInfo contains information from a ClientHello message in order to 217 // guide certificate selection in the GetCertificate callback. 218 type ClientHelloInfo struct { 219 // CipherSuites lists the CipherSuites supported by the client (e.g. 220 // TLS_RSA_WITH_RC4_128_SHA). 221 CipherSuites []uint16 222 223 // ServerName indicates the name of the server requested by the client 224 // in order to support virtual hosting. ServerName is only set if the 225 // client is using SNI (see 226 // http://tools.ietf.org/html/rfc4366#section-3.1). 227 ServerName string 228 229 // SupportedCurves lists the elliptic curves supported by the client. 230 // SupportedCurves is set only if the Supported Elliptic Curves 231 // Extension is being used (see 232 // http://tools.ietf.org/html/rfc4492#section-5.1.1). 233 SupportedCurves []CurveID 234 235 // SupportedPoints lists the point formats supported by the client. 236 // SupportedPoints is set only if the Supported Point Formats Extension 237 // is being used (see 238 // http://tools.ietf.org/html/rfc4492#section-5.1.2). 239 SupportedPoints []uint8 240 } 241 242 // RenegotiationSupport enumerates the different levels of support for TLS 243 // renegotiation. TLS renegotiation is the act of performing subsequent 244 // handshakes on a connection after the first. This significantly complicates 245 // the state machine and has been the source of numerous, subtle security 246 // issues. Initiating a renegotiation is not supported, but support for 247 // accepting renegotiation requests may be enabled. 248 // 249 // Even when enabled, the server may not change its identity between handshakes 250 // (i.e. the leaf certificate must be the same). Additionally, concurrent 251 // handshake and application data flow is not permitted so renegotiation can 252 // only be used with protocols that synchronise with the renegotiation, such as 253 // HTTPS. 254 type RenegotiationSupport int 255 256 const ( 257 // RenegotiateNever disables renegotiation. 258 RenegotiateNever RenegotiationSupport = iota 259 260 // RenegotiateOnceAsClient allows a remote server to request 261 // renegotiation once per connection. 262 RenegotiateOnceAsClient 263 264 // RenegotiateFreelyAsClient allows a remote server to repeatedly 265 // request renegotiation. 266 RenegotiateFreelyAsClient 267 ) 268 269 // A Config structure is used to configure a TLS client or server. 270 // After one has been passed to a TLS function it must not be 271 // modified. A Config may be reused; the tls package will also not 272 // modify it. 273 type Config struct { 274 // Rand provides the source of entropy for nonces and RSA blinding. 275 // If Rand is nil, TLS uses the cryptographic random reader in package 276 // crypto/rand. 277 // The Reader must be safe for use by multiple goroutines. 278 Rand io.Reader 279 280 // Time returns the current time as the number of seconds since the epoch. 281 // If Time is nil, TLS uses time.Now. 282 Time func() time.Time 283 284 // Certificates contains one or more certificate chains 285 // to present to the other side of the connection. 286 // Server configurations must include at least one certificate 287 // or else set GetCertificate. 288 Certificates []Certificate 289 290 // NameToCertificate maps from a certificate name to an element of 291 // Certificates. Note that a certificate name can be of the form 292 // '*.example.com' and so doesn't have to be a domain name as such. 293 // See Config.BuildNameToCertificate 294 // The nil value causes the first element of Certificates to be used 295 // for all connections. 296 NameToCertificate map[string]*Certificate 297 298 // GetCertificate returns a Certificate based on the given 299 // ClientHelloInfo. It will only be called if the client supplies SNI 300 // information or if Certificates is empty. 301 // 302 // If GetCertificate is nil or returns nil, then the certificate is 303 // retrieved from NameToCertificate. If NameToCertificate is nil, the 304 // first element of Certificates will be used. 305 GetCertificate func(clientHello *ClientHelloInfo) (*Certificate, error) 306 307 // RootCAs defines the set of root certificate authorities 308 // that clients use when verifying server certificates. 309 // If RootCAs is nil, TLS uses the host's root CA set. 310 RootCAs *x509.CertPool 311 312 // NextProtos is a list of supported, application level protocols. 313 NextProtos []string 314 315 // ServerName is used to verify the hostname on the returned 316 // certificates unless InsecureSkipVerify is given. It is also included 317 // in the client's handshake to support virtual hosting unless it is 318 // an IP address. 319 ServerName string 320 321 // ClientAuth determines the server's policy for 322 // TLS Client Authentication. The default is NoClientCert. 323 ClientAuth ClientAuthType 324 325 // ClientCAs defines the set of root certificate authorities 326 // that servers use if required to verify a client certificate 327 // by the policy in ClientAuth. 328 ClientCAs *x509.CertPool 329 330 // InsecureSkipVerify controls whether a client verifies the 331 // server's certificate chain and host name. 332 // If InsecureSkipVerify is true, TLS accepts any certificate 333 // presented by the server and any host name in that certificate. 334 // In this mode, TLS is susceptible to man-in-the-middle attacks. 335 // This should be used only for testing. 336 InsecureSkipVerify bool 337 338 // CipherSuites is a list of supported cipher suites. If CipherSuites 339 // is nil, TLS uses a list of suites supported by the implementation. 340 CipherSuites []uint16 341 342 // PreferServerCipherSuites controls whether the server selects the 343 // client's most preferred ciphersuite, or the server's most preferred 344 // ciphersuite. If true then the server's preference, as expressed in 345 // the order of elements in CipherSuites, is used. 346 PreferServerCipherSuites bool 347 348 // SessionTicketsDisabled may be set to true to disable session ticket 349 // (resumption) support. 350 SessionTicketsDisabled bool 351 352 // SessionTicketKey is used by TLS servers to provide session 353 // resumption. See RFC 5077. If zero, it will be filled with 354 // random data before the first server handshake. 355 // 356 // If multiple servers are terminating connections for the same host 357 // they should all have the same SessionTicketKey. If the 358 // SessionTicketKey leaks, previously recorded and future TLS 359 // connections using that key are compromised. 360 SessionTicketKey [32]byte 361 362 // SessionCache is a cache of ClientSessionState entries for TLS session 363 // resumption. 364 ClientSessionCache ClientSessionCache 365 366 // MinVersion contains the minimum SSL/TLS version that is acceptable. 367 // If zero, then TLS 1.0 is taken as the minimum. 368 MinVersion uint16 369 370 // MaxVersion contains the maximum SSL/TLS version that is acceptable. 371 // If zero, then the maximum version supported by this package is used, 372 // which is currently TLS 1.2. 373 MaxVersion uint16 374 375 // CurvePreferences contains the elliptic curves that will be used in 376 // an ECDHE handshake, in preference order. If empty, the default will 377 // be used. 378 CurvePreferences []CurveID 379 380 // DynamicRecordSizingDisabled disables adaptive sizing of TLS records. 381 // When true, the largest possible TLS record size is always used. When 382 // false, the size of TLS records may be adjusted in an attempt to 383 // improve latency. 384 DynamicRecordSizingDisabled bool 385 386 // Renegotiation controls what types of renegotiation are supported. 387 // The default, none, is correct for the vast majority of applications. 388 Renegotiation RenegotiationSupport 389 390 serverInitOnce sync.Once // guards calling (*Config).serverInit 391 392 // mutex protects sessionTicketKeys 393 mutex sync.RWMutex 394 // sessionTicketKeys contains zero or more ticket keys. If the length 395 // is zero, SessionTicketsDisabled must be true. The first key is used 396 // for new tickets and any subsequent keys can be used to decrypt old 397 // tickets. 398 sessionTicketKeys []ticketKey 399 } 400 401 // ticketKeyNameLen is the number of bytes of identifier that is prepended to 402 // an encrypted session ticket in order to identify the key used to encrypt it. 403 const ticketKeyNameLen = 16 404 405 // ticketKey is the internal representation of a session ticket key. 406 type ticketKey struct { 407 // keyName is an opaque byte string that serves to identify the session 408 // ticket key. It's exposed as plaintext in every session ticket. 409 keyName [ticketKeyNameLen]byte 410 aesKey [16]byte 411 hmacKey [16]byte 412 } 413 414 // ticketKeyFromBytes converts from the external representation of a session 415 // ticket key to a ticketKey. Externally, session ticket keys are 32 random 416 // bytes and this function expands that into sufficient name and key material. 417 func ticketKeyFromBytes(b [32]byte) (key ticketKey) { 418 hashed := sha512.Sum512(b[:]) 419 copy(key.keyName[:], hashed[:ticketKeyNameLen]) 420 copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16]) 421 copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32]) 422 return key 423 } 424 425 // clone returns a copy of c. Only the exported fields are copied. 426 func (c *Config) clone() *Config { 427 return &Config{ 428 Rand: c.Rand, 429 Time: c.Time, 430 Certificates: c.Certificates, 431 NameToCertificate: c.NameToCertificate, 432 GetCertificate: c.GetCertificate, 433 RootCAs: c.RootCAs, 434 NextProtos: c.NextProtos, 435 ServerName: c.ServerName, 436 ClientAuth: c.ClientAuth, 437 ClientCAs: c.ClientCAs, 438 InsecureSkipVerify: c.InsecureSkipVerify, 439 CipherSuites: c.CipherSuites, 440 PreferServerCipherSuites: c.PreferServerCipherSuites, 441 SessionTicketsDisabled: c.SessionTicketsDisabled, 442 SessionTicketKey: c.SessionTicketKey, 443 ClientSessionCache: c.ClientSessionCache, 444 MinVersion: c.MinVersion, 445 MaxVersion: c.MaxVersion, 446 CurvePreferences: c.CurvePreferences, 447 DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled, 448 Renegotiation: c.Renegotiation, 449 } 450 } 451 452 func (c *Config) serverInit() { 453 if c.SessionTicketsDisabled { 454 return 455 } 456 457 alreadySet := false 458 for _, b := range c.SessionTicketKey { 459 if b != 0 { 460 alreadySet = true 461 break 462 } 463 } 464 465 if !alreadySet { 466 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil { 467 c.SessionTicketsDisabled = true 468 return 469 } 470 } 471 472 c.sessionTicketKeys = []ticketKey{ticketKeyFromBytes(c.SessionTicketKey)} 473 } 474 475 func (c *Config) ticketKeys() []ticketKey { 476 c.mutex.RLock() 477 // c.sessionTicketKeys is constant once created. SetSessionTicketKeys 478 // will only update it by replacing it with a new value. 479 ret := c.sessionTicketKeys 480 c.mutex.RUnlock() 481 return ret 482 } 483 484 // SetSessionTicketKeys updates the session ticket keys for a server. The first 485 // key will be used when creating new tickets, while all keys can be used for 486 // decrypting tickets. It is safe to call this function while the server is 487 // running in order to rotate the session ticket keys. The function will panic 488 // if keys is empty. 489 func (c *Config) SetSessionTicketKeys(keys [][32]byte) { 490 if len(keys) == 0 { 491 panic("tls: keys must have at least one key") 492 } 493 494 newKeys := make([]ticketKey, len(keys)) 495 for i, bytes := range keys { 496 newKeys[i] = ticketKeyFromBytes(bytes) 497 } 498 499 c.mutex.Lock() 500 c.sessionTicketKeys = newKeys 501 c.mutex.Unlock() 502 } 503 504 func (c *Config) rand() io.Reader { 505 r := c.Rand 506 if r == nil { 507 return rand.Reader 508 } 509 return r 510 } 511 512 func (c *Config) time() time.Time { 513 t := c.Time 514 if t == nil { 515 t = time.Now 516 } 517 return t() 518 } 519 520 func (c *Config) cipherSuites() []uint16 { 521 s := c.CipherSuites 522 if s == nil { 523 s = defaultCipherSuites() 524 } 525 return s 526 } 527 528 func (c *Config) minVersion() uint16 { 529 if c == nil || c.MinVersion == 0 { 530 return minVersion 531 } 532 return c.MinVersion 533 } 534 535 func (c *Config) maxVersion() uint16 { 536 if c == nil || c.MaxVersion == 0 { 537 return maxVersion 538 } 539 return c.MaxVersion 540 } 541 542 var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521} 543 544 func (c *Config) curvePreferences() []CurveID { 545 if c == nil || len(c.CurvePreferences) == 0 { 546 return defaultCurvePreferences 547 } 548 return c.CurvePreferences 549 } 550 551 // mutualVersion returns the protocol version to use given the advertised 552 // version of the peer. 553 func (c *Config) mutualVersion(vers uint16) (uint16, bool) { 554 minVersion := c.minVersion() 555 maxVersion := c.maxVersion() 556 557 if vers < minVersion { 558 return 0, false 559 } 560 if vers > maxVersion { 561 vers = maxVersion 562 } 563 return vers, true 564 } 565 566 // getCertificate returns the best certificate for the given ClientHelloInfo, 567 // defaulting to the first element of c.Certificates. 568 func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) { 569 if c.GetCertificate != nil && 570 (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) { 571 cert, err := c.GetCertificate(clientHello) 572 if cert != nil || err != nil { 573 return cert, err 574 } 575 } 576 577 if len(c.Certificates) == 0 { 578 return nil, errors.New("tls: no certificates configured") 579 } 580 581 if len(c.Certificates) == 1 || c.NameToCertificate == nil { 582 // There's only one choice, so no point doing any work. 583 return &c.Certificates[0], nil 584 } 585 586 name := strings.ToLower(clientHello.ServerName) 587 for len(name) > 0 && name[len(name)-1] == '.' { 588 name = name[:len(name)-1] 589 } 590 591 if cert, ok := c.NameToCertificate[name]; ok { 592 return cert, nil 593 } 594 595 // try replacing labels in the name with wildcards until we get a 596 // match. 597 labels := strings.Split(name, ".") 598 for i := range labels { 599 labels[i] = "*" 600 candidate := strings.Join(labels, ".") 601 if cert, ok := c.NameToCertificate[candidate]; ok { 602 return cert, nil 603 } 604 } 605 606 // If nothing matches, return the first certificate. 607 return &c.Certificates[0], nil 608 } 609 610 // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate 611 // from the CommonName and SubjectAlternateName fields of each of the leaf 612 // certificates. 613 func (c *Config) BuildNameToCertificate() { 614 c.NameToCertificate = make(map[string]*Certificate) 615 for i := range c.Certificates { 616 cert := &c.Certificates[i] 617 x509Cert, err := x509.ParseCertificate(cert.Certificate[0]) 618 if err != nil { 619 continue 620 } 621 if len(x509Cert.Subject.CommonName) > 0 { 622 c.NameToCertificate[x509Cert.Subject.CommonName] = cert 623 } 624 for _, san := range x509Cert.DNSNames { 625 c.NameToCertificate[san] = cert 626 } 627 } 628 } 629 630 // A Certificate is a chain of one or more certificates, leaf first. 631 type Certificate struct { 632 Certificate [][]byte 633 // PrivateKey contains the private key corresponding to the public key 634 // in Leaf. For a server, this must implement crypto.Signer and/or 635 // crypto.Decrypter, with an RSA or ECDSA PublicKey. For a client 636 // (performing client authentication), this must be a crypto.Signer 637 // with an RSA or ECDSA PublicKey. 638 PrivateKey crypto.PrivateKey 639 // OCSPStaple contains an optional OCSP response which will be served 640 // to clients that request it. 641 OCSPStaple []byte 642 // SignedCertificateTimestamps contains an optional list of Signed 643 // Certificate Timestamps which will be served to clients that request it. 644 SignedCertificateTimestamps [][]byte 645 // Leaf is the parsed form of the leaf certificate, which may be 646 // initialized using x509.ParseCertificate to reduce per-handshake 647 // processing for TLS clients doing client authentication. If nil, the 648 // leaf certificate will be parsed as needed. 649 Leaf *x509.Certificate 650 } 651 652 type handshakeMessage interface { 653 marshal() []byte 654 unmarshal([]byte) bool 655 } 656 657 // lruSessionCache is a ClientSessionCache implementation that uses an LRU 658 // caching strategy. 659 type lruSessionCache struct { 660 sync.Mutex 661 662 m map[string]*list.Element 663 q *list.List 664 capacity int 665 } 666 667 type lruSessionCacheEntry struct { 668 sessionKey string 669 state *ClientSessionState 670 } 671 672 // NewLRUClientSessionCache returns a ClientSessionCache with the given 673 // capacity that uses an LRU strategy. If capacity is < 1, a default capacity 674 // is used instead. 675 func NewLRUClientSessionCache(capacity int) ClientSessionCache { 676 const defaultSessionCacheCapacity = 64 677 678 if capacity < 1 { 679 capacity = defaultSessionCacheCapacity 680 } 681 return &lruSessionCache{ 682 m: make(map[string]*list.Element), 683 q: list.New(), 684 capacity: capacity, 685 } 686 } 687 688 // Put adds the provided (sessionKey, cs) pair to the cache. 689 func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) { 690 c.Lock() 691 defer c.Unlock() 692 693 if elem, ok := c.m[sessionKey]; ok { 694 entry := elem.Value.(*lruSessionCacheEntry) 695 entry.state = cs 696 c.q.MoveToFront(elem) 697 return 698 } 699 700 if c.q.Len() < c.capacity { 701 entry := &lruSessionCacheEntry{sessionKey, cs} 702 c.m[sessionKey] = c.q.PushFront(entry) 703 return 704 } 705 706 elem := c.q.Back() 707 entry := elem.Value.(*lruSessionCacheEntry) 708 delete(c.m, entry.sessionKey) 709 entry.sessionKey = sessionKey 710 entry.state = cs 711 c.q.MoveToFront(elem) 712 c.m[sessionKey] = elem 713 } 714 715 // Get returns the ClientSessionState value associated with a given key. It 716 // returns (nil, false) if no value is found. 717 func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) { 718 c.Lock() 719 defer c.Unlock() 720 721 if elem, ok := c.m[sessionKey]; ok { 722 c.q.MoveToFront(elem) 723 return elem.Value.(*lruSessionCacheEntry).state, true 724 } 725 return nil, false 726 } 727 728 // TODO(jsing): Make these available to both crypto/x509 and crypto/tls. 729 type dsaSignature struct { 730 R, S *big.Int 731 } 732 733 type ecdsaSignature dsaSignature 734 735 var emptyConfig Config 736 737 func defaultConfig() *Config { 738 return &emptyConfig 739 } 740 741 var ( 742 once sync.Once 743 varDefaultCipherSuites []uint16 744 ) 745 746 func defaultCipherSuites() []uint16 { 747 once.Do(initDefaultCipherSuites) 748 return varDefaultCipherSuites 749 } 750 751 func initDefaultCipherSuites() { 752 varDefaultCipherSuites = make([]uint16, 0, len(cipherSuites)) 753 for _, suite := range cipherSuites { 754 if suite.flags&suiteDefaultOff != 0 { 755 continue 756 } 757 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id) 758 } 759 } 760 761 func unexpectedMessageError(wanted, got interface{}) error { 762 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted) 763 } 764 765 func isSupportedSignatureAndHash(sigHash signatureAndHash, sigHashes []signatureAndHash) bool { 766 for _, s := range sigHashes { 767 if s == sigHash { 768 return true 769 } 770 } 771 return false 772 }