blob: 0ae360ac29a817dda002ee00324bb199b79875c8 [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
Steven Valdez143e8b32016-07-11 13:19:03 -040021const enableTLS13Handshake = true
Nick Harperb41d2e42016-07-01 17:50:32 -040022
Adam Langley95c29f32014-06-20 12:00:00 -070023const (
24 VersionSSL30 = 0x0300
25 VersionTLS10 = 0x0301
26 VersionTLS11 = 0x0302
27 VersionTLS12 = 0x0303
Nick Harper1fd39d82016-06-14 18:14:35 -070028 VersionTLS13 = 0x0304
Adam Langley95c29f32014-06-20 12:00:00 -070029)
30
31const (
David Benjamin83c0bc92014-08-04 01:23:53 -040032 maxPlaintext = 16384 // maximum plaintext payload length
33 maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
34 tlsRecordHeaderLen = 5 // record header length
35 dtlsRecordHeaderLen = 13
36 maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
Adam Langley95c29f32014-06-20 12:00:00 -070037
38 minVersion = VersionSSL30
Nick Harper1fd39d82016-06-14 18:14:35 -070039 maxVersion = VersionTLS13
Adam Langley95c29f32014-06-20 12:00:00 -070040)
41
42// TLS record types.
43type recordType uint8
44
45const (
46 recordTypeChangeCipherSpec recordType = 20
47 recordTypeAlert recordType = 21
48 recordTypeHandshake recordType = 22
49 recordTypeApplicationData recordType = 23
50)
51
52// TLS handshake message types.
53const (
David Benjamincedff872016-06-30 18:55:18 -040054 typeHelloRequest uint8 = 0
55 typeClientHello uint8 = 1
56 typeServerHello uint8 = 2
57 typeHelloVerifyRequest uint8 = 3
58 typeNewSessionTicket uint8 = 4
59 typeHelloRetryRequest uint8 = 6 // draft-ietf-tls-tls13-13
60 typeEncryptedExtensions uint8 = 8 // draft-ietf-tls-tls13-13
61 typeCertificate uint8 = 11
62 typeServerKeyExchange uint8 = 12
63 typeCertificateRequest uint8 = 13
64 typeServerHelloDone uint8 = 14
65 typeCertificateVerify uint8 = 15
66 typeClientKeyExchange uint8 = 16
67 typeFinished uint8 = 20
68 typeCertificateStatus uint8 = 22
69 typeNextProtocol uint8 = 67 // Not IANA assigned
70 typeChannelID uint8 = 203 // Not IANA assigned
Adam Langley95c29f32014-06-20 12:00:00 -070071)
72
73// TLS compression types.
74const (
75 compressionNone uint8 = 0
76)
77
78// TLS extension numbers
79const (
David Benjamin61f95272014-11-25 01:55:35 -050080 extensionServerName uint16 = 0
81 extensionStatusRequest uint16 = 5
82 extensionSupportedCurves uint16 = 10
83 extensionSupportedPoints uint16 = 11
84 extensionSignatureAlgorithms uint16 = 13
85 extensionUseSRTP uint16 = 14
86 extensionALPN uint16 = 16
87 extensionSignedCertificateTimestamp uint16 = 18
88 extensionExtendedMasterSecret uint16 = 23
89 extensionSessionTicket uint16 = 35
David Benjamincedff872016-06-30 18:55:18 -040090 extensionKeyShare uint16 = 40 // draft-ietf-tls-tls13-13
91 extensionPreSharedKey uint16 = 41 // draft-ietf-tls-tls13-13
92 extensionEarlyData uint16 = 42 // draft-ietf-tls-tls13-13
93 extensionCookie uint16 = 44 // draft-ietf-tls-tls13-13
David Benjamin399e7c92015-07-30 23:01:27 -040094 extensionCustom uint16 = 1234 // not IANA assigned
David Benjamin61f95272014-11-25 01:55:35 -050095 extensionNextProtoNeg uint16 = 13172 // not IANA assigned
96 extensionRenegotiationInfo uint16 = 0xff01
97 extensionChannelID uint16 = 30032 // not IANA assigned
Adam Langley95c29f32014-06-20 12:00:00 -070098)
99
100// TLS signaling cipher suite values
101const (
102 scsvRenegotiation uint16 = 0x00ff
103)
104
105// CurveID is the type of a TLS identifier for an elliptic curve. See
106// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
107type CurveID uint16
108
109const (
David Benjamincba2b622015-12-18 22:13:41 -0500110 CurveP224 CurveID = 21
111 CurveP256 CurveID = 23
112 CurveP384 CurveID = 24
113 CurveP521 CurveID = 25
114 CurveX25519 CurveID = 29
Adam Langley95c29f32014-06-20 12:00:00 -0700115)
116
117// TLS Elliptic Curve Point Formats
118// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
119const (
120 pointFormatUncompressed uint8 = 0
121)
122
123// TLS CertificateStatusType (RFC 3546)
124const (
125 statusTypeOCSP uint8 = 1
126)
127
128// Certificate types (for certificateRequestMsg)
129const (
David Benjamin7b030512014-07-08 17:30:11 -0400130 CertTypeRSASign = 1 // A certificate containing an RSA key
131 CertTypeDSSSign = 2 // A certificate containing a DSA key
132 CertTypeRSAFixedDH = 3 // A certificate containing a static DH key
133 CertTypeDSSFixedDH = 4 // A certificate containing a static DH key
Adam Langley95c29f32014-06-20 12:00:00 -0700134
135 // See RFC4492 sections 3 and 5.5.
David Benjamin7b030512014-07-08 17:30:11 -0400136 CertTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
137 CertTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
138 CertTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
Adam Langley95c29f32014-06-20 12:00:00 -0700139
140 // Rest of these are reserved by the TLS spec
141)
142
Nick Harper60edffd2016-06-21 15:19:24 -0700143// signatureAlgorithm corresponds to a SignatureScheme value from TLS 1.3. Note
144// that TLS 1.3 names the production 'SignatureScheme' to avoid colliding with
145// TLS 1.2's SignatureAlgorithm but otherwise refers to them as 'signature
146// algorithms' throughout. We match the latter.
147type signatureAlgorithm uint16
Adam Langley95c29f32014-06-20 12:00:00 -0700148
Adam Langley95c29f32014-06-20 12:00:00 -0700149const (
Nick Harper60edffd2016-06-21 15:19:24 -0700150 // RSASSA-PKCS1-v1_5 algorithms
151 signatureRSAPKCS1WithMD5 signatureAlgorithm = 0x0101
152 signatureRSAPKCS1WithSHA1 signatureAlgorithm = 0x0201
153 signatureRSAPKCS1WithSHA256 signatureAlgorithm = 0x0401
154 signatureRSAPKCS1WithSHA384 signatureAlgorithm = 0x0501
155 signatureRSAPKCS1WithSHA512 signatureAlgorithm = 0x0601
Adam Langley95c29f32014-06-20 12:00:00 -0700156
Nick Harper60edffd2016-06-21 15:19:24 -0700157 // ECDSA algorithms
158 signatureECDSAWithSHA1 signatureAlgorithm = 0x0203
159 signatureECDSAWithP256AndSHA256 signatureAlgorithm = 0x0403
160 signatureECDSAWithP384AndSHA384 signatureAlgorithm = 0x0503
161 signatureECDSAWithP521AndSHA512 signatureAlgorithm = 0x0603
162
163 // RSASSA-PSS algorithms
164 signatureRSAPSSWithSHA256 signatureAlgorithm = 0x0700
165 signatureRSAPSSWithSHA384 signatureAlgorithm = 0x0701
166 signatureRSAPSSWithSHA512 signatureAlgorithm = 0x0702
167
168 // EdDSA algorithms
169 signatureEd25519 signatureAlgorithm = 0x0703
170 signatureEd448 signatureAlgorithm = 0x0704
171)
Adam Langley95c29f32014-06-20 12:00:00 -0700172
David Benjamin7a41d372016-07-09 11:21:54 -0700173// supportedSignatureAlgorithms contains the default supported signature
174// algorithms.
175var supportedSignatureAlgorithms = []signatureAlgorithm{
176 signatureRSAPSSWithSHA256,
Nick Harper60edffd2016-06-21 15:19:24 -0700177 signatureRSAPKCS1WithSHA256,
178 signatureECDSAWithP256AndSHA256,
179 signatureRSAPKCS1WithSHA1,
180 signatureECDSAWithSHA1,
Adam Langley95c29f32014-06-20 12:00:00 -0700181}
182
David Benjaminca6c8262014-11-15 19:06:08 -0500183// SRTP protection profiles (See RFC 5764, section 4.1.2)
184const (
185 SRTP_AES128_CM_HMAC_SHA1_80 uint16 = 0x0001
186 SRTP_AES128_CM_HMAC_SHA1_32 = 0x0002
187)
188
Adam Langley95c29f32014-06-20 12:00:00 -0700189// ConnectionState records basic TLS details about the connection.
190type ConnectionState struct {
191 Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
192 HandshakeComplete bool // TLS handshake is complete
193 DidResume bool // connection resumes a previous TLS connection
194 CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
195 NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos)
196 NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server
David Benjaminfc7b0862014-09-06 13:21:53 -0400197 NegotiatedProtocolFromALPN bool // protocol negotiated with ALPN
Adam Langley95c29f32014-06-20 12:00:00 -0700198 ServerName string // server name requested by client, if any (server side only)
199 PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
200 VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
David Benjamind30a9902014-08-24 01:44:23 -0400201 ChannelID *ecdsa.PublicKey // the channel ID for this connection
David Benjaminca6c8262014-11-15 19:06:08 -0500202 SRTPProtectionProfile uint16 // the negotiated DTLS-SRTP protection profile
David Benjaminc0577622015-09-12 18:28:38 -0400203 TLSUnique []byte // the tls-unique channel binding
Paul Lietar4fac72e2015-09-09 13:44:55 +0100204 SCTList []byte // signed certificate timestamp list
Nick Harper60edffd2016-06-21 15:19:24 -0700205 PeerSignatureAlgorithm signatureAlgorithm // algorithm used by the peer in the handshake
Adam Langley95c29f32014-06-20 12:00:00 -0700206}
207
208// ClientAuthType declares the policy the server will follow for
209// TLS Client Authentication.
210type ClientAuthType int
211
212const (
213 NoClientCert ClientAuthType = iota
214 RequestClientCert
215 RequireAnyClientCert
216 VerifyClientCertIfGiven
217 RequireAndVerifyClientCert
218)
219
220// ClientSessionState contains the state needed by clients to resume TLS
221// sessions.
222type ClientSessionState struct {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500223 sessionId []uint8 // Session ID supplied by the server. nil if the session has a ticket.
Adam Langley75712922014-10-10 16:23:43 -0700224 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
225 vers uint16 // SSL/TLS version negotiated for the session
226 cipherSuite uint16 // Ciphersuite negotiated for the session
227 masterSecret []byte // MasterSecret generated by client on a full handshake
228 handshakeHash []byte // Handshake hash for Channel ID purposes.
229 serverCertificates []*x509.Certificate // Certificate chain presented by the server
230 extendedMasterSecret bool // Whether an extended master secret was used to generate the session
Paul Lietar62be8ac2015-09-16 10:03:30 +0100231 sctList []byte
232 ocspResponse []byte
Adam Langley95c29f32014-06-20 12:00:00 -0700233}
234
235// ClientSessionCache is a cache of ClientSessionState objects that can be used
236// by a client to resume a TLS session with a given server. ClientSessionCache
237// implementations should expect to be called concurrently from different
238// goroutines.
239type ClientSessionCache interface {
240 // Get searches for a ClientSessionState associated with the given key.
241 // On return, ok is true if one was found.
242 Get(sessionKey string) (session *ClientSessionState, ok bool)
243
244 // Put adds the ClientSessionState to the cache with the given key.
245 Put(sessionKey string, cs *ClientSessionState)
246}
247
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500248// ServerSessionCache is a cache of sessionState objects that can be used by a
249// client to resume a TLS session with a given server. ServerSessionCache
250// implementations should expect to be called concurrently from different
251// goroutines.
252type ServerSessionCache interface {
253 // Get searches for a sessionState associated with the given session
254 // ID. On return, ok is true if one was found.
255 Get(sessionId string) (session *sessionState, ok bool)
256
257 // Put adds the sessionState to the cache with the given session ID.
258 Put(sessionId string, session *sessionState)
259}
260
Adam Langley95c29f32014-06-20 12:00:00 -0700261// A Config structure is used to configure a TLS client or server.
262// After one has been passed to a TLS function it must not be
263// modified. A Config may be reused; the tls package will also not
264// modify it.
265type Config struct {
266 // Rand provides the source of entropy for nonces and RSA blinding.
267 // If Rand is nil, TLS uses the cryptographic random reader in package
268 // crypto/rand.
269 // The Reader must be safe for use by multiple goroutines.
270 Rand io.Reader
271
272 // Time returns the current time as the number of seconds since the epoch.
273 // If Time is nil, TLS uses time.Now.
274 Time func() time.Time
275
276 // Certificates contains one or more certificate chains
277 // to present to the other side of the connection.
278 // Server configurations must include at least one certificate.
279 Certificates []Certificate
280
281 // NameToCertificate maps from a certificate name to an element of
282 // Certificates. Note that a certificate name can be of the form
283 // '*.example.com' and so doesn't have to be a domain name as such.
284 // See Config.BuildNameToCertificate
285 // The nil value causes the first element of Certificates to be used
286 // for all connections.
287 NameToCertificate map[string]*Certificate
288
289 // RootCAs defines the set of root certificate authorities
290 // that clients use when verifying server certificates.
291 // If RootCAs is nil, TLS uses the host's root CA set.
292 RootCAs *x509.CertPool
293
294 // NextProtos is a list of supported, application level protocols.
295 NextProtos []string
296
297 // ServerName is used to verify the hostname on the returned
298 // certificates unless InsecureSkipVerify is given. It is also included
299 // in the client's handshake to support virtual hosting.
300 ServerName string
301
302 // ClientAuth determines the server's policy for
303 // TLS Client Authentication. The default is NoClientCert.
304 ClientAuth ClientAuthType
305
306 // ClientCAs defines the set of root certificate authorities
307 // that servers use if required to verify a client certificate
308 // by the policy in ClientAuth.
309 ClientCAs *x509.CertPool
310
David Benjamin7b030512014-07-08 17:30:11 -0400311 // ClientCertificateTypes defines the set of allowed client certificate
312 // types. The default is CertTypeRSASign and CertTypeECDSASign.
313 ClientCertificateTypes []byte
314
Adam Langley95c29f32014-06-20 12:00:00 -0700315 // InsecureSkipVerify controls whether a client verifies the
316 // server's certificate chain and host name.
317 // If InsecureSkipVerify is true, TLS accepts any certificate
318 // presented by the server and any host name in that certificate.
319 // In this mode, TLS is susceptible to man-in-the-middle attacks.
320 // This should be used only for testing.
321 InsecureSkipVerify bool
322
323 // CipherSuites is a list of supported cipher suites. If CipherSuites
324 // is nil, TLS uses a list of suites supported by the implementation.
325 CipherSuites []uint16
326
327 // PreferServerCipherSuites controls whether the server selects the
328 // client's most preferred ciphersuite, or the server's most preferred
329 // ciphersuite. If true then the server's preference, as expressed in
330 // the order of elements in CipherSuites, is used.
331 PreferServerCipherSuites bool
332
333 // SessionTicketsDisabled may be set to true to disable session ticket
334 // (resumption) support.
335 SessionTicketsDisabled bool
336
337 // SessionTicketKey is used by TLS servers to provide session
338 // resumption. See RFC 5077. If zero, it will be filled with
339 // random data before the first server handshake.
340 //
341 // If multiple servers are terminating connections for the same host
342 // they should all have the same SessionTicketKey. If the
343 // SessionTicketKey leaks, previously recorded and future TLS
344 // connections using that key are compromised.
345 SessionTicketKey [32]byte
346
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500347 // ClientSessionCache is a cache of ClientSessionState entries
348 // for TLS session resumption.
Adam Langley95c29f32014-06-20 12:00:00 -0700349 ClientSessionCache ClientSessionCache
350
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500351 // ServerSessionCache is a cache of sessionState entries for TLS session
352 // resumption.
353 ServerSessionCache ServerSessionCache
354
Adam Langley95c29f32014-06-20 12:00:00 -0700355 // MinVersion contains the minimum SSL/TLS version that is acceptable.
356 // If zero, then SSLv3 is taken as the minimum.
357 MinVersion uint16
358
359 // MaxVersion contains the maximum SSL/TLS version that is acceptable.
360 // If zero, then the maximum version supported by this package is used,
361 // which is currently TLS 1.2.
362 MaxVersion uint16
363
364 // CurvePreferences contains the elliptic curves that will be used in
365 // an ECDHE handshake, in preference order. If empty, the default will
366 // be used.
367 CurvePreferences []CurveID
368
David Benjamind30a9902014-08-24 01:44:23 -0400369 // ChannelID contains the ECDSA key for the client to use as
370 // its TLS Channel ID.
371 ChannelID *ecdsa.PrivateKey
372
373 // RequestChannelID controls whether the server requests a TLS
374 // Channel ID. If negotiated, the client's public key is
375 // returned in the ConnectionState.
376 RequestChannelID bool
377
David Benjamin48cae082014-10-27 01:06:24 -0400378 // PreSharedKey, if not nil, is the pre-shared key to use with
379 // the PSK cipher suites.
380 PreSharedKey []byte
381
382 // PreSharedKeyIdentity, if not empty, is the identity to use
383 // with the PSK cipher suites.
384 PreSharedKeyIdentity string
385
David Benjaminca6c8262014-11-15 19:06:08 -0500386 // SRTPProtectionProfiles, if not nil, is the list of SRTP
387 // protection profiles to offer in DTLS-SRTP.
388 SRTPProtectionProfiles []uint16
389
David Benjamin7a41d372016-07-09 11:21:54 -0700390 // SignSignatureAlgorithms, if not nil, overrides the default set of
391 // supported signature algorithms to sign with.
392 SignSignatureAlgorithms []signatureAlgorithm
393
394 // VerifySignatureAlgorithms, if not nil, overrides the default set of
395 // supported signature algorithms that are accepted.
396 VerifySignatureAlgorithms []signatureAlgorithm
David Benjamin000800a2014-11-14 01:43:59 -0500397
Adam Langley95c29f32014-06-20 12:00:00 -0700398 // Bugs specifies optional misbehaviour to be used for testing other
399 // implementations.
400 Bugs ProtocolBugs
401
402 serverInitOnce sync.Once // guards calling (*Config).serverInit
403}
404
405type BadValue int
406
407const (
408 BadValueNone BadValue = iota
409 BadValueNegative
410 BadValueZero
411 BadValueLimit
412 BadValueLarge
413 NumBadValues
414)
415
David Benjaminb36a3952015-12-01 18:53:13 -0500416type RSABadValue int
417
418const (
419 RSABadValueNone RSABadValue = iota
420 RSABadValueCorrupt
421 RSABadValueTooLong
422 RSABadValueTooShort
423 RSABadValueWrongVersion
424 NumRSABadValues
425)
426
Adam Langley95c29f32014-06-20 12:00:00 -0700427type ProtocolBugs struct {
David Benjamin5208fd42016-07-13 21:43:25 -0400428 // InvalidSignature specifies that the signature in a ServerKeyExchange
429 // or CertificateVerify message should be invalid.
430 InvalidSignature bool
David Benjamin6de0e532015-07-28 22:43:19 -0400431
David Benjamin4c3ddf72016-06-29 18:13:53 -0400432 // SendCurve, if non-zero, causes the ServerKeyExchange message to use
433 // the specified curve ID rather than the negotiated one.
434 SendCurve CurveID
Adam Langley95c29f32014-06-20 12:00:00 -0700435
David Benjamin2b07fa42016-03-02 00:23:57 -0500436 // InvalidECDHPoint, if true, causes the ECC points in
437 // ServerKeyExchange or ClientKeyExchange messages to be invalid.
438 InvalidECDHPoint bool
439
Adam Langley95c29f32014-06-20 12:00:00 -0700440 // BadECDSAR controls ways in which the 'r' value of an ECDSA signature
441 // can be invalid.
442 BadECDSAR BadValue
443 BadECDSAS BadValue
Adam Langley80842bd2014-06-20 12:00:00 -0700444
445 // MaxPadding causes CBC records to have the maximum possible padding.
446 MaxPadding bool
447 // PaddingFirstByteBad causes the first byte of the padding to be
448 // incorrect.
449 PaddingFirstByteBad bool
450 // PaddingFirstByteBadIf255 causes the first byte of padding to be
451 // incorrect if there's a maximum amount of padding (i.e. 255 bytes).
452 PaddingFirstByteBadIf255 bool
Adam Langleyac61fa32014-06-23 12:03:11 -0700453
454 // FailIfNotFallbackSCSV causes a server handshake to fail if the
455 // client doesn't send the fallback SCSV value.
456 FailIfNotFallbackSCSV bool
David Benjamin35a7a442014-07-05 00:23:20 -0400457
458 // DuplicateExtension causes an extra empty extension of bogus type to
459 // be emitted in either the ClientHello or the ServerHello.
460 DuplicateExtension bool
David Benjamin1c375dd2014-07-12 00:48:23 -0400461
462 // UnauthenticatedECDH causes the server to pretend ECDHE_RSA
463 // and ECDHE_ECDSA cipher suites are actually ECDH_anon. No
464 // Certificate message is sent and no signature is added to
465 // ServerKeyExchange.
466 UnauthenticatedECDH bool
David Benjamin9c651c92014-07-12 13:27:45 -0400467
David Benjaminb80168e2015-02-08 18:30:14 -0500468 // SkipHelloVerifyRequest causes a DTLS server to skip the
469 // HelloVerifyRequest message.
470 SkipHelloVerifyRequest bool
471
David Benjamindcd979f2015-04-20 18:26:52 -0400472 // SkipCertificateStatus, if true, causes the server to skip the
473 // CertificateStatus message. This is legal because CertificateStatus is
474 // optional, even with a status_request in ServerHello.
475 SkipCertificateStatus bool
476
David Benjamin9c651c92014-07-12 13:27:45 -0400477 // SkipServerKeyExchange causes the server to skip sending
478 // ServerKeyExchange messages.
479 SkipServerKeyExchange bool
David Benjamina0e52232014-07-19 17:39:58 -0400480
David Benjaminb80168e2015-02-08 18:30:14 -0500481 // SkipNewSessionTicket causes the server to skip sending the
482 // NewSessionTicket message despite promising to in ServerHello.
483 SkipNewSessionTicket bool
484
David Benjamin0b7ca7d2016-03-10 15:44:22 -0500485 // SkipClientCertificate causes the client to skip the Certificate
486 // message.
487 SkipClientCertificate bool
488
David Benjamina0e52232014-07-19 17:39:58 -0400489 // SkipChangeCipherSpec causes the implementation to skip
490 // sending the ChangeCipherSpec message (and adjusting cipher
491 // state accordingly for the Finished message).
492 SkipChangeCipherSpec bool
David Benjaminf3ec83d2014-07-21 22:42:34 -0400493
David Benjaminb80168e2015-02-08 18:30:14 -0500494 // SkipFinished causes the implementation to skip sending the Finished
495 // message.
496 SkipFinished bool
497
David Benjaminf3ec83d2014-07-21 22:42:34 -0400498 // EarlyChangeCipherSpec causes the client to send an early
499 // ChangeCipherSpec message before the ClientKeyExchange. A value of
500 // zero disables this behavior. One and two configure variants for 0.9.8
501 // and 1.0.1 modes, respectively.
502 EarlyChangeCipherSpec int
David Benjamind23f4122014-07-23 15:09:48 -0400503
David Benjamin8144f992016-06-22 17:05:13 -0400504 // StrayChangeCipherSpec causes every pre-ChangeCipherSpec handshake
505 // message in DTLS to be prefaced by stray ChangeCipherSpec record. This
506 // may be used to test DTLS's handling of reordered ChangeCipherSpec.
507 StrayChangeCipherSpec bool
508
David Benjamin86271ee2014-07-21 16:14:03 -0400509 // FragmentAcrossChangeCipherSpec causes the implementation to fragment
510 // the Finished (or NextProto) message around the ChangeCipherSpec
511 // messages.
512 FragmentAcrossChangeCipherSpec bool
513
David Benjamin61672812016-07-14 23:10:43 -0400514 // SendUnencryptedFinished, if true, causes the Finished message to be
515 // send unencrypted before ChangeCipherSpec rather than after it.
516 SendUnencryptedFinished bool
517
David Benjamin7964b182016-07-14 23:36:30 -0400518 // PartialEncryptedExtensionsWithServerHello, if true, causes the TLS
519 // 1.3 server to send part of EncryptedExtensions unencrypted
520 // in the same record as ServerHello.
521 PartialEncryptedExtensionsWithServerHello bool
522
523 // PartialClientFinishedWithClientHello, if true, causes the TLS 1.3
524 // client to send part of Finished unencrypted in the same record as
525 // ClientHello.
526 PartialClientFinishedWithClientHello bool
527
David Benjamind86c7672014-08-02 04:07:12 -0400528 // SendV2ClientHello causes the client to send a V2ClientHello
529 // instead of a normal ClientHello.
530 SendV2ClientHello bool
David Benjaminbef270a2014-08-02 04:22:02 -0400531
532 // SendFallbackSCSV causes the client to include
533 // TLS_FALLBACK_SCSV in the ClientHello.
534 SendFallbackSCSV bool
David Benjamin43ec06f2014-08-05 02:28:57 -0400535
Adam Langley5021b222015-06-12 18:27:58 -0700536 // SendRenegotiationSCSV causes the client to include the renegotiation
537 // SCSV in the ClientHello.
538 SendRenegotiationSCSV bool
539
David Benjamin43ec06f2014-08-05 02:28:57 -0400540 // MaxHandshakeRecordLength, if non-zero, is the maximum size of a
David Benjamin98214542014-08-07 18:02:39 -0400541 // handshake record. Handshake messages will be split into multiple
542 // records at the specified size, except that the client_version will
David Benjaminbd15a8e2015-05-29 18:48:16 -0400543 // never be fragmented. For DTLS, it is the maximum handshake fragment
544 // size, not record size; DTLS allows multiple handshake fragments in a
545 // single handshake record. See |PackHandshakeFragments|.
David Benjamin43ec06f2014-08-05 02:28:57 -0400546 MaxHandshakeRecordLength int
David Benjamina8e3e0e2014-08-06 22:11:10 -0400547
David Benjamin98214542014-08-07 18:02:39 -0400548 // FragmentClientVersion will allow MaxHandshakeRecordLength to apply to
549 // the first 6 bytes of the ClientHello.
550 FragmentClientVersion bool
551
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400552 // FragmentAlert will cause all alerts to be fragmented across
553 // two records.
554 FragmentAlert bool
555
David Benjamin0d3a8c62016-03-11 22:25:18 -0500556 // DoubleAlert will cause all alerts to be sent as two copies packed
557 // within one record.
558 DoubleAlert bool
559
David Benjamin3fd1fbd2015-02-03 16:07:32 -0500560 // SendSpuriousAlert, if non-zero, will cause an spurious, unwanted
561 // alert to be sent.
562 SendSpuriousAlert alert
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400563
David Benjaminb36a3952015-12-01 18:53:13 -0500564 // BadRSAClientKeyExchange causes the client to send a corrupted RSA
565 // ClientKeyExchange which would not pass padding checks.
566 BadRSAClientKeyExchange RSABadValue
David Benjaminbed9aae2014-08-07 19:13:38 -0400567
568 // RenewTicketOnResume causes the server to renew the session ticket and
569 // send a NewSessionTicket message during an abbreviated handshake.
570 RenewTicketOnResume bool
David Benjamin98e882e2014-08-08 13:24:34 -0400571
572 // SendClientVersion, if non-zero, causes the client to send a different
573 // TLS version in the ClientHello than the maximum supported version.
574 SendClientVersion uint16
David Benjamin83c0bc92014-08-04 01:23:53 -0400575
David Benjamin1f61f0d2016-07-10 12:20:35 -0400576 // NegotiateVersion, if non-zero, causes the server to negotiate the
577 // specifed TLS version rather than the version supported by either
578 // peer.
579 NegotiateVersion uint16
580
David Benjamine58c4f52014-08-24 03:47:07 -0400581 // ExpectFalseStart causes the server to, on full handshakes,
582 // expect the peer to False Start; the server Finished message
583 // isn't sent until we receive an application data record
584 // from the peer.
585 ExpectFalseStart bool
David Benjamin5c24a1d2014-08-31 00:59:27 -0400586
David Benjamin1c633152015-04-02 20:19:11 -0400587 // AlertBeforeFalseStartTest, if non-zero, causes the server to, on full
588 // handshakes, send an alert just before reading the application data
589 // record to test False Start. This can be used in a negative False
590 // Start test to determine whether the peer processed the alert (and
591 // closed the connection) before or after sending app data.
592 AlertBeforeFalseStartTest alert
593
David Benjamine78bfde2014-09-06 12:45:15 -0400594 // ExpectServerName, if not empty, is the hostname the client
595 // must specify in the server_name extension.
596 ExpectServerName string
David Benjaminfc7b0862014-09-06 13:21:53 -0400597
David Benjamin76c2efc2015-08-31 14:24:29 -0400598 // SwapNPNAndALPN switches the relative order between NPN and ALPN in
599 // both ClientHello and ServerHello.
David Benjaminfc7b0862014-09-06 13:21:53 -0400600 SwapNPNAndALPN bool
David Benjamin01fe8202014-09-24 15:21:44 -0400601
Adam Langleyefb0e162015-07-09 11:35:04 -0700602 // ALPNProtocol, if not nil, sets the ALPN protocol that a server will
603 // return.
604 ALPNProtocol *string
605
David Benjamin01fe8202014-09-24 15:21:44 -0400606 // AllowSessionVersionMismatch causes the server to resume sessions
607 // regardless of the version associated with the session.
608 AllowSessionVersionMismatch bool
Adam Langley38311732014-10-16 19:04:35 -0700609
610 // CorruptTicket causes a client to corrupt a session ticket before
611 // sending it in a resume handshake.
612 CorruptTicket bool
613
614 // OversizedSessionId causes the session id that is sent with a ticket
615 // resumption attempt to be too large (33 bytes).
616 OversizedSessionId bool
Adam Langley75712922014-10-10 16:23:43 -0700617
618 // RequireExtendedMasterSecret, if true, requires that the peer support
619 // the extended master secret option.
620 RequireExtendedMasterSecret bool
621
David Benjaminca6554b2014-11-08 12:31:52 -0500622 // NoExtendedMasterSecret causes the client and server to behave as if
Adam Langley75712922014-10-10 16:23:43 -0700623 // they didn't support an extended master secret.
624 NoExtendedMasterSecret bool
Adam Langley2ae77d22014-10-28 17:29:33 -0700625
626 // EmptyRenegotiationInfo causes the renegotiation extension to be
627 // empty in a renegotiation handshake.
628 EmptyRenegotiationInfo bool
629
630 // BadRenegotiationInfo causes the renegotiation extension value in a
631 // renegotiation handshake to be incorrect.
632 BadRenegotiationInfo bool
David Benjamin5e961c12014-11-07 01:48:35 -0500633
David Benjamin3e052de2015-11-25 20:10:31 -0500634 // NoRenegotiationInfo disables renegotiation info support in all
635 // handshakes.
David Benjaminca6554b2014-11-08 12:31:52 -0500636 NoRenegotiationInfo bool
637
David Benjamin3e052de2015-11-25 20:10:31 -0500638 // NoRenegotiationInfoInInitial disables renegotiation info support in
639 // the initial handshake.
640 NoRenegotiationInfoInInitial bool
641
642 // NoRenegotiationInfoAfterInitial disables renegotiation info support
643 // in renegotiation handshakes.
644 NoRenegotiationInfoAfterInitial bool
645
Adam Langley5021b222015-06-12 18:27:58 -0700646 // RequireRenegotiationInfo, if true, causes the client to return an
647 // error if the server doesn't reply with the renegotiation extension.
648 RequireRenegotiationInfo bool
649
David Benjamin8e6db492015-07-25 18:29:23 -0400650 // SequenceNumberMapping, if non-nil, is the mapping function to apply
651 // to the sequence number of outgoing packets. For both TLS and DTLS,
652 // the two most-significant bytes in the resulting sequence number are
653 // ignored so that the DTLS epoch cannot be changed.
654 SequenceNumberMapping func(uint64) uint64
David Benjamin9114fae2014-11-08 11:41:14 -0500655
David Benjamina3e89492015-02-26 15:16:22 -0500656 // RSAEphemeralKey, if true, causes the server to send a
657 // ServerKeyExchange message containing an ephemeral key (as in
658 // RSA_EXPORT) in the plain RSA key exchange.
659 RSAEphemeralKey bool
David Benjaminca6c8262014-11-15 19:06:08 -0500660
661 // SRTPMasterKeyIdentifer, if not empty, is the SRTP MKI value that the
662 // client offers when negotiating SRTP. MKI support is still missing so
663 // the peer must still send none.
664 SRTPMasterKeyIdentifer string
665
666 // SendSRTPProtectionProfile, if non-zero, is the SRTP profile that the
667 // server sends in the ServerHello instead of the negotiated one.
668 SendSRTPProtectionProfile uint16
David Benjamin000800a2014-11-14 01:43:59 -0500669
Nick Harper60edffd2016-06-21 15:19:24 -0700670 // NoSignatureAlgorithms, if true, causes the client to omit the
David Benjamin000800a2014-11-14 01:43:59 -0500671 // signature and hashes extension.
672 //
673 // For a server, it will cause an empty list to be sent in the
674 // CertificateRequest message. None the less, the configured set will
675 // still be enforced.
Nick Harper60edffd2016-06-21 15:19:24 -0700676 NoSignatureAlgorithms bool
David Benjaminc44b1df2014-11-23 12:11:01 -0500677
David Benjamin55a43642015-04-20 14:45:55 -0400678 // NoSupportedCurves, if true, causes the client to omit the
679 // supported_curves extension.
680 NoSupportedCurves bool
681
David Benjaminc44b1df2014-11-23 12:11:01 -0500682 // RequireSameRenegoClientVersion, if true, causes the server
683 // to require that all ClientHellos match in offered version
684 // across a renego.
685 RequireSameRenegoClientVersion bool
Feng Lu41aa3252014-11-21 22:47:56 -0800686
David Benjamin1e29a6b2014-12-10 02:27:24 -0500687 // ExpectInitialRecordVersion, if non-zero, is the expected
688 // version of the records before the version is determined.
689 ExpectInitialRecordVersion uint16
David Benjamin13be1de2015-01-11 16:29:36 -0500690
691 // MaxPacketLength, if non-zero, is the maximum acceptable size for a
692 // packet.
693 MaxPacketLength int
David Benjamin6095de82014-12-27 01:50:38 -0500694
695 // SendCipherSuite, if non-zero, is the cipher suite value that the
696 // server will send in the ServerHello. This does not affect the cipher
697 // the server believes it has actually negotiated.
698 SendCipherSuite uint16
David Benjamin4189bd92015-01-25 23:52:39 -0500699
David Benjamin4cf369b2015-08-22 01:35:43 -0400700 // AppDataBeforeHandshake, if not nil, causes application data to be
701 // sent immediately before the first handshake message.
702 AppDataBeforeHandshake []byte
703
704 // AppDataAfterChangeCipherSpec, if not nil, causes application data to
David Benjamin4189bd92015-01-25 23:52:39 -0500705 // be sent immediately after ChangeCipherSpec.
706 AppDataAfterChangeCipherSpec []byte
David Benjamin83f90402015-01-27 01:09:43 -0500707
David Benjamindc3da932015-03-12 15:09:02 -0400708 // AlertAfterChangeCipherSpec, if non-zero, causes an alert to be sent
709 // immediately after ChangeCipherSpec.
710 AlertAfterChangeCipherSpec alert
711
David Benjamin83f90402015-01-27 01:09:43 -0500712 // TimeoutSchedule is the schedule of packet drops and simulated
713 // timeouts for before each handshake leg from the peer.
714 TimeoutSchedule []time.Duration
715
716 // PacketAdaptor is the packetAdaptor to use to simulate timeouts.
717 PacketAdaptor *packetAdaptor
David Benjaminb3774b92015-01-31 17:16:01 -0500718
719 // ReorderHandshakeFragments, if true, causes handshake fragments in
720 // DTLS to overlap and be sent in the wrong order. It also causes
721 // pre-CCS flights to be sent twice. (Post-CCS flights consist of
722 // Finished and will trigger a spurious retransmit.)
723 ReorderHandshakeFragments bool
David Benjaminddb9f152015-02-03 15:44:39 -0500724
David Benjamin61672812016-07-14 23:10:43 -0400725 // ReverseHandshakeFragments, if true, causes handshake fragments in
726 // DTLS to be reversed within a flight.
727 ReverseHandshakeFragments bool
728
David Benjamin75381222015-03-02 19:30:30 -0500729 // MixCompleteMessageWithFragments, if true, causes handshake
730 // messages in DTLS to redundantly both fragment the message
731 // and include a copy of the full one.
732 MixCompleteMessageWithFragments bool
733
David Benjaminddb9f152015-02-03 15:44:39 -0500734 // SendInvalidRecordType, if true, causes a record with an invalid
735 // content type to be sent immediately following the handshake.
736 SendInvalidRecordType bool
David Benjaminbcb2d912015-02-24 23:45:43 -0500737
David Benjamin0b8d5da2016-07-15 00:39:56 -0400738 // SendWrongMessageType, if non-zero, causes messages of the specified
739 // type to be sent with the wrong value.
740 SendWrongMessageType byte
David Benjamin75381222015-03-02 19:30:30 -0500741
742 // FragmentMessageTypeMismatch, if true, causes all non-initial
743 // handshake fragments in DTLS to have the wrong message type.
744 FragmentMessageTypeMismatch bool
745
746 // FragmentMessageLengthMismatch, if true, causes all non-initial
747 // handshake fragments in DTLS to have the wrong message length.
748 FragmentMessageLengthMismatch bool
749
David Benjamin11fc66a2015-06-16 11:40:24 -0400750 // SplitFragments, if non-zero, causes the handshake fragments in DTLS
751 // to be split across two records. The value of |SplitFragments| is the
752 // number of bytes in the first fragment.
753 SplitFragments int
David Benjamin75381222015-03-02 19:30:30 -0500754
755 // SendEmptyFragments, if true, causes handshakes to include empty
756 // fragments in DTLS.
757 SendEmptyFragments bool
David Benjamincdea40c2015-03-19 14:09:43 -0400758
David Benjamin9a41d1b2015-05-16 01:30:09 -0400759 // SendSplitAlert, if true, causes an alert to be sent with the header
760 // and record body split across multiple packets. The peer should
761 // discard these packets rather than process it.
762 SendSplitAlert bool
763
David Benjamin4b27d9f2015-05-12 22:42:52 -0400764 // FailIfResumeOnRenego, if true, causes renegotiations to fail if the
765 // client offers a resumption or the server accepts one.
766 FailIfResumeOnRenego bool
David Benjamin3c9746a2015-03-19 15:00:10 -0400767
David Benjamin67d1fb52015-03-16 15:16:23 -0400768 // IgnorePeerCipherPreferences, if true, causes the peer's cipher
769 // preferences to be ignored.
770 IgnorePeerCipherPreferences bool
David Benjamin72dc7832015-03-16 17:49:43 -0400771
772 // IgnorePeerSignatureAlgorithmPreferences, if true, causes the peer's
773 // signature algorithm preferences to be ignored.
774 IgnorePeerSignatureAlgorithmPreferences bool
David Benjamin340d5ed2015-03-21 02:21:37 -0400775
David Benjaminc574f412015-04-20 11:13:01 -0400776 // IgnorePeerCurvePreferences, if true, causes the peer's curve
777 // preferences to be ignored.
778 IgnorePeerCurvePreferences bool
779
David Benjamin513f0ea2015-04-02 19:33:31 -0400780 // BadFinished, if true, causes the Finished hash to be broken.
781 BadFinished bool
Adam Langleya7997f12015-05-14 17:38:50 -0700782
783 // DHGroupPrime, if not nil, is used to define the (finite field)
784 // Diffie-Hellman group. The generator used is always two.
785 DHGroupPrime *big.Int
David Benjaminbd15a8e2015-05-29 18:48:16 -0400786
David Benjamin582ba042016-07-07 12:33:25 -0700787 // PackHandshakeFragments, if true, causes handshake fragments in DTLS
788 // to be packed into individual handshake records, up to the specified
789 // record size.
David Benjaminbd15a8e2015-05-29 18:48:16 -0400790 PackHandshakeFragments int
791
David Benjamin582ba042016-07-07 12:33:25 -0700792 // PackHandshakeRecords, if true, causes handshake records in DTLS to be
793 // packed into individual packets, up to the specified packet size.
David Benjaminbd15a8e2015-05-29 18:48:16 -0400794 PackHandshakeRecords int
David Benjamin0fa40122015-05-30 17:13:12 -0400795
David Benjamin582ba042016-07-07 12:33:25 -0700796 // PackHandshakeFlight, if true, causes each handshake flight in TLS to
797 // be packed into records, up to the largest size record available.
798 PackHandshakeFlight bool
799
David Benjamin0407e762016-06-17 16:41:18 -0400800 // EnableAllCiphers, if true, causes all configured ciphers to be
801 // enabled.
802 EnableAllCiphers bool
David Benjamin8923c0b2015-06-07 11:42:34 -0400803
804 // EmptyCertificateList, if true, causes the server to send an empty
805 // certificate list in the Certificate message.
806 EmptyCertificateList bool
David Benjamind98452d2015-06-16 14:16:23 -0400807
808 // ExpectNewTicket, if true, causes the client to abort if it does not
809 // receive a new ticket.
810 ExpectNewTicket bool
Adam Langley33ad2b52015-07-20 17:43:53 -0700811
812 // RequireClientHelloSize, if not zero, is the required length in bytes
813 // of the ClientHello /record/. This is checked by the server.
814 RequireClientHelloSize int
Adam Langley09505632015-07-30 18:10:13 -0700815
816 // CustomExtension, if not empty, contains the contents of an extension
817 // that will be added to client/server hellos.
818 CustomExtension string
819
820 // ExpectedCustomExtension, if not nil, contains the expected contents
821 // of a custom extension.
822 ExpectedCustomExtension *string
David Benjamin30789da2015-08-29 22:56:45 -0400823
824 // NoCloseNotify, if true, causes the close_notify alert to be skipped
825 // on connection shutdown.
826 NoCloseNotify bool
827
David Benjaminfa214e42016-05-10 17:03:10 -0400828 // SendAlertOnShutdown, if non-zero, is the alert to send instead of
829 // close_notify on shutdown.
830 SendAlertOnShutdown alert
831
David Benjamin30789da2015-08-29 22:56:45 -0400832 // ExpectCloseNotify, if true, requires a close_notify from the peer on
833 // shutdown. Records from the peer received after close_notify is sent
834 // are not discard.
835 ExpectCloseNotify bool
David Benjamin2c99d282015-09-01 10:23:00 -0400836
837 // SendLargeRecords, if true, allows outgoing records to be sent
838 // arbitrarily large.
839 SendLargeRecords bool
David Benjamin76c2efc2015-08-31 14:24:29 -0400840
841 // NegotiateALPNAndNPN, if true, causes the server to negotiate both
842 // ALPN and NPN in the same connetion.
843 NegotiateALPNAndNPN bool
David Benjamindd6fed92015-10-23 17:41:12 -0400844
845 // SendEmptySessionTicket, if true, causes the server to send an empty
846 // session ticket.
847 SendEmptySessionTicket bool
848
849 // FailIfSessionOffered, if true, causes the server to fail any
850 // connections where the client offers a non-empty session ID or session
851 // ticket.
852 FailIfSessionOffered bool
Adam Langley27a0d082015-11-03 13:34:10 -0800853
854 // SendHelloRequestBeforeEveryAppDataRecord, if true, causes a
855 // HelloRequest handshake message to be sent before each application
856 // data record. This only makes sense for a server.
857 SendHelloRequestBeforeEveryAppDataRecord bool
Adam Langleyc4f25ce2015-11-26 16:39:08 -0800858
David Benjamin71dd6662016-07-08 14:10:48 -0700859 // SendHelloRequestBeforeEveryHandshakeMessage, if true, causes a
860 // HelloRequest handshake message to be sent before each handshake
861 // message. This only makes sense for a server.
862 SendHelloRequestBeforeEveryHandshakeMessage bool
863
Adam Langleyc4f25ce2015-11-26 16:39:08 -0800864 // RequireDHPublicValueLen causes a fatal error if the length (in
865 // bytes) of the server's Diffie-Hellman public value is not equal to
866 // this.
867 RequireDHPublicValueLen int
David Benjamin8411b242015-11-26 12:07:28 -0500868
869 // BadChangeCipherSpec, if not nil, is the body to be sent in
870 // ChangeCipherSpec records instead of {1}.
871 BadChangeCipherSpec []byte
David Benjaminef5dfd22015-12-06 13:17:07 -0500872
873 // BadHelloRequest, if not nil, is what to send instead of a
874 // HelloRequest.
875 BadHelloRequest []byte
David Benjaminef1b0092015-11-21 14:05:44 -0500876
877 // RequireSessionTickets, if true, causes the client to require new
878 // sessions use session tickets instead of session IDs.
879 RequireSessionTickets bool
David Benjaminf2b83632016-03-01 22:57:46 -0500880
881 // NullAllCiphers, if true, causes every cipher to behave like the null
882 // cipher.
883 NullAllCiphers bool
David Benjamin80d1b352016-05-04 19:19:06 -0400884
885 // SendSCTListOnResume, if not nil, causes the server to send the
886 // supplied SCT list in resumption handshakes.
887 SendSCTListOnResume []byte
Matt Braithwaite54217e42016-06-13 13:03:47 -0700888
889 // CECPQ1BadX25519Part corrupts the X25519 part of a CECPQ1 key exchange, as
890 // a trivial proof that it is actually used.
891 CECPQ1BadX25519Part bool
892
893 // CECPQ1BadNewhopePart corrupts the Newhope part of a CECPQ1 key exchange,
894 // as a trivial proof that it is actually used.
895 CECPQ1BadNewhopePart bool
David Benjaminc9ae27c2016-06-24 22:56:37 -0400896
897 // RecordPadding is the number of bytes of padding to add to each
898 // encrypted record in TLS 1.3.
899 RecordPadding int
900
901 // OmitRecordContents, if true, causes encrypted records in TLS 1.3 to
902 // be missing their body and content type. Padding, if configured, is
903 // still added.
904 OmitRecordContents bool
905
906 // OuterRecordType, if non-zero, is the outer record type to use instead
907 // of application data.
908 OuterRecordType recordType
David Benjamina95e9f32016-07-08 16:28:04 -0700909
910 // SendSignatureAlgorithm, if non-zero, causes all signatures to be sent
911 // with the given signature algorithm rather than the one negotiated.
912 SendSignatureAlgorithm signatureAlgorithm
David Benjamin1fb125c2016-07-08 18:52:12 -0700913
914 // SkipECDSACurveCheck, if true, causes all ECDSA curve checks to be
915 // skipped.
916 SkipECDSACurveCheck bool
David Benjaminfd5c45f2016-06-30 18:30:40 -0400917
918 // IgnoreSignatureVersionChecks, if true, causes all signature
919 // algorithms to be enabled at all TLS versions.
920 IgnoreSignatureVersionChecks bool
Steven Valdez143e8b32016-07-11 13:19:03 -0400921
922 // NegotiateRenegotiationInfoAtAllVersions, if true, causes
923 // Renegotiation Info to be negotiated at all versions.
924 NegotiateRenegotiationInfoAtAllVersions bool
925
926 // NegotiateChannelIDAtAllVersions, if true, causes Channel ID to be
927 // negotiated at all versions.
928 NegotiateChannelIDAtAllVersions bool
929
930 // NegotiateNPNAtAllVersions, if true, causes NPN to be negotiated at
931 // all versions.
932 NegotiateNPNAtAllVersions bool
933
934 // NegotiateEMSAtAllVersions, if true, causes EMS to be negotiated at
935 // all versions.
936 NegotiateEMSAtAllVersions bool
937
938 // AdvertiseTicketExtension, if true, causes the ticket extension to be
939 // advertised in server extensions
940 AdvertiseTicketExtension bool
941
942 // MissingKeyShare, if true, causes the TLS 1.3 implementation to skip
943 // sending a key_share extension and use the zero ECDHE secret
944 // instead.
945 MissingKeyShare bool
946
947 // DuplicateKeyShares, if true, causes the TLS 1.3 client to send two
948 // copies of each KeyShareEntry.
949 DuplicateKeyShares bool
950
951 // EmptyEncryptedExtensions, if true, causes the TLS 1.3 server to
952 // emit an empty EncryptedExtensions block.
953 EmptyEncryptedExtensions bool
954
955 // EncryptedExtensionsWithKeyShare, if true, causes the TLS 1.3 server to
956 // include the KeyShare extension in the EncryptedExtensions block.
957 EncryptedExtensionsWithKeyShare bool
Adam Langley95c29f32014-06-20 12:00:00 -0700958}
959
960func (c *Config) serverInit() {
961 if c.SessionTicketsDisabled {
962 return
963 }
964
965 // If the key has already been set then we have nothing to do.
966 for _, b := range c.SessionTicketKey {
967 if b != 0 {
968 return
969 }
970 }
971
972 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
973 c.SessionTicketsDisabled = true
974 }
975}
976
977func (c *Config) rand() io.Reader {
978 r := c.Rand
979 if r == nil {
980 return rand.Reader
981 }
982 return r
983}
984
985func (c *Config) time() time.Time {
986 t := c.Time
987 if t == nil {
988 t = time.Now
989 }
990 return t()
991}
992
993func (c *Config) cipherSuites() []uint16 {
994 s := c.CipherSuites
995 if s == nil {
996 s = defaultCipherSuites()
997 }
998 return s
999}
1000
David Benjamincecee272016-06-30 13:33:47 -04001001func (c *Config) minVersion(isDTLS bool) uint16 {
1002 ret := uint16(minVersion)
1003 if c != nil && c.MinVersion != 0 {
1004 ret = c.MinVersion
Adam Langley95c29f32014-06-20 12:00:00 -07001005 }
David Benjamincecee272016-06-30 13:33:47 -04001006 if isDTLS {
1007 // The lowest version of DTLS is 1.0. There is no DSSL 3.0.
1008 if ret < VersionTLS10 {
1009 return VersionTLS10
1010 }
1011 // There is no such thing as DTLS 1.1.
1012 if ret == VersionTLS11 {
1013 return VersionTLS12
1014 }
1015 }
1016 return ret
Adam Langley95c29f32014-06-20 12:00:00 -07001017}
1018
David Benjamincecee272016-06-30 13:33:47 -04001019func (c *Config) maxVersion(isDTLS bool) uint16 {
1020 ret := uint16(maxVersion)
1021 if c != nil && c.MaxVersion != 0 {
1022 ret = c.MaxVersion
Adam Langley95c29f32014-06-20 12:00:00 -07001023 }
David Benjamincecee272016-06-30 13:33:47 -04001024 if isDTLS {
1025 // We only implement up to DTLS 1.2.
1026 if ret > VersionTLS12 {
1027 return VersionTLS12
1028 }
1029 // There is no such thing as DTLS 1.1.
1030 if ret == VersionTLS11 {
1031 return VersionTLS10
1032 }
1033 }
1034 return ret
Adam Langley95c29f32014-06-20 12:00:00 -07001035}
1036
David Benjamincba2b622015-12-18 22:13:41 -05001037var defaultCurvePreferences = []CurveID{CurveX25519, CurveP256, CurveP384, CurveP521}
Adam Langley95c29f32014-06-20 12:00:00 -07001038
1039func (c *Config) curvePreferences() []CurveID {
1040 if c == nil || len(c.CurvePreferences) == 0 {
1041 return defaultCurvePreferences
1042 }
1043 return c.CurvePreferences
1044}
1045
1046// mutualVersion returns the protocol version to use given the advertised
1047// version of the peer.
David Benjamincecee272016-06-30 13:33:47 -04001048func (c *Config) mutualVersion(vers uint16, isDTLS bool) (uint16, bool) {
1049 // There is no such thing as DTLS 1.1.
1050 if isDTLS && vers == VersionTLS11 {
1051 vers = VersionTLS10
1052 }
1053
1054 minVersion := c.minVersion(isDTLS)
1055 maxVersion := c.maxVersion(isDTLS)
Adam Langley95c29f32014-06-20 12:00:00 -07001056
1057 if vers < minVersion {
1058 return 0, false
1059 }
1060 if vers > maxVersion {
1061 vers = maxVersion
1062 }
1063 return vers, true
1064}
1065
1066// getCertificateForName returns the best certificate for the given name,
1067// defaulting to the first element of c.Certificates if there are no good
1068// options.
1069func (c *Config) getCertificateForName(name string) *Certificate {
1070 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
1071 // There's only one choice, so no point doing any work.
1072 return &c.Certificates[0]
1073 }
1074
1075 name = strings.ToLower(name)
1076 for len(name) > 0 && name[len(name)-1] == '.' {
1077 name = name[:len(name)-1]
1078 }
1079
1080 if cert, ok := c.NameToCertificate[name]; ok {
1081 return cert
1082 }
1083
1084 // try replacing labels in the name with wildcards until we get a
1085 // match.
1086 labels := strings.Split(name, ".")
1087 for i := range labels {
1088 labels[i] = "*"
1089 candidate := strings.Join(labels, ".")
1090 if cert, ok := c.NameToCertificate[candidate]; ok {
1091 return cert
1092 }
1093 }
1094
1095 // If nothing matches, return the first certificate.
1096 return &c.Certificates[0]
1097}
1098
David Benjamin7a41d372016-07-09 11:21:54 -07001099func (c *Config) signSignatureAlgorithms() []signatureAlgorithm {
1100 if c != nil && c.SignSignatureAlgorithms != nil {
1101 return c.SignSignatureAlgorithms
David Benjamin000800a2014-11-14 01:43:59 -05001102 }
David Benjamin7a41d372016-07-09 11:21:54 -07001103 return supportedSignatureAlgorithms
David Benjamin000800a2014-11-14 01:43:59 -05001104}
1105
David Benjamin7a41d372016-07-09 11:21:54 -07001106func (c *Config) verifySignatureAlgorithms() []signatureAlgorithm {
1107 if c != nil && c.VerifySignatureAlgorithms != nil {
1108 return c.VerifySignatureAlgorithms
David Benjamin000800a2014-11-14 01:43:59 -05001109 }
David Benjamin7a41d372016-07-09 11:21:54 -07001110 return supportedSignatureAlgorithms
David Benjamin000800a2014-11-14 01:43:59 -05001111}
1112
Adam Langley95c29f32014-06-20 12:00:00 -07001113// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
1114// from the CommonName and SubjectAlternateName fields of each of the leaf
1115// certificates.
1116func (c *Config) BuildNameToCertificate() {
1117 c.NameToCertificate = make(map[string]*Certificate)
1118 for i := range c.Certificates {
1119 cert := &c.Certificates[i]
1120 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
1121 if err != nil {
1122 continue
1123 }
1124 if len(x509Cert.Subject.CommonName) > 0 {
1125 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
1126 }
1127 for _, san := range x509Cert.DNSNames {
1128 c.NameToCertificate[san] = cert
1129 }
1130 }
1131}
1132
1133// A Certificate is a chain of one or more certificates, leaf first.
1134type Certificate struct {
1135 Certificate [][]byte
1136 PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
1137 // OCSPStaple contains an optional OCSP response which will be served
1138 // to clients that request it.
1139 OCSPStaple []byte
David Benjamin61f95272014-11-25 01:55:35 -05001140 // SignedCertificateTimestampList contains an optional encoded
1141 // SignedCertificateTimestampList structure which will be
1142 // served to clients that request it.
1143 SignedCertificateTimestampList []byte
Adam Langley95c29f32014-06-20 12:00:00 -07001144 // Leaf is the parsed form of the leaf certificate, which may be
1145 // initialized using x509.ParseCertificate to reduce per-handshake
1146 // processing for TLS clients doing client authentication. If nil, the
1147 // leaf certificate will be parsed as needed.
1148 Leaf *x509.Certificate
1149}
1150
1151// A TLS record.
1152type record struct {
1153 contentType recordType
1154 major, minor uint8
1155 payload []byte
1156}
1157
1158type handshakeMessage interface {
1159 marshal() []byte
1160 unmarshal([]byte) bool
1161}
1162
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001163// lruSessionCache is a client or server session cache implementation
1164// that uses an LRU caching strategy.
Adam Langley95c29f32014-06-20 12:00:00 -07001165type lruSessionCache struct {
1166 sync.Mutex
1167
1168 m map[string]*list.Element
1169 q *list.List
1170 capacity int
1171}
1172
1173type lruSessionCacheEntry struct {
1174 sessionKey string
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001175 state interface{}
Adam Langley95c29f32014-06-20 12:00:00 -07001176}
1177
1178// Put adds the provided (sessionKey, cs) pair to the cache.
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001179func (c *lruSessionCache) Put(sessionKey string, cs interface{}) {
Adam Langley95c29f32014-06-20 12:00:00 -07001180 c.Lock()
1181 defer c.Unlock()
1182
1183 if elem, ok := c.m[sessionKey]; ok {
1184 entry := elem.Value.(*lruSessionCacheEntry)
1185 entry.state = cs
1186 c.q.MoveToFront(elem)
1187 return
1188 }
1189
1190 if c.q.Len() < c.capacity {
1191 entry := &lruSessionCacheEntry{sessionKey, cs}
1192 c.m[sessionKey] = c.q.PushFront(entry)
1193 return
1194 }
1195
1196 elem := c.q.Back()
1197 entry := elem.Value.(*lruSessionCacheEntry)
1198 delete(c.m, entry.sessionKey)
1199 entry.sessionKey = sessionKey
1200 entry.state = cs
1201 c.q.MoveToFront(elem)
1202 c.m[sessionKey] = elem
1203}
1204
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001205// Get returns the value associated with a given key. It returns (nil,
1206// false) if no value is found.
1207func (c *lruSessionCache) Get(sessionKey string) (interface{}, bool) {
Adam Langley95c29f32014-06-20 12:00:00 -07001208 c.Lock()
1209 defer c.Unlock()
1210
1211 if elem, ok := c.m[sessionKey]; ok {
1212 c.q.MoveToFront(elem)
1213 return elem.Value.(*lruSessionCacheEntry).state, true
1214 }
1215 return nil, false
1216}
1217
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001218// lruClientSessionCache is a ClientSessionCache implementation that
1219// uses an LRU caching strategy.
1220type lruClientSessionCache struct {
1221 lruSessionCache
1222}
1223
1224func (c *lruClientSessionCache) Put(sessionKey string, cs *ClientSessionState) {
1225 c.lruSessionCache.Put(sessionKey, cs)
1226}
1227
1228func (c *lruClientSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
1229 cs, ok := c.lruSessionCache.Get(sessionKey)
1230 if !ok {
1231 return nil, false
1232 }
1233 return cs.(*ClientSessionState), true
1234}
1235
1236// lruServerSessionCache is a ServerSessionCache implementation that
1237// uses an LRU caching strategy.
1238type lruServerSessionCache struct {
1239 lruSessionCache
1240}
1241
1242func (c *lruServerSessionCache) Put(sessionId string, session *sessionState) {
1243 c.lruSessionCache.Put(sessionId, session)
1244}
1245
1246func (c *lruServerSessionCache) Get(sessionId string) (*sessionState, bool) {
1247 cs, ok := c.lruSessionCache.Get(sessionId)
1248 if !ok {
1249 return nil, false
1250 }
1251 return cs.(*sessionState), true
1252}
1253
1254// NewLRUClientSessionCache returns a ClientSessionCache with the given
1255// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1256// is used instead.
1257func NewLRUClientSessionCache(capacity int) ClientSessionCache {
1258 const defaultSessionCacheCapacity = 64
1259
1260 if capacity < 1 {
1261 capacity = defaultSessionCacheCapacity
1262 }
1263 return &lruClientSessionCache{
1264 lruSessionCache{
1265 m: make(map[string]*list.Element),
1266 q: list.New(),
1267 capacity: capacity,
1268 },
1269 }
1270}
1271
1272// NewLRUServerSessionCache returns a ServerSessionCache with the given
1273// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1274// is used instead.
1275func NewLRUServerSessionCache(capacity int) ServerSessionCache {
1276 const defaultSessionCacheCapacity = 64
1277
1278 if capacity < 1 {
1279 capacity = defaultSessionCacheCapacity
1280 }
1281 return &lruServerSessionCache{
1282 lruSessionCache{
1283 m: make(map[string]*list.Element),
1284 q: list.New(),
1285 capacity: capacity,
1286 },
1287 }
1288}
1289
Adam Langley95c29f32014-06-20 12:00:00 -07001290// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
1291type dsaSignature struct {
1292 R, S *big.Int
1293}
1294
1295type ecdsaSignature dsaSignature
1296
1297var emptyConfig Config
1298
1299func defaultConfig() *Config {
1300 return &emptyConfig
1301}
1302
1303var (
1304 once sync.Once
1305 varDefaultCipherSuites []uint16
1306)
1307
1308func defaultCipherSuites() []uint16 {
1309 once.Do(initDefaultCipherSuites)
1310 return varDefaultCipherSuites
1311}
1312
1313func initDefaultCipherSuites() {
David Benjamin48cae082014-10-27 01:06:24 -04001314 for _, suite := range cipherSuites {
1315 if suite.flags&suitePSK == 0 {
1316 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
1317 }
Adam Langley95c29f32014-06-20 12:00:00 -07001318 }
1319}
1320
1321func unexpectedMessageError(wanted, got interface{}) error {
1322 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1323}
David Benjamin000800a2014-11-14 01:43:59 -05001324
Nick Harper60edffd2016-06-21 15:19:24 -07001325func isSupportedSignatureAlgorithm(sigAlg signatureAlgorithm, sigAlgs []signatureAlgorithm) bool {
1326 for _, s := range sigAlgs {
1327 if s == sigAlg {
David Benjamin000800a2014-11-14 01:43:59 -05001328 return true
1329 }
1330 }
1331 return false
1332}
Nick Harper85f20c22016-07-04 10:11:59 -07001333
1334var (
1335 // See draft-ietf-tls-tls13-13, section 6.3.1.2.
1336 downgradeTLS13 = []byte{0x44, 0x4f, 0x57, 0x4e, 0x47, 0x52, 0x44, 0x01}
1337 downgradeTLS12 = []byte{0x44, 0x4f, 0x57, 0x4e, 0x47, 0x52, 0x44, 0x00}
1338)