blob: 0e5d9e444b1d22187c2ea2bf87d2c7dbb8155851 [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
Nick Harper1fd39d82016-06-14 18:14:35 -070026 VersionTLS13 = 0x0304
Adam Langley95c29f32014-06-20 12:00:00 -070027)
28
29const (
David Benjamin83c0bc92014-08-04 01:23:53 -040030 maxPlaintext = 16384 // maximum plaintext payload length
31 maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
32 tlsRecordHeaderLen = 5 // record header length
33 dtlsRecordHeaderLen = 13
34 maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
Adam Langley95c29f32014-06-20 12:00:00 -070035
36 minVersion = VersionSSL30
Nick Harper1fd39d82016-06-14 18:14:35 -070037 maxVersion = VersionTLS13
Adam Langley95c29f32014-06-20 12:00:00 -070038)
39
40// TLS record types.
41type recordType uint8
42
43const (
44 recordTypeChangeCipherSpec recordType = 20
45 recordTypeAlert recordType = 21
46 recordTypeHandshake recordType = 22
47 recordTypeApplicationData recordType = 23
48)
49
50// TLS handshake message types.
51const (
David Benjamincedff872016-06-30 18:55:18 -040052 typeHelloRequest uint8 = 0
53 typeClientHello uint8 = 1
54 typeServerHello uint8 = 2
55 typeHelloVerifyRequest uint8 = 3
56 typeNewSessionTicket uint8 = 4
57 typeHelloRetryRequest uint8 = 6 // draft-ietf-tls-tls13-13
58 typeEncryptedExtensions uint8 = 8 // draft-ietf-tls-tls13-13
59 typeCertificate uint8 = 11
60 typeServerKeyExchange uint8 = 12
61 typeCertificateRequest uint8 = 13
62 typeServerHelloDone uint8 = 14
63 typeCertificateVerify uint8 = 15
64 typeClientKeyExchange uint8 = 16
65 typeFinished uint8 = 20
66 typeCertificateStatus uint8 = 22
67 typeNextProtocol uint8 = 67 // Not IANA assigned
68 typeChannelID uint8 = 203 // Not IANA assigned
Adam Langley95c29f32014-06-20 12:00:00 -070069)
70
71// TLS compression types.
72const (
73 compressionNone uint8 = 0
74)
75
76// TLS extension numbers
77const (
David Benjamin61f95272014-11-25 01:55:35 -050078 extensionServerName uint16 = 0
79 extensionStatusRequest uint16 = 5
80 extensionSupportedCurves uint16 = 10
81 extensionSupportedPoints uint16 = 11
82 extensionSignatureAlgorithms uint16 = 13
83 extensionUseSRTP uint16 = 14
84 extensionALPN uint16 = 16
85 extensionSignedCertificateTimestamp uint16 = 18
86 extensionExtendedMasterSecret uint16 = 23
87 extensionSessionTicket uint16 = 35
David Benjamincedff872016-06-30 18:55:18 -040088 extensionKeyShare uint16 = 40 // draft-ietf-tls-tls13-13
89 extensionPreSharedKey uint16 = 41 // draft-ietf-tls-tls13-13
90 extensionEarlyData uint16 = 42 // draft-ietf-tls-tls13-13
91 extensionCookie uint16 = 44 // draft-ietf-tls-tls13-13
David Benjamin399e7c92015-07-30 23:01:27 -040092 extensionCustom uint16 = 1234 // not IANA assigned
David Benjamin61f95272014-11-25 01:55:35 -050093 extensionNextProtoNeg uint16 = 13172 // not IANA assigned
94 extensionRenegotiationInfo uint16 = 0xff01
95 extensionChannelID uint16 = 30032 // not IANA assigned
Adam Langley95c29f32014-06-20 12:00:00 -070096)
97
98// TLS signaling cipher suite values
99const (
100 scsvRenegotiation uint16 = 0x00ff
101)
102
103// CurveID is the type of a TLS identifier for an elliptic curve. See
104// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
105type CurveID uint16
106
107const (
David Benjamincba2b622015-12-18 22:13:41 -0500108 CurveP224 CurveID = 21
109 CurveP256 CurveID = 23
110 CurveP384 CurveID = 24
111 CurveP521 CurveID = 25
112 CurveX25519 CurveID = 29
Adam Langley95c29f32014-06-20 12:00:00 -0700113)
114
115// TLS Elliptic Curve Point Formats
116// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
117const (
118 pointFormatUncompressed uint8 = 0
119)
120
121// TLS CertificateStatusType (RFC 3546)
122const (
123 statusTypeOCSP uint8 = 1
124)
125
126// Certificate types (for certificateRequestMsg)
127const (
David Benjamin7b030512014-07-08 17:30:11 -0400128 CertTypeRSASign = 1 // A certificate containing an RSA key
129 CertTypeDSSSign = 2 // A certificate containing a DSA key
130 CertTypeRSAFixedDH = 3 // A certificate containing a static DH key
131 CertTypeDSSFixedDH = 4 // A certificate containing a static DH key
Adam Langley95c29f32014-06-20 12:00:00 -0700132
133 // See RFC4492 sections 3 and 5.5.
David Benjamin7b030512014-07-08 17:30:11 -0400134 CertTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
135 CertTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
136 CertTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
Adam Langley95c29f32014-06-20 12:00:00 -0700137
138 // Rest of these are reserved by the TLS spec
139)
140
Nick Harper60edffd2016-06-21 15:19:24 -0700141// signatureAlgorithm corresponds to a SignatureScheme value from TLS 1.3. Note
142// that TLS 1.3 names the production 'SignatureScheme' to avoid colliding with
143// TLS 1.2's SignatureAlgorithm but otherwise refers to them as 'signature
144// algorithms' throughout. We match the latter.
145type signatureAlgorithm uint16
Adam Langley95c29f32014-06-20 12:00:00 -0700146
Adam Langley95c29f32014-06-20 12:00:00 -0700147const (
Nick Harper60edffd2016-06-21 15:19:24 -0700148 // RSASSA-PKCS1-v1_5 algorithms
149 signatureRSAPKCS1WithMD5 signatureAlgorithm = 0x0101
150 signatureRSAPKCS1WithSHA1 signatureAlgorithm = 0x0201
151 signatureRSAPKCS1WithSHA256 signatureAlgorithm = 0x0401
152 signatureRSAPKCS1WithSHA384 signatureAlgorithm = 0x0501
153 signatureRSAPKCS1WithSHA512 signatureAlgorithm = 0x0601
Adam Langley95c29f32014-06-20 12:00:00 -0700154
Nick Harper60edffd2016-06-21 15:19:24 -0700155 // ECDSA algorithms
156 signatureECDSAWithSHA1 signatureAlgorithm = 0x0203
157 signatureECDSAWithP256AndSHA256 signatureAlgorithm = 0x0403
158 signatureECDSAWithP384AndSHA384 signatureAlgorithm = 0x0503
159 signatureECDSAWithP521AndSHA512 signatureAlgorithm = 0x0603
160
161 // RSASSA-PSS algorithms
162 signatureRSAPSSWithSHA256 signatureAlgorithm = 0x0700
163 signatureRSAPSSWithSHA384 signatureAlgorithm = 0x0701
164 signatureRSAPSSWithSHA512 signatureAlgorithm = 0x0702
165
166 // EdDSA algorithms
167 signatureEd25519 signatureAlgorithm = 0x0703
168 signatureEd448 signatureAlgorithm = 0x0704
169)
Adam Langley95c29f32014-06-20 12:00:00 -0700170
171// supportedSKXSignatureAlgorithms contains the signature and hash algorithms
172// that the code advertises as supported in a TLS 1.2 ClientHello.
Nick Harper60edffd2016-06-21 15:19:24 -0700173var supportedSKXSignatureAlgorithms = []signatureAlgorithm{
174 signatureRSAPKCS1WithSHA256,
175 signatureECDSAWithP256AndSHA256,
176 signatureRSAPKCS1WithSHA1,
177 signatureECDSAWithSHA1,
Adam Langley95c29f32014-06-20 12:00:00 -0700178}
179
Nick Harper60edffd2016-06-21 15:19:24 -0700180// supportedPeerSignatureAlgorithms contains the signature and hash
Adam Langley95c29f32014-06-20 12:00:00 -0700181// algorithms that the code advertises as supported in a TLS 1.2
182// CertificateRequest.
Nick Harper60edffd2016-06-21 15:19:24 -0700183var supportedPeerSignatureAlgorithms = []signatureAlgorithm{
184 signatureRSAPKCS1WithSHA256,
185 signatureECDSAWithP256AndSHA256,
Adam Langley95c29f32014-06-20 12:00:00 -0700186}
187
David Benjaminca6c8262014-11-15 19:06:08 -0500188// SRTP protection profiles (See RFC 5764, section 4.1.2)
189const (
190 SRTP_AES128_CM_HMAC_SHA1_80 uint16 = 0x0001
191 SRTP_AES128_CM_HMAC_SHA1_32 = 0x0002
192)
193
Adam Langley95c29f32014-06-20 12:00:00 -0700194// ConnectionState records basic TLS details about the connection.
195type ConnectionState struct {
196 Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
197 HandshakeComplete bool // TLS handshake is complete
198 DidResume bool // connection resumes a previous TLS connection
199 CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
200 NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos)
201 NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server
David Benjaminfc7b0862014-09-06 13:21:53 -0400202 NegotiatedProtocolFromALPN bool // protocol negotiated with ALPN
Adam Langley95c29f32014-06-20 12:00:00 -0700203 ServerName string // server name requested by client, if any (server side only)
204 PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
205 VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
David Benjamind30a9902014-08-24 01:44:23 -0400206 ChannelID *ecdsa.PublicKey // the channel ID for this connection
David Benjaminca6c8262014-11-15 19:06:08 -0500207 SRTPProtectionProfile uint16 // the negotiated DTLS-SRTP protection profile
David Benjaminc0577622015-09-12 18:28:38 -0400208 TLSUnique []byte // the tls-unique channel binding
Paul Lietar4fac72e2015-09-09 13:44:55 +0100209 SCTList []byte // signed certificate timestamp list
Nick Harper60edffd2016-06-21 15:19:24 -0700210 PeerSignatureAlgorithm signatureAlgorithm // algorithm used by the peer in the handshake
Adam Langley95c29f32014-06-20 12:00:00 -0700211}
212
213// ClientAuthType declares the policy the server will follow for
214// TLS Client Authentication.
215type ClientAuthType int
216
217const (
218 NoClientCert ClientAuthType = iota
219 RequestClientCert
220 RequireAnyClientCert
221 VerifyClientCertIfGiven
222 RequireAndVerifyClientCert
223)
224
225// ClientSessionState contains the state needed by clients to resume TLS
226// sessions.
227type ClientSessionState struct {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500228 sessionId []uint8 // Session ID supplied by the server. nil if the session has a ticket.
Adam Langley75712922014-10-10 16:23:43 -0700229 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
230 vers uint16 // SSL/TLS version negotiated for the session
231 cipherSuite uint16 // Ciphersuite negotiated for the session
232 masterSecret []byte // MasterSecret generated by client on a full handshake
233 handshakeHash []byte // Handshake hash for Channel ID purposes.
234 serverCertificates []*x509.Certificate // Certificate chain presented by the server
235 extendedMasterSecret bool // Whether an extended master secret was used to generate the session
Paul Lietar62be8ac2015-09-16 10:03:30 +0100236 sctList []byte
237 ocspResponse []byte
Adam Langley95c29f32014-06-20 12:00:00 -0700238}
239
240// ClientSessionCache is a cache of ClientSessionState objects that can be used
241// by a client to resume a TLS session with a given server. ClientSessionCache
242// implementations should expect to be called concurrently from different
243// goroutines.
244type ClientSessionCache interface {
245 // Get searches for a ClientSessionState associated with the given key.
246 // On return, ok is true if one was found.
247 Get(sessionKey string) (session *ClientSessionState, ok bool)
248
249 // Put adds the ClientSessionState to the cache with the given key.
250 Put(sessionKey string, cs *ClientSessionState)
251}
252
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500253// ServerSessionCache is a cache of sessionState objects that can be used by a
254// client to resume a TLS session with a given server. ServerSessionCache
255// implementations should expect to be called concurrently from different
256// goroutines.
257type ServerSessionCache interface {
258 // Get searches for a sessionState associated with the given session
259 // ID. On return, ok is true if one was found.
260 Get(sessionId string) (session *sessionState, ok bool)
261
262 // Put adds the sessionState to the cache with the given session ID.
263 Put(sessionId string, session *sessionState)
264}
265
Adam Langley95c29f32014-06-20 12:00:00 -0700266// A Config structure is used to configure a TLS client or server.
267// After one has been passed to a TLS function it must not be
268// modified. A Config may be reused; the tls package will also not
269// modify it.
270type Config struct {
271 // Rand provides the source of entropy for nonces and RSA blinding.
272 // If Rand is nil, TLS uses the cryptographic random reader in package
273 // crypto/rand.
274 // The Reader must be safe for use by multiple goroutines.
275 Rand io.Reader
276
277 // Time returns the current time as the number of seconds since the epoch.
278 // If Time is nil, TLS uses time.Now.
279 Time func() time.Time
280
281 // Certificates contains one or more certificate chains
282 // to present to the other side of the connection.
283 // Server configurations must include at least one certificate.
284 Certificates []Certificate
285
286 // NameToCertificate maps from a certificate name to an element of
287 // Certificates. Note that a certificate name can be of the form
288 // '*.example.com' and so doesn't have to be a domain name as such.
289 // See Config.BuildNameToCertificate
290 // The nil value causes the first element of Certificates to be used
291 // for all connections.
292 NameToCertificate map[string]*Certificate
293
294 // RootCAs defines the set of root certificate authorities
295 // that clients use when verifying server certificates.
296 // If RootCAs is nil, TLS uses the host's root CA set.
297 RootCAs *x509.CertPool
298
299 // NextProtos is a list of supported, application level protocols.
300 NextProtos []string
301
302 // ServerName is used to verify the hostname on the returned
303 // certificates unless InsecureSkipVerify is given. It is also included
304 // in the client's handshake to support virtual hosting.
305 ServerName string
306
307 // ClientAuth determines the server's policy for
308 // TLS Client Authentication. The default is NoClientCert.
309 ClientAuth ClientAuthType
310
311 // ClientCAs defines the set of root certificate authorities
312 // that servers use if required to verify a client certificate
313 // by the policy in ClientAuth.
314 ClientCAs *x509.CertPool
315
David Benjamin7b030512014-07-08 17:30:11 -0400316 // ClientCertificateTypes defines the set of allowed client certificate
317 // types. The default is CertTypeRSASign and CertTypeECDSASign.
318 ClientCertificateTypes []byte
319
Adam Langley95c29f32014-06-20 12:00:00 -0700320 // InsecureSkipVerify controls whether a client verifies the
321 // server's certificate chain and host name.
322 // If InsecureSkipVerify is true, TLS accepts any certificate
323 // presented by the server and any host name in that certificate.
324 // In this mode, TLS is susceptible to man-in-the-middle attacks.
325 // This should be used only for testing.
326 InsecureSkipVerify bool
327
328 // CipherSuites is a list of supported cipher suites. If CipherSuites
329 // is nil, TLS uses a list of suites supported by the implementation.
330 CipherSuites []uint16
331
332 // PreferServerCipherSuites controls whether the server selects the
333 // client's most preferred ciphersuite, or the server's most preferred
334 // ciphersuite. If true then the server's preference, as expressed in
335 // the order of elements in CipherSuites, is used.
336 PreferServerCipherSuites bool
337
338 // SessionTicketsDisabled may be set to true to disable session ticket
339 // (resumption) support.
340 SessionTicketsDisabled bool
341
342 // SessionTicketKey is used by TLS servers to provide session
343 // resumption. See RFC 5077. If zero, it will be filled with
344 // random data before the first server handshake.
345 //
346 // If multiple servers are terminating connections for the same host
347 // they should all have the same SessionTicketKey. If the
348 // SessionTicketKey leaks, previously recorded and future TLS
349 // connections using that key are compromised.
350 SessionTicketKey [32]byte
351
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500352 // ClientSessionCache is a cache of ClientSessionState entries
353 // for TLS session resumption.
Adam Langley95c29f32014-06-20 12:00:00 -0700354 ClientSessionCache ClientSessionCache
355
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500356 // ServerSessionCache is a cache of sessionState entries for TLS session
357 // resumption.
358 ServerSessionCache ServerSessionCache
359
Adam Langley95c29f32014-06-20 12:00:00 -0700360 // MinVersion contains the minimum SSL/TLS version that is acceptable.
361 // If zero, then SSLv3 is taken as the minimum.
362 MinVersion uint16
363
364 // MaxVersion contains the maximum SSL/TLS version that is acceptable.
365 // If zero, then the maximum version supported by this package is used,
366 // which is currently TLS 1.2.
367 MaxVersion uint16
368
369 // CurvePreferences contains the elliptic curves that will be used in
370 // an ECDHE handshake, in preference order. If empty, the default will
371 // be used.
372 CurvePreferences []CurveID
373
David Benjamind30a9902014-08-24 01:44:23 -0400374 // ChannelID contains the ECDSA key for the client to use as
375 // its TLS Channel ID.
376 ChannelID *ecdsa.PrivateKey
377
378 // RequestChannelID controls whether the server requests a TLS
379 // Channel ID. If negotiated, the client's public key is
380 // returned in the ConnectionState.
381 RequestChannelID bool
382
David Benjamin48cae082014-10-27 01:06:24 -0400383 // PreSharedKey, if not nil, is the pre-shared key to use with
384 // the PSK cipher suites.
385 PreSharedKey []byte
386
387 // PreSharedKeyIdentity, if not empty, is the identity to use
388 // with the PSK cipher suites.
389 PreSharedKeyIdentity string
390
David Benjaminca6c8262014-11-15 19:06:08 -0500391 // SRTPProtectionProfiles, if not nil, is the list of SRTP
392 // protection profiles to offer in DTLS-SRTP.
393 SRTPProtectionProfiles []uint16
394
Nick Harper60edffd2016-06-21 15:19:24 -0700395 // SignatureAlgorithms, if not nil, overrides the default set of
David Benjamin000800a2014-11-14 01:43:59 -0500396 // supported signature and hash algorithms to advertise in
397 // CertificateRequest.
Nick Harper60edffd2016-06-21 15:19:24 -0700398 SignatureAlgorithms []signatureAlgorithm
David Benjamin000800a2014-11-14 01:43:59 -0500399
Adam Langley95c29f32014-06-20 12:00:00 -0700400 // Bugs specifies optional misbehaviour to be used for testing other
401 // implementations.
402 Bugs ProtocolBugs
403
404 serverInitOnce sync.Once // guards calling (*Config).serverInit
405}
406
407type BadValue int
408
409const (
410 BadValueNone BadValue = iota
411 BadValueNegative
412 BadValueZero
413 BadValueLimit
414 BadValueLarge
415 NumBadValues
416)
417
David Benjaminb36a3952015-12-01 18:53:13 -0500418type RSABadValue int
419
420const (
421 RSABadValueNone RSABadValue = iota
422 RSABadValueCorrupt
423 RSABadValueTooLong
424 RSABadValueTooShort
425 RSABadValueWrongVersion
426 NumRSABadValues
427)
428
Adam Langley95c29f32014-06-20 12:00:00 -0700429type ProtocolBugs struct {
430 // InvalidSKXSignature specifies that the signature in a
431 // ServerKeyExchange message should be invalid.
432 InvalidSKXSignature bool
433
David Benjamin6de0e532015-07-28 22:43:19 -0400434 // InvalidCertVerifySignature specifies that the signature in a
435 // CertificateVerify message should be invalid.
436 InvalidCertVerifySignature bool
437
David Benjamin4c3ddf72016-06-29 18:13:53 -0400438 // SendCurve, if non-zero, causes the ServerKeyExchange message to use
439 // the specified curve ID rather than the negotiated one.
440 SendCurve CurveID
Adam Langley95c29f32014-06-20 12:00:00 -0700441
David Benjamin2b07fa42016-03-02 00:23:57 -0500442 // InvalidECDHPoint, if true, causes the ECC points in
443 // ServerKeyExchange or ClientKeyExchange messages to be invalid.
444 InvalidECDHPoint bool
445
Adam Langley95c29f32014-06-20 12:00:00 -0700446 // BadECDSAR controls ways in which the 'r' value of an ECDSA signature
447 // can be invalid.
448 BadECDSAR BadValue
449 BadECDSAS BadValue
Adam Langley80842bd2014-06-20 12:00:00 -0700450
451 // MaxPadding causes CBC records to have the maximum possible padding.
452 MaxPadding bool
453 // PaddingFirstByteBad causes the first byte of the padding to be
454 // incorrect.
455 PaddingFirstByteBad bool
456 // PaddingFirstByteBadIf255 causes the first byte of padding to be
457 // incorrect if there's a maximum amount of padding (i.e. 255 bytes).
458 PaddingFirstByteBadIf255 bool
Adam Langleyac61fa32014-06-23 12:03:11 -0700459
460 // FailIfNotFallbackSCSV causes a server handshake to fail if the
461 // client doesn't send the fallback SCSV value.
462 FailIfNotFallbackSCSV bool
David Benjamin35a7a442014-07-05 00:23:20 -0400463
464 // DuplicateExtension causes an extra empty extension of bogus type to
465 // be emitted in either the ClientHello or the ServerHello.
466 DuplicateExtension bool
David Benjamin1c375dd2014-07-12 00:48:23 -0400467
468 // UnauthenticatedECDH causes the server to pretend ECDHE_RSA
469 // and ECDHE_ECDSA cipher suites are actually ECDH_anon. No
470 // Certificate message is sent and no signature is added to
471 // ServerKeyExchange.
472 UnauthenticatedECDH bool
David Benjamin9c651c92014-07-12 13:27:45 -0400473
David Benjaminb80168e2015-02-08 18:30:14 -0500474 // SkipHelloVerifyRequest causes a DTLS server to skip the
475 // HelloVerifyRequest message.
476 SkipHelloVerifyRequest bool
477
David Benjamindcd979f2015-04-20 18:26:52 -0400478 // SkipCertificateStatus, if true, causes the server to skip the
479 // CertificateStatus message. This is legal because CertificateStatus is
480 // optional, even with a status_request in ServerHello.
481 SkipCertificateStatus bool
482
David Benjamin9c651c92014-07-12 13:27:45 -0400483 // SkipServerKeyExchange causes the server to skip sending
484 // ServerKeyExchange messages.
485 SkipServerKeyExchange bool
David Benjamina0e52232014-07-19 17:39:58 -0400486
David Benjaminb80168e2015-02-08 18:30:14 -0500487 // SkipNewSessionTicket causes the server to skip sending the
488 // NewSessionTicket message despite promising to in ServerHello.
489 SkipNewSessionTicket bool
490
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500491 // SkipClientCertificate causes the client to skip the Certificate
492 // message.
493 SkipClientCertificate bool
494
David Benjamina0e52232014-07-19 17:39:58 -0400495 // SkipChangeCipherSpec causes the implementation to skip
496 // sending the ChangeCipherSpec message (and adjusting cipher
497 // state accordingly for the Finished message).
498 SkipChangeCipherSpec bool
David Benjaminf3ec83d2014-07-21 22:42:34 -0400499
David Benjaminb80168e2015-02-08 18:30:14 -0500500 // SkipFinished causes the implementation to skip sending the Finished
501 // message.
502 SkipFinished bool
503
David Benjaminf3ec83d2014-07-21 22:42:34 -0400504 // EarlyChangeCipherSpec causes the client to send an early
505 // ChangeCipherSpec message before the ClientKeyExchange. A value of
506 // zero disables this behavior. One and two configure variants for 0.9.8
507 // and 1.0.1 modes, respectively.
508 EarlyChangeCipherSpec int
David Benjamind23f4122014-07-23 15:09:48 -0400509
David Benjamin8144f992016-06-22 17:05:13 -0400510 // StrayChangeCipherSpec causes every pre-ChangeCipherSpec handshake
511 // message in DTLS to be prefaced by stray ChangeCipherSpec record. This
512 // may be used to test DTLS's handling of reordered ChangeCipherSpec.
513 StrayChangeCipherSpec bool
514
David Benjamin86271ee2014-07-21 16:14:03 -0400515 // FragmentAcrossChangeCipherSpec causes the implementation to fragment
516 // the Finished (or NextProto) message around the ChangeCipherSpec
517 // messages.
518 FragmentAcrossChangeCipherSpec bool
519
David Benjamind86c7672014-08-02 04:07:12 -0400520 // SendV2ClientHello causes the client to send a V2ClientHello
521 // instead of a normal ClientHello.
522 SendV2ClientHello bool
David Benjaminbef270a2014-08-02 04:22:02 -0400523
524 // SendFallbackSCSV causes the client to include
525 // TLS_FALLBACK_SCSV in the ClientHello.
526 SendFallbackSCSV bool
David Benjamin43ec06f2014-08-05 02:28:57 -0400527
Adam Langley5021b222015-06-12 18:27:58 -0700528 // SendRenegotiationSCSV causes the client to include the renegotiation
529 // SCSV in the ClientHello.
530 SendRenegotiationSCSV bool
531
David Benjamin43ec06f2014-08-05 02:28:57 -0400532 // MaxHandshakeRecordLength, if non-zero, is the maximum size of a
David Benjamin98214542014-08-07 18:02:39 -0400533 // handshake record. Handshake messages will be split into multiple
534 // records at the specified size, except that the client_version will
David Benjaminbd15a8e2015-05-29 18:48:16 -0400535 // never be fragmented. For DTLS, it is the maximum handshake fragment
536 // size, not record size; DTLS allows multiple handshake fragments in a
537 // single handshake record. See |PackHandshakeFragments|.
David Benjamin43ec06f2014-08-05 02:28:57 -0400538 MaxHandshakeRecordLength int
David Benjamina8e3e0e2014-08-06 22:11:10 -0400539
David Benjamin98214542014-08-07 18:02:39 -0400540 // FragmentClientVersion will allow MaxHandshakeRecordLength to apply to
541 // the first 6 bytes of the ClientHello.
542 FragmentClientVersion bool
543
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400544 // FragmentAlert will cause all alerts to be fragmented across
545 // two records.
546 FragmentAlert bool
547
David Benjamin0d3a8c62016-03-11 22:25:18 -0500548 // DoubleAlert will cause all alerts to be sent as two copies packed
549 // within one record.
550 DoubleAlert bool
551
David Benjamin3fd1fbd2015-02-03 16:07:32 -0500552 // SendSpuriousAlert, if non-zero, will cause an spurious, unwanted
553 // alert to be sent.
554 SendSpuriousAlert alert
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400555
David Benjaminb36a3952015-12-01 18:53:13 -0500556 // BadRSAClientKeyExchange causes the client to send a corrupted RSA
557 // ClientKeyExchange which would not pass padding checks.
558 BadRSAClientKeyExchange RSABadValue
David Benjaminbed9aae2014-08-07 19:13:38 -0400559
560 // RenewTicketOnResume causes the server to renew the session ticket and
561 // send a NewSessionTicket message during an abbreviated handshake.
562 RenewTicketOnResume bool
David Benjamin98e882e2014-08-08 13:24:34 -0400563
564 // SendClientVersion, if non-zero, causes the client to send a different
565 // TLS version in the ClientHello than the maximum supported version.
566 SendClientVersion uint16
David Benjamin83c0bc92014-08-04 01:23:53 -0400567
David Benjamine58c4f52014-08-24 03:47:07 -0400568 // ExpectFalseStart causes the server to, on full handshakes,
569 // expect the peer to False Start; the server Finished message
570 // isn't sent until we receive an application data record
571 // from the peer.
572 ExpectFalseStart bool
David Benjamin5c24a1d2014-08-31 00:59:27 -0400573
David Benjamin1c633152015-04-02 20:19:11 -0400574 // AlertBeforeFalseStartTest, if non-zero, causes the server to, on full
575 // handshakes, send an alert just before reading the application data
576 // record to test False Start. This can be used in a negative False
577 // Start test to determine whether the peer processed the alert (and
578 // closed the connection) before or after sending app data.
579 AlertBeforeFalseStartTest alert
580
David Benjamine78bfde2014-09-06 12:45:15 -0400581 // ExpectServerName, if not empty, is the hostname the client
582 // must specify in the server_name extension.
583 ExpectServerName string
David Benjaminfc7b0862014-09-06 13:21:53 -0400584
David Benjamin76c2efc2015-08-31 14:24:29 -0400585 // SwapNPNAndALPN switches the relative order between NPN and ALPN in
586 // both ClientHello and ServerHello.
David Benjaminfc7b0862014-09-06 13:21:53 -0400587 SwapNPNAndALPN bool
David Benjamin01fe8202014-09-24 15:21:44 -0400588
Adam Langleyefb0e162015-07-09 11:35:04 -0700589 // ALPNProtocol, if not nil, sets the ALPN protocol that a server will
590 // return.
591 ALPNProtocol *string
592
David Benjamin01fe8202014-09-24 15:21:44 -0400593 // AllowSessionVersionMismatch causes the server to resume sessions
594 // regardless of the version associated with the session.
595 AllowSessionVersionMismatch bool
Adam Langley38311732014-10-16 19:04:35 -0700596
597 // CorruptTicket causes a client to corrupt a session ticket before
598 // sending it in a resume handshake.
599 CorruptTicket bool
600
601 // OversizedSessionId causes the session id that is sent with a ticket
602 // resumption attempt to be too large (33 bytes).
603 OversizedSessionId bool
Adam Langley75712922014-10-10 16:23:43 -0700604
605 // RequireExtendedMasterSecret, if true, requires that the peer support
606 // the extended master secret option.
607 RequireExtendedMasterSecret bool
608
David Benjaminca6554b2014-11-08 12:31:52 -0500609 // NoExtendedMasterSecret causes the client and server to behave as if
Adam Langley75712922014-10-10 16:23:43 -0700610 // they didn't support an extended master secret.
611 NoExtendedMasterSecret bool
Adam Langley2ae77d22014-10-28 17:29:33 -0700612
613 // EmptyRenegotiationInfo causes the renegotiation extension to be
614 // empty in a renegotiation handshake.
615 EmptyRenegotiationInfo bool
616
617 // BadRenegotiationInfo causes the renegotiation extension value in a
618 // renegotiation handshake to be incorrect.
619 BadRenegotiationInfo bool
David Benjamin5e961c12014-11-07 01:48:35 -0500620
David Benjamin3e052de2015-11-25 20:10:31 -0500621 // NoRenegotiationInfo disables renegotiation info support in all
622 // handshakes.
David Benjaminca6554b2014-11-08 12:31:52 -0500623 NoRenegotiationInfo bool
624
David Benjamin3e052de2015-11-25 20:10:31 -0500625 // NoRenegotiationInfoInInitial disables renegotiation info support in
626 // the initial handshake.
627 NoRenegotiationInfoInInitial bool
628
629 // NoRenegotiationInfoAfterInitial disables renegotiation info support
630 // in renegotiation handshakes.
631 NoRenegotiationInfoAfterInitial bool
632
Adam Langley5021b222015-06-12 18:27:58 -0700633 // RequireRenegotiationInfo, if true, causes the client to return an
634 // error if the server doesn't reply with the renegotiation extension.
635 RequireRenegotiationInfo bool
636
David Benjamin8e6db492015-07-25 18:29:23 -0400637 // SequenceNumberMapping, if non-nil, is the mapping function to apply
638 // to the sequence number of outgoing packets. For both TLS and DTLS,
639 // the two most-significant bytes in the resulting sequence number are
640 // ignored so that the DTLS epoch cannot be changed.
641 SequenceNumberMapping func(uint64) uint64
David Benjamin9114fae2014-11-08 11:41:14 -0500642
David Benjamina3e89492015-02-26 15:16:22 -0500643 // RSAEphemeralKey, if true, causes the server to send a
644 // ServerKeyExchange message containing an ephemeral key (as in
645 // RSA_EXPORT) in the plain RSA key exchange.
646 RSAEphemeralKey bool
David Benjaminca6c8262014-11-15 19:06:08 -0500647
648 // SRTPMasterKeyIdentifer, if not empty, is the SRTP MKI value that the
649 // client offers when negotiating SRTP. MKI support is still missing so
650 // the peer must still send none.
651 SRTPMasterKeyIdentifer string
652
653 // SendSRTPProtectionProfile, if non-zero, is the SRTP profile that the
654 // server sends in the ServerHello instead of the negotiated one.
655 SendSRTPProtectionProfile uint16
David Benjamin000800a2014-11-14 01:43:59 -0500656
Nick Harper60edffd2016-06-21 15:19:24 -0700657 // NoSignatureAlgorithms, if true, causes the client to omit the
David Benjamin000800a2014-11-14 01:43:59 -0500658 // signature and hashes extension.
659 //
660 // For a server, it will cause an empty list to be sent in the
661 // CertificateRequest message. None the less, the configured set will
662 // still be enforced.
Nick Harper60edffd2016-06-21 15:19:24 -0700663 NoSignatureAlgorithms bool
David Benjaminc44b1df2014-11-23 12:11:01 -0500664
David Benjamin55a43642015-04-20 14:45:55 -0400665 // NoSupportedCurves, if true, causes the client to omit the
666 // supported_curves extension.
667 NoSupportedCurves bool
668
David Benjaminc44b1df2014-11-23 12:11:01 -0500669 // RequireSameRenegoClientVersion, if true, causes the server
670 // to require that all ClientHellos match in offered version
671 // across a renego.
672 RequireSameRenegoClientVersion bool
Feng Lu41aa3252014-11-21 22:47:56 -0800673
David Benjamin1e29a6b2014-12-10 02:27:24 -0500674 // ExpectInitialRecordVersion, if non-zero, is the expected
675 // version of the records before the version is determined.
676 ExpectInitialRecordVersion uint16
David Benjamin13be1de2015-01-11 16:29:36 -0500677
678 // MaxPacketLength, if non-zero, is the maximum acceptable size for a
679 // packet.
680 MaxPacketLength int
David Benjamin6095de82014-12-27 01:50:38 -0500681
682 // SendCipherSuite, if non-zero, is the cipher suite value that the
683 // server will send in the ServerHello. This does not affect the cipher
684 // the server believes it has actually negotiated.
685 SendCipherSuite uint16
David Benjamin4189bd92015-01-25 23:52:39 -0500686
David Benjamin4cf369b2015-08-22 01:35:43 -0400687 // AppDataBeforeHandshake, if not nil, causes application data to be
688 // sent immediately before the first handshake message.
689 AppDataBeforeHandshake []byte
690
691 // AppDataAfterChangeCipherSpec, if not nil, causes application data to
David Benjamin4189bd92015-01-25 23:52:39 -0500692 // be sent immediately after ChangeCipherSpec.
693 AppDataAfterChangeCipherSpec []byte
David Benjamin83f90402015-01-27 01:09:43 -0500694
David Benjamindc3da932015-03-12 15:09:02 -0400695 // AlertAfterChangeCipherSpec, if non-zero, causes an alert to be sent
696 // immediately after ChangeCipherSpec.
697 AlertAfterChangeCipherSpec alert
698
David Benjamin83f90402015-01-27 01:09:43 -0500699 // TimeoutSchedule is the schedule of packet drops and simulated
700 // timeouts for before each handshake leg from the peer.
701 TimeoutSchedule []time.Duration
702
703 // PacketAdaptor is the packetAdaptor to use to simulate timeouts.
704 PacketAdaptor *packetAdaptor
David Benjaminb3774b92015-01-31 17:16:01 -0500705
706 // ReorderHandshakeFragments, if true, causes handshake fragments in
707 // DTLS to overlap and be sent in the wrong order. It also causes
708 // pre-CCS flights to be sent twice. (Post-CCS flights consist of
709 // Finished and will trigger a spurious retransmit.)
710 ReorderHandshakeFragments bool
David Benjaminddb9f152015-02-03 15:44:39 -0500711
David Benjamin75381222015-03-02 19:30:30 -0500712 // MixCompleteMessageWithFragments, if true, causes handshake
713 // messages in DTLS to redundantly both fragment the message
714 // and include a copy of the full one.
715 MixCompleteMessageWithFragments bool
716
David Benjaminddb9f152015-02-03 15:44:39 -0500717 // SendInvalidRecordType, if true, causes a record with an invalid
718 // content type to be sent immediately following the handshake.
719 SendInvalidRecordType bool
David Benjaminbcb2d912015-02-24 23:45:43 -0500720
721 // WrongCertificateMessageType, if true, causes Certificate message to
722 // be sent with the wrong message type.
723 WrongCertificateMessageType bool
David Benjamin75381222015-03-02 19:30:30 -0500724
725 // FragmentMessageTypeMismatch, if true, causes all non-initial
726 // handshake fragments in DTLS to have the wrong message type.
727 FragmentMessageTypeMismatch bool
728
729 // FragmentMessageLengthMismatch, if true, causes all non-initial
730 // handshake fragments in DTLS to have the wrong message length.
731 FragmentMessageLengthMismatch bool
732
David Benjamin11fc66a2015-06-16 11:40:24 -0400733 // SplitFragments, if non-zero, causes the handshake fragments in DTLS
734 // to be split across two records. The value of |SplitFragments| is the
735 // number of bytes in the first fragment.
736 SplitFragments int
David Benjamin75381222015-03-02 19:30:30 -0500737
738 // SendEmptyFragments, if true, causes handshakes to include empty
739 // fragments in DTLS.
740 SendEmptyFragments bool
David Benjamincdea40c2015-03-19 14:09:43 -0400741
David Benjamin9a41d1b2015-05-16 01:30:09 -0400742 // SendSplitAlert, if true, causes an alert to be sent with the header
743 // and record body split across multiple packets. The peer should
744 // discard these packets rather than process it.
745 SendSplitAlert bool
746
David Benjamin4b27d9f2015-05-12 22:42:52 -0400747 // FailIfResumeOnRenego, if true, causes renegotiations to fail if the
748 // client offers a resumption or the server accepts one.
749 FailIfResumeOnRenego bool
David Benjamin3c9746a2015-03-19 15:00:10 -0400750
David Benjamin67d1fb52015-03-16 15:16:23 -0400751 // IgnorePeerCipherPreferences, if true, causes the peer's cipher
752 // preferences to be ignored.
753 IgnorePeerCipherPreferences bool
David Benjamin72dc7832015-03-16 17:49:43 -0400754
755 // IgnorePeerSignatureAlgorithmPreferences, if true, causes the peer's
756 // signature algorithm preferences to be ignored.
757 IgnorePeerSignatureAlgorithmPreferences bool
David Benjamin340d5ed2015-03-21 02:21:37 -0400758
David Benjaminc574f412015-04-20 11:13:01 -0400759 // IgnorePeerCurvePreferences, if true, causes the peer's curve
760 // preferences to be ignored.
761 IgnorePeerCurvePreferences bool
762
David Benjamin513f0ea2015-04-02 19:33:31 -0400763 // BadFinished, if true, causes the Finished hash to be broken.
764 BadFinished bool
Adam Langleya7997f12015-05-14 17:38:50 -0700765
766 // DHGroupPrime, if not nil, is used to define the (finite field)
767 // Diffie-Hellman group. The generator used is always two.
768 DHGroupPrime *big.Int
David Benjaminbd15a8e2015-05-29 18:48:16 -0400769
770 // PackHandshakeFragments, if true, causes handshake fragments to be
771 // packed into individual handshake records, up to the specified record
772 // size.
773 PackHandshakeFragments int
774
775 // PackHandshakeRecords, if true, causes handshake records to be packed
776 // into individual packets, up to the specified packet size.
777 PackHandshakeRecords int
David Benjamin0fa40122015-05-30 17:13:12 -0400778
David Benjamin0407e762016-06-17 16:41:18 -0400779 // EnableAllCiphers, if true, causes all configured ciphers to be
780 // enabled.
781 EnableAllCiphers bool
David Benjamin8923c0b2015-06-07 11:42:34 -0400782
783 // EmptyCertificateList, if true, causes the server to send an empty
784 // certificate list in the Certificate message.
785 EmptyCertificateList bool
David Benjamind98452d2015-06-16 14:16:23 -0400786
787 // ExpectNewTicket, if true, causes the client to abort if it does not
788 // receive a new ticket.
789 ExpectNewTicket bool
Adam Langley33ad2b52015-07-20 17:43:53 -0700790
791 // RequireClientHelloSize, if not zero, is the required length in bytes
792 // of the ClientHello /record/. This is checked by the server.
793 RequireClientHelloSize int
Adam Langley09505632015-07-30 18:10:13 -0700794
795 // CustomExtension, if not empty, contains the contents of an extension
796 // that will be added to client/server hellos.
797 CustomExtension string
798
799 // ExpectedCustomExtension, if not nil, contains the expected contents
800 // of a custom extension.
801 ExpectedCustomExtension *string
David Benjamin30789da2015-08-29 22:56:45 -0400802
803 // NoCloseNotify, if true, causes the close_notify alert to be skipped
804 // on connection shutdown.
805 NoCloseNotify bool
806
David Benjaminfa214e42016-05-10 17:03:10 -0400807 // SendAlertOnShutdown, if non-zero, is the alert to send instead of
808 // close_notify on shutdown.
809 SendAlertOnShutdown alert
810
David Benjamin30789da2015-08-29 22:56:45 -0400811 // ExpectCloseNotify, if true, requires a close_notify from the peer on
812 // shutdown. Records from the peer received after close_notify is sent
813 // are not discard.
814 ExpectCloseNotify bool
David Benjamin2c99d282015-09-01 10:23:00 -0400815
816 // SendLargeRecords, if true, allows outgoing records to be sent
817 // arbitrarily large.
818 SendLargeRecords bool
David Benjamin76c2efc2015-08-31 14:24:29 -0400819
820 // NegotiateALPNAndNPN, if true, causes the server to negotiate both
821 // ALPN and NPN in the same connetion.
822 NegotiateALPNAndNPN bool
David Benjamindd6fed92015-10-23 17:41:12 -0400823
824 // SendEmptySessionTicket, if true, causes the server to send an empty
825 // session ticket.
826 SendEmptySessionTicket bool
827
828 // FailIfSessionOffered, if true, causes the server to fail any
829 // connections where the client offers a non-empty session ID or session
830 // ticket.
831 FailIfSessionOffered bool
Adam Langley27a0d082015-11-03 13:34:10 -0800832
833 // SendHelloRequestBeforeEveryAppDataRecord, if true, causes a
834 // HelloRequest handshake message to be sent before each application
835 // data record. This only makes sense for a server.
836 SendHelloRequestBeforeEveryAppDataRecord bool
Adam Langleyc4f25ce2015-11-26 16:39:08 -0800837
838 // RequireDHPublicValueLen causes a fatal error if the length (in
839 // bytes) of the server's Diffie-Hellman public value is not equal to
840 // this.
841 RequireDHPublicValueLen int
David Benjamin8411b242015-11-26 12:07:28 -0500842
843 // BadChangeCipherSpec, if not nil, is the body to be sent in
844 // ChangeCipherSpec records instead of {1}.
845 BadChangeCipherSpec []byte
David Benjaminef5dfd22015-12-06 13:17:07 -0500846
847 // BadHelloRequest, if not nil, is what to send instead of a
848 // HelloRequest.
849 BadHelloRequest []byte
David Benjaminef1b0092015-11-21 14:05:44 -0500850
851 // RequireSessionTickets, if true, causes the client to require new
852 // sessions use session tickets instead of session IDs.
853 RequireSessionTickets bool
David Benjaminf2b83632016-03-01 22:57:46 -0500854
855 // NullAllCiphers, if true, causes every cipher to behave like the null
856 // cipher.
857 NullAllCiphers bool
David Benjamin80d1b352016-05-04 19:19:06 -0400858
859 // SendSCTListOnResume, if not nil, causes the server to send the
860 // supplied SCT list in resumption handshakes.
861 SendSCTListOnResume []byte
Matt Braithwaite54217e42016-06-13 13:03:47 -0700862
863 // CECPQ1BadX25519Part corrupts the X25519 part of a CECPQ1 key exchange, as
864 // a trivial proof that it is actually used.
865 CECPQ1BadX25519Part bool
866
867 // CECPQ1BadNewhopePart corrupts the Newhope part of a CECPQ1 key exchange,
868 // as a trivial proof that it is actually used.
869 CECPQ1BadNewhopePart bool
David Benjaminc9ae27c2016-06-24 22:56:37 -0400870
871 // RecordPadding is the number of bytes of padding to add to each
872 // encrypted record in TLS 1.3.
873 RecordPadding int
874
875 // OmitRecordContents, if true, causes encrypted records in TLS 1.3 to
876 // be missing their body and content type. Padding, if configured, is
877 // still added.
878 OmitRecordContents bool
879
880 // OuterRecordType, if non-zero, is the outer record type to use instead
881 // of application data.
882 OuterRecordType recordType
Adam Langley95c29f32014-06-20 12:00:00 -0700883}
884
885func (c *Config) serverInit() {
886 if c.SessionTicketsDisabled {
887 return
888 }
889
890 // If the key has already been set then we have nothing to do.
891 for _, b := range c.SessionTicketKey {
892 if b != 0 {
893 return
894 }
895 }
896
897 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
898 c.SessionTicketsDisabled = true
899 }
900}
901
902func (c *Config) rand() io.Reader {
903 r := c.Rand
904 if r == nil {
905 return rand.Reader
906 }
907 return r
908}
909
910func (c *Config) time() time.Time {
911 t := c.Time
912 if t == nil {
913 t = time.Now
914 }
915 return t()
916}
917
918func (c *Config) cipherSuites() []uint16 {
919 s := c.CipherSuites
920 if s == nil {
921 s = defaultCipherSuites()
922 }
923 return s
924}
925
David Benjamincecee272016-06-30 13:33:47 -0400926func (c *Config) minVersion(isDTLS bool) uint16 {
927 ret := uint16(minVersion)
928 if c != nil && c.MinVersion != 0 {
929 ret = c.MinVersion
Adam Langley95c29f32014-06-20 12:00:00 -0700930 }
David Benjamincecee272016-06-30 13:33:47 -0400931 if isDTLS {
932 // The lowest version of DTLS is 1.0. There is no DSSL 3.0.
933 if ret < VersionTLS10 {
934 return VersionTLS10
935 }
936 // There is no such thing as DTLS 1.1.
937 if ret == VersionTLS11 {
938 return VersionTLS12
939 }
940 }
941 return ret
Adam Langley95c29f32014-06-20 12:00:00 -0700942}
943
David Benjamincecee272016-06-30 13:33:47 -0400944func (c *Config) maxVersion(isDTLS bool) uint16 {
945 ret := uint16(maxVersion)
946 if c != nil && c.MaxVersion != 0 {
947 ret = c.MaxVersion
Adam Langley95c29f32014-06-20 12:00:00 -0700948 }
David Benjamincecee272016-06-30 13:33:47 -0400949 if isDTLS {
950 // We only implement up to DTLS 1.2.
951 if ret > VersionTLS12 {
952 return VersionTLS12
953 }
954 // There is no such thing as DTLS 1.1.
955 if ret == VersionTLS11 {
956 return VersionTLS10
957 }
958 }
959 return ret
Adam Langley95c29f32014-06-20 12:00:00 -0700960}
961
David Benjamincba2b622015-12-18 22:13:41 -0500962var defaultCurvePreferences = []CurveID{CurveX25519, CurveP256, CurveP384, CurveP521}
Adam Langley95c29f32014-06-20 12:00:00 -0700963
964func (c *Config) curvePreferences() []CurveID {
965 if c == nil || len(c.CurvePreferences) == 0 {
966 return defaultCurvePreferences
967 }
968 return c.CurvePreferences
969}
970
971// mutualVersion returns the protocol version to use given the advertised
972// version of the peer.
David Benjamincecee272016-06-30 13:33:47 -0400973func (c *Config) mutualVersion(vers uint16, isDTLS bool) (uint16, bool) {
974 // There is no such thing as DTLS 1.1.
975 if isDTLS && vers == VersionTLS11 {
976 vers = VersionTLS10
977 }
978
979 minVersion := c.minVersion(isDTLS)
980 maxVersion := c.maxVersion(isDTLS)
Adam Langley95c29f32014-06-20 12:00:00 -0700981
982 if vers < minVersion {
983 return 0, false
984 }
985 if vers > maxVersion {
986 vers = maxVersion
987 }
988 return vers, true
989}
990
991// getCertificateForName returns the best certificate for the given name,
992// defaulting to the first element of c.Certificates if there are no good
993// options.
994func (c *Config) getCertificateForName(name string) *Certificate {
995 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
996 // There's only one choice, so no point doing any work.
997 return &c.Certificates[0]
998 }
999
1000 name = strings.ToLower(name)
1001 for len(name) > 0 && name[len(name)-1] == '.' {
1002 name = name[:len(name)-1]
1003 }
1004
1005 if cert, ok := c.NameToCertificate[name]; ok {
1006 return cert
1007 }
1008
1009 // try replacing labels in the name with wildcards until we get a
1010 // match.
1011 labels := strings.Split(name, ".")
1012 for i := range labels {
1013 labels[i] = "*"
1014 candidate := strings.Join(labels, ".")
1015 if cert, ok := c.NameToCertificate[candidate]; ok {
1016 return cert
1017 }
1018 }
1019
1020 // If nothing matches, return the first certificate.
1021 return &c.Certificates[0]
1022}
1023
Nick Harper60edffd2016-06-21 15:19:24 -07001024func (c *Config) signatureAlgorithmsForServer() []signatureAlgorithm {
1025 if c != nil && c.SignatureAlgorithms != nil {
1026 return c.SignatureAlgorithms
David Benjamin000800a2014-11-14 01:43:59 -05001027 }
Nick Harper60edffd2016-06-21 15:19:24 -07001028 return supportedPeerSignatureAlgorithms
David Benjamin000800a2014-11-14 01:43:59 -05001029}
1030
Nick Harper60edffd2016-06-21 15:19:24 -07001031func (c *Config) signatureAlgorithmsForClient() []signatureAlgorithm {
1032 if c != nil && c.SignatureAlgorithms != nil {
1033 return c.SignatureAlgorithms
David Benjamin000800a2014-11-14 01:43:59 -05001034 }
1035 return supportedSKXSignatureAlgorithms
1036}
1037
Adam Langley95c29f32014-06-20 12:00:00 -07001038// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
1039// from the CommonName and SubjectAlternateName fields of each of the leaf
1040// certificates.
1041func (c *Config) BuildNameToCertificate() {
1042 c.NameToCertificate = make(map[string]*Certificate)
1043 for i := range c.Certificates {
1044 cert := &c.Certificates[i]
1045 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
1046 if err != nil {
1047 continue
1048 }
1049 if len(x509Cert.Subject.CommonName) > 0 {
1050 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
1051 }
1052 for _, san := range x509Cert.DNSNames {
1053 c.NameToCertificate[san] = cert
1054 }
1055 }
1056}
1057
1058// A Certificate is a chain of one or more certificates, leaf first.
1059type Certificate struct {
1060 Certificate [][]byte
1061 PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
1062 // OCSPStaple contains an optional OCSP response which will be served
1063 // to clients that request it.
1064 OCSPStaple []byte
David Benjamin61f95272014-11-25 01:55:35 -05001065 // SignedCertificateTimestampList contains an optional encoded
1066 // SignedCertificateTimestampList structure which will be
1067 // served to clients that request it.
1068 SignedCertificateTimestampList []byte
Adam Langley95c29f32014-06-20 12:00:00 -07001069 // Leaf is the parsed form of the leaf certificate, which may be
1070 // initialized using x509.ParseCertificate to reduce per-handshake
1071 // processing for TLS clients doing client authentication. If nil, the
1072 // leaf certificate will be parsed as needed.
1073 Leaf *x509.Certificate
1074}
1075
1076// A TLS record.
1077type record struct {
1078 contentType recordType
1079 major, minor uint8
1080 payload []byte
1081}
1082
1083type handshakeMessage interface {
1084 marshal() []byte
1085 unmarshal([]byte) bool
1086}
1087
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001088// lruSessionCache is a client or server session cache implementation
1089// that uses an LRU caching strategy.
Adam Langley95c29f32014-06-20 12:00:00 -07001090type lruSessionCache struct {
1091 sync.Mutex
1092
1093 m map[string]*list.Element
1094 q *list.List
1095 capacity int
1096}
1097
1098type lruSessionCacheEntry struct {
1099 sessionKey string
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001100 state interface{}
Adam Langley95c29f32014-06-20 12:00:00 -07001101}
1102
1103// Put adds the provided (sessionKey, cs) pair to the cache.
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001104func (c *lruSessionCache) Put(sessionKey string, cs interface{}) {
Adam Langley95c29f32014-06-20 12:00:00 -07001105 c.Lock()
1106 defer c.Unlock()
1107
1108 if elem, ok := c.m[sessionKey]; ok {
1109 entry := elem.Value.(*lruSessionCacheEntry)
1110 entry.state = cs
1111 c.q.MoveToFront(elem)
1112 return
1113 }
1114
1115 if c.q.Len() < c.capacity {
1116 entry := &lruSessionCacheEntry{sessionKey, cs}
1117 c.m[sessionKey] = c.q.PushFront(entry)
1118 return
1119 }
1120
1121 elem := c.q.Back()
1122 entry := elem.Value.(*lruSessionCacheEntry)
1123 delete(c.m, entry.sessionKey)
1124 entry.sessionKey = sessionKey
1125 entry.state = cs
1126 c.q.MoveToFront(elem)
1127 c.m[sessionKey] = elem
1128}
1129
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001130// Get returns the value associated with a given key. It returns (nil,
1131// false) if no value is found.
1132func (c *lruSessionCache) Get(sessionKey string) (interface{}, bool) {
Adam Langley95c29f32014-06-20 12:00:00 -07001133 c.Lock()
1134 defer c.Unlock()
1135
1136 if elem, ok := c.m[sessionKey]; ok {
1137 c.q.MoveToFront(elem)
1138 return elem.Value.(*lruSessionCacheEntry).state, true
1139 }
1140 return nil, false
1141}
1142
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001143// lruClientSessionCache is a ClientSessionCache implementation that
1144// uses an LRU caching strategy.
1145type lruClientSessionCache struct {
1146 lruSessionCache
1147}
1148
1149func (c *lruClientSessionCache) Put(sessionKey string, cs *ClientSessionState) {
1150 c.lruSessionCache.Put(sessionKey, cs)
1151}
1152
1153func (c *lruClientSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
1154 cs, ok := c.lruSessionCache.Get(sessionKey)
1155 if !ok {
1156 return nil, false
1157 }
1158 return cs.(*ClientSessionState), true
1159}
1160
1161// lruServerSessionCache is a ServerSessionCache implementation that
1162// uses an LRU caching strategy.
1163type lruServerSessionCache struct {
1164 lruSessionCache
1165}
1166
1167func (c *lruServerSessionCache) Put(sessionId string, session *sessionState) {
1168 c.lruSessionCache.Put(sessionId, session)
1169}
1170
1171func (c *lruServerSessionCache) Get(sessionId string) (*sessionState, bool) {
1172 cs, ok := c.lruSessionCache.Get(sessionId)
1173 if !ok {
1174 return nil, false
1175 }
1176 return cs.(*sessionState), true
1177}
1178
1179// NewLRUClientSessionCache returns a ClientSessionCache with the given
1180// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1181// is used instead.
1182func NewLRUClientSessionCache(capacity int) ClientSessionCache {
1183 const defaultSessionCacheCapacity = 64
1184
1185 if capacity < 1 {
1186 capacity = defaultSessionCacheCapacity
1187 }
1188 return &lruClientSessionCache{
1189 lruSessionCache{
1190 m: make(map[string]*list.Element),
1191 q: list.New(),
1192 capacity: capacity,
1193 },
1194 }
1195}
1196
1197// NewLRUServerSessionCache returns a ServerSessionCache with the given
1198// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1199// is used instead.
1200func NewLRUServerSessionCache(capacity int) ServerSessionCache {
1201 const defaultSessionCacheCapacity = 64
1202
1203 if capacity < 1 {
1204 capacity = defaultSessionCacheCapacity
1205 }
1206 return &lruServerSessionCache{
1207 lruSessionCache{
1208 m: make(map[string]*list.Element),
1209 q: list.New(),
1210 capacity: capacity,
1211 },
1212 }
1213}
1214
Adam Langley95c29f32014-06-20 12:00:00 -07001215// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
1216type dsaSignature struct {
1217 R, S *big.Int
1218}
1219
1220type ecdsaSignature dsaSignature
1221
1222var emptyConfig Config
1223
1224func defaultConfig() *Config {
1225 return &emptyConfig
1226}
1227
1228var (
1229 once sync.Once
1230 varDefaultCipherSuites []uint16
1231)
1232
1233func defaultCipherSuites() []uint16 {
1234 once.Do(initDefaultCipherSuites)
1235 return varDefaultCipherSuites
1236}
1237
1238func initDefaultCipherSuites() {
David Benjamin48cae082014-10-27 01:06:24 -04001239 for _, suite := range cipherSuites {
1240 if suite.flags&suitePSK == 0 {
1241 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
1242 }
Adam Langley95c29f32014-06-20 12:00:00 -07001243 }
1244}
1245
1246func unexpectedMessageError(wanted, got interface{}) error {
1247 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1248}
David Benjamin000800a2014-11-14 01:43:59 -05001249
Nick Harper60edffd2016-06-21 15:19:24 -07001250func isSupportedSignatureAlgorithm(sigAlg signatureAlgorithm, sigAlgs []signatureAlgorithm) bool {
1251 for _, s := range sigAlgs {
1252 if s == sigAlg {
David Benjamin000800a2014-11-14 01:43:59 -05001253 return true
1254 }
1255 }
1256 return false
1257}