blob: 9af30637fa8c5d9b20aef8b1d1fa9e33e48fa2a4 [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 {
David Benjamine098ec22014-08-27 23:13:20 -0400141 signature, hash uint8
Adam Langley95c29f32014-06-20 12:00:00 -0700142}
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{
David Benjamine098ec22014-08-27 23:13:20 -0400147 {signatureRSA, hashSHA256},
148 {signatureECDSA, hashSHA256},
149 {signatureRSA, hashSHA1},
150 {signatureECDSA, hashSHA1},
Adam Langley95c29f32014-06-20 12:00:00 -0700151}
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{
David Benjamine098ec22014-08-27 23:13:20 -0400157 {signatureRSA, hashSHA256},
158 {signatureECDSA, hashSHA256},
Adam Langley95c29f32014-06-20 12:00:00 -0700159}
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
David Benjamine58c4f52014-08-24 03:47:07 -0400437
438 // ExpectFalseStart causes the server to, on full handshakes,
439 // expect the peer to False Start; the server Finished message
440 // isn't sent until we receive an application data record
441 // from the peer.
442 ExpectFalseStart bool
David Benjamin5c24a1d2014-08-31 00:59:27 -0400443
444 // SSL3RSAKeyExchange causes the client to always send an RSA
445 // ClientKeyExchange message without the two-byte length
446 // prefix, as if it were SSL3.
447 SSL3RSAKeyExchange bool
David Benjamin39ebf532014-08-31 02:23:49 -0400448
449 // SkipCipherVersionCheck causes the server to negotiate
450 // TLS 1.2 ciphers in earlier versions of TLS.
451 SkipCipherVersionCheck bool
David Benjamine78bfde2014-09-06 12:45:15 -0400452
453 // ExpectServerName, if not empty, is the hostname the client
454 // must specify in the server_name extension.
455 ExpectServerName string
Adam Langley95c29f32014-06-20 12:00:00 -0700456}
457
458func (c *Config) serverInit() {
459 if c.SessionTicketsDisabled {
460 return
461 }
462
463 // If the key has already been set then we have nothing to do.
464 for _, b := range c.SessionTicketKey {
465 if b != 0 {
466 return
467 }
468 }
469
470 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
471 c.SessionTicketsDisabled = true
472 }
473}
474
475func (c *Config) rand() io.Reader {
476 r := c.Rand
477 if r == nil {
478 return rand.Reader
479 }
480 return r
481}
482
483func (c *Config) time() time.Time {
484 t := c.Time
485 if t == nil {
486 t = time.Now
487 }
488 return t()
489}
490
491func (c *Config) cipherSuites() []uint16 {
492 s := c.CipherSuites
493 if s == nil {
494 s = defaultCipherSuites()
495 }
496 return s
497}
498
499func (c *Config) minVersion() uint16 {
500 if c == nil || c.MinVersion == 0 {
501 return minVersion
502 }
503 return c.MinVersion
504}
505
506func (c *Config) maxVersion() uint16 {
507 if c == nil || c.MaxVersion == 0 {
508 return maxVersion
509 }
510 return c.MaxVersion
511}
512
513var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
514
515func (c *Config) curvePreferences() []CurveID {
516 if c == nil || len(c.CurvePreferences) == 0 {
517 return defaultCurvePreferences
518 }
519 return c.CurvePreferences
520}
521
522// mutualVersion returns the protocol version to use given the advertised
523// version of the peer.
524func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
525 minVersion := c.minVersion()
526 maxVersion := c.maxVersion()
527
528 if vers < minVersion {
529 return 0, false
530 }
531 if vers > maxVersion {
532 vers = maxVersion
533 }
534 return vers, true
535}
536
537// getCertificateForName returns the best certificate for the given name,
538// defaulting to the first element of c.Certificates if there are no good
539// options.
540func (c *Config) getCertificateForName(name string) *Certificate {
541 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
542 // There's only one choice, so no point doing any work.
543 return &c.Certificates[0]
544 }
545
546 name = strings.ToLower(name)
547 for len(name) > 0 && name[len(name)-1] == '.' {
548 name = name[:len(name)-1]
549 }
550
551 if cert, ok := c.NameToCertificate[name]; ok {
552 return cert
553 }
554
555 // try replacing labels in the name with wildcards until we get a
556 // match.
557 labels := strings.Split(name, ".")
558 for i := range labels {
559 labels[i] = "*"
560 candidate := strings.Join(labels, ".")
561 if cert, ok := c.NameToCertificate[candidate]; ok {
562 return cert
563 }
564 }
565
566 // If nothing matches, return the first certificate.
567 return &c.Certificates[0]
568}
569
570// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
571// from the CommonName and SubjectAlternateName fields of each of the leaf
572// certificates.
573func (c *Config) BuildNameToCertificate() {
574 c.NameToCertificate = make(map[string]*Certificate)
575 for i := range c.Certificates {
576 cert := &c.Certificates[i]
577 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
578 if err != nil {
579 continue
580 }
581 if len(x509Cert.Subject.CommonName) > 0 {
582 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
583 }
584 for _, san := range x509Cert.DNSNames {
585 c.NameToCertificate[san] = cert
586 }
587 }
588}
589
590// A Certificate is a chain of one or more certificates, leaf first.
591type Certificate struct {
592 Certificate [][]byte
593 PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
594 // OCSPStaple contains an optional OCSP response which will be served
595 // to clients that request it.
596 OCSPStaple []byte
597 // Leaf is the parsed form of the leaf certificate, which may be
598 // initialized using x509.ParseCertificate to reduce per-handshake
599 // processing for TLS clients doing client authentication. If nil, the
600 // leaf certificate will be parsed as needed.
601 Leaf *x509.Certificate
602}
603
604// A TLS record.
605type record struct {
606 contentType recordType
607 major, minor uint8
608 payload []byte
609}
610
611type handshakeMessage interface {
612 marshal() []byte
613 unmarshal([]byte) bool
614}
615
616// lruSessionCache is a ClientSessionCache implementation that uses an LRU
617// caching strategy.
618type lruSessionCache struct {
619 sync.Mutex
620
621 m map[string]*list.Element
622 q *list.List
623 capacity int
624}
625
626type lruSessionCacheEntry struct {
627 sessionKey string
628 state *ClientSessionState
629}
630
631// NewLRUClientSessionCache returns a ClientSessionCache with the given
632// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
633// is used instead.
634func NewLRUClientSessionCache(capacity int) ClientSessionCache {
635 const defaultSessionCacheCapacity = 64
636
637 if capacity < 1 {
638 capacity = defaultSessionCacheCapacity
639 }
640 return &lruSessionCache{
641 m: make(map[string]*list.Element),
642 q: list.New(),
643 capacity: capacity,
644 }
645}
646
647// Put adds the provided (sessionKey, cs) pair to the cache.
648func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
649 c.Lock()
650 defer c.Unlock()
651
652 if elem, ok := c.m[sessionKey]; ok {
653 entry := elem.Value.(*lruSessionCacheEntry)
654 entry.state = cs
655 c.q.MoveToFront(elem)
656 return
657 }
658
659 if c.q.Len() < c.capacity {
660 entry := &lruSessionCacheEntry{sessionKey, cs}
661 c.m[sessionKey] = c.q.PushFront(entry)
662 return
663 }
664
665 elem := c.q.Back()
666 entry := elem.Value.(*lruSessionCacheEntry)
667 delete(c.m, entry.sessionKey)
668 entry.sessionKey = sessionKey
669 entry.state = cs
670 c.q.MoveToFront(elem)
671 c.m[sessionKey] = elem
672}
673
674// Get returns the ClientSessionState value associated with a given key. It
675// returns (nil, false) if no value is found.
676func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
677 c.Lock()
678 defer c.Unlock()
679
680 if elem, ok := c.m[sessionKey]; ok {
681 c.q.MoveToFront(elem)
682 return elem.Value.(*lruSessionCacheEntry).state, true
683 }
684 return nil, false
685}
686
687// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
688type dsaSignature struct {
689 R, S *big.Int
690}
691
692type ecdsaSignature dsaSignature
693
694var emptyConfig Config
695
696func defaultConfig() *Config {
697 return &emptyConfig
698}
699
700var (
701 once sync.Once
702 varDefaultCipherSuites []uint16
703)
704
705func defaultCipherSuites() []uint16 {
706 once.Do(initDefaultCipherSuites)
707 return varDefaultCipherSuites
708}
709
710func initDefaultCipherSuites() {
711 varDefaultCipherSuites = make([]uint16, len(cipherSuites))
712 for i, suite := range cipherSuites {
713 varDefaultCipherSuites[i] = suite.id
714 }
715}
716
717func unexpectedMessageError(wanted, got interface{}) error {
718 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
719}