blob: 0b8bfe589d0fcbcaef9f6b3d994c83ad016201b5 [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 (
David Benjamin61f95272014-11-25 01:55:35 -050075 extensionServerName uint16 = 0
76 extensionStatusRequest uint16 = 5
77 extensionSupportedCurves uint16 = 10
78 extensionSupportedPoints uint16 = 11
79 extensionSignatureAlgorithms uint16 = 13
80 extensionUseSRTP uint16 = 14
81 extensionALPN uint16 = 16
82 extensionSignedCertificateTimestamp uint16 = 18
83 extensionExtendedMasterSecret uint16 = 23
84 extensionSessionTicket uint16 = 35
David Benjamin399e7c92015-07-30 23:01:27 -040085 extensionCustom uint16 = 1234 // not IANA assigned
David Benjamin61f95272014-11-25 01:55:35 -050086 extensionNextProtoNeg uint16 = 13172 // not IANA assigned
87 extensionRenegotiationInfo uint16 = 0xff01
88 extensionChannelID uint16 = 30032 // not IANA assigned
Adam Langley95c29f32014-06-20 12:00:00 -070089)
90
91// TLS signaling cipher suite values
92const (
93 scsvRenegotiation uint16 = 0x00ff
94)
95
96// CurveID is the type of a TLS identifier for an elliptic curve. See
97// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
98type CurveID uint16
99
100const (
David Benjaminc574f412015-04-20 11:13:01 -0400101 CurveP224 CurveID = 21
Adam Langley95c29f32014-06-20 12:00:00 -0700102 CurveP256 CurveID = 23
103 CurveP384 CurveID = 24
104 CurveP521 CurveID = 25
105)
106
107// TLS Elliptic Curve Point Formats
108// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
109const (
110 pointFormatUncompressed uint8 = 0
111)
112
113// TLS CertificateStatusType (RFC 3546)
114const (
115 statusTypeOCSP uint8 = 1
116)
117
118// Certificate types (for certificateRequestMsg)
119const (
David Benjamin7b030512014-07-08 17:30:11 -0400120 CertTypeRSASign = 1 // A certificate containing an RSA key
121 CertTypeDSSSign = 2 // A certificate containing a DSA key
122 CertTypeRSAFixedDH = 3 // A certificate containing a static DH key
123 CertTypeDSSFixedDH = 4 // A certificate containing a static DH key
Adam Langley95c29f32014-06-20 12:00:00 -0700124
125 // See RFC4492 sections 3 and 5.5.
David Benjamin7b030512014-07-08 17:30:11 -0400126 CertTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
127 CertTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
128 CertTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
Adam Langley95c29f32014-06-20 12:00:00 -0700129
130 // Rest of these are reserved by the TLS spec
131)
132
133// Hash functions for TLS 1.2 (See RFC 5246, section A.4.1)
134const (
David Benjamin000800a2014-11-14 01:43:59 -0500135 hashMD5 uint8 = 1
Adam Langley95c29f32014-06-20 12:00:00 -0700136 hashSHA1 uint8 = 2
David Benjamin000800a2014-11-14 01:43:59 -0500137 hashSHA224 uint8 = 3
Adam Langley95c29f32014-06-20 12:00:00 -0700138 hashSHA256 uint8 = 4
David Benjamin000800a2014-11-14 01:43:59 -0500139 hashSHA384 uint8 = 5
140 hashSHA512 uint8 = 6
Adam Langley95c29f32014-06-20 12:00:00 -0700141)
142
143// Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
144const (
145 signatureRSA uint8 = 1
146 signatureECDSA uint8 = 3
147)
148
149// signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See
150// RFC 5246, section A.4.1.
151type signatureAndHash struct {
David Benjamine098ec22014-08-27 23:13:20 -0400152 signature, hash uint8
Adam Langley95c29f32014-06-20 12:00:00 -0700153}
154
155// supportedSKXSignatureAlgorithms contains the signature and hash algorithms
156// that the code advertises as supported in a TLS 1.2 ClientHello.
157var supportedSKXSignatureAlgorithms = []signatureAndHash{
David Benjamine098ec22014-08-27 23:13:20 -0400158 {signatureRSA, hashSHA256},
159 {signatureECDSA, hashSHA256},
160 {signatureRSA, hashSHA1},
161 {signatureECDSA, hashSHA1},
Adam Langley95c29f32014-06-20 12:00:00 -0700162}
163
164// supportedClientCertSignatureAlgorithms contains the signature and hash
165// algorithms that the code advertises as supported in a TLS 1.2
166// CertificateRequest.
167var supportedClientCertSignatureAlgorithms = []signatureAndHash{
David Benjamine098ec22014-08-27 23:13:20 -0400168 {signatureRSA, hashSHA256},
169 {signatureECDSA, hashSHA256},
Adam Langley95c29f32014-06-20 12:00:00 -0700170}
171
David Benjaminca6c8262014-11-15 19:06:08 -0500172// SRTP protection profiles (See RFC 5764, section 4.1.2)
173const (
174 SRTP_AES128_CM_HMAC_SHA1_80 uint16 = 0x0001
175 SRTP_AES128_CM_HMAC_SHA1_32 = 0x0002
176)
177
Adam Langley95c29f32014-06-20 12:00:00 -0700178// ConnectionState records basic TLS details about the connection.
179type ConnectionState struct {
180 Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
181 HandshakeComplete bool // TLS handshake is complete
182 DidResume bool // connection resumes a previous TLS connection
183 CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
184 NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos)
185 NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server
David Benjaminfc7b0862014-09-06 13:21:53 -0400186 NegotiatedProtocolFromALPN bool // protocol negotiated with ALPN
Adam Langley95c29f32014-06-20 12:00:00 -0700187 ServerName string // server name requested by client, if any (server side only)
188 PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
189 VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
David Benjamind30a9902014-08-24 01:44:23 -0400190 ChannelID *ecdsa.PublicKey // the channel ID for this connection
David Benjaminca6c8262014-11-15 19:06:08 -0500191 SRTPProtectionProfile uint16 // the negotiated DTLS-SRTP protection profile
Adam Langleyaf0e32c2015-06-03 09:57:23 -0700192 TLSUnique []byte
Paul Lietar4fac72e2015-09-09 13:44:55 +0100193 SCTList []byte // signed certificate timestamp list
Adam Langley95c29f32014-06-20 12:00:00 -0700194}
195
196// ClientAuthType declares the policy the server will follow for
197// TLS Client Authentication.
198type ClientAuthType int
199
200const (
201 NoClientCert ClientAuthType = iota
202 RequestClientCert
203 RequireAnyClientCert
204 VerifyClientCertIfGiven
205 RequireAndVerifyClientCert
206)
207
208// ClientSessionState contains the state needed by clients to resume TLS
209// sessions.
210type ClientSessionState struct {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500211 sessionId []uint8 // Session ID supplied by the server. nil if the session has a ticket.
Adam Langley75712922014-10-10 16:23:43 -0700212 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
213 vers uint16 // SSL/TLS version negotiated for the session
214 cipherSuite uint16 // Ciphersuite negotiated for the session
215 masterSecret []byte // MasterSecret generated by client on a full handshake
216 handshakeHash []byte // Handshake hash for Channel ID purposes.
217 serverCertificates []*x509.Certificate // Certificate chain presented by the server
218 extendedMasterSecret bool // Whether an extended master secret was used to generate the session
Adam Langley95c29f32014-06-20 12:00:00 -0700219}
220
221// ClientSessionCache is a cache of ClientSessionState objects that can be used
222// by a client to resume a TLS session with a given server. ClientSessionCache
223// implementations should expect to be called concurrently from different
224// goroutines.
225type ClientSessionCache interface {
226 // Get searches for a ClientSessionState associated with the given key.
227 // On return, ok is true if one was found.
228 Get(sessionKey string) (session *ClientSessionState, ok bool)
229
230 // Put adds the ClientSessionState to the cache with the given key.
231 Put(sessionKey string, cs *ClientSessionState)
232}
233
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500234// ServerSessionCache is a cache of sessionState objects that can be used by a
235// client to resume a TLS session with a given server. ServerSessionCache
236// implementations should expect to be called concurrently from different
237// goroutines.
238type ServerSessionCache interface {
239 // Get searches for a sessionState associated with the given session
240 // ID. On return, ok is true if one was found.
241 Get(sessionId string) (session *sessionState, ok bool)
242
243 // Put adds the sessionState to the cache with the given session ID.
244 Put(sessionId string, session *sessionState)
245}
246
Adam Langley95c29f32014-06-20 12:00:00 -0700247// A Config structure is used to configure a TLS client or server.
248// After one has been passed to a TLS function it must not be
249// modified. A Config may be reused; the tls package will also not
250// modify it.
251type Config struct {
252 // Rand provides the source of entropy for nonces and RSA blinding.
253 // If Rand is nil, TLS uses the cryptographic random reader in package
254 // crypto/rand.
255 // The Reader must be safe for use by multiple goroutines.
256 Rand io.Reader
257
258 // Time returns the current time as the number of seconds since the epoch.
259 // If Time is nil, TLS uses time.Now.
260 Time func() time.Time
261
262 // Certificates contains one or more certificate chains
263 // to present to the other side of the connection.
264 // Server configurations must include at least one certificate.
265 Certificates []Certificate
266
267 // NameToCertificate maps from a certificate name to an element of
268 // Certificates. Note that a certificate name can be of the form
269 // '*.example.com' and so doesn't have to be a domain name as such.
270 // See Config.BuildNameToCertificate
271 // The nil value causes the first element of Certificates to be used
272 // for all connections.
273 NameToCertificate map[string]*Certificate
274
275 // RootCAs defines the set of root certificate authorities
276 // that clients use when verifying server certificates.
277 // If RootCAs is nil, TLS uses the host's root CA set.
278 RootCAs *x509.CertPool
279
280 // NextProtos is a list of supported, application level protocols.
281 NextProtos []string
282
283 // ServerName is used to verify the hostname on the returned
284 // certificates unless InsecureSkipVerify is given. It is also included
285 // in the client's handshake to support virtual hosting.
286 ServerName string
287
288 // ClientAuth determines the server's policy for
289 // TLS Client Authentication. The default is NoClientCert.
290 ClientAuth ClientAuthType
291
292 // ClientCAs defines the set of root certificate authorities
293 // that servers use if required to verify a client certificate
294 // by the policy in ClientAuth.
295 ClientCAs *x509.CertPool
296
David Benjamin7b030512014-07-08 17:30:11 -0400297 // ClientCertificateTypes defines the set of allowed client certificate
298 // types. The default is CertTypeRSASign and CertTypeECDSASign.
299 ClientCertificateTypes []byte
300
Adam Langley95c29f32014-06-20 12:00:00 -0700301 // InsecureSkipVerify controls whether a client verifies the
302 // server's certificate chain and host name.
303 // If InsecureSkipVerify is true, TLS accepts any certificate
304 // presented by the server and any host name in that certificate.
305 // In this mode, TLS is susceptible to man-in-the-middle attacks.
306 // This should be used only for testing.
307 InsecureSkipVerify bool
308
309 // CipherSuites is a list of supported cipher suites. If CipherSuites
310 // is nil, TLS uses a list of suites supported by the implementation.
311 CipherSuites []uint16
312
313 // PreferServerCipherSuites controls whether the server selects the
314 // client's most preferred ciphersuite, or the server's most preferred
315 // ciphersuite. If true then the server's preference, as expressed in
316 // the order of elements in CipherSuites, is used.
317 PreferServerCipherSuites bool
318
319 // SessionTicketsDisabled may be set to true to disable session ticket
320 // (resumption) support.
321 SessionTicketsDisabled bool
322
323 // SessionTicketKey is used by TLS servers to provide session
324 // resumption. See RFC 5077. If zero, it will be filled with
325 // random data before the first server handshake.
326 //
327 // If multiple servers are terminating connections for the same host
328 // they should all have the same SessionTicketKey. If the
329 // SessionTicketKey leaks, previously recorded and future TLS
330 // connections using that key are compromised.
331 SessionTicketKey [32]byte
332
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500333 // ClientSessionCache is a cache of ClientSessionState entries
334 // for TLS session resumption.
Adam Langley95c29f32014-06-20 12:00:00 -0700335 ClientSessionCache ClientSessionCache
336
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500337 // ServerSessionCache is a cache of sessionState entries for TLS session
338 // resumption.
339 ServerSessionCache ServerSessionCache
340
Adam Langley95c29f32014-06-20 12:00:00 -0700341 // MinVersion contains the minimum SSL/TLS version that is acceptable.
342 // If zero, then SSLv3 is taken as the minimum.
343 MinVersion uint16
344
345 // MaxVersion contains the maximum SSL/TLS version that is acceptable.
346 // If zero, then the maximum version supported by this package is used,
347 // which is currently TLS 1.2.
348 MaxVersion uint16
349
350 // CurvePreferences contains the elliptic curves that will be used in
351 // an ECDHE handshake, in preference order. If empty, the default will
352 // be used.
353 CurvePreferences []CurveID
354
David Benjamind30a9902014-08-24 01:44:23 -0400355 // ChannelID contains the ECDSA key for the client to use as
356 // its TLS Channel ID.
357 ChannelID *ecdsa.PrivateKey
358
359 // RequestChannelID controls whether the server requests a TLS
360 // Channel ID. If negotiated, the client's public key is
361 // returned in the ConnectionState.
362 RequestChannelID bool
363
David Benjamin48cae082014-10-27 01:06:24 -0400364 // PreSharedKey, if not nil, is the pre-shared key to use with
365 // the PSK cipher suites.
366 PreSharedKey []byte
367
368 // PreSharedKeyIdentity, if not empty, is the identity to use
369 // with the PSK cipher suites.
370 PreSharedKeyIdentity string
371
David Benjaminca6c8262014-11-15 19:06:08 -0500372 // SRTPProtectionProfiles, if not nil, is the list of SRTP
373 // protection profiles to offer in DTLS-SRTP.
374 SRTPProtectionProfiles []uint16
375
David Benjamin000800a2014-11-14 01:43:59 -0500376 // SignatureAndHashes, if not nil, overrides the default set of
377 // supported signature and hash algorithms to advertise in
378 // CertificateRequest.
379 SignatureAndHashes []signatureAndHash
380
Adam Langley95c29f32014-06-20 12:00:00 -0700381 // Bugs specifies optional misbehaviour to be used for testing other
382 // implementations.
383 Bugs ProtocolBugs
384
385 serverInitOnce sync.Once // guards calling (*Config).serverInit
386}
387
388type BadValue int
389
390const (
391 BadValueNone BadValue = iota
392 BadValueNegative
393 BadValueZero
394 BadValueLimit
395 BadValueLarge
396 NumBadValues
397)
398
399type ProtocolBugs struct {
400 // InvalidSKXSignature specifies that the signature in a
401 // ServerKeyExchange message should be invalid.
402 InvalidSKXSignature bool
403
David Benjamin6de0e532015-07-28 22:43:19 -0400404 // InvalidCertVerifySignature specifies that the signature in a
405 // CertificateVerify message should be invalid.
406 InvalidCertVerifySignature bool
407
Adam Langley95c29f32014-06-20 12:00:00 -0700408 // InvalidSKXCurve causes the curve ID in the ServerKeyExchange message
409 // to be wrong.
410 InvalidSKXCurve bool
411
412 // BadECDSAR controls ways in which the 'r' value of an ECDSA signature
413 // can be invalid.
414 BadECDSAR BadValue
415 BadECDSAS BadValue
Adam Langley80842bd2014-06-20 12:00:00 -0700416
417 // MaxPadding causes CBC records to have the maximum possible padding.
418 MaxPadding bool
419 // PaddingFirstByteBad causes the first byte of the padding to be
420 // incorrect.
421 PaddingFirstByteBad bool
422 // PaddingFirstByteBadIf255 causes the first byte of padding to be
423 // incorrect if there's a maximum amount of padding (i.e. 255 bytes).
424 PaddingFirstByteBadIf255 bool
Adam Langleyac61fa32014-06-23 12:03:11 -0700425
426 // FailIfNotFallbackSCSV causes a server handshake to fail if the
427 // client doesn't send the fallback SCSV value.
428 FailIfNotFallbackSCSV bool
David Benjamin35a7a442014-07-05 00:23:20 -0400429
430 // DuplicateExtension causes an extra empty extension of bogus type to
431 // be emitted in either the ClientHello or the ServerHello.
432 DuplicateExtension bool
David Benjamin1c375dd2014-07-12 00:48:23 -0400433
434 // UnauthenticatedECDH causes the server to pretend ECDHE_RSA
435 // and ECDHE_ECDSA cipher suites are actually ECDH_anon. No
436 // Certificate message is sent and no signature is added to
437 // ServerKeyExchange.
438 UnauthenticatedECDH bool
David Benjamin9c651c92014-07-12 13:27:45 -0400439
David Benjaminb80168e2015-02-08 18:30:14 -0500440 // SkipHelloVerifyRequest causes a DTLS server to skip the
441 // HelloVerifyRequest message.
442 SkipHelloVerifyRequest bool
443
David Benjamindcd979f2015-04-20 18:26:52 -0400444 // SkipCertificateStatus, if true, causes the server to skip the
445 // CertificateStatus message. This is legal because CertificateStatus is
446 // optional, even with a status_request in ServerHello.
447 SkipCertificateStatus bool
448
David Benjamin9c651c92014-07-12 13:27:45 -0400449 // SkipServerKeyExchange causes the server to skip sending
450 // ServerKeyExchange messages.
451 SkipServerKeyExchange bool
David Benjamina0e52232014-07-19 17:39:58 -0400452
David Benjaminb80168e2015-02-08 18:30:14 -0500453 // SkipNewSessionTicket causes the server to skip sending the
454 // NewSessionTicket message despite promising to in ServerHello.
455 SkipNewSessionTicket bool
456
David Benjamina0e52232014-07-19 17:39:58 -0400457 // SkipChangeCipherSpec causes the implementation to skip
458 // sending the ChangeCipherSpec message (and adjusting cipher
459 // state accordingly for the Finished message).
460 SkipChangeCipherSpec bool
David Benjaminf3ec83d2014-07-21 22:42:34 -0400461
David Benjaminb80168e2015-02-08 18:30:14 -0500462 // SkipFinished causes the implementation to skip sending the Finished
463 // message.
464 SkipFinished bool
465
David Benjaminf3ec83d2014-07-21 22:42:34 -0400466 // EarlyChangeCipherSpec causes the client to send an early
467 // ChangeCipherSpec message before the ClientKeyExchange. A value of
468 // zero disables this behavior. One and two configure variants for 0.9.8
469 // and 1.0.1 modes, respectively.
470 EarlyChangeCipherSpec int
David Benjamind23f4122014-07-23 15:09:48 -0400471
David Benjamin86271ee2014-07-21 16:14:03 -0400472 // FragmentAcrossChangeCipherSpec causes the implementation to fragment
473 // the Finished (or NextProto) message around the ChangeCipherSpec
474 // messages.
475 FragmentAcrossChangeCipherSpec bool
476
David Benjamind86c7672014-08-02 04:07:12 -0400477 // SendV2ClientHello causes the client to send a V2ClientHello
478 // instead of a normal ClientHello.
479 SendV2ClientHello bool
David Benjaminbef270a2014-08-02 04:22:02 -0400480
481 // SendFallbackSCSV causes the client to include
482 // TLS_FALLBACK_SCSV in the ClientHello.
483 SendFallbackSCSV bool
David Benjamin43ec06f2014-08-05 02:28:57 -0400484
Adam Langley5021b222015-06-12 18:27:58 -0700485 // SendRenegotiationSCSV causes the client to include the renegotiation
486 // SCSV in the ClientHello.
487 SendRenegotiationSCSV bool
488
David Benjamin43ec06f2014-08-05 02:28:57 -0400489 // MaxHandshakeRecordLength, if non-zero, is the maximum size of a
David Benjamin98214542014-08-07 18:02:39 -0400490 // handshake record. Handshake messages will be split into multiple
491 // records at the specified size, except that the client_version will
David Benjaminbd15a8e2015-05-29 18:48:16 -0400492 // never be fragmented. For DTLS, it is the maximum handshake fragment
493 // size, not record size; DTLS allows multiple handshake fragments in a
494 // single handshake record. See |PackHandshakeFragments|.
David Benjamin43ec06f2014-08-05 02:28:57 -0400495 MaxHandshakeRecordLength int
David Benjamina8e3e0e2014-08-06 22:11:10 -0400496
David Benjamin98214542014-08-07 18:02:39 -0400497 // FragmentClientVersion will allow MaxHandshakeRecordLength to apply to
498 // the first 6 bytes of the ClientHello.
499 FragmentClientVersion bool
500
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400501 // FragmentAlert will cause all alerts to be fragmented across
502 // two records.
503 FragmentAlert bool
504
David Benjamin3fd1fbd2015-02-03 16:07:32 -0500505 // SendSpuriousAlert, if non-zero, will cause an spurious, unwanted
506 // alert to be sent.
507 SendSpuriousAlert alert
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400508
David Benjamina8e3e0e2014-08-06 22:11:10 -0400509 // RsaClientKeyExchangeVersion, if non-zero, causes the client to send a
510 // ClientKeyExchange with the specified version rather than the
511 // client_version when performing the RSA key exchange.
512 RsaClientKeyExchangeVersion uint16
David Benjaminbed9aae2014-08-07 19:13:38 -0400513
514 // RenewTicketOnResume causes the server to renew the session ticket and
515 // send a NewSessionTicket message during an abbreviated handshake.
516 RenewTicketOnResume bool
David Benjamin98e882e2014-08-08 13:24:34 -0400517
518 // SendClientVersion, if non-zero, causes the client to send a different
519 // TLS version in the ClientHello than the maximum supported version.
520 SendClientVersion uint16
David Benjamin83c0bc92014-08-04 01:23:53 -0400521
David Benjamine58c4f52014-08-24 03:47:07 -0400522 // ExpectFalseStart causes the server to, on full handshakes,
523 // expect the peer to False Start; the server Finished message
524 // isn't sent until we receive an application data record
525 // from the peer.
526 ExpectFalseStart bool
David Benjamin5c24a1d2014-08-31 00:59:27 -0400527
David Benjamin1c633152015-04-02 20:19:11 -0400528 // AlertBeforeFalseStartTest, if non-zero, causes the server to, on full
529 // handshakes, send an alert just before reading the application data
530 // record to test False Start. This can be used in a negative False
531 // Start test to determine whether the peer processed the alert (and
532 // closed the connection) before or after sending app data.
533 AlertBeforeFalseStartTest alert
534
David Benjamin5c24a1d2014-08-31 00:59:27 -0400535 // SSL3RSAKeyExchange causes the client to always send an RSA
536 // ClientKeyExchange message without the two-byte length
537 // prefix, as if it were SSL3.
538 SSL3RSAKeyExchange bool
David Benjamin39ebf532014-08-31 02:23:49 -0400539
540 // SkipCipherVersionCheck causes the server to negotiate
541 // TLS 1.2 ciphers in earlier versions of TLS.
542 SkipCipherVersionCheck bool
David Benjamine78bfde2014-09-06 12:45:15 -0400543
544 // ExpectServerName, if not empty, is the hostname the client
545 // must specify in the server_name extension.
546 ExpectServerName string
David Benjaminfc7b0862014-09-06 13:21:53 -0400547
David Benjamin76c2efc2015-08-31 14:24:29 -0400548 // SwapNPNAndALPN switches the relative order between NPN and ALPN in
549 // both ClientHello and ServerHello.
David Benjaminfc7b0862014-09-06 13:21:53 -0400550 SwapNPNAndALPN bool
David Benjamin01fe8202014-09-24 15:21:44 -0400551
Adam Langleyefb0e162015-07-09 11:35:04 -0700552 // ALPNProtocol, if not nil, sets the ALPN protocol that a server will
553 // return.
554 ALPNProtocol *string
555
David Benjamin01fe8202014-09-24 15:21:44 -0400556 // AllowSessionVersionMismatch causes the server to resume sessions
557 // regardless of the version associated with the session.
558 AllowSessionVersionMismatch bool
Adam Langley38311732014-10-16 19:04:35 -0700559
560 // CorruptTicket causes a client to corrupt a session ticket before
561 // sending it in a resume handshake.
562 CorruptTicket bool
563
564 // OversizedSessionId causes the session id that is sent with a ticket
565 // resumption attempt to be too large (33 bytes).
566 OversizedSessionId bool
Adam Langley75712922014-10-10 16:23:43 -0700567
568 // RequireExtendedMasterSecret, if true, requires that the peer support
569 // the extended master secret option.
570 RequireExtendedMasterSecret bool
571
David Benjaminca6554b2014-11-08 12:31:52 -0500572 // NoExtendedMasterSecret causes the client and server to behave as if
Adam Langley75712922014-10-10 16:23:43 -0700573 // they didn't support an extended master secret.
574 NoExtendedMasterSecret bool
Adam Langley2ae77d22014-10-28 17:29:33 -0700575
576 // EmptyRenegotiationInfo causes the renegotiation extension to be
577 // empty in a renegotiation handshake.
578 EmptyRenegotiationInfo bool
579
580 // BadRenegotiationInfo causes the renegotiation extension value in a
581 // renegotiation handshake to be incorrect.
582 BadRenegotiationInfo bool
David Benjamin5e961c12014-11-07 01:48:35 -0500583
David Benjaminca6554b2014-11-08 12:31:52 -0500584 // NoRenegotiationInfo causes the client to behave as if it
585 // didn't support the renegotiation info extension.
586 NoRenegotiationInfo bool
587
Adam Langley5021b222015-06-12 18:27:58 -0700588 // RequireRenegotiationInfo, if true, causes the client to return an
589 // error if the server doesn't reply with the renegotiation extension.
590 RequireRenegotiationInfo bool
591
David Benjamin8e6db492015-07-25 18:29:23 -0400592 // SequenceNumberMapping, if non-nil, is the mapping function to apply
593 // to the sequence number of outgoing packets. For both TLS and DTLS,
594 // the two most-significant bytes in the resulting sequence number are
595 // ignored so that the DTLS epoch cannot be changed.
596 SequenceNumberMapping func(uint64) uint64
David Benjamin9114fae2014-11-08 11:41:14 -0500597
David Benjamina3e89492015-02-26 15:16:22 -0500598 // RSAEphemeralKey, if true, causes the server to send a
599 // ServerKeyExchange message containing an ephemeral key (as in
600 // RSA_EXPORT) in the plain RSA key exchange.
601 RSAEphemeralKey bool
David Benjaminca6c8262014-11-15 19:06:08 -0500602
603 // SRTPMasterKeyIdentifer, if not empty, is the SRTP MKI value that the
604 // client offers when negotiating SRTP. MKI support is still missing so
605 // the peer must still send none.
606 SRTPMasterKeyIdentifer string
607
608 // SendSRTPProtectionProfile, if non-zero, is the SRTP profile that the
609 // server sends in the ServerHello instead of the negotiated one.
610 SendSRTPProtectionProfile uint16
David Benjamin000800a2014-11-14 01:43:59 -0500611
612 // NoSignatureAndHashes, if true, causes the client to omit the
613 // signature and hashes extension.
614 //
615 // For a server, it will cause an empty list to be sent in the
616 // CertificateRequest message. None the less, the configured set will
617 // still be enforced.
618 NoSignatureAndHashes bool
David Benjaminc44b1df2014-11-23 12:11:01 -0500619
David Benjamin55a43642015-04-20 14:45:55 -0400620 // NoSupportedCurves, if true, causes the client to omit the
621 // supported_curves extension.
622 NoSupportedCurves bool
623
David Benjaminc44b1df2014-11-23 12:11:01 -0500624 // RequireSameRenegoClientVersion, if true, causes the server
625 // to require that all ClientHellos match in offered version
626 // across a renego.
627 RequireSameRenegoClientVersion bool
Feng Lu41aa3252014-11-21 22:47:56 -0800628
David Benjamin1e29a6b2014-12-10 02:27:24 -0500629 // ExpectInitialRecordVersion, if non-zero, is the expected
630 // version of the records before the version is determined.
631 ExpectInitialRecordVersion uint16
David Benjamin13be1de2015-01-11 16:29:36 -0500632
633 // MaxPacketLength, if non-zero, is the maximum acceptable size for a
634 // packet.
635 MaxPacketLength int
David Benjamin6095de82014-12-27 01:50:38 -0500636
637 // SendCipherSuite, if non-zero, is the cipher suite value that the
638 // server will send in the ServerHello. This does not affect the cipher
639 // the server believes it has actually negotiated.
640 SendCipherSuite uint16
David Benjamin4189bd92015-01-25 23:52:39 -0500641
David Benjamin4cf369b2015-08-22 01:35:43 -0400642 // AppDataBeforeHandshake, if not nil, causes application data to be
643 // sent immediately before the first handshake message.
644 AppDataBeforeHandshake []byte
645
646 // AppDataAfterChangeCipherSpec, if not nil, causes application data to
David Benjamin4189bd92015-01-25 23:52:39 -0500647 // be sent immediately after ChangeCipherSpec.
648 AppDataAfterChangeCipherSpec []byte
David Benjamin83f90402015-01-27 01:09:43 -0500649
David Benjamindc3da932015-03-12 15:09:02 -0400650 // AlertAfterChangeCipherSpec, if non-zero, causes an alert to be sent
651 // immediately after ChangeCipherSpec.
652 AlertAfterChangeCipherSpec alert
653
David Benjamin83f90402015-01-27 01:09:43 -0500654 // TimeoutSchedule is the schedule of packet drops and simulated
655 // timeouts for before each handshake leg from the peer.
656 TimeoutSchedule []time.Duration
657
658 // PacketAdaptor is the packetAdaptor to use to simulate timeouts.
659 PacketAdaptor *packetAdaptor
David Benjaminb3774b92015-01-31 17:16:01 -0500660
661 // ReorderHandshakeFragments, if true, causes handshake fragments in
662 // DTLS to overlap and be sent in the wrong order. It also causes
663 // pre-CCS flights to be sent twice. (Post-CCS flights consist of
664 // Finished and will trigger a spurious retransmit.)
665 ReorderHandshakeFragments bool
David Benjaminddb9f152015-02-03 15:44:39 -0500666
David Benjamin75381222015-03-02 19:30:30 -0500667 // MixCompleteMessageWithFragments, if true, causes handshake
668 // messages in DTLS to redundantly both fragment the message
669 // and include a copy of the full one.
670 MixCompleteMessageWithFragments bool
671
David Benjaminddb9f152015-02-03 15:44:39 -0500672 // SendInvalidRecordType, if true, causes a record with an invalid
673 // content type to be sent immediately following the handshake.
674 SendInvalidRecordType bool
David Benjaminbcb2d912015-02-24 23:45:43 -0500675
676 // WrongCertificateMessageType, if true, causes Certificate message to
677 // be sent with the wrong message type.
678 WrongCertificateMessageType bool
David Benjamin75381222015-03-02 19:30:30 -0500679
680 // FragmentMessageTypeMismatch, if true, causes all non-initial
681 // handshake fragments in DTLS to have the wrong message type.
682 FragmentMessageTypeMismatch bool
683
684 // FragmentMessageLengthMismatch, if true, causes all non-initial
685 // handshake fragments in DTLS to have the wrong message length.
686 FragmentMessageLengthMismatch bool
687
David Benjamin11fc66a2015-06-16 11:40:24 -0400688 // SplitFragments, if non-zero, causes the handshake fragments in DTLS
689 // to be split across two records. The value of |SplitFragments| is the
690 // number of bytes in the first fragment.
691 SplitFragments int
David Benjamin75381222015-03-02 19:30:30 -0500692
693 // SendEmptyFragments, if true, causes handshakes to include empty
694 // fragments in DTLS.
695 SendEmptyFragments bool
David Benjamincdea40c2015-03-19 14:09:43 -0400696
David Benjamin9a41d1b2015-05-16 01:30:09 -0400697 // SendSplitAlert, if true, causes an alert to be sent with the header
698 // and record body split across multiple packets. The peer should
699 // discard these packets rather than process it.
700 SendSplitAlert bool
701
David Benjamin4b27d9f2015-05-12 22:42:52 -0400702 // FailIfResumeOnRenego, if true, causes renegotiations to fail if the
703 // client offers a resumption or the server accepts one.
704 FailIfResumeOnRenego bool
David Benjamin3c9746a2015-03-19 15:00:10 -0400705
David Benjamin67d1fb52015-03-16 15:16:23 -0400706 // IgnorePeerCipherPreferences, if true, causes the peer's cipher
707 // preferences to be ignored.
708 IgnorePeerCipherPreferences bool
David Benjamin72dc7832015-03-16 17:49:43 -0400709
710 // IgnorePeerSignatureAlgorithmPreferences, if true, causes the peer's
711 // signature algorithm preferences to be ignored.
712 IgnorePeerSignatureAlgorithmPreferences bool
David Benjamin340d5ed2015-03-21 02:21:37 -0400713
David Benjaminc574f412015-04-20 11:13:01 -0400714 // IgnorePeerCurvePreferences, if true, causes the peer's curve
715 // preferences to be ignored.
716 IgnorePeerCurvePreferences bool
717
David Benjamin513f0ea2015-04-02 19:33:31 -0400718 // BadFinished, if true, causes the Finished hash to be broken.
719 BadFinished bool
Adam Langleya7997f12015-05-14 17:38:50 -0700720
721 // DHGroupPrime, if not nil, is used to define the (finite field)
722 // Diffie-Hellman group. The generator used is always two.
723 DHGroupPrime *big.Int
David Benjaminbd15a8e2015-05-29 18:48:16 -0400724
725 // PackHandshakeFragments, if true, causes handshake fragments to be
726 // packed into individual handshake records, up to the specified record
727 // size.
728 PackHandshakeFragments int
729
730 // PackHandshakeRecords, if true, causes handshake records to be packed
731 // into individual packets, up to the specified packet size.
732 PackHandshakeRecords int
David Benjamin0fa40122015-05-30 17:13:12 -0400733
734 // EnableAllCiphersInDTLS, if true, causes RC4 to be enabled in DTLS.
735 EnableAllCiphersInDTLS bool
David Benjamin8923c0b2015-06-07 11:42:34 -0400736
737 // EmptyCertificateList, if true, causes the server to send an empty
738 // certificate list in the Certificate message.
739 EmptyCertificateList bool
David Benjamind98452d2015-06-16 14:16:23 -0400740
741 // ExpectNewTicket, if true, causes the client to abort if it does not
742 // receive a new ticket.
743 ExpectNewTicket bool
Adam Langley33ad2b52015-07-20 17:43:53 -0700744
745 // RequireClientHelloSize, if not zero, is the required length in bytes
746 // of the ClientHello /record/. This is checked by the server.
747 RequireClientHelloSize int
Adam Langley09505632015-07-30 18:10:13 -0700748
749 // CustomExtension, if not empty, contains the contents of an extension
750 // that will be added to client/server hellos.
751 CustomExtension string
752
753 // ExpectedCustomExtension, if not nil, contains the expected contents
754 // of a custom extension.
755 ExpectedCustomExtension *string
David Benjamin30789da2015-08-29 22:56:45 -0400756
757 // NoCloseNotify, if true, causes the close_notify alert to be skipped
758 // on connection shutdown.
759 NoCloseNotify bool
760
761 // ExpectCloseNotify, if true, requires a close_notify from the peer on
762 // shutdown. Records from the peer received after close_notify is sent
763 // are not discard.
764 ExpectCloseNotify bool
David Benjamin2c99d282015-09-01 10:23:00 -0400765
766 // SendLargeRecords, if true, allows outgoing records to be sent
767 // arbitrarily large.
768 SendLargeRecords bool
David Benjamin76c2efc2015-08-31 14:24:29 -0400769
770 // NegotiateALPNAndNPN, if true, causes the server to negotiate both
771 // ALPN and NPN in the same connetion.
772 NegotiateALPNAndNPN bool
Adam Langley95c29f32014-06-20 12:00:00 -0700773}
774
775func (c *Config) serverInit() {
776 if c.SessionTicketsDisabled {
777 return
778 }
779
780 // If the key has already been set then we have nothing to do.
781 for _, b := range c.SessionTicketKey {
782 if b != 0 {
783 return
784 }
785 }
786
787 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
788 c.SessionTicketsDisabled = true
789 }
790}
791
792func (c *Config) rand() io.Reader {
793 r := c.Rand
794 if r == nil {
795 return rand.Reader
796 }
797 return r
798}
799
800func (c *Config) time() time.Time {
801 t := c.Time
802 if t == nil {
803 t = time.Now
804 }
805 return t()
806}
807
808func (c *Config) cipherSuites() []uint16 {
809 s := c.CipherSuites
810 if s == nil {
811 s = defaultCipherSuites()
812 }
813 return s
814}
815
816func (c *Config) minVersion() uint16 {
817 if c == nil || c.MinVersion == 0 {
818 return minVersion
819 }
820 return c.MinVersion
821}
822
823func (c *Config) maxVersion() uint16 {
824 if c == nil || c.MaxVersion == 0 {
825 return maxVersion
826 }
827 return c.MaxVersion
828}
829
830var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
831
832func (c *Config) curvePreferences() []CurveID {
833 if c == nil || len(c.CurvePreferences) == 0 {
834 return defaultCurvePreferences
835 }
836 return c.CurvePreferences
837}
838
839// mutualVersion returns the protocol version to use given the advertised
840// version of the peer.
841func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
842 minVersion := c.minVersion()
843 maxVersion := c.maxVersion()
844
845 if vers < minVersion {
846 return 0, false
847 }
848 if vers > maxVersion {
849 vers = maxVersion
850 }
851 return vers, true
852}
853
854// getCertificateForName returns the best certificate for the given name,
855// defaulting to the first element of c.Certificates if there are no good
856// options.
857func (c *Config) getCertificateForName(name string) *Certificate {
858 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
859 // There's only one choice, so no point doing any work.
860 return &c.Certificates[0]
861 }
862
863 name = strings.ToLower(name)
864 for len(name) > 0 && name[len(name)-1] == '.' {
865 name = name[:len(name)-1]
866 }
867
868 if cert, ok := c.NameToCertificate[name]; ok {
869 return cert
870 }
871
872 // try replacing labels in the name with wildcards until we get a
873 // match.
874 labels := strings.Split(name, ".")
875 for i := range labels {
876 labels[i] = "*"
877 candidate := strings.Join(labels, ".")
878 if cert, ok := c.NameToCertificate[candidate]; ok {
879 return cert
880 }
881 }
882
883 // If nothing matches, return the first certificate.
884 return &c.Certificates[0]
885}
886
David Benjamin000800a2014-11-14 01:43:59 -0500887func (c *Config) signatureAndHashesForServer() []signatureAndHash {
888 if c != nil && c.SignatureAndHashes != nil {
889 return c.SignatureAndHashes
890 }
891 return supportedClientCertSignatureAlgorithms
892}
893
894func (c *Config) signatureAndHashesForClient() []signatureAndHash {
895 if c != nil && c.SignatureAndHashes != nil {
896 return c.SignatureAndHashes
897 }
898 return supportedSKXSignatureAlgorithms
899}
900
Adam Langley95c29f32014-06-20 12:00:00 -0700901// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
902// from the CommonName and SubjectAlternateName fields of each of the leaf
903// certificates.
904func (c *Config) BuildNameToCertificate() {
905 c.NameToCertificate = make(map[string]*Certificate)
906 for i := range c.Certificates {
907 cert := &c.Certificates[i]
908 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
909 if err != nil {
910 continue
911 }
912 if len(x509Cert.Subject.CommonName) > 0 {
913 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
914 }
915 for _, san := range x509Cert.DNSNames {
916 c.NameToCertificate[san] = cert
917 }
918 }
919}
920
921// A Certificate is a chain of one or more certificates, leaf first.
922type Certificate struct {
923 Certificate [][]byte
924 PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
925 // OCSPStaple contains an optional OCSP response which will be served
926 // to clients that request it.
927 OCSPStaple []byte
David Benjamin61f95272014-11-25 01:55:35 -0500928 // SignedCertificateTimestampList contains an optional encoded
929 // SignedCertificateTimestampList structure which will be
930 // served to clients that request it.
931 SignedCertificateTimestampList []byte
Adam Langley95c29f32014-06-20 12:00:00 -0700932 // Leaf is the parsed form of the leaf certificate, which may be
933 // initialized using x509.ParseCertificate to reduce per-handshake
934 // processing for TLS clients doing client authentication. If nil, the
935 // leaf certificate will be parsed as needed.
936 Leaf *x509.Certificate
937}
938
939// A TLS record.
940type record struct {
941 contentType recordType
942 major, minor uint8
943 payload []byte
944}
945
946type handshakeMessage interface {
947 marshal() []byte
948 unmarshal([]byte) bool
949}
950
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500951// lruSessionCache is a client or server session cache implementation
952// that uses an LRU caching strategy.
Adam Langley95c29f32014-06-20 12:00:00 -0700953type lruSessionCache struct {
954 sync.Mutex
955
956 m map[string]*list.Element
957 q *list.List
958 capacity int
959}
960
961type lruSessionCacheEntry struct {
962 sessionKey string
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500963 state interface{}
Adam Langley95c29f32014-06-20 12:00:00 -0700964}
965
966// Put adds the provided (sessionKey, cs) pair to the cache.
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500967func (c *lruSessionCache) Put(sessionKey string, cs interface{}) {
Adam Langley95c29f32014-06-20 12:00:00 -0700968 c.Lock()
969 defer c.Unlock()
970
971 if elem, ok := c.m[sessionKey]; ok {
972 entry := elem.Value.(*lruSessionCacheEntry)
973 entry.state = cs
974 c.q.MoveToFront(elem)
975 return
976 }
977
978 if c.q.Len() < c.capacity {
979 entry := &lruSessionCacheEntry{sessionKey, cs}
980 c.m[sessionKey] = c.q.PushFront(entry)
981 return
982 }
983
984 elem := c.q.Back()
985 entry := elem.Value.(*lruSessionCacheEntry)
986 delete(c.m, entry.sessionKey)
987 entry.sessionKey = sessionKey
988 entry.state = cs
989 c.q.MoveToFront(elem)
990 c.m[sessionKey] = elem
991}
992
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500993// Get returns the value associated with a given key. It returns (nil,
994// false) if no value is found.
995func (c *lruSessionCache) Get(sessionKey string) (interface{}, bool) {
Adam Langley95c29f32014-06-20 12:00:00 -0700996 c.Lock()
997 defer c.Unlock()
998
999 if elem, ok := c.m[sessionKey]; ok {
1000 c.q.MoveToFront(elem)
1001 return elem.Value.(*lruSessionCacheEntry).state, true
1002 }
1003 return nil, false
1004}
1005
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001006// lruClientSessionCache is a ClientSessionCache implementation that
1007// uses an LRU caching strategy.
1008type lruClientSessionCache struct {
1009 lruSessionCache
1010}
1011
1012func (c *lruClientSessionCache) Put(sessionKey string, cs *ClientSessionState) {
1013 c.lruSessionCache.Put(sessionKey, cs)
1014}
1015
1016func (c *lruClientSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
1017 cs, ok := c.lruSessionCache.Get(sessionKey)
1018 if !ok {
1019 return nil, false
1020 }
1021 return cs.(*ClientSessionState), true
1022}
1023
1024// lruServerSessionCache is a ServerSessionCache implementation that
1025// uses an LRU caching strategy.
1026type lruServerSessionCache struct {
1027 lruSessionCache
1028}
1029
1030func (c *lruServerSessionCache) Put(sessionId string, session *sessionState) {
1031 c.lruSessionCache.Put(sessionId, session)
1032}
1033
1034func (c *lruServerSessionCache) Get(sessionId string) (*sessionState, bool) {
1035 cs, ok := c.lruSessionCache.Get(sessionId)
1036 if !ok {
1037 return nil, false
1038 }
1039 return cs.(*sessionState), true
1040}
1041
1042// NewLRUClientSessionCache returns a ClientSessionCache with the given
1043// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1044// is used instead.
1045func NewLRUClientSessionCache(capacity int) ClientSessionCache {
1046 const defaultSessionCacheCapacity = 64
1047
1048 if capacity < 1 {
1049 capacity = defaultSessionCacheCapacity
1050 }
1051 return &lruClientSessionCache{
1052 lruSessionCache{
1053 m: make(map[string]*list.Element),
1054 q: list.New(),
1055 capacity: capacity,
1056 },
1057 }
1058}
1059
1060// NewLRUServerSessionCache returns a ServerSessionCache with the given
1061// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1062// is used instead.
1063func NewLRUServerSessionCache(capacity int) ServerSessionCache {
1064 const defaultSessionCacheCapacity = 64
1065
1066 if capacity < 1 {
1067 capacity = defaultSessionCacheCapacity
1068 }
1069 return &lruServerSessionCache{
1070 lruSessionCache{
1071 m: make(map[string]*list.Element),
1072 q: list.New(),
1073 capacity: capacity,
1074 },
1075 }
1076}
1077
Adam Langley95c29f32014-06-20 12:00:00 -07001078// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
1079type dsaSignature struct {
1080 R, S *big.Int
1081}
1082
1083type ecdsaSignature dsaSignature
1084
1085var emptyConfig Config
1086
1087func defaultConfig() *Config {
1088 return &emptyConfig
1089}
1090
1091var (
1092 once sync.Once
1093 varDefaultCipherSuites []uint16
1094)
1095
1096func defaultCipherSuites() []uint16 {
1097 once.Do(initDefaultCipherSuites)
1098 return varDefaultCipherSuites
1099}
1100
1101func initDefaultCipherSuites() {
David Benjamin48cae082014-10-27 01:06:24 -04001102 for _, suite := range cipherSuites {
1103 if suite.flags&suitePSK == 0 {
1104 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
1105 }
Adam Langley95c29f32014-06-20 12:00:00 -07001106 }
1107}
1108
1109func unexpectedMessageError(wanted, got interface{}) error {
1110 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1111}
David Benjamin000800a2014-11-14 01:43:59 -05001112
1113func isSupportedSignatureAndHash(sigHash signatureAndHash, sigHashes []signatureAndHash) bool {
1114 for _, s := range sigHashes {
1115 if s == sigHash {
1116 return true
1117 }
1118 }
1119 return false
1120}