blob: 4aa21bb55b180661c9124943e289851de241249a [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
David Benjamin48cae082014-10-27 01:06:24 -0400328 // PreSharedKey, if not nil, is the pre-shared key to use with
329 // the PSK cipher suites.
330 PreSharedKey []byte
331
332 // PreSharedKeyIdentity, if not empty, is the identity to use
333 // with the PSK cipher suites.
334 PreSharedKeyIdentity string
335
Adam Langley95c29f32014-06-20 12:00:00 -0700336 // Bugs specifies optional misbehaviour to be used for testing other
337 // implementations.
338 Bugs ProtocolBugs
339
340 serverInitOnce sync.Once // guards calling (*Config).serverInit
341}
342
343type BadValue int
344
345const (
346 BadValueNone BadValue = iota
347 BadValueNegative
348 BadValueZero
349 BadValueLimit
350 BadValueLarge
351 NumBadValues
352)
353
354type ProtocolBugs struct {
355 // InvalidSKXSignature specifies that the signature in a
356 // ServerKeyExchange message should be invalid.
357 InvalidSKXSignature bool
358
359 // InvalidSKXCurve causes the curve ID in the ServerKeyExchange message
360 // to be wrong.
361 InvalidSKXCurve bool
362
363 // BadECDSAR controls ways in which the 'r' value of an ECDSA signature
364 // can be invalid.
365 BadECDSAR BadValue
366 BadECDSAS BadValue
Adam Langley80842bd2014-06-20 12:00:00 -0700367
368 // MaxPadding causes CBC records to have the maximum possible padding.
369 MaxPadding bool
370 // PaddingFirstByteBad causes the first byte of the padding to be
371 // incorrect.
372 PaddingFirstByteBad bool
373 // PaddingFirstByteBadIf255 causes the first byte of padding to be
374 // incorrect if there's a maximum amount of padding (i.e. 255 bytes).
375 PaddingFirstByteBadIf255 bool
Adam Langleyac61fa32014-06-23 12:03:11 -0700376
377 // FailIfNotFallbackSCSV causes a server handshake to fail if the
378 // client doesn't send the fallback SCSV value.
379 FailIfNotFallbackSCSV bool
David Benjamin35a7a442014-07-05 00:23:20 -0400380
381 // DuplicateExtension causes an extra empty extension of bogus type to
382 // be emitted in either the ClientHello or the ServerHello.
383 DuplicateExtension bool
David Benjamin1c375dd2014-07-12 00:48:23 -0400384
385 // UnauthenticatedECDH causes the server to pretend ECDHE_RSA
386 // and ECDHE_ECDSA cipher suites are actually ECDH_anon. No
387 // Certificate message is sent and no signature is added to
388 // ServerKeyExchange.
389 UnauthenticatedECDH bool
David Benjamin9c651c92014-07-12 13:27:45 -0400390
391 // SkipServerKeyExchange causes the server to skip sending
392 // ServerKeyExchange messages.
393 SkipServerKeyExchange bool
David Benjamina0e52232014-07-19 17:39:58 -0400394
395 // SkipChangeCipherSpec causes the implementation to skip
396 // sending the ChangeCipherSpec message (and adjusting cipher
397 // state accordingly for the Finished message).
398 SkipChangeCipherSpec bool
David Benjaminf3ec83d2014-07-21 22:42:34 -0400399
400 // EarlyChangeCipherSpec causes the client to send an early
401 // ChangeCipherSpec message before the ClientKeyExchange. A value of
402 // zero disables this behavior. One and two configure variants for 0.9.8
403 // and 1.0.1 modes, respectively.
404 EarlyChangeCipherSpec int
David Benjamind23f4122014-07-23 15:09:48 -0400405
David Benjamin86271ee2014-07-21 16:14:03 -0400406 // FragmentAcrossChangeCipherSpec causes the implementation to fragment
407 // the Finished (or NextProto) message around the ChangeCipherSpec
408 // messages.
409 FragmentAcrossChangeCipherSpec bool
410
David Benjamind23f4122014-07-23 15:09:48 -0400411 // SkipNewSessionTicket causes the server to skip sending the
412 // NewSessionTicket message despite promising to in ServerHello.
413 SkipNewSessionTicket bool
David Benjamind86c7672014-08-02 04:07:12 -0400414
415 // SendV2ClientHello causes the client to send a V2ClientHello
416 // instead of a normal ClientHello.
417 SendV2ClientHello bool
David Benjaminbef270a2014-08-02 04:22:02 -0400418
419 // SendFallbackSCSV causes the client to include
420 // TLS_FALLBACK_SCSV in the ClientHello.
421 SendFallbackSCSV bool
David Benjamin43ec06f2014-08-05 02:28:57 -0400422
423 // MaxHandshakeRecordLength, if non-zero, is the maximum size of a
David Benjamin98214542014-08-07 18:02:39 -0400424 // handshake record. Handshake messages will be split into multiple
425 // records at the specified size, except that the client_version will
426 // never be fragmented.
David Benjamin43ec06f2014-08-05 02:28:57 -0400427 MaxHandshakeRecordLength int
David Benjamina8e3e0e2014-08-06 22:11:10 -0400428
David Benjamin98214542014-08-07 18:02:39 -0400429 // FragmentClientVersion will allow MaxHandshakeRecordLength to apply to
430 // the first 6 bytes of the ClientHello.
431 FragmentClientVersion bool
432
David Benjamina8e3e0e2014-08-06 22:11:10 -0400433 // RsaClientKeyExchangeVersion, if non-zero, causes the client to send a
434 // ClientKeyExchange with the specified version rather than the
435 // client_version when performing the RSA key exchange.
436 RsaClientKeyExchangeVersion uint16
David Benjaminbed9aae2014-08-07 19:13:38 -0400437
438 // RenewTicketOnResume causes the server to renew the session ticket and
439 // send a NewSessionTicket message during an abbreviated handshake.
440 RenewTicketOnResume bool
David Benjamin98e882e2014-08-08 13:24:34 -0400441
442 // SendClientVersion, if non-zero, causes the client to send a different
443 // TLS version in the ClientHello than the maximum supported version.
444 SendClientVersion uint16
David Benjamin83c0bc92014-08-04 01:23:53 -0400445
446 // SkipHelloVerifyRequest causes a DTLS server to skip the
447 // HelloVerifyRequest message.
448 SkipHelloVerifyRequest bool
David Benjamine58c4f52014-08-24 03:47:07 -0400449
450 // ExpectFalseStart causes the server to, on full handshakes,
451 // expect the peer to False Start; the server Finished message
452 // isn't sent until we receive an application data record
453 // from the peer.
454 ExpectFalseStart bool
David Benjamin5c24a1d2014-08-31 00:59:27 -0400455
456 // SSL3RSAKeyExchange causes the client to always send an RSA
457 // ClientKeyExchange message without the two-byte length
458 // prefix, as if it were SSL3.
459 SSL3RSAKeyExchange bool
David Benjamin39ebf532014-08-31 02:23:49 -0400460
461 // SkipCipherVersionCheck causes the server to negotiate
462 // TLS 1.2 ciphers in earlier versions of TLS.
463 SkipCipherVersionCheck bool
David Benjamine78bfde2014-09-06 12:45:15 -0400464
465 // ExpectServerName, if not empty, is the hostname the client
466 // must specify in the server_name extension.
467 ExpectServerName string
David Benjaminfc7b0862014-09-06 13:21:53 -0400468
469 // SwapNPNAndALPN switches the relative order between NPN and
470 // ALPN on the server. This is to test that server preference
471 // of ALPN works regardless of their relative order.
472 SwapNPNAndALPN bool
David Benjamin01fe8202014-09-24 15:21:44 -0400473
474 // AllowSessionVersionMismatch causes the server to resume sessions
475 // regardless of the version associated with the session.
476 AllowSessionVersionMismatch bool
Adam Langley38311732014-10-16 19:04:35 -0700477
478 // CorruptTicket causes a client to corrupt a session ticket before
479 // sending it in a resume handshake.
480 CorruptTicket bool
481
482 // OversizedSessionId causes the session id that is sent with a ticket
483 // resumption attempt to be too large (33 bytes).
484 OversizedSessionId bool
Adam Langley75712922014-10-10 16:23:43 -0700485
486 // RequireExtendedMasterSecret, if true, requires that the peer support
487 // the extended master secret option.
488 RequireExtendedMasterSecret bool
489
490 // NoExtendedMasterSecret causes the client and server to behave is if
491 // they didn't support an extended master secret.
492 NoExtendedMasterSecret bool
Adam Langley95c29f32014-06-20 12:00:00 -0700493}
494
495func (c *Config) serverInit() {
496 if c.SessionTicketsDisabled {
497 return
498 }
499
500 // If the key has already been set then we have nothing to do.
501 for _, b := range c.SessionTicketKey {
502 if b != 0 {
503 return
504 }
505 }
506
507 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
508 c.SessionTicketsDisabled = true
509 }
510}
511
512func (c *Config) rand() io.Reader {
513 r := c.Rand
514 if r == nil {
515 return rand.Reader
516 }
517 return r
518}
519
520func (c *Config) time() time.Time {
521 t := c.Time
522 if t == nil {
523 t = time.Now
524 }
525 return t()
526}
527
528func (c *Config) cipherSuites() []uint16 {
529 s := c.CipherSuites
530 if s == nil {
531 s = defaultCipherSuites()
532 }
533 return s
534}
535
536func (c *Config) minVersion() uint16 {
537 if c == nil || c.MinVersion == 0 {
538 return minVersion
539 }
540 return c.MinVersion
541}
542
543func (c *Config) maxVersion() uint16 {
544 if c == nil || c.MaxVersion == 0 {
545 return maxVersion
546 }
547 return c.MaxVersion
548}
549
550var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
551
552func (c *Config) curvePreferences() []CurveID {
553 if c == nil || len(c.CurvePreferences) == 0 {
554 return defaultCurvePreferences
555 }
556 return c.CurvePreferences
557}
558
559// mutualVersion returns the protocol version to use given the advertised
560// version of the peer.
561func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
562 minVersion := c.minVersion()
563 maxVersion := c.maxVersion()
564
565 if vers < minVersion {
566 return 0, false
567 }
568 if vers > maxVersion {
569 vers = maxVersion
570 }
571 return vers, true
572}
573
574// getCertificateForName returns the best certificate for the given name,
575// defaulting to the first element of c.Certificates if there are no good
576// options.
577func (c *Config) getCertificateForName(name string) *Certificate {
578 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
579 // There's only one choice, so no point doing any work.
580 return &c.Certificates[0]
581 }
582
583 name = strings.ToLower(name)
584 for len(name) > 0 && name[len(name)-1] == '.' {
585 name = name[:len(name)-1]
586 }
587
588 if cert, ok := c.NameToCertificate[name]; ok {
589 return cert
590 }
591
592 // try replacing labels in the name with wildcards until we get a
593 // match.
594 labels := strings.Split(name, ".")
595 for i := range labels {
596 labels[i] = "*"
597 candidate := strings.Join(labels, ".")
598 if cert, ok := c.NameToCertificate[candidate]; ok {
599 return cert
600 }
601 }
602
603 // If nothing matches, return the first certificate.
604 return &c.Certificates[0]
605}
606
607// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
608// from the CommonName and SubjectAlternateName fields of each of the leaf
609// certificates.
610func (c *Config) BuildNameToCertificate() {
611 c.NameToCertificate = make(map[string]*Certificate)
612 for i := range c.Certificates {
613 cert := &c.Certificates[i]
614 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
615 if err != nil {
616 continue
617 }
618 if len(x509Cert.Subject.CommonName) > 0 {
619 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
620 }
621 for _, san := range x509Cert.DNSNames {
622 c.NameToCertificate[san] = cert
623 }
624 }
625}
626
627// A Certificate is a chain of one or more certificates, leaf first.
628type Certificate struct {
629 Certificate [][]byte
630 PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
631 // OCSPStaple contains an optional OCSP response which will be served
632 // to clients that request it.
633 OCSPStaple []byte
634 // Leaf is the parsed form of the leaf certificate, which may be
635 // initialized using x509.ParseCertificate to reduce per-handshake
636 // processing for TLS clients doing client authentication. If nil, the
637 // leaf certificate will be parsed as needed.
638 Leaf *x509.Certificate
639}
640
641// A TLS record.
642type record struct {
643 contentType recordType
644 major, minor uint8
645 payload []byte
646}
647
648type handshakeMessage interface {
649 marshal() []byte
650 unmarshal([]byte) bool
651}
652
653// lruSessionCache is a ClientSessionCache implementation that uses an LRU
654// caching strategy.
655type lruSessionCache struct {
656 sync.Mutex
657
658 m map[string]*list.Element
659 q *list.List
660 capacity int
661}
662
663type lruSessionCacheEntry struct {
664 sessionKey string
665 state *ClientSessionState
666}
667
668// NewLRUClientSessionCache returns a ClientSessionCache with the given
669// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
670// is used instead.
671func NewLRUClientSessionCache(capacity int) ClientSessionCache {
672 const defaultSessionCacheCapacity = 64
673
674 if capacity < 1 {
675 capacity = defaultSessionCacheCapacity
676 }
677 return &lruSessionCache{
678 m: make(map[string]*list.Element),
679 q: list.New(),
680 capacity: capacity,
681 }
682}
683
684// Put adds the provided (sessionKey, cs) pair to the cache.
685func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
686 c.Lock()
687 defer c.Unlock()
688
689 if elem, ok := c.m[sessionKey]; ok {
690 entry := elem.Value.(*lruSessionCacheEntry)
691 entry.state = cs
692 c.q.MoveToFront(elem)
693 return
694 }
695
696 if c.q.Len() < c.capacity {
697 entry := &lruSessionCacheEntry{sessionKey, cs}
698 c.m[sessionKey] = c.q.PushFront(entry)
699 return
700 }
701
702 elem := c.q.Back()
703 entry := elem.Value.(*lruSessionCacheEntry)
704 delete(c.m, entry.sessionKey)
705 entry.sessionKey = sessionKey
706 entry.state = cs
707 c.q.MoveToFront(elem)
708 c.m[sessionKey] = elem
709}
710
711// Get returns the ClientSessionState value associated with a given key. It
712// returns (nil, false) if no value is found.
713func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
714 c.Lock()
715 defer c.Unlock()
716
717 if elem, ok := c.m[sessionKey]; ok {
718 c.q.MoveToFront(elem)
719 return elem.Value.(*lruSessionCacheEntry).state, true
720 }
721 return nil, false
722}
723
724// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
725type dsaSignature struct {
726 R, S *big.Int
727}
728
729type ecdsaSignature dsaSignature
730
731var emptyConfig Config
732
733func defaultConfig() *Config {
734 return &emptyConfig
735}
736
737var (
738 once sync.Once
739 varDefaultCipherSuites []uint16
740)
741
742func defaultCipherSuites() []uint16 {
743 once.Do(initDefaultCipherSuites)
744 return varDefaultCipherSuites
745}
746
747func initDefaultCipherSuites() {
David Benjamin48cae082014-10-27 01:06:24 -0400748 for _, suite := range cipherSuites {
749 if suite.flags&suitePSK == 0 {
750 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
751 }
Adam Langley95c29f32014-06-20 12:00:00 -0700752 }
753}
754
755func unexpectedMessageError(wanted, got interface{}) error {
756 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
757}