blob: daeeb5e2b0a132ec0013e91fc5b74dff0390b890 [file] [log] [blame]
Adam Langley95c29f32014-06-20 12:00:00 -07001// 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
5package main
6
7import (
8 "container/list"
9 "crypto"
David Benjamind30a9902014-08-24 01:44:23 -040010 "crypto/ecdsa"
Adam Langley95c29f32014-06-20 12:00:00 -070011 "crypto/rand"
12 "crypto/x509"
13 "fmt"
14 "io"
15 "math/big"
16 "strings"
17 "sync"
18 "time"
19)
20
21const (
22 VersionSSL30 = 0x0300
23 VersionTLS10 = 0x0301
24 VersionTLS11 = 0x0302
25 VersionTLS12 = 0x0303
26)
27
28const (
David Benjamin83c0bc92014-08-04 01:23:53 -040029 maxPlaintext = 16384 // maximum plaintext payload length
30 maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
31 tlsRecordHeaderLen = 5 // record header length
32 dtlsRecordHeaderLen = 13
33 maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
Adam Langley95c29f32014-06-20 12:00:00 -070034
35 minVersion = VersionSSL30
36 maxVersion = VersionTLS12
37)
38
39// TLS record types.
40type recordType uint8
41
42const (
43 recordTypeChangeCipherSpec recordType = 20
44 recordTypeAlert recordType = 21
45 recordTypeHandshake recordType = 22
46 recordTypeApplicationData recordType = 23
47)
48
49// TLS handshake message types.
50const (
David Benjamind30a9902014-08-24 01:44:23 -040051 typeClientHello uint8 = 1
52 typeServerHello uint8 = 2
53 typeHelloVerifyRequest uint8 = 3
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 typeEncryptedExtensions uint8 = 203 // Not IANA assigned
Adam Langley95c29f32014-06-20 12:00:00 -070065)
66
67// TLS compression types.
68const (
69 compressionNone uint8 = 0
70)
71
72// TLS extension numbers
73const (
74 extensionServerName uint16 = 0
75 extensionStatusRequest uint16 = 5
76 extensionSupportedCurves uint16 = 10
77 extensionSupportedPoints uint16 = 11
78 extensionSignatureAlgorithms uint16 = 13
79 extensionSessionTicket uint16 = 35
80 extensionNextProtoNeg uint16 = 13172 // not IANA assigned
81 extensionRenegotiationInfo uint16 = 0xff01
David Benjamind30a9902014-08-24 01:44:23 -040082 extensionChannelID uint16 = 30032 // not IANA assigned
Adam Langley95c29f32014-06-20 12:00:00 -070083)
84
85// TLS signaling cipher suite values
86const (
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
92type CurveID uint16
93
94const (
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
102const (
103 pointFormatUncompressed uint8 = 0
104)
105
106// TLS CertificateStatusType (RFC 3546)
107const (
108 statusTypeOCSP uint8 = 1
109)
110
111// Certificate types (for certificateRequestMsg)
112const (
David Benjamin7b030512014-07-08 17:30:11 -0400113 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
Adam Langley95c29f32014-06-20 12:00:00 -0700117
118 // See RFC4492 sections 3 and 5.5.
David Benjamin7b030512014-07-08 17:30:11 -0400119 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.
Adam Langley95c29f32014-06-20 12:00:00 -0700122
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)
127const (
128 hashSHA1 uint8 = 2
129 hashSHA256 uint8 = 4
130)
131
132// Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
133const (
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.
140type signatureAndHash struct {
141 hash, signature uint8
142}
143
144// supportedSKXSignatureAlgorithms contains the signature and hash algorithms
145// that the code advertises as supported in a TLS 1.2 ClientHello.
146var supportedSKXSignatureAlgorithms = []signatureAndHash{
147 {hashSHA256, signatureRSA},
148 {hashSHA256, signatureECDSA},
149 {hashSHA1, signatureRSA},
150 {hashSHA1, signatureECDSA},
151}
152
153// supportedClientCertSignatureAlgorithms contains the signature and hash
154// algorithms that the code advertises as supported in a TLS 1.2
155// CertificateRequest.
156var supportedClientCertSignatureAlgorithms = []signatureAndHash{
157 {hashSHA256, signatureRSA},
158 {hashSHA256, signatureECDSA},
159}
160
161// ConnectionState records basic TLS details about the connection.
162type 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 (from Config.NextProtos)
168 NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server
169 ServerName string // server name requested by client, if any (server side only)
170 PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
171 VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
David Benjamind30a9902014-08-24 01:44:23 -0400172 ChannelID *ecdsa.PublicKey // the channel ID for this connection
Adam Langley95c29f32014-06-20 12:00:00 -0700173}
174
175// ClientAuthType declares the policy the server will follow for
176// TLS Client Authentication.
177type ClientAuthType int
178
179const (
180 NoClientCert ClientAuthType = iota
181 RequestClientCert
182 RequireAnyClientCert
183 VerifyClientCertIfGiven
184 RequireAndVerifyClientCert
185)
186
187// ClientSessionState contains the state needed by clients to resume TLS
188// sessions.
189type ClientSessionState struct {
190 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
191 vers uint16 // SSL/TLS version negotiated for the session
192 cipherSuite uint16 // Ciphersuite negotiated for the session
193 masterSecret []byte // MasterSecret generated by client on a full handshake
David Benjamind30a9902014-08-24 01:44:23 -0400194 handshakeHash []byte // Handshake hash for Channel ID purposes.
Adam Langley95c29f32014-06-20 12:00:00 -0700195 serverCertificates []*x509.Certificate // Certificate chain presented by the server
196}
197
198// ClientSessionCache is a cache of ClientSessionState objects that can be used
199// by a client to resume a TLS session with a given server. ClientSessionCache
200// implementations should expect to be called concurrently from different
201// goroutines.
202type ClientSessionCache interface {
203 // Get searches for a ClientSessionState associated with the given key.
204 // On return, ok is true if one was found.
205 Get(sessionKey string) (session *ClientSessionState, ok bool)
206
207 // Put adds the ClientSessionState to the cache with the given key.
208 Put(sessionKey string, cs *ClientSessionState)
209}
210
211// A Config structure is used to configure a TLS client or server.
212// After one has been passed to a TLS function it must not be
213// modified. A Config may be reused; the tls package will also not
214// modify it.
215type Config struct {
216 // Rand provides the source of entropy for nonces and RSA blinding.
217 // If Rand is nil, TLS uses the cryptographic random reader in package
218 // crypto/rand.
219 // The Reader must be safe for use by multiple goroutines.
220 Rand io.Reader
221
222 // Time returns the current time as the number of seconds since the epoch.
223 // If Time is nil, TLS uses time.Now.
224 Time func() time.Time
225
226 // Certificates contains one or more certificate chains
227 // to present to the other side of the connection.
228 // Server configurations must include at least one certificate.
229 Certificates []Certificate
230
231 // NameToCertificate maps from a certificate name to an element of
232 // Certificates. Note that a certificate name can be of the form
233 // '*.example.com' and so doesn't have to be a domain name as such.
234 // See Config.BuildNameToCertificate
235 // The nil value causes the first element of Certificates to be used
236 // for all connections.
237 NameToCertificate map[string]*Certificate
238
239 // RootCAs defines the set of root certificate authorities
240 // that clients use when verifying server certificates.
241 // If RootCAs is nil, TLS uses the host's root CA set.
242 RootCAs *x509.CertPool
243
244 // NextProtos is a list of supported, application level protocols.
245 NextProtos []string
246
247 // ServerName is used to verify the hostname on the returned
248 // certificates unless InsecureSkipVerify is given. It is also included
249 // in the client's handshake to support virtual hosting.
250 ServerName string
251
252 // ClientAuth determines the server's policy for
253 // TLS Client Authentication. The default is NoClientCert.
254 ClientAuth ClientAuthType
255
256 // ClientCAs defines the set of root certificate authorities
257 // that servers use if required to verify a client certificate
258 // by the policy in ClientAuth.
259 ClientCAs *x509.CertPool
260
David Benjamin7b030512014-07-08 17:30:11 -0400261 // ClientCertificateTypes defines the set of allowed client certificate
262 // types. The default is CertTypeRSASign and CertTypeECDSASign.
263 ClientCertificateTypes []byte
264
Adam Langley95c29f32014-06-20 12:00:00 -0700265 // InsecureSkipVerify controls whether a client verifies the
266 // server's certificate chain and host name.
267 // If InsecureSkipVerify is true, TLS accepts any certificate
268 // presented by the server and any host name in that certificate.
269 // In this mode, TLS is susceptible to man-in-the-middle attacks.
270 // This should be used only for testing.
271 InsecureSkipVerify bool
272
273 // CipherSuites is a list of supported cipher suites. If CipherSuites
274 // is nil, TLS uses a list of suites supported by the implementation.
275 CipherSuites []uint16
276
277 // PreferServerCipherSuites controls whether the server selects the
278 // client's most preferred ciphersuite, or the server's most preferred
279 // ciphersuite. If true then the server's preference, as expressed in
280 // the order of elements in CipherSuites, is used.
281 PreferServerCipherSuites bool
282
283 // SessionTicketsDisabled may be set to true to disable session ticket
284 // (resumption) support.
285 SessionTicketsDisabled bool
286
287 // SessionTicketKey is used by TLS servers to provide session
288 // resumption. See RFC 5077. If zero, it will be filled with
289 // random data before the first server handshake.
290 //
291 // If multiple servers are terminating connections for the same host
292 // they should all have the same SessionTicketKey. If the
293 // SessionTicketKey leaks, previously recorded and future TLS
294 // connections using that key are compromised.
295 SessionTicketKey [32]byte
296
297 // SessionCache is a cache of ClientSessionState entries for TLS session
298 // resumption.
299 ClientSessionCache ClientSessionCache
300
301 // MinVersion contains the minimum SSL/TLS version that is acceptable.
302 // If zero, then SSLv3 is taken as the minimum.
303 MinVersion uint16
304
305 // MaxVersion contains the maximum SSL/TLS version that is acceptable.
306 // If zero, then the maximum version supported by this package is used,
307 // which is currently TLS 1.2.
308 MaxVersion uint16
309
310 // CurvePreferences contains the elliptic curves that will be used in
311 // an ECDHE handshake, in preference order. If empty, the default will
312 // be used.
313 CurvePreferences []CurveID
314
David Benjamind30a9902014-08-24 01:44:23 -0400315 // ChannelID contains the ECDSA key for the client to use as
316 // its TLS Channel ID.
317 ChannelID *ecdsa.PrivateKey
318
319 // RequestChannelID controls whether the server requests a TLS
320 // Channel ID. If negotiated, the client's public key is
321 // returned in the ConnectionState.
322 RequestChannelID bool
323
Adam Langley95c29f32014-06-20 12:00:00 -0700324 // Bugs specifies optional misbehaviour to be used for testing other
325 // implementations.
326 Bugs ProtocolBugs
327
328 serverInitOnce sync.Once // guards calling (*Config).serverInit
329}
330
331type BadValue int
332
333const (
334 BadValueNone BadValue = iota
335 BadValueNegative
336 BadValueZero
337 BadValueLimit
338 BadValueLarge
339 NumBadValues
340)
341
342type ProtocolBugs struct {
343 // InvalidSKXSignature specifies that the signature in a
344 // ServerKeyExchange message should be invalid.
345 InvalidSKXSignature bool
346
347 // InvalidSKXCurve causes the curve ID in the ServerKeyExchange message
348 // to be wrong.
349 InvalidSKXCurve bool
350
351 // BadECDSAR controls ways in which the 'r' value of an ECDSA signature
352 // can be invalid.
353 BadECDSAR BadValue
354 BadECDSAS BadValue
Adam Langley80842bd2014-06-20 12:00:00 -0700355
356 // MaxPadding causes CBC records to have the maximum possible padding.
357 MaxPadding bool
358 // PaddingFirstByteBad causes the first byte of the padding to be
359 // incorrect.
360 PaddingFirstByteBad bool
361 // PaddingFirstByteBadIf255 causes the first byte of padding to be
362 // incorrect if there's a maximum amount of padding (i.e. 255 bytes).
363 PaddingFirstByteBadIf255 bool
Adam Langleyac61fa32014-06-23 12:03:11 -0700364
365 // FailIfNotFallbackSCSV causes a server handshake to fail if the
366 // client doesn't send the fallback SCSV value.
367 FailIfNotFallbackSCSV bool
David Benjamin35a7a442014-07-05 00:23:20 -0400368
369 // DuplicateExtension causes an extra empty extension of bogus type to
370 // be emitted in either the ClientHello or the ServerHello.
371 DuplicateExtension bool
David Benjamin1c375dd2014-07-12 00:48:23 -0400372
373 // UnauthenticatedECDH causes the server to pretend ECDHE_RSA
374 // and ECDHE_ECDSA cipher suites are actually ECDH_anon. No
375 // Certificate message is sent and no signature is added to
376 // ServerKeyExchange.
377 UnauthenticatedECDH bool
David Benjamin9c651c92014-07-12 13:27:45 -0400378
379 // SkipServerKeyExchange causes the server to skip sending
380 // ServerKeyExchange messages.
381 SkipServerKeyExchange bool
David Benjamina0e52232014-07-19 17:39:58 -0400382
383 // SkipChangeCipherSpec causes the implementation to skip
384 // sending the ChangeCipherSpec message (and adjusting cipher
385 // state accordingly for the Finished message).
386 SkipChangeCipherSpec bool
David Benjaminf3ec83d2014-07-21 22:42:34 -0400387
388 // EarlyChangeCipherSpec causes the client to send an early
389 // ChangeCipherSpec message before the ClientKeyExchange. A value of
390 // zero disables this behavior. One and two configure variants for 0.9.8
391 // and 1.0.1 modes, respectively.
392 EarlyChangeCipherSpec int
David Benjamind23f4122014-07-23 15:09:48 -0400393
David Benjamin86271ee2014-07-21 16:14:03 -0400394 // FragmentAcrossChangeCipherSpec causes the implementation to fragment
395 // the Finished (or NextProto) message around the ChangeCipherSpec
396 // messages.
397 FragmentAcrossChangeCipherSpec bool
398
David Benjamind23f4122014-07-23 15:09:48 -0400399 // SkipNewSessionTicket causes the server to skip sending the
400 // NewSessionTicket message despite promising to in ServerHello.
401 SkipNewSessionTicket bool
David Benjamind86c7672014-08-02 04:07:12 -0400402
403 // SendV2ClientHello causes the client to send a V2ClientHello
404 // instead of a normal ClientHello.
405 SendV2ClientHello bool
David Benjaminbef270a2014-08-02 04:22:02 -0400406
407 // SendFallbackSCSV causes the client to include
408 // TLS_FALLBACK_SCSV in the ClientHello.
409 SendFallbackSCSV bool
David Benjamin43ec06f2014-08-05 02:28:57 -0400410
411 // MaxHandshakeRecordLength, if non-zero, is the maximum size of a
David Benjamin98214542014-08-07 18:02:39 -0400412 // handshake record. Handshake messages will be split into multiple
413 // records at the specified size, except that the client_version will
414 // never be fragmented.
David Benjamin43ec06f2014-08-05 02:28:57 -0400415 MaxHandshakeRecordLength int
David Benjamina8e3e0e2014-08-06 22:11:10 -0400416
David Benjamin98214542014-08-07 18:02:39 -0400417 // FragmentClientVersion will allow MaxHandshakeRecordLength to apply to
418 // the first 6 bytes of the ClientHello.
419 FragmentClientVersion bool
420
David Benjamina8e3e0e2014-08-06 22:11:10 -0400421 // RsaClientKeyExchangeVersion, if non-zero, causes the client to send a
422 // ClientKeyExchange with the specified version rather than the
423 // client_version when performing the RSA key exchange.
424 RsaClientKeyExchangeVersion uint16
David Benjaminbed9aae2014-08-07 19:13:38 -0400425
426 // RenewTicketOnResume causes the server to renew the session ticket and
427 // send a NewSessionTicket message during an abbreviated handshake.
428 RenewTicketOnResume bool
David Benjamin98e882e2014-08-08 13:24:34 -0400429
430 // SendClientVersion, if non-zero, causes the client to send a different
431 // TLS version in the ClientHello than the maximum supported version.
432 SendClientVersion uint16
David Benjamin83c0bc92014-08-04 01:23:53 -0400433
434 // SkipHelloVerifyRequest causes a DTLS server to skip the
435 // HelloVerifyRequest message.
436 SkipHelloVerifyRequest bool
Adam Langley95c29f32014-06-20 12:00:00 -0700437}
438
439func (c *Config) serverInit() {
440 if c.SessionTicketsDisabled {
441 return
442 }
443
444 // If the key has already been set then we have nothing to do.
445 for _, b := range c.SessionTicketKey {
446 if b != 0 {
447 return
448 }
449 }
450
451 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
452 c.SessionTicketsDisabled = true
453 }
454}
455
456func (c *Config) rand() io.Reader {
457 r := c.Rand
458 if r == nil {
459 return rand.Reader
460 }
461 return r
462}
463
464func (c *Config) time() time.Time {
465 t := c.Time
466 if t == nil {
467 t = time.Now
468 }
469 return t()
470}
471
472func (c *Config) cipherSuites() []uint16 {
473 s := c.CipherSuites
474 if s == nil {
475 s = defaultCipherSuites()
476 }
477 return s
478}
479
480func (c *Config) minVersion() uint16 {
481 if c == nil || c.MinVersion == 0 {
482 return minVersion
483 }
484 return c.MinVersion
485}
486
487func (c *Config) maxVersion() uint16 {
488 if c == nil || c.MaxVersion == 0 {
489 return maxVersion
490 }
491 return c.MaxVersion
492}
493
494var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
495
496func (c *Config) curvePreferences() []CurveID {
497 if c == nil || len(c.CurvePreferences) == 0 {
498 return defaultCurvePreferences
499 }
500 return c.CurvePreferences
501}
502
503// mutualVersion returns the protocol version to use given the advertised
504// version of the peer.
505func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
506 minVersion := c.minVersion()
507 maxVersion := c.maxVersion()
508
509 if vers < minVersion {
510 return 0, false
511 }
512 if vers > maxVersion {
513 vers = maxVersion
514 }
515 return vers, true
516}
517
518// getCertificateForName returns the best certificate for the given name,
519// defaulting to the first element of c.Certificates if there are no good
520// options.
521func (c *Config) getCertificateForName(name string) *Certificate {
522 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
523 // There's only one choice, so no point doing any work.
524 return &c.Certificates[0]
525 }
526
527 name = strings.ToLower(name)
528 for len(name) > 0 && name[len(name)-1] == '.' {
529 name = name[:len(name)-1]
530 }
531
532 if cert, ok := c.NameToCertificate[name]; ok {
533 return cert
534 }
535
536 // try replacing labels in the name with wildcards until we get a
537 // match.
538 labels := strings.Split(name, ".")
539 for i := range labels {
540 labels[i] = "*"
541 candidate := strings.Join(labels, ".")
542 if cert, ok := c.NameToCertificate[candidate]; ok {
543 return cert
544 }
545 }
546
547 // If nothing matches, return the first certificate.
548 return &c.Certificates[0]
549}
550
551// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
552// from the CommonName and SubjectAlternateName fields of each of the leaf
553// certificates.
554func (c *Config) BuildNameToCertificate() {
555 c.NameToCertificate = make(map[string]*Certificate)
556 for i := range c.Certificates {
557 cert := &c.Certificates[i]
558 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
559 if err != nil {
560 continue
561 }
562 if len(x509Cert.Subject.CommonName) > 0 {
563 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
564 }
565 for _, san := range x509Cert.DNSNames {
566 c.NameToCertificate[san] = cert
567 }
568 }
569}
570
571// A Certificate is a chain of one or more certificates, leaf first.
572type Certificate struct {
573 Certificate [][]byte
574 PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
575 // OCSPStaple contains an optional OCSP response which will be served
576 // to clients that request it.
577 OCSPStaple []byte
578 // Leaf is the parsed form of the leaf certificate, which may be
579 // initialized using x509.ParseCertificate to reduce per-handshake
580 // processing for TLS clients doing client authentication. If nil, the
581 // leaf certificate will be parsed as needed.
582 Leaf *x509.Certificate
583}
584
585// A TLS record.
586type record struct {
587 contentType recordType
588 major, minor uint8
589 payload []byte
590}
591
592type handshakeMessage interface {
593 marshal() []byte
594 unmarshal([]byte) bool
595}
596
597// lruSessionCache is a ClientSessionCache implementation that uses an LRU
598// caching strategy.
599type lruSessionCache struct {
600 sync.Mutex
601
602 m map[string]*list.Element
603 q *list.List
604 capacity int
605}
606
607type lruSessionCacheEntry struct {
608 sessionKey string
609 state *ClientSessionState
610}
611
612// NewLRUClientSessionCache returns a ClientSessionCache with the given
613// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
614// is used instead.
615func NewLRUClientSessionCache(capacity int) ClientSessionCache {
616 const defaultSessionCacheCapacity = 64
617
618 if capacity < 1 {
619 capacity = defaultSessionCacheCapacity
620 }
621 return &lruSessionCache{
622 m: make(map[string]*list.Element),
623 q: list.New(),
624 capacity: capacity,
625 }
626}
627
628// Put adds the provided (sessionKey, cs) pair to the cache.
629func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
630 c.Lock()
631 defer c.Unlock()
632
633 if elem, ok := c.m[sessionKey]; ok {
634 entry := elem.Value.(*lruSessionCacheEntry)
635 entry.state = cs
636 c.q.MoveToFront(elem)
637 return
638 }
639
640 if c.q.Len() < c.capacity {
641 entry := &lruSessionCacheEntry{sessionKey, cs}
642 c.m[sessionKey] = c.q.PushFront(entry)
643 return
644 }
645
646 elem := c.q.Back()
647 entry := elem.Value.(*lruSessionCacheEntry)
648 delete(c.m, entry.sessionKey)
649 entry.sessionKey = sessionKey
650 entry.state = cs
651 c.q.MoveToFront(elem)
652 c.m[sessionKey] = elem
653}
654
655// Get returns the ClientSessionState value associated with a given key. It
656// returns (nil, false) if no value is found.
657func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
658 c.Lock()
659 defer c.Unlock()
660
661 if elem, ok := c.m[sessionKey]; ok {
662 c.q.MoveToFront(elem)
663 return elem.Value.(*lruSessionCacheEntry).state, true
664 }
665 return nil, false
666}
667
668// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
669type dsaSignature struct {
670 R, S *big.Int
671}
672
673type ecdsaSignature dsaSignature
674
675var emptyConfig Config
676
677func defaultConfig() *Config {
678 return &emptyConfig
679}
680
681var (
682 once sync.Once
683 varDefaultCipherSuites []uint16
684)
685
686func defaultCipherSuites() []uint16 {
687 once.Do(initDefaultCipherSuites)
688 return varDefaultCipherSuites
689}
690
691func initDefaultCipherSuites() {
692 varDefaultCipherSuites = make([]uint16, len(cipherSuites))
693 for i, suite := range cipherSuites {
694 varDefaultCipherSuites[i] = suite.id
695 }
696}
697
698func unexpectedMessageError(wanted, got interface{}) error {
699 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
700}