blob: 078c227ee1d8119f9081e8b28faa96c0eb331f8c [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
Adam Langleydc7e9c42015-09-29 15:21:04 -07005package runner
Adam Langley95c29f32014-06-20 12:00:00 -07006
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
Steven Valdez0d62f262015-09-04 12:41:04 -0400194 ClientCertSignatureHash uint8 // TLS id of the hash used by the client to sign the handshake
Adam Langley95c29f32014-06-20 12:00:00 -0700195}
196
197// ClientAuthType declares the policy the server will follow for
198// TLS Client Authentication.
199type ClientAuthType int
200
201const (
202 NoClientCert ClientAuthType = iota
203 RequestClientCert
204 RequireAnyClientCert
205 VerifyClientCertIfGiven
206 RequireAndVerifyClientCert
207)
208
209// ClientSessionState contains the state needed by clients to resume TLS
210// sessions.
211type ClientSessionState struct {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500212 sessionId []uint8 // Session ID supplied by the server. nil if the session has a ticket.
Adam Langley75712922014-10-10 16:23:43 -0700213 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
214 vers uint16 // SSL/TLS version negotiated for the session
215 cipherSuite uint16 // Ciphersuite negotiated for the session
216 masterSecret []byte // MasterSecret generated by client on a full handshake
217 handshakeHash []byte // Handshake hash for Channel ID purposes.
218 serverCertificates []*x509.Certificate // Certificate chain presented by the server
219 extendedMasterSecret bool // Whether an extended master secret was used to generate the session
Paul Lietar62be8ac2015-09-16 10:03:30 +0100220 sctList []byte
221 ocspResponse []byte
Adam Langley95c29f32014-06-20 12:00:00 -0700222}
223
224// ClientSessionCache is a cache of ClientSessionState objects that can be used
225// by a client to resume a TLS session with a given server. ClientSessionCache
226// implementations should expect to be called concurrently from different
227// goroutines.
228type ClientSessionCache interface {
229 // Get searches for a ClientSessionState associated with the given key.
230 // On return, ok is true if one was found.
231 Get(sessionKey string) (session *ClientSessionState, ok bool)
232
233 // Put adds the ClientSessionState to the cache with the given key.
234 Put(sessionKey string, cs *ClientSessionState)
235}
236
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500237// ServerSessionCache is a cache of sessionState objects that can be used by a
238// client to resume a TLS session with a given server. ServerSessionCache
239// implementations should expect to be called concurrently from different
240// goroutines.
241type ServerSessionCache interface {
242 // Get searches for a sessionState associated with the given session
243 // ID. On return, ok is true if one was found.
244 Get(sessionId string) (session *sessionState, ok bool)
245
246 // Put adds the sessionState to the cache with the given session ID.
247 Put(sessionId string, session *sessionState)
248}
249
Adam Langley95c29f32014-06-20 12:00:00 -0700250// A Config structure is used to configure a TLS client or server.
251// After one has been passed to a TLS function it must not be
252// modified. A Config may be reused; the tls package will also not
253// modify it.
254type Config struct {
255 // Rand provides the source of entropy for nonces and RSA blinding.
256 // If Rand is nil, TLS uses the cryptographic random reader in package
257 // crypto/rand.
258 // The Reader must be safe for use by multiple goroutines.
259 Rand io.Reader
260
261 // Time returns the current time as the number of seconds since the epoch.
262 // If Time is nil, TLS uses time.Now.
263 Time func() time.Time
264
265 // Certificates contains one or more certificate chains
266 // to present to the other side of the connection.
267 // Server configurations must include at least one certificate.
268 Certificates []Certificate
269
270 // NameToCertificate maps from a certificate name to an element of
271 // Certificates. Note that a certificate name can be of the form
272 // '*.example.com' and so doesn't have to be a domain name as such.
273 // See Config.BuildNameToCertificate
274 // The nil value causes the first element of Certificates to be used
275 // for all connections.
276 NameToCertificate map[string]*Certificate
277
278 // RootCAs defines the set of root certificate authorities
279 // that clients use when verifying server certificates.
280 // If RootCAs is nil, TLS uses the host's root CA set.
281 RootCAs *x509.CertPool
282
283 // NextProtos is a list of supported, application level protocols.
284 NextProtos []string
285
286 // ServerName is used to verify the hostname on the returned
287 // certificates unless InsecureSkipVerify is given. It is also included
288 // in the client's handshake to support virtual hosting.
289 ServerName string
290
291 // ClientAuth determines the server's policy for
292 // TLS Client Authentication. The default is NoClientCert.
293 ClientAuth ClientAuthType
294
295 // ClientCAs defines the set of root certificate authorities
296 // that servers use if required to verify a client certificate
297 // by the policy in ClientAuth.
298 ClientCAs *x509.CertPool
299
David Benjamin7b030512014-07-08 17:30:11 -0400300 // ClientCertificateTypes defines the set of allowed client certificate
301 // types. The default is CertTypeRSASign and CertTypeECDSASign.
302 ClientCertificateTypes []byte
303
Adam Langley95c29f32014-06-20 12:00:00 -0700304 // InsecureSkipVerify controls whether a client verifies the
305 // server's certificate chain and host name.
306 // If InsecureSkipVerify is true, TLS accepts any certificate
307 // presented by the server and any host name in that certificate.
308 // In this mode, TLS is susceptible to man-in-the-middle attacks.
309 // This should be used only for testing.
310 InsecureSkipVerify bool
311
312 // CipherSuites is a list of supported cipher suites. If CipherSuites
313 // is nil, TLS uses a list of suites supported by the implementation.
314 CipherSuites []uint16
315
316 // PreferServerCipherSuites controls whether the server selects the
317 // client's most preferred ciphersuite, or the server's most preferred
318 // ciphersuite. If true then the server's preference, as expressed in
319 // the order of elements in CipherSuites, is used.
320 PreferServerCipherSuites bool
321
322 // SessionTicketsDisabled may be set to true to disable session ticket
323 // (resumption) support.
324 SessionTicketsDisabled bool
325
326 // SessionTicketKey is used by TLS servers to provide session
327 // resumption. See RFC 5077. If zero, it will be filled with
328 // random data before the first server handshake.
329 //
330 // If multiple servers are terminating connections for the same host
331 // they should all have the same SessionTicketKey. If the
332 // SessionTicketKey leaks, previously recorded and future TLS
333 // connections using that key are compromised.
334 SessionTicketKey [32]byte
335
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500336 // ClientSessionCache is a cache of ClientSessionState entries
337 // for TLS session resumption.
Adam Langley95c29f32014-06-20 12:00:00 -0700338 ClientSessionCache ClientSessionCache
339
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500340 // ServerSessionCache is a cache of sessionState entries for TLS session
341 // resumption.
342 ServerSessionCache ServerSessionCache
343
Adam Langley95c29f32014-06-20 12:00:00 -0700344 // MinVersion contains the minimum SSL/TLS version that is acceptable.
345 // If zero, then SSLv3 is taken as the minimum.
346 MinVersion uint16
347
348 // MaxVersion contains the maximum SSL/TLS version that is acceptable.
349 // If zero, then the maximum version supported by this package is used,
350 // which is currently TLS 1.2.
351 MaxVersion uint16
352
353 // CurvePreferences contains the elliptic curves that will be used in
354 // an ECDHE handshake, in preference order. If empty, the default will
355 // be used.
356 CurvePreferences []CurveID
357
David Benjamind30a9902014-08-24 01:44:23 -0400358 // ChannelID contains the ECDSA key for the client to use as
359 // its TLS Channel ID.
360 ChannelID *ecdsa.PrivateKey
361
362 // RequestChannelID controls whether the server requests a TLS
363 // Channel ID. If negotiated, the client's public key is
364 // returned in the ConnectionState.
365 RequestChannelID bool
366
David Benjamin48cae082014-10-27 01:06:24 -0400367 // PreSharedKey, if not nil, is the pre-shared key to use with
368 // the PSK cipher suites.
369 PreSharedKey []byte
370
371 // PreSharedKeyIdentity, if not empty, is the identity to use
372 // with the PSK cipher suites.
373 PreSharedKeyIdentity string
374
David Benjaminca6c8262014-11-15 19:06:08 -0500375 // SRTPProtectionProfiles, if not nil, is the list of SRTP
376 // protection profiles to offer in DTLS-SRTP.
377 SRTPProtectionProfiles []uint16
378
David Benjamin000800a2014-11-14 01:43:59 -0500379 // SignatureAndHashes, if not nil, overrides the default set of
380 // supported signature and hash algorithms to advertise in
381 // CertificateRequest.
382 SignatureAndHashes []signatureAndHash
383
Adam Langley95c29f32014-06-20 12:00:00 -0700384 // Bugs specifies optional misbehaviour to be used for testing other
385 // implementations.
386 Bugs ProtocolBugs
387
388 serverInitOnce sync.Once // guards calling (*Config).serverInit
389}
390
391type BadValue int
392
393const (
394 BadValueNone BadValue = iota
395 BadValueNegative
396 BadValueZero
397 BadValueLimit
398 BadValueLarge
399 NumBadValues
400)
401
402type ProtocolBugs struct {
403 // InvalidSKXSignature specifies that the signature in a
404 // ServerKeyExchange message should be invalid.
405 InvalidSKXSignature bool
406
David Benjamin6de0e532015-07-28 22:43:19 -0400407 // InvalidCertVerifySignature specifies that the signature in a
408 // CertificateVerify message should be invalid.
409 InvalidCertVerifySignature bool
410
Adam Langley95c29f32014-06-20 12:00:00 -0700411 // InvalidSKXCurve causes the curve ID in the ServerKeyExchange message
412 // to be wrong.
413 InvalidSKXCurve bool
414
415 // BadECDSAR controls ways in which the 'r' value of an ECDSA signature
416 // can be invalid.
417 BadECDSAR BadValue
418 BadECDSAS BadValue
Adam Langley80842bd2014-06-20 12:00:00 -0700419
420 // MaxPadding causes CBC records to have the maximum possible padding.
421 MaxPadding bool
422 // PaddingFirstByteBad causes the first byte of the padding to be
423 // incorrect.
424 PaddingFirstByteBad bool
425 // PaddingFirstByteBadIf255 causes the first byte of padding to be
426 // incorrect if there's a maximum amount of padding (i.e. 255 bytes).
427 PaddingFirstByteBadIf255 bool
Adam Langleyac61fa32014-06-23 12:03:11 -0700428
429 // FailIfNotFallbackSCSV causes a server handshake to fail if the
430 // client doesn't send the fallback SCSV value.
431 FailIfNotFallbackSCSV bool
David Benjamin35a7a442014-07-05 00:23:20 -0400432
433 // DuplicateExtension causes an extra empty extension of bogus type to
434 // be emitted in either the ClientHello or the ServerHello.
435 DuplicateExtension bool
David Benjamin1c375dd2014-07-12 00:48:23 -0400436
437 // UnauthenticatedECDH causes the server to pretend ECDHE_RSA
438 // and ECDHE_ECDSA cipher suites are actually ECDH_anon. No
439 // Certificate message is sent and no signature is added to
440 // ServerKeyExchange.
441 UnauthenticatedECDH bool
David Benjamin9c651c92014-07-12 13:27:45 -0400442
David Benjaminb80168e2015-02-08 18:30:14 -0500443 // SkipHelloVerifyRequest causes a DTLS server to skip the
444 // HelloVerifyRequest message.
445 SkipHelloVerifyRequest bool
446
David Benjamindcd979f2015-04-20 18:26:52 -0400447 // SkipCertificateStatus, if true, causes the server to skip the
448 // CertificateStatus message. This is legal because CertificateStatus is
449 // optional, even with a status_request in ServerHello.
450 SkipCertificateStatus bool
451
David Benjamin9c651c92014-07-12 13:27:45 -0400452 // SkipServerKeyExchange causes the server to skip sending
453 // ServerKeyExchange messages.
454 SkipServerKeyExchange bool
David Benjamina0e52232014-07-19 17:39:58 -0400455
David Benjaminb80168e2015-02-08 18:30:14 -0500456 // SkipNewSessionTicket causes the server to skip sending the
457 // NewSessionTicket message despite promising to in ServerHello.
458 SkipNewSessionTicket bool
459
David Benjamina0e52232014-07-19 17:39:58 -0400460 // SkipChangeCipherSpec causes the implementation to skip
461 // sending the ChangeCipherSpec message (and adjusting cipher
462 // state accordingly for the Finished message).
463 SkipChangeCipherSpec bool
David Benjaminf3ec83d2014-07-21 22:42:34 -0400464
David Benjaminb80168e2015-02-08 18:30:14 -0500465 // SkipFinished causes the implementation to skip sending the Finished
466 // message.
467 SkipFinished bool
468
David Benjaminf3ec83d2014-07-21 22:42:34 -0400469 // EarlyChangeCipherSpec causes the client to send an early
470 // ChangeCipherSpec message before the ClientKeyExchange. A value of
471 // zero disables this behavior. One and two configure variants for 0.9.8
472 // and 1.0.1 modes, respectively.
473 EarlyChangeCipherSpec int
David Benjamind23f4122014-07-23 15:09:48 -0400474
David Benjamin86271ee2014-07-21 16:14:03 -0400475 // FragmentAcrossChangeCipherSpec causes the implementation to fragment
476 // the Finished (or NextProto) message around the ChangeCipherSpec
477 // messages.
478 FragmentAcrossChangeCipherSpec bool
479
David Benjamind86c7672014-08-02 04:07:12 -0400480 // SendV2ClientHello causes the client to send a V2ClientHello
481 // instead of a normal ClientHello.
482 SendV2ClientHello bool
David Benjaminbef270a2014-08-02 04:22:02 -0400483
484 // SendFallbackSCSV causes the client to include
485 // TLS_FALLBACK_SCSV in the ClientHello.
486 SendFallbackSCSV bool
David Benjamin43ec06f2014-08-05 02:28:57 -0400487
Adam Langley5021b222015-06-12 18:27:58 -0700488 // SendRenegotiationSCSV causes the client to include the renegotiation
489 // SCSV in the ClientHello.
490 SendRenegotiationSCSV bool
491
David Benjamin43ec06f2014-08-05 02:28:57 -0400492 // MaxHandshakeRecordLength, if non-zero, is the maximum size of a
David Benjamin98214542014-08-07 18:02:39 -0400493 // handshake record. Handshake messages will be split into multiple
494 // records at the specified size, except that the client_version will
David Benjaminbd15a8e2015-05-29 18:48:16 -0400495 // never be fragmented. For DTLS, it is the maximum handshake fragment
496 // size, not record size; DTLS allows multiple handshake fragments in a
497 // single handshake record. See |PackHandshakeFragments|.
David Benjamin43ec06f2014-08-05 02:28:57 -0400498 MaxHandshakeRecordLength int
David Benjamina8e3e0e2014-08-06 22:11:10 -0400499
David Benjamin98214542014-08-07 18:02:39 -0400500 // FragmentClientVersion will allow MaxHandshakeRecordLength to apply to
501 // the first 6 bytes of the ClientHello.
502 FragmentClientVersion bool
503
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400504 // FragmentAlert will cause all alerts to be fragmented across
505 // two records.
506 FragmentAlert bool
507
David Benjamin3fd1fbd2015-02-03 16:07:32 -0500508 // SendSpuriousAlert, if non-zero, will cause an spurious, unwanted
509 // alert to be sent.
510 SendSpuriousAlert alert
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400511
David Benjamina8e3e0e2014-08-06 22:11:10 -0400512 // RsaClientKeyExchangeVersion, if non-zero, causes the client to send a
513 // ClientKeyExchange with the specified version rather than the
514 // client_version when performing the RSA key exchange.
515 RsaClientKeyExchangeVersion uint16
David Benjaminbed9aae2014-08-07 19:13:38 -0400516
517 // RenewTicketOnResume causes the server to renew the session ticket and
518 // send a NewSessionTicket message during an abbreviated handshake.
519 RenewTicketOnResume bool
David Benjamin98e882e2014-08-08 13:24:34 -0400520
521 // SendClientVersion, if non-zero, causes the client to send a different
522 // TLS version in the ClientHello than the maximum supported version.
523 SendClientVersion uint16
David Benjamin83c0bc92014-08-04 01:23:53 -0400524
David Benjamine58c4f52014-08-24 03:47:07 -0400525 // ExpectFalseStart causes the server to, on full handshakes,
526 // expect the peer to False Start; the server Finished message
527 // isn't sent until we receive an application data record
528 // from the peer.
529 ExpectFalseStart bool
David Benjamin5c24a1d2014-08-31 00:59:27 -0400530
David Benjamin1c633152015-04-02 20:19:11 -0400531 // AlertBeforeFalseStartTest, if non-zero, causes the server to, on full
532 // handshakes, send an alert just before reading the application data
533 // record to test False Start. This can be used in a negative False
534 // Start test to determine whether the peer processed the alert (and
535 // closed the connection) before or after sending app data.
536 AlertBeforeFalseStartTest alert
537
David Benjamin5c24a1d2014-08-31 00:59:27 -0400538 // SSL3RSAKeyExchange causes the client to always send an RSA
539 // ClientKeyExchange message without the two-byte length
540 // prefix, as if it were SSL3.
541 SSL3RSAKeyExchange bool
David Benjamin39ebf532014-08-31 02:23:49 -0400542
543 // SkipCipherVersionCheck causes the server to negotiate
544 // TLS 1.2 ciphers in earlier versions of TLS.
545 SkipCipherVersionCheck bool
David Benjamine78bfde2014-09-06 12:45:15 -0400546
547 // ExpectServerName, if not empty, is the hostname the client
548 // must specify in the server_name extension.
549 ExpectServerName string
David Benjaminfc7b0862014-09-06 13:21:53 -0400550
David Benjamin76c2efc2015-08-31 14:24:29 -0400551 // SwapNPNAndALPN switches the relative order between NPN and ALPN in
552 // both ClientHello and ServerHello.
David Benjaminfc7b0862014-09-06 13:21:53 -0400553 SwapNPNAndALPN bool
David Benjamin01fe8202014-09-24 15:21:44 -0400554
Adam Langleyefb0e162015-07-09 11:35:04 -0700555 // ALPNProtocol, if not nil, sets the ALPN protocol that a server will
556 // return.
557 ALPNProtocol *string
558
David Benjamin01fe8202014-09-24 15:21:44 -0400559 // AllowSessionVersionMismatch causes the server to resume sessions
560 // regardless of the version associated with the session.
561 AllowSessionVersionMismatch bool
Adam Langley38311732014-10-16 19:04:35 -0700562
563 // CorruptTicket causes a client to corrupt a session ticket before
564 // sending it in a resume handshake.
565 CorruptTicket bool
566
567 // OversizedSessionId causes the session id that is sent with a ticket
568 // resumption attempt to be too large (33 bytes).
569 OversizedSessionId bool
Adam Langley75712922014-10-10 16:23:43 -0700570
571 // RequireExtendedMasterSecret, if true, requires that the peer support
572 // the extended master secret option.
573 RequireExtendedMasterSecret bool
574
David Benjaminca6554b2014-11-08 12:31:52 -0500575 // NoExtendedMasterSecret causes the client and server to behave as if
Adam Langley75712922014-10-10 16:23:43 -0700576 // they didn't support an extended master secret.
577 NoExtendedMasterSecret bool
Adam Langley2ae77d22014-10-28 17:29:33 -0700578
579 // EmptyRenegotiationInfo causes the renegotiation extension to be
580 // empty in a renegotiation handshake.
581 EmptyRenegotiationInfo bool
582
583 // BadRenegotiationInfo causes the renegotiation extension value in a
584 // renegotiation handshake to be incorrect.
585 BadRenegotiationInfo bool
David Benjamin5e961c12014-11-07 01:48:35 -0500586
David Benjaminca6554b2014-11-08 12:31:52 -0500587 // NoRenegotiationInfo causes the client to behave as if it
588 // didn't support the renegotiation info extension.
589 NoRenegotiationInfo bool
590
Adam Langley5021b222015-06-12 18:27:58 -0700591 // RequireRenegotiationInfo, if true, causes the client to return an
592 // error if the server doesn't reply with the renegotiation extension.
593 RequireRenegotiationInfo bool
594
David Benjamin8e6db492015-07-25 18:29:23 -0400595 // SequenceNumberMapping, if non-nil, is the mapping function to apply
596 // to the sequence number of outgoing packets. For both TLS and DTLS,
597 // the two most-significant bytes in the resulting sequence number are
598 // ignored so that the DTLS epoch cannot be changed.
599 SequenceNumberMapping func(uint64) uint64
David Benjamin9114fae2014-11-08 11:41:14 -0500600
David Benjamina3e89492015-02-26 15:16:22 -0500601 // RSAEphemeralKey, if true, causes the server to send a
602 // ServerKeyExchange message containing an ephemeral key (as in
603 // RSA_EXPORT) in the plain RSA key exchange.
604 RSAEphemeralKey bool
David Benjaminca6c8262014-11-15 19:06:08 -0500605
606 // SRTPMasterKeyIdentifer, if not empty, is the SRTP MKI value that the
607 // client offers when negotiating SRTP. MKI support is still missing so
608 // the peer must still send none.
609 SRTPMasterKeyIdentifer string
610
611 // SendSRTPProtectionProfile, if non-zero, is the SRTP profile that the
612 // server sends in the ServerHello instead of the negotiated one.
613 SendSRTPProtectionProfile uint16
David Benjamin000800a2014-11-14 01:43:59 -0500614
615 // NoSignatureAndHashes, if true, causes the client to omit the
616 // signature and hashes extension.
617 //
618 // For a server, it will cause an empty list to be sent in the
619 // CertificateRequest message. None the less, the configured set will
620 // still be enforced.
621 NoSignatureAndHashes bool
David Benjaminc44b1df2014-11-23 12:11:01 -0500622
David Benjamin55a43642015-04-20 14:45:55 -0400623 // NoSupportedCurves, if true, causes the client to omit the
624 // supported_curves extension.
625 NoSupportedCurves bool
626
David Benjaminc44b1df2014-11-23 12:11:01 -0500627 // RequireSameRenegoClientVersion, if true, causes the server
628 // to require that all ClientHellos match in offered version
629 // across a renego.
630 RequireSameRenegoClientVersion bool
Feng Lu41aa3252014-11-21 22:47:56 -0800631
David Benjamin1e29a6b2014-12-10 02:27:24 -0500632 // ExpectInitialRecordVersion, if non-zero, is the expected
633 // version of the records before the version is determined.
634 ExpectInitialRecordVersion uint16
David Benjamin13be1de2015-01-11 16:29:36 -0500635
636 // MaxPacketLength, if non-zero, is the maximum acceptable size for a
637 // packet.
638 MaxPacketLength int
David Benjamin6095de82014-12-27 01:50:38 -0500639
640 // SendCipherSuite, if non-zero, is the cipher suite value that the
641 // server will send in the ServerHello. This does not affect the cipher
642 // the server believes it has actually negotiated.
643 SendCipherSuite uint16
David Benjamin4189bd92015-01-25 23:52:39 -0500644
David Benjamin4cf369b2015-08-22 01:35:43 -0400645 // AppDataBeforeHandshake, if not nil, causes application data to be
646 // sent immediately before the first handshake message.
647 AppDataBeforeHandshake []byte
648
649 // AppDataAfterChangeCipherSpec, if not nil, causes application data to
David Benjamin4189bd92015-01-25 23:52:39 -0500650 // be sent immediately after ChangeCipherSpec.
651 AppDataAfterChangeCipherSpec []byte
David Benjamin83f90402015-01-27 01:09:43 -0500652
David Benjamindc3da932015-03-12 15:09:02 -0400653 // AlertAfterChangeCipherSpec, if non-zero, causes an alert to be sent
654 // immediately after ChangeCipherSpec.
655 AlertAfterChangeCipherSpec alert
656
David Benjamin83f90402015-01-27 01:09:43 -0500657 // TimeoutSchedule is the schedule of packet drops and simulated
658 // timeouts for before each handshake leg from the peer.
659 TimeoutSchedule []time.Duration
660
661 // PacketAdaptor is the packetAdaptor to use to simulate timeouts.
662 PacketAdaptor *packetAdaptor
David Benjaminb3774b92015-01-31 17:16:01 -0500663
664 // ReorderHandshakeFragments, if true, causes handshake fragments in
665 // DTLS to overlap and be sent in the wrong order. It also causes
666 // pre-CCS flights to be sent twice. (Post-CCS flights consist of
667 // Finished and will trigger a spurious retransmit.)
668 ReorderHandshakeFragments bool
David Benjaminddb9f152015-02-03 15:44:39 -0500669
David Benjamin75381222015-03-02 19:30:30 -0500670 // MixCompleteMessageWithFragments, if true, causes handshake
671 // messages in DTLS to redundantly both fragment the message
672 // and include a copy of the full one.
673 MixCompleteMessageWithFragments bool
674
David Benjaminddb9f152015-02-03 15:44:39 -0500675 // SendInvalidRecordType, if true, causes a record with an invalid
676 // content type to be sent immediately following the handshake.
677 SendInvalidRecordType bool
David Benjaminbcb2d912015-02-24 23:45:43 -0500678
679 // WrongCertificateMessageType, if true, causes Certificate message to
680 // be sent with the wrong message type.
681 WrongCertificateMessageType bool
David Benjamin75381222015-03-02 19:30:30 -0500682
683 // FragmentMessageTypeMismatch, if true, causes all non-initial
684 // handshake fragments in DTLS to have the wrong message type.
685 FragmentMessageTypeMismatch bool
686
687 // FragmentMessageLengthMismatch, if true, causes all non-initial
688 // handshake fragments in DTLS to have the wrong message length.
689 FragmentMessageLengthMismatch bool
690
David Benjamin11fc66a2015-06-16 11:40:24 -0400691 // SplitFragments, if non-zero, causes the handshake fragments in DTLS
692 // to be split across two records. The value of |SplitFragments| is the
693 // number of bytes in the first fragment.
694 SplitFragments int
David Benjamin75381222015-03-02 19:30:30 -0500695
696 // SendEmptyFragments, if true, causes handshakes to include empty
697 // fragments in DTLS.
698 SendEmptyFragments bool
David Benjamincdea40c2015-03-19 14:09:43 -0400699
David Benjamin9a41d1b2015-05-16 01:30:09 -0400700 // SendSplitAlert, if true, causes an alert to be sent with the header
701 // and record body split across multiple packets. The peer should
702 // discard these packets rather than process it.
703 SendSplitAlert bool
704
David Benjamin4b27d9f2015-05-12 22:42:52 -0400705 // FailIfResumeOnRenego, if true, causes renegotiations to fail if the
706 // client offers a resumption or the server accepts one.
707 FailIfResumeOnRenego bool
David Benjamin3c9746a2015-03-19 15:00:10 -0400708
David Benjamin67d1fb52015-03-16 15:16:23 -0400709 // IgnorePeerCipherPreferences, if true, causes the peer's cipher
710 // preferences to be ignored.
711 IgnorePeerCipherPreferences bool
David Benjamin72dc7832015-03-16 17:49:43 -0400712
713 // IgnorePeerSignatureAlgorithmPreferences, if true, causes the peer's
714 // signature algorithm preferences to be ignored.
715 IgnorePeerSignatureAlgorithmPreferences bool
David Benjamin340d5ed2015-03-21 02:21:37 -0400716
David Benjaminc574f412015-04-20 11:13:01 -0400717 // IgnorePeerCurvePreferences, if true, causes the peer's curve
718 // preferences to be ignored.
719 IgnorePeerCurvePreferences bool
720
David Benjamin513f0ea2015-04-02 19:33:31 -0400721 // BadFinished, if true, causes the Finished hash to be broken.
722 BadFinished bool
Adam Langleya7997f12015-05-14 17:38:50 -0700723
724 // DHGroupPrime, if not nil, is used to define the (finite field)
725 // Diffie-Hellman group. The generator used is always two.
726 DHGroupPrime *big.Int
David Benjaminbd15a8e2015-05-29 18:48:16 -0400727
728 // PackHandshakeFragments, if true, causes handshake fragments to be
729 // packed into individual handshake records, up to the specified record
730 // size.
731 PackHandshakeFragments int
732
733 // PackHandshakeRecords, if true, causes handshake records to be packed
734 // into individual packets, up to the specified packet size.
735 PackHandshakeRecords int
David Benjamin0fa40122015-05-30 17:13:12 -0400736
737 // EnableAllCiphersInDTLS, if true, causes RC4 to be enabled in DTLS.
738 EnableAllCiphersInDTLS bool
David Benjamin8923c0b2015-06-07 11:42:34 -0400739
740 // EmptyCertificateList, if true, causes the server to send an empty
741 // certificate list in the Certificate message.
742 EmptyCertificateList bool
David Benjamind98452d2015-06-16 14:16:23 -0400743
744 // ExpectNewTicket, if true, causes the client to abort if it does not
745 // receive a new ticket.
746 ExpectNewTicket bool
Adam Langley33ad2b52015-07-20 17:43:53 -0700747
748 // RequireClientHelloSize, if not zero, is the required length in bytes
749 // of the ClientHello /record/. This is checked by the server.
750 RequireClientHelloSize int
Adam Langley09505632015-07-30 18:10:13 -0700751
752 // CustomExtension, if not empty, contains the contents of an extension
753 // that will be added to client/server hellos.
754 CustomExtension string
755
756 // ExpectedCustomExtension, if not nil, contains the expected contents
757 // of a custom extension.
758 ExpectedCustomExtension *string
David Benjamin30789da2015-08-29 22:56:45 -0400759
760 // NoCloseNotify, if true, causes the close_notify alert to be skipped
761 // on connection shutdown.
762 NoCloseNotify bool
763
764 // ExpectCloseNotify, if true, requires a close_notify from the peer on
765 // shutdown. Records from the peer received after close_notify is sent
766 // are not discard.
767 ExpectCloseNotify bool
David Benjamin2c99d282015-09-01 10:23:00 -0400768
769 // SendLargeRecords, if true, allows outgoing records to be sent
770 // arbitrarily large.
771 SendLargeRecords bool
David Benjamin76c2efc2015-08-31 14:24:29 -0400772
773 // NegotiateALPNAndNPN, if true, causes the server to negotiate both
774 // ALPN and NPN in the same connetion.
775 NegotiateALPNAndNPN bool
David Benjamindd6fed92015-10-23 17:41:12 -0400776
777 // SendEmptySessionTicket, if true, causes the server to send an empty
778 // session ticket.
779 SendEmptySessionTicket bool
780
781 // FailIfSessionOffered, if true, causes the server to fail any
782 // connections where the client offers a non-empty session ID or session
783 // ticket.
784 FailIfSessionOffered bool
Adam Langley27a0d082015-11-03 13:34:10 -0800785
786 // SendHelloRequestBeforeEveryAppDataRecord, if true, causes a
787 // HelloRequest handshake message to be sent before each application
788 // data record. This only makes sense for a server.
789 SendHelloRequestBeforeEveryAppDataRecord bool
Adam Langley95c29f32014-06-20 12:00:00 -0700790}
791
792func (c *Config) serverInit() {
793 if c.SessionTicketsDisabled {
794 return
795 }
796
797 // If the key has already been set then we have nothing to do.
798 for _, b := range c.SessionTicketKey {
799 if b != 0 {
800 return
801 }
802 }
803
804 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
805 c.SessionTicketsDisabled = true
806 }
807}
808
809func (c *Config) rand() io.Reader {
810 r := c.Rand
811 if r == nil {
812 return rand.Reader
813 }
814 return r
815}
816
817func (c *Config) time() time.Time {
818 t := c.Time
819 if t == nil {
820 t = time.Now
821 }
822 return t()
823}
824
825func (c *Config) cipherSuites() []uint16 {
826 s := c.CipherSuites
827 if s == nil {
828 s = defaultCipherSuites()
829 }
830 return s
831}
832
833func (c *Config) minVersion() uint16 {
834 if c == nil || c.MinVersion == 0 {
835 return minVersion
836 }
837 return c.MinVersion
838}
839
840func (c *Config) maxVersion() uint16 {
841 if c == nil || c.MaxVersion == 0 {
842 return maxVersion
843 }
844 return c.MaxVersion
845}
846
847var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
848
849func (c *Config) curvePreferences() []CurveID {
850 if c == nil || len(c.CurvePreferences) == 0 {
851 return defaultCurvePreferences
852 }
853 return c.CurvePreferences
854}
855
856// mutualVersion returns the protocol version to use given the advertised
857// version of the peer.
858func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
859 minVersion := c.minVersion()
860 maxVersion := c.maxVersion()
861
862 if vers < minVersion {
863 return 0, false
864 }
865 if vers > maxVersion {
866 vers = maxVersion
867 }
868 return vers, true
869}
870
871// getCertificateForName returns the best certificate for the given name,
872// defaulting to the first element of c.Certificates if there are no good
873// options.
874func (c *Config) getCertificateForName(name string) *Certificate {
875 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
876 // There's only one choice, so no point doing any work.
877 return &c.Certificates[0]
878 }
879
880 name = strings.ToLower(name)
881 for len(name) > 0 && name[len(name)-1] == '.' {
882 name = name[:len(name)-1]
883 }
884
885 if cert, ok := c.NameToCertificate[name]; ok {
886 return cert
887 }
888
889 // try replacing labels in the name with wildcards until we get a
890 // match.
891 labels := strings.Split(name, ".")
892 for i := range labels {
893 labels[i] = "*"
894 candidate := strings.Join(labels, ".")
895 if cert, ok := c.NameToCertificate[candidate]; ok {
896 return cert
897 }
898 }
899
900 // If nothing matches, return the first certificate.
901 return &c.Certificates[0]
902}
903
David Benjamin000800a2014-11-14 01:43:59 -0500904func (c *Config) signatureAndHashesForServer() []signatureAndHash {
905 if c != nil && c.SignatureAndHashes != nil {
906 return c.SignatureAndHashes
907 }
908 return supportedClientCertSignatureAlgorithms
909}
910
911func (c *Config) signatureAndHashesForClient() []signatureAndHash {
912 if c != nil && c.SignatureAndHashes != nil {
913 return c.SignatureAndHashes
914 }
915 return supportedSKXSignatureAlgorithms
916}
917
Adam Langley95c29f32014-06-20 12:00:00 -0700918// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
919// from the CommonName and SubjectAlternateName fields of each of the leaf
920// certificates.
921func (c *Config) BuildNameToCertificate() {
922 c.NameToCertificate = make(map[string]*Certificate)
923 for i := range c.Certificates {
924 cert := &c.Certificates[i]
925 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
926 if err != nil {
927 continue
928 }
929 if len(x509Cert.Subject.CommonName) > 0 {
930 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
931 }
932 for _, san := range x509Cert.DNSNames {
933 c.NameToCertificate[san] = cert
934 }
935 }
936}
937
938// A Certificate is a chain of one or more certificates, leaf first.
939type Certificate struct {
940 Certificate [][]byte
941 PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
942 // OCSPStaple contains an optional OCSP response which will be served
943 // to clients that request it.
944 OCSPStaple []byte
David Benjamin61f95272014-11-25 01:55:35 -0500945 // SignedCertificateTimestampList contains an optional encoded
946 // SignedCertificateTimestampList structure which will be
947 // served to clients that request it.
948 SignedCertificateTimestampList []byte
Adam Langley95c29f32014-06-20 12:00:00 -0700949 // Leaf is the parsed form of the leaf certificate, which may be
950 // initialized using x509.ParseCertificate to reduce per-handshake
951 // processing for TLS clients doing client authentication. If nil, the
952 // leaf certificate will be parsed as needed.
953 Leaf *x509.Certificate
954}
955
956// A TLS record.
957type record struct {
958 contentType recordType
959 major, minor uint8
960 payload []byte
961}
962
963type handshakeMessage interface {
964 marshal() []byte
965 unmarshal([]byte) bool
966}
967
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500968// lruSessionCache is a client or server session cache implementation
969// that uses an LRU caching strategy.
Adam Langley95c29f32014-06-20 12:00:00 -0700970type lruSessionCache struct {
971 sync.Mutex
972
973 m map[string]*list.Element
974 q *list.List
975 capacity int
976}
977
978type lruSessionCacheEntry struct {
979 sessionKey string
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500980 state interface{}
Adam Langley95c29f32014-06-20 12:00:00 -0700981}
982
983// Put adds the provided (sessionKey, cs) pair to the cache.
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500984func (c *lruSessionCache) Put(sessionKey string, cs interface{}) {
Adam Langley95c29f32014-06-20 12:00:00 -0700985 c.Lock()
986 defer c.Unlock()
987
988 if elem, ok := c.m[sessionKey]; ok {
989 entry := elem.Value.(*lruSessionCacheEntry)
990 entry.state = cs
991 c.q.MoveToFront(elem)
992 return
993 }
994
995 if c.q.Len() < c.capacity {
996 entry := &lruSessionCacheEntry{sessionKey, cs}
997 c.m[sessionKey] = c.q.PushFront(entry)
998 return
999 }
1000
1001 elem := c.q.Back()
1002 entry := elem.Value.(*lruSessionCacheEntry)
1003 delete(c.m, entry.sessionKey)
1004 entry.sessionKey = sessionKey
1005 entry.state = cs
1006 c.q.MoveToFront(elem)
1007 c.m[sessionKey] = elem
1008}
1009
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001010// Get returns the value associated with a given key. It returns (nil,
1011// false) if no value is found.
1012func (c *lruSessionCache) Get(sessionKey string) (interface{}, bool) {
Adam Langley95c29f32014-06-20 12:00:00 -07001013 c.Lock()
1014 defer c.Unlock()
1015
1016 if elem, ok := c.m[sessionKey]; ok {
1017 c.q.MoveToFront(elem)
1018 return elem.Value.(*lruSessionCacheEntry).state, true
1019 }
1020 return nil, false
1021}
1022
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001023// lruClientSessionCache is a ClientSessionCache implementation that
1024// uses an LRU caching strategy.
1025type lruClientSessionCache struct {
1026 lruSessionCache
1027}
1028
1029func (c *lruClientSessionCache) Put(sessionKey string, cs *ClientSessionState) {
1030 c.lruSessionCache.Put(sessionKey, cs)
1031}
1032
1033func (c *lruClientSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
1034 cs, ok := c.lruSessionCache.Get(sessionKey)
1035 if !ok {
1036 return nil, false
1037 }
1038 return cs.(*ClientSessionState), true
1039}
1040
1041// lruServerSessionCache is a ServerSessionCache implementation that
1042// uses an LRU caching strategy.
1043type lruServerSessionCache struct {
1044 lruSessionCache
1045}
1046
1047func (c *lruServerSessionCache) Put(sessionId string, session *sessionState) {
1048 c.lruSessionCache.Put(sessionId, session)
1049}
1050
1051func (c *lruServerSessionCache) Get(sessionId string) (*sessionState, bool) {
1052 cs, ok := c.lruSessionCache.Get(sessionId)
1053 if !ok {
1054 return nil, false
1055 }
1056 return cs.(*sessionState), true
1057}
1058
1059// NewLRUClientSessionCache returns a ClientSessionCache with the given
1060// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1061// is used instead.
1062func NewLRUClientSessionCache(capacity int) ClientSessionCache {
1063 const defaultSessionCacheCapacity = 64
1064
1065 if capacity < 1 {
1066 capacity = defaultSessionCacheCapacity
1067 }
1068 return &lruClientSessionCache{
1069 lruSessionCache{
1070 m: make(map[string]*list.Element),
1071 q: list.New(),
1072 capacity: capacity,
1073 },
1074 }
1075}
1076
1077// NewLRUServerSessionCache returns a ServerSessionCache with the given
1078// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1079// is used instead.
1080func NewLRUServerSessionCache(capacity int) ServerSessionCache {
1081 const defaultSessionCacheCapacity = 64
1082
1083 if capacity < 1 {
1084 capacity = defaultSessionCacheCapacity
1085 }
1086 return &lruServerSessionCache{
1087 lruSessionCache{
1088 m: make(map[string]*list.Element),
1089 q: list.New(),
1090 capacity: capacity,
1091 },
1092 }
1093}
1094
Adam Langley95c29f32014-06-20 12:00:00 -07001095// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
1096type dsaSignature struct {
1097 R, S *big.Int
1098}
1099
1100type ecdsaSignature dsaSignature
1101
1102var emptyConfig Config
1103
1104func defaultConfig() *Config {
1105 return &emptyConfig
1106}
1107
1108var (
1109 once sync.Once
1110 varDefaultCipherSuites []uint16
1111)
1112
1113func defaultCipherSuites() []uint16 {
1114 once.Do(initDefaultCipherSuites)
1115 return varDefaultCipherSuites
1116}
1117
1118func initDefaultCipherSuites() {
David Benjamin48cae082014-10-27 01:06:24 -04001119 for _, suite := range cipherSuites {
1120 if suite.flags&suitePSK == 0 {
1121 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
1122 }
Adam Langley95c29f32014-06-20 12:00:00 -07001123 }
1124}
1125
1126func unexpectedMessageError(wanted, got interface{}) error {
1127 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1128}
David Benjamin000800a2014-11-14 01:43:59 -05001129
1130func isSupportedSignatureAndHash(sigHash signatureAndHash, sigHashes []signatureAndHash) bool {
1131 for _, s := range sigHashes {
1132 if s == sigHash {
1133 return true
1134 }
1135 }
1136 return false
1137}