blob: 7dbc1f018a6ea54a01c2be5afb6ad029da4b6ae7 [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
David Benjaminfa055a22014-09-15 16:51:51 -040079 extensionALPN uint16 = 16
Adam Langley95c29f32014-06-20 12:00:00 -070080 extensionSessionTicket uint16 = 35
81 extensionNextProtoNeg uint16 = 13172 // not IANA assigned
82 extensionRenegotiationInfo uint16 = 0xff01
David Benjamind30a9902014-08-24 01:44:23 -040083 extensionChannelID uint16 = 30032 // not IANA assigned
Adam Langley95c29f32014-06-20 12:00:00 -070084)
85
86// TLS signaling cipher suite values
87const (
88 scsvRenegotiation uint16 = 0x00ff
89)
90
91// CurveID is the type of a TLS identifier for an elliptic curve. See
92// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
93type CurveID uint16
94
95const (
96 CurveP256 CurveID = 23
97 CurveP384 CurveID = 24
98 CurveP521 CurveID = 25
99)
100
101// TLS Elliptic Curve Point Formats
102// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
103const (
104 pointFormatUncompressed uint8 = 0
105)
106
107// TLS CertificateStatusType (RFC 3546)
108const (
109 statusTypeOCSP uint8 = 1
110)
111
112// Certificate types (for certificateRequestMsg)
113const (
David Benjamin7b030512014-07-08 17:30:11 -0400114 CertTypeRSASign = 1 // A certificate containing an RSA key
115 CertTypeDSSSign = 2 // A certificate containing a DSA key
116 CertTypeRSAFixedDH = 3 // A certificate containing a static DH key
117 CertTypeDSSFixedDH = 4 // A certificate containing a static DH key
Adam Langley95c29f32014-06-20 12:00:00 -0700118
119 // See RFC4492 sections 3 and 5.5.
David Benjamin7b030512014-07-08 17:30:11 -0400120 CertTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
121 CertTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
122 CertTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
Adam Langley95c29f32014-06-20 12:00:00 -0700123
124 // Rest of these are reserved by the TLS spec
125)
126
127// Hash functions for TLS 1.2 (See RFC 5246, section A.4.1)
128const (
129 hashSHA1 uint8 = 2
130 hashSHA256 uint8 = 4
131)
132
133// Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
134const (
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.
141type signatureAndHash struct {
David Benjamine098ec22014-08-27 23:13:20 -0400142 signature, hash uint8
Adam Langley95c29f32014-06-20 12:00:00 -0700143}
144
145// supportedSKXSignatureAlgorithms contains the signature and hash algorithms
146// that the code advertises as supported in a TLS 1.2 ClientHello.
147var supportedSKXSignatureAlgorithms = []signatureAndHash{
David Benjamine098ec22014-08-27 23:13:20 -0400148 {signatureRSA, hashSHA256},
149 {signatureECDSA, hashSHA256},
150 {signatureRSA, hashSHA1},
151 {signatureECDSA, hashSHA1},
Adam Langley95c29f32014-06-20 12:00:00 -0700152}
153
154// supportedClientCertSignatureAlgorithms contains the signature and hash
155// algorithms that the code advertises as supported in a TLS 1.2
156// CertificateRequest.
157var supportedClientCertSignatureAlgorithms = []signatureAndHash{
David Benjamine098ec22014-08-27 23:13:20 -0400158 {signatureRSA, hashSHA256},
159 {signatureECDSA, hashSHA256},
Adam Langley95c29f32014-06-20 12:00:00 -0700160}
161
162// ConnectionState records basic TLS details about the connection.
163type ConnectionState struct {
164 Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
165 HandshakeComplete bool // TLS handshake is complete
166 DidResume bool // connection resumes a previous TLS connection
167 CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
168 NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos)
169 NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server
David Benjaminfc7b0862014-09-06 13:21:53 -0400170 NegotiatedProtocolFromALPN bool // protocol negotiated with ALPN
Adam Langley95c29f32014-06-20 12:00:00 -0700171 ServerName string // server name requested by client, if any (server side only)
172 PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
173 VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
David Benjamind30a9902014-08-24 01:44:23 -0400174 ChannelID *ecdsa.PublicKey // the channel ID for this connection
Adam Langley95c29f32014-06-20 12:00:00 -0700175}
176
177// ClientAuthType declares the policy the server will follow for
178// TLS Client Authentication.
179type ClientAuthType int
180
181const (
182 NoClientCert ClientAuthType = iota
183 RequestClientCert
184 RequireAnyClientCert
185 VerifyClientCertIfGiven
186 RequireAndVerifyClientCert
187)
188
189// ClientSessionState contains the state needed by clients to resume TLS
190// sessions.
191type ClientSessionState struct {
192 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
193 vers uint16 // SSL/TLS version negotiated for the session
194 cipherSuite uint16 // Ciphersuite negotiated for the session
195 masterSecret []byte // MasterSecret generated by client on a full handshake
David Benjamind30a9902014-08-24 01:44:23 -0400196 handshakeHash []byte // Handshake hash for Channel ID purposes.
Adam Langley95c29f32014-06-20 12:00:00 -0700197 serverCertificates []*x509.Certificate // Certificate chain presented by the server
198}
199
200// ClientSessionCache is a cache of ClientSessionState objects that can be used
201// by a client to resume a TLS session with a given server. ClientSessionCache
202// implementations should expect to be called concurrently from different
203// goroutines.
204type ClientSessionCache interface {
205 // Get searches for a ClientSessionState associated with the given key.
206 // On return, ok is true if one was found.
207 Get(sessionKey string) (session *ClientSessionState, ok bool)
208
209 // Put adds the ClientSessionState to the cache with the given key.
210 Put(sessionKey string, cs *ClientSessionState)
211}
212
213// A Config structure is used to configure a TLS client or server.
214// After one has been passed to a TLS function it must not be
215// modified. A Config may be reused; the tls package will also not
216// modify it.
217type Config struct {
218 // Rand provides the source of entropy for nonces and RSA blinding.
219 // If Rand is nil, TLS uses the cryptographic random reader in package
220 // crypto/rand.
221 // The Reader must be safe for use by multiple goroutines.
222 Rand io.Reader
223
224 // Time returns the current time as the number of seconds since the epoch.
225 // If Time is nil, TLS uses time.Now.
226 Time func() time.Time
227
228 // Certificates contains one or more certificate chains
229 // to present to the other side of the connection.
230 // Server configurations must include at least one certificate.
231 Certificates []Certificate
232
233 // NameToCertificate maps from a certificate name to an element of
234 // Certificates. Note that a certificate name can be of the form
235 // '*.example.com' and so doesn't have to be a domain name as such.
236 // See Config.BuildNameToCertificate
237 // The nil value causes the first element of Certificates to be used
238 // for all connections.
239 NameToCertificate map[string]*Certificate
240
241 // RootCAs defines the set of root certificate authorities
242 // that clients use when verifying server certificates.
243 // If RootCAs is nil, TLS uses the host's root CA set.
244 RootCAs *x509.CertPool
245
246 // NextProtos is a list of supported, application level protocols.
247 NextProtos []string
248
249 // ServerName is used to verify the hostname on the returned
250 // certificates unless InsecureSkipVerify is given. It is also included
251 // in the client's handshake to support virtual hosting.
252 ServerName string
253
254 // ClientAuth determines the server's policy for
255 // TLS Client Authentication. The default is NoClientCert.
256 ClientAuth ClientAuthType
257
258 // ClientCAs defines the set of root certificate authorities
259 // that servers use if required to verify a client certificate
260 // by the policy in ClientAuth.
261 ClientCAs *x509.CertPool
262
David Benjamin7b030512014-07-08 17:30:11 -0400263 // ClientCertificateTypes defines the set of allowed client certificate
264 // types. The default is CertTypeRSASign and CertTypeECDSASign.
265 ClientCertificateTypes []byte
266
Adam Langley95c29f32014-06-20 12:00:00 -0700267 // InsecureSkipVerify controls whether a client verifies the
268 // server's certificate chain and host name.
269 // If InsecureSkipVerify is true, TLS accepts any certificate
270 // presented by the server and any host name in that certificate.
271 // In this mode, TLS is susceptible to man-in-the-middle attacks.
272 // This should be used only for testing.
273 InsecureSkipVerify bool
274
275 // CipherSuites is a list of supported cipher suites. If CipherSuites
276 // is nil, TLS uses a list of suites supported by the implementation.
277 CipherSuites []uint16
278
279 // PreferServerCipherSuites controls whether the server selects the
280 // client's most preferred ciphersuite, or the server's most preferred
281 // ciphersuite. If true then the server's preference, as expressed in
282 // the order of elements in CipherSuites, is used.
283 PreferServerCipherSuites bool
284
285 // SessionTicketsDisabled may be set to true to disable session ticket
286 // (resumption) support.
287 SessionTicketsDisabled bool
288
289 // SessionTicketKey is used by TLS servers to provide session
290 // resumption. See RFC 5077. If zero, it will be filled with
291 // random data before the first server handshake.
292 //
293 // If multiple servers are terminating connections for the same host
294 // they should all have the same SessionTicketKey. If the
295 // SessionTicketKey leaks, previously recorded and future TLS
296 // connections using that key are compromised.
297 SessionTicketKey [32]byte
298
299 // SessionCache is a cache of ClientSessionState entries for TLS session
300 // resumption.
301 ClientSessionCache ClientSessionCache
302
303 // MinVersion contains the minimum SSL/TLS version that is acceptable.
304 // If zero, then SSLv3 is taken as the minimum.
305 MinVersion uint16
306
307 // MaxVersion contains the maximum SSL/TLS version that is acceptable.
308 // If zero, then the maximum version supported by this package is used,
309 // which is currently TLS 1.2.
310 MaxVersion uint16
311
312 // CurvePreferences contains the elliptic curves that will be used in
313 // an ECDHE handshake, in preference order. If empty, the default will
314 // be used.
315 CurvePreferences []CurveID
316
David Benjamind30a9902014-08-24 01:44:23 -0400317 // ChannelID contains the ECDSA key for the client to use as
318 // its TLS Channel ID.
319 ChannelID *ecdsa.PrivateKey
320
321 // RequestChannelID controls whether the server requests a TLS
322 // Channel ID. If negotiated, the client's public key is
323 // returned in the ConnectionState.
324 RequestChannelID bool
325
Adam Langley95c29f32014-06-20 12:00:00 -0700326 // Bugs specifies optional misbehaviour to be used for testing other
327 // implementations.
328 Bugs ProtocolBugs
329
330 serverInitOnce sync.Once // guards calling (*Config).serverInit
331}
332
333type BadValue int
334
335const (
336 BadValueNone BadValue = iota
337 BadValueNegative
338 BadValueZero
339 BadValueLimit
340 BadValueLarge
341 NumBadValues
342)
343
344type ProtocolBugs struct {
345 // InvalidSKXSignature specifies that the signature in a
346 // ServerKeyExchange message should be invalid.
347 InvalidSKXSignature bool
348
349 // InvalidSKXCurve causes the curve ID in the ServerKeyExchange message
350 // to be wrong.
351 InvalidSKXCurve bool
352
353 // BadECDSAR controls ways in which the 'r' value of an ECDSA signature
354 // can be invalid.
355 BadECDSAR BadValue
356 BadECDSAS BadValue
Adam Langley80842bd2014-06-20 12:00:00 -0700357
358 // MaxPadding causes CBC records to have the maximum possible padding.
359 MaxPadding bool
360 // PaddingFirstByteBad causes the first byte of the padding to be
361 // incorrect.
362 PaddingFirstByteBad bool
363 // PaddingFirstByteBadIf255 causes the first byte of padding to be
364 // incorrect if there's a maximum amount of padding (i.e. 255 bytes).
365 PaddingFirstByteBadIf255 bool
Adam Langleyac61fa32014-06-23 12:03:11 -0700366
367 // FailIfNotFallbackSCSV causes a server handshake to fail if the
368 // client doesn't send the fallback SCSV value.
369 FailIfNotFallbackSCSV bool
David Benjamin35a7a442014-07-05 00:23:20 -0400370
371 // DuplicateExtension causes an extra empty extension of bogus type to
372 // be emitted in either the ClientHello or the ServerHello.
373 DuplicateExtension bool
David Benjamin1c375dd2014-07-12 00:48:23 -0400374
375 // UnauthenticatedECDH causes the server to pretend ECDHE_RSA
376 // and ECDHE_ECDSA cipher suites are actually ECDH_anon. No
377 // Certificate message is sent and no signature is added to
378 // ServerKeyExchange.
379 UnauthenticatedECDH bool
David Benjamin9c651c92014-07-12 13:27:45 -0400380
381 // SkipServerKeyExchange causes the server to skip sending
382 // ServerKeyExchange messages.
383 SkipServerKeyExchange bool
David Benjamina0e52232014-07-19 17:39:58 -0400384
385 // SkipChangeCipherSpec causes the implementation to skip
386 // sending the ChangeCipherSpec message (and adjusting cipher
387 // state accordingly for the Finished message).
388 SkipChangeCipherSpec bool
David Benjaminf3ec83d2014-07-21 22:42:34 -0400389
390 // EarlyChangeCipherSpec causes the client to send an early
391 // ChangeCipherSpec message before the ClientKeyExchange. A value of
392 // zero disables this behavior. One and two configure variants for 0.9.8
393 // and 1.0.1 modes, respectively.
394 EarlyChangeCipherSpec int
David Benjamind23f4122014-07-23 15:09:48 -0400395
David Benjamin86271ee2014-07-21 16:14:03 -0400396 // FragmentAcrossChangeCipherSpec causes the implementation to fragment
397 // the Finished (or NextProto) message around the ChangeCipherSpec
398 // messages.
399 FragmentAcrossChangeCipherSpec bool
400
David Benjamind23f4122014-07-23 15:09:48 -0400401 // SkipNewSessionTicket causes the server to skip sending the
402 // NewSessionTicket message despite promising to in ServerHello.
403 SkipNewSessionTicket bool
David Benjamind86c7672014-08-02 04:07:12 -0400404
405 // SendV2ClientHello causes the client to send a V2ClientHello
406 // instead of a normal ClientHello.
407 SendV2ClientHello bool
David Benjaminbef270a2014-08-02 04:22:02 -0400408
409 // SendFallbackSCSV causes the client to include
410 // TLS_FALLBACK_SCSV in the ClientHello.
411 SendFallbackSCSV bool
David Benjamin43ec06f2014-08-05 02:28:57 -0400412
413 // MaxHandshakeRecordLength, if non-zero, is the maximum size of a
David Benjamin98214542014-08-07 18:02:39 -0400414 // handshake record. Handshake messages will be split into multiple
415 // records at the specified size, except that the client_version will
416 // never be fragmented.
David Benjamin43ec06f2014-08-05 02:28:57 -0400417 MaxHandshakeRecordLength int
David Benjamina8e3e0e2014-08-06 22:11:10 -0400418
David Benjamin98214542014-08-07 18:02:39 -0400419 // FragmentClientVersion will allow MaxHandshakeRecordLength to apply to
420 // the first 6 bytes of the ClientHello.
421 FragmentClientVersion bool
422
David Benjamina8e3e0e2014-08-06 22:11:10 -0400423 // RsaClientKeyExchangeVersion, if non-zero, causes the client to send a
424 // ClientKeyExchange with the specified version rather than the
425 // client_version when performing the RSA key exchange.
426 RsaClientKeyExchangeVersion uint16
David Benjaminbed9aae2014-08-07 19:13:38 -0400427
428 // RenewTicketOnResume causes the server to renew the session ticket and
429 // send a NewSessionTicket message during an abbreviated handshake.
430 RenewTicketOnResume bool
David Benjamin98e882e2014-08-08 13:24:34 -0400431
432 // SendClientVersion, if non-zero, causes the client to send a different
433 // TLS version in the ClientHello than the maximum supported version.
434 SendClientVersion uint16
David Benjamin83c0bc92014-08-04 01:23:53 -0400435
436 // SkipHelloVerifyRequest causes a DTLS server to skip the
437 // HelloVerifyRequest message.
438 SkipHelloVerifyRequest bool
David Benjamine58c4f52014-08-24 03:47:07 -0400439
440 // ExpectFalseStart causes the server to, on full handshakes,
441 // expect the peer to False Start; the server Finished message
442 // isn't sent until we receive an application data record
443 // from the peer.
444 ExpectFalseStart bool
David Benjamin5c24a1d2014-08-31 00:59:27 -0400445
446 // SSL3RSAKeyExchange causes the client to always send an RSA
447 // ClientKeyExchange message without the two-byte length
448 // prefix, as if it were SSL3.
449 SSL3RSAKeyExchange bool
David Benjamin39ebf532014-08-31 02:23:49 -0400450
451 // SkipCipherVersionCheck causes the server to negotiate
452 // TLS 1.2 ciphers in earlier versions of TLS.
453 SkipCipherVersionCheck bool
David Benjamine78bfde2014-09-06 12:45:15 -0400454
455 // ExpectServerName, if not empty, is the hostname the client
456 // must specify in the server_name extension.
457 ExpectServerName string
David Benjaminfc7b0862014-09-06 13:21:53 -0400458
459 // SwapNPNAndALPN switches the relative order between NPN and
460 // ALPN on the server. This is to test that server preference
461 // of ALPN works regardless of their relative order.
462 SwapNPNAndALPN bool
Adam Langley95c29f32014-06-20 12:00:00 -0700463}
464
465func (c *Config) serverInit() {
466 if c.SessionTicketsDisabled {
467 return
468 }
469
470 // If the key has already been set then we have nothing to do.
471 for _, b := range c.SessionTicketKey {
472 if b != 0 {
473 return
474 }
475 }
476
477 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
478 c.SessionTicketsDisabled = true
479 }
480}
481
482func (c *Config) rand() io.Reader {
483 r := c.Rand
484 if r == nil {
485 return rand.Reader
486 }
487 return r
488}
489
490func (c *Config) time() time.Time {
491 t := c.Time
492 if t == nil {
493 t = time.Now
494 }
495 return t()
496}
497
498func (c *Config) cipherSuites() []uint16 {
499 s := c.CipherSuites
500 if s == nil {
501 s = defaultCipherSuites()
502 }
503 return s
504}
505
506func (c *Config) minVersion() uint16 {
507 if c == nil || c.MinVersion == 0 {
508 return minVersion
509 }
510 return c.MinVersion
511}
512
513func (c *Config) maxVersion() uint16 {
514 if c == nil || c.MaxVersion == 0 {
515 return maxVersion
516 }
517 return c.MaxVersion
518}
519
520var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
521
522func (c *Config) curvePreferences() []CurveID {
523 if c == nil || len(c.CurvePreferences) == 0 {
524 return defaultCurvePreferences
525 }
526 return c.CurvePreferences
527}
528
529// mutualVersion returns the protocol version to use given the advertised
530// version of the peer.
531func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
532 minVersion := c.minVersion()
533 maxVersion := c.maxVersion()
534
535 if vers < minVersion {
536 return 0, false
537 }
538 if vers > maxVersion {
539 vers = maxVersion
540 }
541 return vers, true
542}
543
544// getCertificateForName returns the best certificate for the given name,
545// defaulting to the first element of c.Certificates if there are no good
546// options.
547func (c *Config) getCertificateForName(name string) *Certificate {
548 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
549 // There's only one choice, so no point doing any work.
550 return &c.Certificates[0]
551 }
552
553 name = strings.ToLower(name)
554 for len(name) > 0 && name[len(name)-1] == '.' {
555 name = name[:len(name)-1]
556 }
557
558 if cert, ok := c.NameToCertificate[name]; ok {
559 return cert
560 }
561
562 // try replacing labels in the name with wildcards until we get a
563 // match.
564 labels := strings.Split(name, ".")
565 for i := range labels {
566 labels[i] = "*"
567 candidate := strings.Join(labels, ".")
568 if cert, ok := c.NameToCertificate[candidate]; ok {
569 return cert
570 }
571 }
572
573 // If nothing matches, return the first certificate.
574 return &c.Certificates[0]
575}
576
577// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
578// from the CommonName and SubjectAlternateName fields of each of the leaf
579// certificates.
580func (c *Config) BuildNameToCertificate() {
581 c.NameToCertificate = make(map[string]*Certificate)
582 for i := range c.Certificates {
583 cert := &c.Certificates[i]
584 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
585 if err != nil {
586 continue
587 }
588 if len(x509Cert.Subject.CommonName) > 0 {
589 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
590 }
591 for _, san := range x509Cert.DNSNames {
592 c.NameToCertificate[san] = cert
593 }
594 }
595}
596
597// A Certificate is a chain of one or more certificates, leaf first.
598type Certificate struct {
599 Certificate [][]byte
600 PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
601 // OCSPStaple contains an optional OCSP response which will be served
602 // to clients that request it.
603 OCSPStaple []byte
604 // Leaf is the parsed form of the leaf certificate, which may be
605 // initialized using x509.ParseCertificate to reduce per-handshake
606 // processing for TLS clients doing client authentication. If nil, the
607 // leaf certificate will be parsed as needed.
608 Leaf *x509.Certificate
609}
610
611// A TLS record.
612type record struct {
613 contentType recordType
614 major, minor uint8
615 payload []byte
616}
617
618type handshakeMessage interface {
619 marshal() []byte
620 unmarshal([]byte) bool
621}
622
623// lruSessionCache is a ClientSessionCache implementation that uses an LRU
624// caching strategy.
625type lruSessionCache struct {
626 sync.Mutex
627
628 m map[string]*list.Element
629 q *list.List
630 capacity int
631}
632
633type lruSessionCacheEntry struct {
634 sessionKey string
635 state *ClientSessionState
636}
637
638// NewLRUClientSessionCache returns a ClientSessionCache with the given
639// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
640// is used instead.
641func NewLRUClientSessionCache(capacity int) ClientSessionCache {
642 const defaultSessionCacheCapacity = 64
643
644 if capacity < 1 {
645 capacity = defaultSessionCacheCapacity
646 }
647 return &lruSessionCache{
648 m: make(map[string]*list.Element),
649 q: list.New(),
650 capacity: capacity,
651 }
652}
653
654// Put adds the provided (sessionKey, cs) pair to the cache.
655func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
656 c.Lock()
657 defer c.Unlock()
658
659 if elem, ok := c.m[sessionKey]; ok {
660 entry := elem.Value.(*lruSessionCacheEntry)
661 entry.state = cs
662 c.q.MoveToFront(elem)
663 return
664 }
665
666 if c.q.Len() < c.capacity {
667 entry := &lruSessionCacheEntry{sessionKey, cs}
668 c.m[sessionKey] = c.q.PushFront(entry)
669 return
670 }
671
672 elem := c.q.Back()
673 entry := elem.Value.(*lruSessionCacheEntry)
674 delete(c.m, entry.sessionKey)
675 entry.sessionKey = sessionKey
676 entry.state = cs
677 c.q.MoveToFront(elem)
678 c.m[sessionKey] = elem
679}
680
681// Get returns the ClientSessionState value associated with a given key. It
682// returns (nil, false) if no value is found.
683func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
684 c.Lock()
685 defer c.Unlock()
686
687 if elem, ok := c.m[sessionKey]; ok {
688 c.q.MoveToFront(elem)
689 return elem.Value.(*lruSessionCacheEntry).state, true
690 }
691 return nil, false
692}
693
694// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
695type dsaSignature struct {
696 R, S *big.Int
697}
698
699type ecdsaSignature dsaSignature
700
701var emptyConfig Config
702
703func defaultConfig() *Config {
704 return &emptyConfig
705}
706
707var (
708 once sync.Once
709 varDefaultCipherSuites []uint16
710)
711
712func defaultCipherSuites() []uint16 {
713 once.Do(initDefaultCipherSuites)
714 return varDefaultCipherSuites
715}
716
717func initDefaultCipherSuites() {
718 varDefaultCipherSuites = make([]uint16, len(cipherSuites))
719 for i, suite := range cipherSuites {
720 varDefaultCipherSuites[i] = suite.id
721 }
722}
723
724func unexpectedMessageError(wanted, got interface{}) error {
725 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
726}