blob: 039d164c799e3a20a4f72bf2f85fcb02e9e227f2 [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
David Benjaminc0577622015-09-12 18:28:38 -0400192 TLSUnique []byte // the tls-unique channel binding
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
Paul Lietar62be8ac2015-09-16 10:03:30 +0100219 sctList []byte
220 ocspResponse []byte
Adam Langley95c29f32014-06-20 12:00:00 -0700221}
222
223// ClientSessionCache is a cache of ClientSessionState objects that can be used
224// by a client to resume a TLS session with a given server. ClientSessionCache
225// implementations should expect to be called concurrently from different
226// goroutines.
227type ClientSessionCache interface {
228 // Get searches for a ClientSessionState associated with the given key.
229 // On return, ok is true if one was found.
230 Get(sessionKey string) (session *ClientSessionState, ok bool)
231
232 // Put adds the ClientSessionState to the cache with the given key.
233 Put(sessionKey string, cs *ClientSessionState)
234}
235
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500236// ServerSessionCache is a cache of sessionState objects that can be used by a
237// client to resume a TLS session with a given server. ServerSessionCache
238// implementations should expect to be called concurrently from different
239// goroutines.
240type ServerSessionCache interface {
241 // Get searches for a sessionState associated with the given session
242 // ID. On return, ok is true if one was found.
243 Get(sessionId string) (session *sessionState, ok bool)
244
245 // Put adds the sessionState to the cache with the given session ID.
246 Put(sessionId string, session *sessionState)
247}
248
Adam Langley95c29f32014-06-20 12:00:00 -0700249// A Config structure is used to configure a TLS client or server.
250// After one has been passed to a TLS function it must not be
251// modified. A Config may be reused; the tls package will also not
252// modify it.
253type Config struct {
254 // Rand provides the source of entropy for nonces and RSA blinding.
255 // If Rand is nil, TLS uses the cryptographic random reader in package
256 // crypto/rand.
257 // The Reader must be safe for use by multiple goroutines.
258 Rand io.Reader
259
260 // Time returns the current time as the number of seconds since the epoch.
261 // If Time is nil, TLS uses time.Now.
262 Time func() time.Time
263
264 // Certificates contains one or more certificate chains
265 // to present to the other side of the connection.
266 // Server configurations must include at least one certificate.
267 Certificates []Certificate
268
269 // NameToCertificate maps from a certificate name to an element of
270 // Certificates. Note that a certificate name can be of the form
271 // '*.example.com' and so doesn't have to be a domain name as such.
272 // See Config.BuildNameToCertificate
273 // The nil value causes the first element of Certificates to be used
274 // for all connections.
275 NameToCertificate map[string]*Certificate
276
277 // RootCAs defines the set of root certificate authorities
278 // that clients use when verifying server certificates.
279 // If RootCAs is nil, TLS uses the host's root CA set.
280 RootCAs *x509.CertPool
281
282 // NextProtos is a list of supported, application level protocols.
283 NextProtos []string
284
285 // ServerName is used to verify the hostname on the returned
286 // certificates unless InsecureSkipVerify is given. It is also included
287 // in the client's handshake to support virtual hosting.
288 ServerName string
289
290 // ClientAuth determines the server's policy for
291 // TLS Client Authentication. The default is NoClientCert.
292 ClientAuth ClientAuthType
293
294 // ClientCAs defines the set of root certificate authorities
295 // that servers use if required to verify a client certificate
296 // by the policy in ClientAuth.
297 ClientCAs *x509.CertPool
298
David Benjamin7b030512014-07-08 17:30:11 -0400299 // ClientCertificateTypes defines the set of allowed client certificate
300 // types. The default is CertTypeRSASign and CertTypeECDSASign.
301 ClientCertificateTypes []byte
302
Adam Langley95c29f32014-06-20 12:00:00 -0700303 // InsecureSkipVerify controls whether a client verifies the
304 // server's certificate chain and host name.
305 // If InsecureSkipVerify is true, TLS accepts any certificate
306 // presented by the server and any host name in that certificate.
307 // In this mode, TLS is susceptible to man-in-the-middle attacks.
308 // This should be used only for testing.
309 InsecureSkipVerify bool
310
311 // CipherSuites is a list of supported cipher suites. If CipherSuites
312 // is nil, TLS uses a list of suites supported by the implementation.
313 CipherSuites []uint16
314
315 // PreferServerCipherSuites controls whether the server selects the
316 // client's most preferred ciphersuite, or the server's most preferred
317 // ciphersuite. If true then the server's preference, as expressed in
318 // the order of elements in CipherSuites, is used.
319 PreferServerCipherSuites bool
320
321 // SessionTicketsDisabled may be set to true to disable session ticket
322 // (resumption) support.
323 SessionTicketsDisabled bool
324
325 // SessionTicketKey is used by TLS servers to provide session
326 // resumption. See RFC 5077. If zero, it will be filled with
327 // random data before the first server handshake.
328 //
329 // If multiple servers are terminating connections for the same host
330 // they should all have the same SessionTicketKey. If the
331 // SessionTicketKey leaks, previously recorded and future TLS
332 // connections using that key are compromised.
333 SessionTicketKey [32]byte
334
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500335 // ClientSessionCache is a cache of ClientSessionState entries
336 // for TLS session resumption.
Adam Langley95c29f32014-06-20 12:00:00 -0700337 ClientSessionCache ClientSessionCache
338
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500339 // ServerSessionCache is a cache of sessionState entries for TLS session
340 // resumption.
341 ServerSessionCache ServerSessionCache
342
Adam Langley95c29f32014-06-20 12:00:00 -0700343 // MinVersion contains the minimum SSL/TLS version that is acceptable.
344 // If zero, then SSLv3 is taken as the minimum.
345 MinVersion uint16
346
347 // MaxVersion contains the maximum SSL/TLS version that is acceptable.
348 // If zero, then the maximum version supported by this package is used,
349 // which is currently TLS 1.2.
350 MaxVersion uint16
351
352 // CurvePreferences contains the elliptic curves that will be used in
353 // an ECDHE handshake, in preference order. If empty, the default will
354 // be used.
355 CurvePreferences []CurveID
356
David Benjamind30a9902014-08-24 01:44:23 -0400357 // ChannelID contains the ECDSA key for the client to use as
358 // its TLS Channel ID.
359 ChannelID *ecdsa.PrivateKey
360
361 // RequestChannelID controls whether the server requests a TLS
362 // Channel ID. If negotiated, the client's public key is
363 // returned in the ConnectionState.
364 RequestChannelID bool
365
David Benjamin48cae082014-10-27 01:06:24 -0400366 // PreSharedKey, if not nil, is the pre-shared key to use with
367 // the PSK cipher suites.
368 PreSharedKey []byte
369
370 // PreSharedKeyIdentity, if not empty, is the identity to use
371 // with the PSK cipher suites.
372 PreSharedKeyIdentity string
373
David Benjaminca6c8262014-11-15 19:06:08 -0500374 // SRTPProtectionProfiles, if not nil, is the list of SRTP
375 // protection profiles to offer in DTLS-SRTP.
376 SRTPProtectionProfiles []uint16
377
David Benjamin000800a2014-11-14 01:43:59 -0500378 // SignatureAndHashes, if not nil, overrides the default set of
379 // supported signature and hash algorithms to advertise in
380 // CertificateRequest.
381 SignatureAndHashes []signatureAndHash
382
Adam Langley95c29f32014-06-20 12:00:00 -0700383 // Bugs specifies optional misbehaviour to be used for testing other
384 // implementations.
385 Bugs ProtocolBugs
386
387 serverInitOnce sync.Once // guards calling (*Config).serverInit
388}
389
390type BadValue int
391
392const (
393 BadValueNone BadValue = iota
394 BadValueNegative
395 BadValueZero
396 BadValueLimit
397 BadValueLarge
398 NumBadValues
399)
400
401type ProtocolBugs struct {
402 // InvalidSKXSignature specifies that the signature in a
403 // ServerKeyExchange message should be invalid.
404 InvalidSKXSignature bool
405
David Benjamin6de0e532015-07-28 22:43:19 -0400406 // InvalidCertVerifySignature specifies that the signature in a
407 // CertificateVerify message should be invalid.
408 InvalidCertVerifySignature bool
409
Adam Langley95c29f32014-06-20 12:00:00 -0700410 // InvalidSKXCurve causes the curve ID in the ServerKeyExchange message
411 // to be wrong.
412 InvalidSKXCurve bool
413
414 // BadECDSAR controls ways in which the 'r' value of an ECDSA signature
415 // can be invalid.
416 BadECDSAR BadValue
417 BadECDSAS BadValue
Adam Langley80842bd2014-06-20 12:00:00 -0700418
419 // MaxPadding causes CBC records to have the maximum possible padding.
420 MaxPadding bool
421 // PaddingFirstByteBad causes the first byte of the padding to be
422 // incorrect.
423 PaddingFirstByteBad bool
424 // PaddingFirstByteBadIf255 causes the first byte of padding to be
425 // incorrect if there's a maximum amount of padding (i.e. 255 bytes).
426 PaddingFirstByteBadIf255 bool
Adam Langleyac61fa32014-06-23 12:03:11 -0700427
428 // FailIfNotFallbackSCSV causes a server handshake to fail if the
429 // client doesn't send the fallback SCSV value.
430 FailIfNotFallbackSCSV bool
David Benjamin35a7a442014-07-05 00:23:20 -0400431
432 // DuplicateExtension causes an extra empty extension of bogus type to
433 // be emitted in either the ClientHello or the ServerHello.
434 DuplicateExtension bool
David Benjamin1c375dd2014-07-12 00:48:23 -0400435
436 // UnauthenticatedECDH causes the server to pretend ECDHE_RSA
437 // and ECDHE_ECDSA cipher suites are actually ECDH_anon. No
438 // Certificate message is sent and no signature is added to
439 // ServerKeyExchange.
440 UnauthenticatedECDH bool
David Benjamin9c651c92014-07-12 13:27:45 -0400441
David Benjaminb80168e2015-02-08 18:30:14 -0500442 // SkipHelloVerifyRequest causes a DTLS server to skip the
443 // HelloVerifyRequest message.
444 SkipHelloVerifyRequest bool
445
David Benjamindcd979f2015-04-20 18:26:52 -0400446 // SkipCertificateStatus, if true, causes the server to skip the
447 // CertificateStatus message. This is legal because CertificateStatus is
448 // optional, even with a status_request in ServerHello.
449 SkipCertificateStatus bool
450
David Benjamin9c651c92014-07-12 13:27:45 -0400451 // SkipServerKeyExchange causes the server to skip sending
452 // ServerKeyExchange messages.
453 SkipServerKeyExchange bool
David Benjamina0e52232014-07-19 17:39:58 -0400454
David Benjaminb80168e2015-02-08 18:30:14 -0500455 // SkipNewSessionTicket causes the server to skip sending the
456 // NewSessionTicket message despite promising to in ServerHello.
457 SkipNewSessionTicket bool
458
David Benjamina0e52232014-07-19 17:39:58 -0400459 // SkipChangeCipherSpec causes the implementation to skip
460 // sending the ChangeCipherSpec message (and adjusting cipher
461 // state accordingly for the Finished message).
462 SkipChangeCipherSpec bool
David Benjaminf3ec83d2014-07-21 22:42:34 -0400463
David Benjaminb80168e2015-02-08 18:30:14 -0500464 // SkipFinished causes the implementation to skip sending the Finished
465 // message.
466 SkipFinished bool
467
David Benjaminf3ec83d2014-07-21 22:42:34 -0400468 // EarlyChangeCipherSpec causes the client to send an early
469 // ChangeCipherSpec message before the ClientKeyExchange. A value of
470 // zero disables this behavior. One and two configure variants for 0.9.8
471 // and 1.0.1 modes, respectively.
472 EarlyChangeCipherSpec int
David Benjamind23f4122014-07-23 15:09:48 -0400473
David Benjamin86271ee2014-07-21 16:14:03 -0400474 // FragmentAcrossChangeCipherSpec causes the implementation to fragment
475 // the Finished (or NextProto) message around the ChangeCipherSpec
476 // messages.
477 FragmentAcrossChangeCipherSpec bool
478
David Benjamind86c7672014-08-02 04:07:12 -0400479 // SendV2ClientHello causes the client to send a V2ClientHello
480 // instead of a normal ClientHello.
481 SendV2ClientHello bool
David Benjaminbef270a2014-08-02 04:22:02 -0400482
483 // SendFallbackSCSV causes the client to include
484 // TLS_FALLBACK_SCSV in the ClientHello.
485 SendFallbackSCSV bool
David Benjamin43ec06f2014-08-05 02:28:57 -0400486
Adam Langley5021b222015-06-12 18:27:58 -0700487 // SendRenegotiationSCSV causes the client to include the renegotiation
488 // SCSV in the ClientHello.
489 SendRenegotiationSCSV bool
490
David Benjamin43ec06f2014-08-05 02:28:57 -0400491 // MaxHandshakeRecordLength, if non-zero, is the maximum size of a
David Benjamin98214542014-08-07 18:02:39 -0400492 // handshake record. Handshake messages will be split into multiple
493 // records at the specified size, except that the client_version will
David Benjaminbd15a8e2015-05-29 18:48:16 -0400494 // never be fragmented. For DTLS, it is the maximum handshake fragment
495 // size, not record size; DTLS allows multiple handshake fragments in a
496 // single handshake record. See |PackHandshakeFragments|.
David Benjamin43ec06f2014-08-05 02:28:57 -0400497 MaxHandshakeRecordLength int
David Benjamina8e3e0e2014-08-06 22:11:10 -0400498
David Benjamin98214542014-08-07 18:02:39 -0400499 // FragmentClientVersion will allow MaxHandshakeRecordLength to apply to
500 // the first 6 bytes of the ClientHello.
501 FragmentClientVersion bool
502
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400503 // FragmentAlert will cause all alerts to be fragmented across
504 // two records.
505 FragmentAlert bool
506
David Benjamin3fd1fbd2015-02-03 16:07:32 -0500507 // SendSpuriousAlert, if non-zero, will cause an spurious, unwanted
508 // alert to be sent.
509 SendSpuriousAlert alert
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400510
David Benjamina8e3e0e2014-08-06 22:11:10 -0400511 // RsaClientKeyExchangeVersion, if non-zero, causes the client to send a
512 // ClientKeyExchange with the specified version rather than the
513 // client_version when performing the RSA key exchange.
514 RsaClientKeyExchangeVersion uint16
David Benjaminbed9aae2014-08-07 19:13:38 -0400515
516 // RenewTicketOnResume causes the server to renew the session ticket and
517 // send a NewSessionTicket message during an abbreviated handshake.
518 RenewTicketOnResume bool
David Benjamin98e882e2014-08-08 13:24:34 -0400519
520 // SendClientVersion, if non-zero, causes the client to send a different
521 // TLS version in the ClientHello than the maximum supported version.
522 SendClientVersion uint16
David Benjamin83c0bc92014-08-04 01:23:53 -0400523
David Benjamine58c4f52014-08-24 03:47:07 -0400524 // ExpectFalseStart causes the server to, on full handshakes,
525 // expect the peer to False Start; the server Finished message
526 // isn't sent until we receive an application data record
527 // from the peer.
528 ExpectFalseStart bool
David Benjamin5c24a1d2014-08-31 00:59:27 -0400529
David Benjamin1c633152015-04-02 20:19:11 -0400530 // AlertBeforeFalseStartTest, if non-zero, causes the server to, on full
531 // handshakes, send an alert just before reading the application data
532 // record to test False Start. This can be used in a negative False
533 // Start test to determine whether the peer processed the alert (and
534 // closed the connection) before or after sending app data.
535 AlertBeforeFalseStartTest alert
536
David Benjamin5c24a1d2014-08-31 00:59:27 -0400537 // SSL3RSAKeyExchange causes the client to always send an RSA
538 // ClientKeyExchange message without the two-byte length
539 // prefix, as if it were SSL3.
540 SSL3RSAKeyExchange bool
David Benjamin39ebf532014-08-31 02:23:49 -0400541
542 // SkipCipherVersionCheck causes the server to negotiate
543 // TLS 1.2 ciphers in earlier versions of TLS.
544 SkipCipherVersionCheck bool
David Benjamine78bfde2014-09-06 12:45:15 -0400545
546 // ExpectServerName, if not empty, is the hostname the client
547 // must specify in the server_name extension.
548 ExpectServerName string
David Benjaminfc7b0862014-09-06 13:21:53 -0400549
David Benjamin76c2efc2015-08-31 14:24:29 -0400550 // SwapNPNAndALPN switches the relative order between NPN and ALPN in
551 // both ClientHello and ServerHello.
David Benjaminfc7b0862014-09-06 13:21:53 -0400552 SwapNPNAndALPN bool
David Benjamin01fe8202014-09-24 15:21:44 -0400553
Adam Langleyefb0e162015-07-09 11:35:04 -0700554 // ALPNProtocol, if not nil, sets the ALPN protocol that a server will
555 // return.
556 ALPNProtocol *string
557
David Benjamin01fe8202014-09-24 15:21:44 -0400558 // AllowSessionVersionMismatch causes the server to resume sessions
559 // regardless of the version associated with the session.
560 AllowSessionVersionMismatch bool
Adam Langley38311732014-10-16 19:04:35 -0700561
562 // CorruptTicket causes a client to corrupt a session ticket before
563 // sending it in a resume handshake.
564 CorruptTicket bool
565
566 // OversizedSessionId causes the session id that is sent with a ticket
567 // resumption attempt to be too large (33 bytes).
568 OversizedSessionId bool
Adam Langley75712922014-10-10 16:23:43 -0700569
570 // RequireExtendedMasterSecret, if true, requires that the peer support
571 // the extended master secret option.
572 RequireExtendedMasterSecret bool
573
David Benjaminca6554b2014-11-08 12:31:52 -0500574 // NoExtendedMasterSecret causes the client and server to behave as if
Adam Langley75712922014-10-10 16:23:43 -0700575 // they didn't support an extended master secret.
576 NoExtendedMasterSecret bool
Adam Langley2ae77d22014-10-28 17:29:33 -0700577
578 // EmptyRenegotiationInfo causes the renegotiation extension to be
579 // empty in a renegotiation handshake.
580 EmptyRenegotiationInfo bool
581
582 // BadRenegotiationInfo causes the renegotiation extension value in a
583 // renegotiation handshake to be incorrect.
584 BadRenegotiationInfo bool
David Benjamin5e961c12014-11-07 01:48:35 -0500585
David Benjaminca6554b2014-11-08 12:31:52 -0500586 // NoRenegotiationInfo causes the client to behave as if it
587 // didn't support the renegotiation info extension.
588 NoRenegotiationInfo bool
589
Adam Langley5021b222015-06-12 18:27:58 -0700590 // RequireRenegotiationInfo, if true, causes the client to return an
591 // error if the server doesn't reply with the renegotiation extension.
592 RequireRenegotiationInfo bool
593
David Benjamin8e6db492015-07-25 18:29:23 -0400594 // SequenceNumberMapping, if non-nil, is the mapping function to apply
595 // to the sequence number of outgoing packets. For both TLS and DTLS,
596 // the two most-significant bytes in the resulting sequence number are
597 // ignored so that the DTLS epoch cannot be changed.
598 SequenceNumberMapping func(uint64) uint64
David Benjamin9114fae2014-11-08 11:41:14 -0500599
David Benjamina3e89492015-02-26 15:16:22 -0500600 // RSAEphemeralKey, if true, causes the server to send a
601 // ServerKeyExchange message containing an ephemeral key (as in
602 // RSA_EXPORT) in the plain RSA key exchange.
603 RSAEphemeralKey bool
David Benjaminca6c8262014-11-15 19:06:08 -0500604
605 // SRTPMasterKeyIdentifer, if not empty, is the SRTP MKI value that the
606 // client offers when negotiating SRTP. MKI support is still missing so
607 // the peer must still send none.
608 SRTPMasterKeyIdentifer string
609
610 // SendSRTPProtectionProfile, if non-zero, is the SRTP profile that the
611 // server sends in the ServerHello instead of the negotiated one.
612 SendSRTPProtectionProfile uint16
David Benjamin000800a2014-11-14 01:43:59 -0500613
614 // NoSignatureAndHashes, if true, causes the client to omit the
615 // signature and hashes extension.
616 //
617 // For a server, it will cause an empty list to be sent in the
618 // CertificateRequest message. None the less, the configured set will
619 // still be enforced.
620 NoSignatureAndHashes bool
David Benjaminc44b1df2014-11-23 12:11:01 -0500621
David Benjamin55a43642015-04-20 14:45:55 -0400622 // NoSupportedCurves, if true, causes the client to omit the
623 // supported_curves extension.
624 NoSupportedCurves bool
625
David Benjaminc44b1df2014-11-23 12:11:01 -0500626 // RequireSameRenegoClientVersion, if true, causes the server
627 // to require that all ClientHellos match in offered version
628 // across a renego.
629 RequireSameRenegoClientVersion bool
Feng Lu41aa3252014-11-21 22:47:56 -0800630
David Benjamin1e29a6b2014-12-10 02:27:24 -0500631 // ExpectInitialRecordVersion, if non-zero, is the expected
632 // version of the records before the version is determined.
633 ExpectInitialRecordVersion uint16
David Benjamin13be1de2015-01-11 16:29:36 -0500634
635 // MaxPacketLength, if non-zero, is the maximum acceptable size for a
636 // packet.
637 MaxPacketLength int
David Benjamin6095de82014-12-27 01:50:38 -0500638
639 // SendCipherSuite, if non-zero, is the cipher suite value that the
640 // server will send in the ServerHello. This does not affect the cipher
641 // the server believes it has actually negotiated.
642 SendCipherSuite uint16
David Benjamin4189bd92015-01-25 23:52:39 -0500643
David Benjamin4cf369b2015-08-22 01:35:43 -0400644 // AppDataBeforeHandshake, if not nil, causes application data to be
645 // sent immediately before the first handshake message.
646 AppDataBeforeHandshake []byte
647
648 // AppDataAfterChangeCipherSpec, if not nil, causes application data to
David Benjamin4189bd92015-01-25 23:52:39 -0500649 // be sent immediately after ChangeCipherSpec.
650 AppDataAfterChangeCipherSpec []byte
David Benjamin83f90402015-01-27 01:09:43 -0500651
David Benjamindc3da932015-03-12 15:09:02 -0400652 // AlertAfterChangeCipherSpec, if non-zero, causes an alert to be sent
653 // immediately after ChangeCipherSpec.
654 AlertAfterChangeCipherSpec alert
655
David Benjamin83f90402015-01-27 01:09:43 -0500656 // TimeoutSchedule is the schedule of packet drops and simulated
657 // timeouts for before each handshake leg from the peer.
658 TimeoutSchedule []time.Duration
659
660 // PacketAdaptor is the packetAdaptor to use to simulate timeouts.
661 PacketAdaptor *packetAdaptor
David Benjaminb3774b92015-01-31 17:16:01 -0500662
663 // ReorderHandshakeFragments, if true, causes handshake fragments in
664 // DTLS to overlap and be sent in the wrong order. It also causes
665 // pre-CCS flights to be sent twice. (Post-CCS flights consist of
666 // Finished and will trigger a spurious retransmit.)
667 ReorderHandshakeFragments bool
David Benjaminddb9f152015-02-03 15:44:39 -0500668
David Benjamin75381222015-03-02 19:30:30 -0500669 // MixCompleteMessageWithFragments, if true, causes handshake
670 // messages in DTLS to redundantly both fragment the message
671 // and include a copy of the full one.
672 MixCompleteMessageWithFragments bool
673
David Benjaminddb9f152015-02-03 15:44:39 -0500674 // SendInvalidRecordType, if true, causes a record with an invalid
675 // content type to be sent immediately following the handshake.
676 SendInvalidRecordType bool
David Benjaminbcb2d912015-02-24 23:45:43 -0500677
678 // WrongCertificateMessageType, if true, causes Certificate message to
679 // be sent with the wrong message type.
680 WrongCertificateMessageType bool
David Benjamin75381222015-03-02 19:30:30 -0500681
682 // FragmentMessageTypeMismatch, if true, causes all non-initial
683 // handshake fragments in DTLS to have the wrong message type.
684 FragmentMessageTypeMismatch bool
685
686 // FragmentMessageLengthMismatch, if true, causes all non-initial
687 // handshake fragments in DTLS to have the wrong message length.
688 FragmentMessageLengthMismatch bool
689
David Benjamin11fc66a2015-06-16 11:40:24 -0400690 // SplitFragments, if non-zero, causes the handshake fragments in DTLS
691 // to be split across two records. The value of |SplitFragments| is the
692 // number of bytes in the first fragment.
693 SplitFragments int
David Benjamin75381222015-03-02 19:30:30 -0500694
695 // SendEmptyFragments, if true, causes handshakes to include empty
696 // fragments in DTLS.
697 SendEmptyFragments bool
David Benjamincdea40c2015-03-19 14:09:43 -0400698
David Benjamin9a41d1b2015-05-16 01:30:09 -0400699 // SendSplitAlert, if true, causes an alert to be sent with the header
700 // and record body split across multiple packets. The peer should
701 // discard these packets rather than process it.
702 SendSplitAlert bool
703
David Benjamin4b27d9f2015-05-12 22:42:52 -0400704 // FailIfResumeOnRenego, if true, causes renegotiations to fail if the
705 // client offers a resumption or the server accepts one.
706 FailIfResumeOnRenego bool
David Benjamin3c9746a2015-03-19 15:00:10 -0400707
David Benjamin67d1fb52015-03-16 15:16:23 -0400708 // IgnorePeerCipherPreferences, if true, causes the peer's cipher
709 // preferences to be ignored.
710 IgnorePeerCipherPreferences bool
David Benjamin72dc7832015-03-16 17:49:43 -0400711
712 // IgnorePeerSignatureAlgorithmPreferences, if true, causes the peer's
713 // signature algorithm preferences to be ignored.
714 IgnorePeerSignatureAlgorithmPreferences bool
David Benjamin340d5ed2015-03-21 02:21:37 -0400715
David Benjaminc574f412015-04-20 11:13:01 -0400716 // IgnorePeerCurvePreferences, if true, causes the peer's curve
717 // preferences to be ignored.
718 IgnorePeerCurvePreferences bool
719
David Benjamin513f0ea2015-04-02 19:33:31 -0400720 // BadFinished, if true, causes the Finished hash to be broken.
721 BadFinished bool
Adam Langleya7997f12015-05-14 17:38:50 -0700722
723 // DHGroupPrime, if not nil, is used to define the (finite field)
724 // Diffie-Hellman group. The generator used is always two.
725 DHGroupPrime *big.Int
David Benjaminbd15a8e2015-05-29 18:48:16 -0400726
727 // PackHandshakeFragments, if true, causes handshake fragments to be
728 // packed into individual handshake records, up to the specified record
729 // size.
730 PackHandshakeFragments int
731
732 // PackHandshakeRecords, if true, causes handshake records to be packed
733 // into individual packets, up to the specified packet size.
734 PackHandshakeRecords int
David Benjamin0fa40122015-05-30 17:13:12 -0400735
736 // EnableAllCiphersInDTLS, if true, causes RC4 to be enabled in DTLS.
737 EnableAllCiphersInDTLS bool
David Benjamin8923c0b2015-06-07 11:42:34 -0400738
739 // EmptyCertificateList, if true, causes the server to send an empty
740 // certificate list in the Certificate message.
741 EmptyCertificateList bool
David Benjamind98452d2015-06-16 14:16:23 -0400742
743 // ExpectNewTicket, if true, causes the client to abort if it does not
744 // receive a new ticket.
745 ExpectNewTicket bool
Adam Langley33ad2b52015-07-20 17:43:53 -0700746
747 // RequireClientHelloSize, if not zero, is the required length in bytes
748 // of the ClientHello /record/. This is checked by the server.
749 RequireClientHelloSize int
Adam Langley09505632015-07-30 18:10:13 -0700750
751 // CustomExtension, if not empty, contains the contents of an extension
752 // that will be added to client/server hellos.
753 CustomExtension string
754
755 // ExpectedCustomExtension, if not nil, contains the expected contents
756 // of a custom extension.
757 ExpectedCustomExtension *string
David Benjamin30789da2015-08-29 22:56:45 -0400758
759 // NoCloseNotify, if true, causes the close_notify alert to be skipped
760 // on connection shutdown.
761 NoCloseNotify bool
762
763 // ExpectCloseNotify, if true, requires a close_notify from the peer on
764 // shutdown. Records from the peer received after close_notify is sent
765 // are not discard.
766 ExpectCloseNotify bool
David Benjamin2c99d282015-09-01 10:23:00 -0400767
768 // SendLargeRecords, if true, allows outgoing records to be sent
769 // arbitrarily large.
770 SendLargeRecords bool
David Benjamin76c2efc2015-08-31 14:24:29 -0400771
772 // NegotiateALPNAndNPN, if true, causes the server to negotiate both
773 // ALPN and NPN in the same connetion.
774 NegotiateALPNAndNPN bool
Adam Langley95c29f32014-06-20 12:00:00 -0700775}
776
777func (c *Config) serverInit() {
778 if c.SessionTicketsDisabled {
779 return
780 }
781
782 // If the key has already been set then we have nothing to do.
783 for _, b := range c.SessionTicketKey {
784 if b != 0 {
785 return
786 }
787 }
788
789 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
790 c.SessionTicketsDisabled = true
791 }
792}
793
794func (c *Config) rand() io.Reader {
795 r := c.Rand
796 if r == nil {
797 return rand.Reader
798 }
799 return r
800}
801
802func (c *Config) time() time.Time {
803 t := c.Time
804 if t == nil {
805 t = time.Now
806 }
807 return t()
808}
809
810func (c *Config) cipherSuites() []uint16 {
811 s := c.CipherSuites
812 if s == nil {
813 s = defaultCipherSuites()
814 }
815 return s
816}
817
818func (c *Config) minVersion() uint16 {
819 if c == nil || c.MinVersion == 0 {
820 return minVersion
821 }
822 return c.MinVersion
823}
824
825func (c *Config) maxVersion() uint16 {
826 if c == nil || c.MaxVersion == 0 {
827 return maxVersion
828 }
829 return c.MaxVersion
830}
831
832var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
833
834func (c *Config) curvePreferences() []CurveID {
835 if c == nil || len(c.CurvePreferences) == 0 {
836 return defaultCurvePreferences
837 }
838 return c.CurvePreferences
839}
840
841// mutualVersion returns the protocol version to use given the advertised
842// version of the peer.
843func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
844 minVersion := c.minVersion()
845 maxVersion := c.maxVersion()
846
847 if vers < minVersion {
848 return 0, false
849 }
850 if vers > maxVersion {
851 vers = maxVersion
852 }
853 return vers, true
854}
855
856// getCertificateForName returns the best certificate for the given name,
857// defaulting to the first element of c.Certificates if there are no good
858// options.
859func (c *Config) getCertificateForName(name string) *Certificate {
860 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
861 // There's only one choice, so no point doing any work.
862 return &c.Certificates[0]
863 }
864
865 name = strings.ToLower(name)
866 for len(name) > 0 && name[len(name)-1] == '.' {
867 name = name[:len(name)-1]
868 }
869
870 if cert, ok := c.NameToCertificate[name]; ok {
871 return cert
872 }
873
874 // try replacing labels in the name with wildcards until we get a
875 // match.
876 labels := strings.Split(name, ".")
877 for i := range labels {
878 labels[i] = "*"
879 candidate := strings.Join(labels, ".")
880 if cert, ok := c.NameToCertificate[candidate]; ok {
881 return cert
882 }
883 }
884
885 // If nothing matches, return the first certificate.
886 return &c.Certificates[0]
887}
888
David Benjamin000800a2014-11-14 01:43:59 -0500889func (c *Config) signatureAndHashesForServer() []signatureAndHash {
890 if c != nil && c.SignatureAndHashes != nil {
891 return c.SignatureAndHashes
892 }
893 return supportedClientCertSignatureAlgorithms
894}
895
896func (c *Config) signatureAndHashesForClient() []signatureAndHash {
897 if c != nil && c.SignatureAndHashes != nil {
898 return c.SignatureAndHashes
899 }
900 return supportedSKXSignatureAlgorithms
901}
902
Adam Langley95c29f32014-06-20 12:00:00 -0700903// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
904// from the CommonName and SubjectAlternateName fields of each of the leaf
905// certificates.
906func (c *Config) BuildNameToCertificate() {
907 c.NameToCertificate = make(map[string]*Certificate)
908 for i := range c.Certificates {
909 cert := &c.Certificates[i]
910 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
911 if err != nil {
912 continue
913 }
914 if len(x509Cert.Subject.CommonName) > 0 {
915 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
916 }
917 for _, san := range x509Cert.DNSNames {
918 c.NameToCertificate[san] = cert
919 }
920 }
921}
922
923// A Certificate is a chain of one or more certificates, leaf first.
924type Certificate struct {
925 Certificate [][]byte
926 PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
927 // OCSPStaple contains an optional OCSP response which will be served
928 // to clients that request it.
929 OCSPStaple []byte
David Benjamin61f95272014-11-25 01:55:35 -0500930 // SignedCertificateTimestampList contains an optional encoded
931 // SignedCertificateTimestampList structure which will be
932 // served to clients that request it.
933 SignedCertificateTimestampList []byte
Adam Langley95c29f32014-06-20 12:00:00 -0700934 // Leaf is the parsed form of the leaf certificate, which may be
935 // initialized using x509.ParseCertificate to reduce per-handshake
936 // processing for TLS clients doing client authentication. If nil, the
937 // leaf certificate will be parsed as needed.
938 Leaf *x509.Certificate
939}
940
941// A TLS record.
942type record struct {
943 contentType recordType
944 major, minor uint8
945 payload []byte
946}
947
948type handshakeMessage interface {
949 marshal() []byte
950 unmarshal([]byte) bool
951}
952
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500953// lruSessionCache is a client or server session cache implementation
954// that uses an LRU caching strategy.
Adam Langley95c29f32014-06-20 12:00:00 -0700955type lruSessionCache struct {
956 sync.Mutex
957
958 m map[string]*list.Element
959 q *list.List
960 capacity int
961}
962
963type lruSessionCacheEntry struct {
964 sessionKey string
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500965 state interface{}
Adam Langley95c29f32014-06-20 12:00:00 -0700966}
967
968// Put adds the provided (sessionKey, cs) pair to the cache.
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500969func (c *lruSessionCache) Put(sessionKey string, cs interface{}) {
Adam Langley95c29f32014-06-20 12:00:00 -0700970 c.Lock()
971 defer c.Unlock()
972
973 if elem, ok := c.m[sessionKey]; ok {
974 entry := elem.Value.(*lruSessionCacheEntry)
975 entry.state = cs
976 c.q.MoveToFront(elem)
977 return
978 }
979
980 if c.q.Len() < c.capacity {
981 entry := &lruSessionCacheEntry{sessionKey, cs}
982 c.m[sessionKey] = c.q.PushFront(entry)
983 return
984 }
985
986 elem := c.q.Back()
987 entry := elem.Value.(*lruSessionCacheEntry)
988 delete(c.m, entry.sessionKey)
989 entry.sessionKey = sessionKey
990 entry.state = cs
991 c.q.MoveToFront(elem)
992 c.m[sessionKey] = elem
993}
994
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500995// Get returns the value associated with a given key. It returns (nil,
996// false) if no value is found.
997func (c *lruSessionCache) Get(sessionKey string) (interface{}, bool) {
Adam Langley95c29f32014-06-20 12:00:00 -0700998 c.Lock()
999 defer c.Unlock()
1000
1001 if elem, ok := c.m[sessionKey]; ok {
1002 c.q.MoveToFront(elem)
1003 return elem.Value.(*lruSessionCacheEntry).state, true
1004 }
1005 return nil, false
1006}
1007
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001008// lruClientSessionCache is a ClientSessionCache implementation that
1009// uses an LRU caching strategy.
1010type lruClientSessionCache struct {
1011 lruSessionCache
1012}
1013
1014func (c *lruClientSessionCache) Put(sessionKey string, cs *ClientSessionState) {
1015 c.lruSessionCache.Put(sessionKey, cs)
1016}
1017
1018func (c *lruClientSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
1019 cs, ok := c.lruSessionCache.Get(sessionKey)
1020 if !ok {
1021 return nil, false
1022 }
1023 return cs.(*ClientSessionState), true
1024}
1025
1026// lruServerSessionCache is a ServerSessionCache implementation that
1027// uses an LRU caching strategy.
1028type lruServerSessionCache struct {
1029 lruSessionCache
1030}
1031
1032func (c *lruServerSessionCache) Put(sessionId string, session *sessionState) {
1033 c.lruSessionCache.Put(sessionId, session)
1034}
1035
1036func (c *lruServerSessionCache) Get(sessionId string) (*sessionState, bool) {
1037 cs, ok := c.lruSessionCache.Get(sessionId)
1038 if !ok {
1039 return nil, false
1040 }
1041 return cs.(*sessionState), true
1042}
1043
1044// NewLRUClientSessionCache returns a ClientSessionCache with the given
1045// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1046// is used instead.
1047func NewLRUClientSessionCache(capacity int) ClientSessionCache {
1048 const defaultSessionCacheCapacity = 64
1049
1050 if capacity < 1 {
1051 capacity = defaultSessionCacheCapacity
1052 }
1053 return &lruClientSessionCache{
1054 lruSessionCache{
1055 m: make(map[string]*list.Element),
1056 q: list.New(),
1057 capacity: capacity,
1058 },
1059 }
1060}
1061
1062// NewLRUServerSessionCache returns a ServerSessionCache with the given
1063// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1064// is used instead.
1065func NewLRUServerSessionCache(capacity int) ServerSessionCache {
1066 const defaultSessionCacheCapacity = 64
1067
1068 if capacity < 1 {
1069 capacity = defaultSessionCacheCapacity
1070 }
1071 return &lruServerSessionCache{
1072 lruSessionCache{
1073 m: make(map[string]*list.Element),
1074 q: list.New(),
1075 capacity: capacity,
1076 },
1077 }
1078}
1079
Adam Langley95c29f32014-06-20 12:00:00 -07001080// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
1081type dsaSignature struct {
1082 R, S *big.Int
1083}
1084
1085type ecdsaSignature dsaSignature
1086
1087var emptyConfig Config
1088
1089func defaultConfig() *Config {
1090 return &emptyConfig
1091}
1092
1093var (
1094 once sync.Once
1095 varDefaultCipherSuites []uint16
1096)
1097
1098func defaultCipherSuites() []uint16 {
1099 once.Do(initDefaultCipherSuites)
1100 return varDefaultCipherSuites
1101}
1102
1103func initDefaultCipherSuites() {
David Benjamin48cae082014-10-27 01:06:24 -04001104 for _, suite := range cipherSuites {
1105 if suite.flags&suitePSK == 0 {
1106 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
1107 }
Adam Langley95c29f32014-06-20 12:00:00 -07001108 }
1109}
1110
1111func unexpectedMessageError(wanted, got interface{}) error {
1112 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1113}
David Benjamin000800a2014-11-14 01:43:59 -05001114
1115func isSupportedSignatureAndHash(sigHash signatureAndHash, sigHashes []signatureAndHash) bool {
1116 for _, s := range sigHashes {
1117 if s == sigHash {
1118 return true
1119 }
1120 }
1121 return false
1122}