...
Run Format

Source file src/crypto/tls/common.go

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

View as plain text