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