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