blob: d316ddd6eba94e5de10a04b044e05587ff345f28 [file] [log] [blame]
Adam Langleyd9e397b2015-01-22 14:27:53 -08001// 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
Kenny Roote99801b2015-11-06 15:31:15 -08005package runner
Adam Langleyd9e397b2015-01-22 14:27:53 -08006
7import (
8 "container/list"
9 "crypto"
10 "crypto/ecdsa"
11 "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
David Benjaminc895d6b2016-08-11 13:26:41 -040026 VersionTLS13 = 0x0304
Adam Langleyd9e397b2015-01-22 14:27:53 -080027)
28
Steven Valdezbb1ceac2016-10-07 10:34:51 -040029// A draft version of TLS 1.3 that is sent over the wire for the current draft.
Steven Valdez909b19f2016-11-21 15:35:44 -050030const tls13DraftVersion = 0x7f12
David Benjaminc895d6b2016-08-11 13:26:41 -040031
Adam Langleyd9e397b2015-01-22 14:27:53 -080032const (
33 maxPlaintext = 16384 // maximum plaintext payload length
34 maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
35 tlsRecordHeaderLen = 5 // record header length
36 dtlsRecordHeaderLen = 13
37 maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
38
39 minVersion = VersionSSL30
David Benjaminc895d6b2016-08-11 13:26:41 -040040 maxVersion = VersionTLS13
Adam Langleyd9e397b2015-01-22 14:27:53 -080041)
42
43// TLS record types.
44type recordType uint8
45
46const (
47 recordTypeChangeCipherSpec recordType = 20
48 recordTypeAlert recordType = 21
49 recordTypeHandshake recordType = 22
50 recordTypeApplicationData recordType = 23
51)
52
53// TLS handshake message types.
54const (
55 typeHelloRequest uint8 = 0
56 typeClientHello uint8 = 1
57 typeServerHello uint8 = 2
58 typeHelloVerifyRequest uint8 = 3
59 typeNewSessionTicket uint8 = 4
David Benjamin95add822016-10-19 01:09:12 -040060 typeHelloRetryRequest uint8 = 6 // draft-ietf-tls-tls13-16
61 typeEncryptedExtensions uint8 = 8 // draft-ietf-tls-tls13-16
Adam Langleyd9e397b2015-01-22 14:27:53 -080062 typeCertificate uint8 = 11
63 typeServerKeyExchange uint8 = 12
64 typeCertificateRequest uint8 = 13
65 typeServerHelloDone uint8 = 14
66 typeCertificateVerify uint8 = 15
67 typeClientKeyExchange uint8 = 16
68 typeFinished uint8 = 20
69 typeCertificateStatus uint8 = 22
David Benjamin95add822016-10-19 01:09:12 -040070 typeKeyUpdate uint8 = 24 // draft-ietf-tls-tls13-16
Adam Langleyd9e397b2015-01-22 14:27:53 -080071 typeNextProtocol uint8 = 67 // Not IANA assigned
David Benjaminc895d6b2016-08-11 13:26:41 -040072 typeChannelID uint8 = 203 // Not IANA assigned
Adam Langleyd9e397b2015-01-22 14:27:53 -080073)
74
75// TLS compression types.
76const (
77 compressionNone uint8 = 0
78)
79
80// TLS extension numbers
81const (
82 extensionServerName uint16 = 0
83 extensionStatusRequest uint16 = 5
84 extensionSupportedCurves uint16 = 10
85 extensionSupportedPoints uint16 = 11
86 extensionSignatureAlgorithms uint16 = 13
87 extensionUseSRTP uint16 = 14
88 extensionALPN uint16 = 16
89 extensionSignedCertificateTimestamp uint16 = 18
90 extensionExtendedMasterSecret uint16 = 23
91 extensionSessionTicket uint16 = 35
David Benjamin95add822016-10-19 01:09:12 -040092 extensionKeyShare uint16 = 40 // draft-ietf-tls-tls13-16
93 extensionPreSharedKey uint16 = 41 // draft-ietf-tls-tls13-16
94 extensionEarlyData uint16 = 42 // draft-ietf-tls-tls13-16
Steven Valdezbb1ceac2016-10-07 10:34:51 -040095 extensionSupportedVersions uint16 = 43 // draft-ietf-tls-tls13-16
David Benjamin95add822016-10-19 01:09:12 -040096 extensionCookie uint16 = 44 // draft-ietf-tls-tls13-16
Steven Valdez909b19f2016-11-21 15:35:44 -050097 extensionPSKKeyExchangeModes uint16 = 45 // draft-ietf-tls-tls13-18
Robert Sloan69939df2017-01-09 10:53:07 -080098 extensionTicketEarlyDataInfo uint16 = 46 // draft-ietf-tls-tls13-18
Kenny Rootb8494592015-09-25 02:29:14 +000099 extensionCustom uint16 = 1234 // not IANA assigned
Adam Langleyd9e397b2015-01-22 14:27:53 -0800100 extensionNextProtoNeg uint16 = 13172 // not IANA assigned
101 extensionRenegotiationInfo uint16 = 0xff01
102 extensionChannelID uint16 = 30032 // not IANA assigned
David Benjamin95add822016-10-19 01:09:12 -0400103)
104
Adam Langleyd9e397b2015-01-22 14:27:53 -0800105// TLS signaling cipher suite values
106const (
107 scsvRenegotiation uint16 = 0x00ff
108)
109
110// CurveID is the type of a TLS identifier for an elliptic curve. See
111// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
112type CurveID uint16
113
114const (
Adam Langley4139edb2016-01-13 15:00:54 -0800115 CurveP224 CurveID = 21
116 CurveP256 CurveID = 23
117 CurveP384 CurveID = 24
118 CurveP521 CurveID = 25
119 CurveX25519 CurveID = 29
Adam Langleyd9e397b2015-01-22 14:27:53 -0800120)
121
122// TLS Elliptic Curve Point Formats
123// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
124const (
Robert Sloan69939df2017-01-09 10:53:07 -0800125 pointFormatUncompressed uint8 = 0
126 pointFormatCompressedPrime uint8 = 1
Adam Langleyd9e397b2015-01-22 14:27:53 -0800127)
128
129// TLS CertificateStatusType (RFC 3546)
130const (
131 statusTypeOCSP uint8 = 1
132)
133
134// Certificate types (for certificateRequestMsg)
135const (
136 CertTypeRSASign = 1 // A certificate containing an RSA key
137 CertTypeDSSSign = 2 // A certificate containing a DSA key
138 CertTypeRSAFixedDH = 3 // A certificate containing a static DH key
139 CertTypeDSSFixedDH = 4 // A certificate containing a static DH key
140
141 // See RFC4492 sections 3 and 5.5.
142 CertTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
143 CertTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
144 CertTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
145
146 // Rest of these are reserved by the TLS spec
147)
148
David Benjaminc895d6b2016-08-11 13:26:41 -0400149// signatureAlgorithm corresponds to a SignatureScheme value from TLS 1.3. Note
150// that TLS 1.3 names the production 'SignatureScheme' to avoid colliding with
151// TLS 1.2's SignatureAlgorithm but otherwise refers to them as 'signature
152// algorithms' throughout. We match the latter.
153type signatureAlgorithm uint16
154
Adam Langleyd9e397b2015-01-22 14:27:53 -0800155const (
David Benjaminc895d6b2016-08-11 13:26:41 -0400156 // RSASSA-PKCS1-v1_5 algorithms
157 signatureRSAPKCS1WithMD5 signatureAlgorithm = 0x0101
158 signatureRSAPKCS1WithSHA1 signatureAlgorithm = 0x0201
159 signatureRSAPKCS1WithSHA256 signatureAlgorithm = 0x0401
160 signatureRSAPKCS1WithSHA384 signatureAlgorithm = 0x0501
161 signatureRSAPKCS1WithSHA512 signatureAlgorithm = 0x0601
162
163 // ECDSA algorithms
164 signatureECDSAWithSHA1 signatureAlgorithm = 0x0203
165 signatureECDSAWithP256AndSHA256 signatureAlgorithm = 0x0403
166 signatureECDSAWithP384AndSHA384 signatureAlgorithm = 0x0503
167 signatureECDSAWithP521AndSHA512 signatureAlgorithm = 0x0603
168
169 // RSASSA-PSS algorithms
David Benjamin7c0d06c2016-08-11 13:26:41 -0400170 signatureRSAPSSWithSHA256 signatureAlgorithm = 0x0804
171 signatureRSAPSSWithSHA384 signatureAlgorithm = 0x0805
172 signatureRSAPSSWithSHA512 signatureAlgorithm = 0x0806
David Benjaminc895d6b2016-08-11 13:26:41 -0400173
174 // EdDSA algorithms
David Benjamin7c0d06c2016-08-11 13:26:41 -0400175 signatureEd25519 signatureAlgorithm = 0x0807
176 signatureEd448 signatureAlgorithm = 0x0808
Adam Langleyd9e397b2015-01-22 14:27:53 -0800177)
178
David Benjaminc895d6b2016-08-11 13:26:41 -0400179// supportedSignatureAlgorithms contains the default supported signature
180// algorithms.
181var supportedSignatureAlgorithms = []signatureAlgorithm{
182 signatureRSAPSSWithSHA256,
183 signatureRSAPKCS1WithSHA256,
184 signatureECDSAWithP256AndSHA256,
185 signatureRSAPKCS1WithSHA1,
186 signatureECDSAWithSHA1,
Adam Langleyd9e397b2015-01-22 14:27:53 -0800187}
188
189// SRTP protection profiles (See RFC 5764, section 4.1.2)
190const (
191 SRTP_AES128_CM_HMAC_SHA1_80 uint16 = 0x0001
192 SRTP_AES128_CM_HMAC_SHA1_32 = 0x0002
193)
194
David Benjamin95add822016-10-19 01:09:12 -0400195// PskKeyExchangeMode values (see draft-ietf-tls-tls13-16)
David Benjaminc895d6b2016-08-11 13:26:41 -0400196const (
Steven Valdezbb1ceac2016-10-07 10:34:51 -0400197 pskKEMode = 0
198 pskDHEKEMode = 1
199)
200
David Benjamin95add822016-10-19 01:09:12 -0400201// KeyUpdateRequest values (see draft-ietf-tls-tls13-16, section 4.5.3)
202const (
203 keyUpdateNotRequested = 0
204 keyUpdateRequested = 1
205)
206
Adam Langleyd9e397b2015-01-22 14:27:53 -0800207// ConnectionState records basic TLS details about the connection.
208type ConnectionState struct {
209 Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
210 HandshakeComplete bool // TLS handshake is complete
211 DidResume bool // connection resumes a previous TLS connection
212 CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
213 NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos)
214 NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server
215 NegotiatedProtocolFromALPN bool // protocol negotiated with ALPN
216 ServerName string // server name requested by client, if any (server side only)
217 PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
218 VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
219 ChannelID *ecdsa.PublicKey // the channel ID for this connection
220 SRTPProtectionProfile uint16 // the negotiated DTLS-SRTP protection profile
Kenny Rootb8494592015-09-25 02:29:14 +0000221 TLSUnique []byte // the tls-unique channel binding
222 SCTList []byte // signed certificate timestamp list
David Benjaminc895d6b2016-08-11 13:26:41 -0400223 PeerSignatureAlgorithm signatureAlgorithm // algorithm used by the peer in the handshake
224 CurveID CurveID // the curve used in ECDHE
Adam Langleyd9e397b2015-01-22 14:27:53 -0800225}
226
227// ClientAuthType declares the policy the server will follow for
228// TLS Client Authentication.
229type ClientAuthType int
230
231const (
232 NoClientCert ClientAuthType = iota
233 RequestClientCert
234 RequireAnyClientCert
235 VerifyClientCertIfGiven
236 RequireAndVerifyClientCert
237)
238
239// ClientSessionState contains the state needed by clients to resume TLS
240// sessions.
241type ClientSessionState struct {
242 sessionId []uint8 // Session ID supplied by the server. nil if the session has a ticket.
243 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
244 vers uint16 // SSL/TLS version negotiated for the session
245 cipherSuite uint16 // Ciphersuite negotiated for the session
246 masterSecret []byte // MasterSecret generated by client on a full handshake
247 handshakeHash []byte // Handshake hash for Channel ID purposes.
248 serverCertificates []*x509.Certificate // Certificate chain presented by the server
249 extendedMasterSecret bool // Whether an extended master secret was used to generate the session
Kenny Rootb8494592015-09-25 02:29:14 +0000250 sctList []byte
251 ocspResponse []byte
David Benjaminc895d6b2016-08-11 13:26:41 -0400252 ticketCreationTime time.Time
253 ticketExpiration time.Time
Steven Valdez909b19f2016-11-21 15:35:44 -0500254 ticketAgeAdd uint32
Robert Sloan47f43ed2017-02-06 14:55:15 -0800255 maxEarlyDataSize uint32
Adam Langleyd9e397b2015-01-22 14:27:53 -0800256}
257
258// ClientSessionCache is a cache of ClientSessionState objects that can be used
259// by a client to resume a TLS session with a given server. ClientSessionCache
260// implementations should expect to be called concurrently from different
261// goroutines.
262type ClientSessionCache interface {
263 // Get searches for a ClientSessionState associated with the given key.
264 // On return, ok is true if one was found.
265 Get(sessionKey string) (session *ClientSessionState, ok bool)
266
267 // Put adds the ClientSessionState to the cache with the given key.
268 Put(sessionKey string, cs *ClientSessionState)
269}
270
271// ServerSessionCache is a cache of sessionState objects that can be used by a
272// client to resume a TLS session with a given server. ServerSessionCache
273// implementations should expect to be called concurrently from different
274// goroutines.
275type ServerSessionCache interface {
276 // Get searches for a sessionState associated with the given session
277 // ID. On return, ok is true if one was found.
278 Get(sessionId string) (session *sessionState, ok bool)
279
280 // Put adds the sessionState to the cache with the given session ID.
281 Put(sessionId string, session *sessionState)
282}
283
284// A Config structure is used to configure a TLS client or server.
285// After one has been passed to a TLS function it must not be
286// modified. A Config may be reused; the tls package will also not
287// modify it.
288type Config struct {
289 // Rand provides the source of entropy for nonces and RSA blinding.
290 // If Rand is nil, TLS uses the cryptographic random reader in package
291 // crypto/rand.
292 // The Reader must be safe for use by multiple goroutines.
293 Rand io.Reader
294
295 // Time returns the current time as the number of seconds since the epoch.
296 // If Time is nil, TLS uses time.Now.
297 Time func() time.Time
298
299 // Certificates contains one or more certificate chains
300 // to present to the other side of the connection.
301 // Server configurations must include at least one certificate.
302 Certificates []Certificate
303
304 // NameToCertificate maps from a certificate name to an element of
305 // Certificates. Note that a certificate name can be of the form
306 // '*.example.com' and so doesn't have to be a domain name as such.
307 // See Config.BuildNameToCertificate
308 // The nil value causes the first element of Certificates to be used
309 // for all connections.
310 NameToCertificate map[string]*Certificate
311
312 // RootCAs defines the set of root certificate authorities
313 // that clients use when verifying server certificates.
314 // If RootCAs is nil, TLS uses the host's root CA set.
315 RootCAs *x509.CertPool
316
317 // NextProtos is a list of supported, application level protocols.
318 NextProtos []string
319
320 // ServerName is used to verify the hostname on the returned
321 // certificates unless InsecureSkipVerify is given. It is also included
322 // in the client's handshake to support virtual hosting.
323 ServerName string
324
325 // ClientAuth determines the server's policy for
326 // TLS Client Authentication. The default is NoClientCert.
327 ClientAuth ClientAuthType
328
329 // ClientCAs defines the set of root certificate authorities
330 // that servers use if required to verify a client certificate
331 // by the policy in ClientAuth.
332 ClientCAs *x509.CertPool
333
334 // ClientCertificateTypes defines the set of allowed client certificate
335 // types. The default is CertTypeRSASign and CertTypeECDSASign.
336 ClientCertificateTypes []byte
337
338 // InsecureSkipVerify controls whether a client verifies the
339 // server's certificate chain and host name.
340 // If InsecureSkipVerify is true, TLS accepts any certificate
341 // presented by the server and any host name in that certificate.
342 // In this mode, TLS is susceptible to man-in-the-middle attacks.
343 // This should be used only for testing.
344 InsecureSkipVerify bool
345
346 // CipherSuites is a list of supported cipher suites. If CipherSuites
347 // is nil, TLS uses a list of suites supported by the implementation.
348 CipherSuites []uint16
349
350 // PreferServerCipherSuites controls whether the server selects the
351 // client's most preferred ciphersuite, or the server's most preferred
352 // ciphersuite. If true then the server's preference, as expressed in
353 // the order of elements in CipherSuites, is used.
354 PreferServerCipherSuites bool
355
356 // SessionTicketsDisabled may be set to true to disable session ticket
357 // (resumption) support.
358 SessionTicketsDisabled bool
359
360 // SessionTicketKey is used by TLS servers to provide session
361 // resumption. See RFC 5077. If zero, it will be filled with
362 // random data before the first server handshake.
363 //
364 // If multiple servers are terminating connections for the same host
365 // they should all have the same SessionTicketKey. If the
366 // SessionTicketKey leaks, previously recorded and future TLS
367 // connections using that key are compromised.
368 SessionTicketKey [32]byte
369
370 // ClientSessionCache is a cache of ClientSessionState entries
371 // for TLS session resumption.
372 ClientSessionCache ClientSessionCache
373
374 // ServerSessionCache is a cache of sessionState entries for TLS session
375 // resumption.
376 ServerSessionCache ServerSessionCache
377
378 // MinVersion contains the minimum SSL/TLS version that is acceptable.
379 // If zero, then SSLv3 is taken as the minimum.
380 MinVersion uint16
381
382 // MaxVersion contains the maximum SSL/TLS version that is acceptable.
383 // If zero, then the maximum version supported by this package is used,
384 // which is currently TLS 1.2.
385 MaxVersion uint16
386
387 // CurvePreferences contains the elliptic curves that will be used in
388 // an ECDHE handshake, in preference order. If empty, the default will
389 // be used.
390 CurvePreferences []CurveID
391
David Benjaminc895d6b2016-08-11 13:26:41 -0400392 // DefaultCurves contains the elliptic curves for which public values will
393 // be sent in the ClientHello's KeyShare extension. If this value is nil,
394 // all supported curves will have public values sent. This field is ignored
395 // on servers.
396 DefaultCurves []CurveID
397
Adam Langleyd9e397b2015-01-22 14:27:53 -0800398 // ChannelID contains the ECDSA key for the client to use as
399 // its TLS Channel ID.
400 ChannelID *ecdsa.PrivateKey
401
402 // RequestChannelID controls whether the server requests a TLS
403 // Channel ID. If negotiated, the client's public key is
404 // returned in the ConnectionState.
405 RequestChannelID bool
406
407 // PreSharedKey, if not nil, is the pre-shared key to use with
408 // the PSK cipher suites.
409 PreSharedKey []byte
410
411 // PreSharedKeyIdentity, if not empty, is the identity to use
412 // with the PSK cipher suites.
413 PreSharedKeyIdentity string
414
Robert Sloan47f43ed2017-02-06 14:55:15 -0800415 // MaxEarlyDataSize controls the maximum number of bytes that the
416 // server will accept in early data and advertise in a
417 // NewSessionTicketMsg. If 0, no early data will be accepted and
418 // the TicketEarlyDataInfo extension in the NewSessionTicketMsg
419 // will be omitted.
420 MaxEarlyDataSize uint32
421
Adam Langleyd9e397b2015-01-22 14:27:53 -0800422 // SRTPProtectionProfiles, if not nil, is the list of SRTP
423 // protection profiles to offer in DTLS-SRTP.
424 SRTPProtectionProfiles []uint16
425
David Benjaminc895d6b2016-08-11 13:26:41 -0400426 // SignSignatureAlgorithms, if not nil, overrides the default set of
427 // supported signature algorithms to sign with.
428 SignSignatureAlgorithms []signatureAlgorithm
429
430 // VerifySignatureAlgorithms, if not nil, overrides the default set of
431 // supported signature algorithms that are accepted.
432 VerifySignatureAlgorithms []signatureAlgorithm
Adam Langleyd9e397b2015-01-22 14:27:53 -0800433
434 // Bugs specifies optional misbehaviour to be used for testing other
435 // implementations.
436 Bugs ProtocolBugs
437
438 serverInitOnce sync.Once // guards calling (*Config).serverInit
439}
440
441type BadValue int
442
443const (
444 BadValueNone BadValue = iota
445 BadValueNegative
446 BadValueZero
447 BadValueLimit
448 BadValueLarge
449 NumBadValues
450)
451
Adam Langley4139edb2016-01-13 15:00:54 -0800452type RSABadValue int
453
454const (
455 RSABadValueNone RSABadValue = iota
456 RSABadValueCorrupt
457 RSABadValueTooLong
458 RSABadValueTooShort
459 RSABadValueWrongVersion
460 NumRSABadValues
461)
462
Adam Langleyd9e397b2015-01-22 14:27:53 -0800463type ProtocolBugs struct {
David Benjaminc895d6b2016-08-11 13:26:41 -0400464 // InvalidSignature specifies that the signature in a ServerKeyExchange
465 // or CertificateVerify message should be invalid.
466 InvalidSignature bool
Adam Langleyd9e397b2015-01-22 14:27:53 -0800467
David Benjaminc895d6b2016-08-11 13:26:41 -0400468 // SendCurve, if non-zero, causes the server to send the specified curve
469 // ID in ServerKeyExchange (TLS 1.2) or ServerHello (TLS 1.3) rather
470 // than the negotiated one.
471 SendCurve CurveID
Kenny Rootb8494592015-09-25 02:29:14 +0000472
David Benjamin4969cc92016-04-22 15:02:23 -0400473 // InvalidECDHPoint, if true, causes the ECC points in
474 // ServerKeyExchange or ClientKeyExchange messages to be invalid.
475 InvalidECDHPoint bool
476
Adam Langleyd9e397b2015-01-22 14:27:53 -0800477 // BadECDSAR controls ways in which the 'r' value of an ECDSA signature
478 // can be invalid.
479 BadECDSAR BadValue
480 BadECDSAS BadValue
481
482 // MaxPadding causes CBC records to have the maximum possible padding.
483 MaxPadding bool
484 // PaddingFirstByteBad causes the first byte of the padding to be
485 // incorrect.
486 PaddingFirstByteBad bool
487 // PaddingFirstByteBadIf255 causes the first byte of padding to be
488 // incorrect if there's a maximum amount of padding (i.e. 255 bytes).
489 PaddingFirstByteBadIf255 bool
490
491 // FailIfNotFallbackSCSV causes a server handshake to fail if the
492 // client doesn't send the fallback SCSV value.
493 FailIfNotFallbackSCSV bool
494
495 // DuplicateExtension causes an extra empty extension of bogus type to
496 // be emitted in either the ClientHello or the ServerHello.
497 DuplicateExtension bool
498
499 // UnauthenticatedECDH causes the server to pretend ECDHE_RSA
500 // and ECDHE_ECDSA cipher suites are actually ECDH_anon. No
501 // Certificate message is sent and no signature is added to
502 // ServerKeyExchange.
503 UnauthenticatedECDH bool
504
Adam Langleye9ada862015-05-11 17:20:37 -0700505 // SkipHelloVerifyRequest causes a DTLS server to skip the
506 // HelloVerifyRequest message.
507 SkipHelloVerifyRequest bool
508
509 // SkipCertificateStatus, if true, causes the server to skip the
510 // CertificateStatus message. This is legal because CertificateStatus is
511 // optional, even with a status_request in ServerHello.
512 SkipCertificateStatus bool
513
Adam Langleyd9e397b2015-01-22 14:27:53 -0800514 // SkipServerKeyExchange causes the server to skip sending
515 // ServerKeyExchange messages.
516 SkipServerKeyExchange bool
517
Adam Langleye9ada862015-05-11 17:20:37 -0700518 // SkipNewSessionTicket causes the server to skip sending the
519 // NewSessionTicket message despite promising to in ServerHello.
520 SkipNewSessionTicket bool
521
David Benjamin4969cc92016-04-22 15:02:23 -0400522 // SkipClientCertificate causes the client to skip the Certificate
523 // message.
524 SkipClientCertificate bool
525
Adam Langleyd9e397b2015-01-22 14:27:53 -0800526 // SkipChangeCipherSpec causes the implementation to skip
527 // sending the ChangeCipherSpec message (and adjusting cipher
528 // state accordingly for the Finished message).
529 SkipChangeCipherSpec bool
530
Adam Langleye9ada862015-05-11 17:20:37 -0700531 // SkipFinished causes the implementation to skip sending the Finished
532 // message.
533 SkipFinished bool
534
Adam Langleyd9e397b2015-01-22 14:27:53 -0800535 // EarlyChangeCipherSpec causes the client to send an early
536 // ChangeCipherSpec message before the ClientKeyExchange. A value of
537 // zero disables this behavior. One and two configure variants for 0.9.8
538 // and 1.0.1 modes, respectively.
539 EarlyChangeCipherSpec int
540
David Benjaminc895d6b2016-08-11 13:26:41 -0400541 // StrayChangeCipherSpec causes every pre-ChangeCipherSpec handshake
542 // message in DTLS to be prefaced by stray ChangeCipherSpec record. This
543 // may be used to test DTLS's handling of reordered ChangeCipherSpec.
544 StrayChangeCipherSpec bool
545
Adam Langleyd9e397b2015-01-22 14:27:53 -0800546 // FragmentAcrossChangeCipherSpec causes the implementation to fragment
547 // the Finished (or NextProto) message around the ChangeCipherSpec
548 // messages.
549 FragmentAcrossChangeCipherSpec bool
550
David Benjaminc895d6b2016-08-11 13:26:41 -0400551 // SendUnencryptedFinished, if true, causes the Finished message to be
552 // send unencrypted before ChangeCipherSpec rather than after it.
553 SendUnencryptedFinished bool
554
555 // PartialEncryptedExtensionsWithServerHello, if true, causes the TLS
556 // 1.3 server to send part of EncryptedExtensions unencrypted
557 // in the same record as ServerHello.
558 PartialEncryptedExtensionsWithServerHello bool
559
560 // PartialClientFinishedWithClientHello, if true, causes the TLS 1.3
561 // client to send part of Finished unencrypted in the same record as
562 // ClientHello.
563 PartialClientFinishedWithClientHello bool
564
Adam Langleyd9e397b2015-01-22 14:27:53 -0800565 // SendV2ClientHello causes the client to send a V2ClientHello
566 // instead of a normal ClientHello.
567 SendV2ClientHello bool
568
569 // SendFallbackSCSV causes the client to include
570 // TLS_FALLBACK_SCSV in the ClientHello.
571 SendFallbackSCSV bool
572
Kenny Rootb8494592015-09-25 02:29:14 +0000573 // SendRenegotiationSCSV causes the client to include the renegotiation
574 // SCSV in the ClientHello.
575 SendRenegotiationSCSV bool
576
Adam Langleyd9e397b2015-01-22 14:27:53 -0800577 // MaxHandshakeRecordLength, if non-zero, is the maximum size of a
578 // handshake record. Handshake messages will be split into multiple
579 // records at the specified size, except that the client_version will
Adam Langleyf4e42722015-06-04 17:45:09 -0700580 // never be fragmented. For DTLS, it is the maximum handshake fragment
581 // size, not record size; DTLS allows multiple handshake fragments in a
582 // single handshake record. See |PackHandshakeFragments|.
Adam Langleyd9e397b2015-01-22 14:27:53 -0800583 MaxHandshakeRecordLength int
584
585 // FragmentClientVersion will allow MaxHandshakeRecordLength to apply to
586 // the first 6 bytes of the ClientHello.
587 FragmentClientVersion bool
588
589 // FragmentAlert will cause all alerts to be fragmented across
590 // two records.
591 FragmentAlert bool
592
David Benjamin4969cc92016-04-22 15:02:23 -0400593 // DoubleAlert will cause all alerts to be sent as two copies packed
594 // within one record.
595 DoubleAlert bool
596
Adam Langleye9ada862015-05-11 17:20:37 -0700597 // SendSpuriousAlert, if non-zero, will cause an spurious, unwanted
598 // alert to be sent.
599 SendSpuriousAlert alert
Adam Langleyd9e397b2015-01-22 14:27:53 -0800600
Adam Langley4139edb2016-01-13 15:00:54 -0800601 // BadRSAClientKeyExchange causes the client to send a corrupted RSA
602 // ClientKeyExchange which would not pass padding checks.
603 BadRSAClientKeyExchange RSABadValue
Adam Langleyd9e397b2015-01-22 14:27:53 -0800604
605 // RenewTicketOnResume causes the server to renew the session ticket and
606 // send a NewSessionTicket message during an abbreviated handshake.
607 RenewTicketOnResume bool
608
Steven Valdezbb1ceac2016-10-07 10:34:51 -0400609 // SendClientVersion, if non-zero, causes the client to send the
610 // specified value in the ClientHello version field.
Adam Langleyd9e397b2015-01-22 14:27:53 -0800611 SendClientVersion uint16
612
Steven Valdezbb1ceac2016-10-07 10:34:51 -0400613 // OmitSupportedVersions, if true, causes the client to omit the
614 // supported versions extension.
615 OmitSupportedVersions bool
616
617 // SendSupportedVersions, if non-empty, causes the client to send a
618 // supported versions extension with the values from array.
619 SendSupportedVersions []uint16
620
David Benjaminc895d6b2016-08-11 13:26:41 -0400621 // NegotiateVersion, if non-zero, causes the server to negotiate the
622 // specifed TLS version rather than the version supported by either
623 // peer.
624 NegotiateVersion uint16
625
626 // NegotiateVersionOnRenego, if non-zero, causes the server to negotiate
627 // the specified TLS version on renegotiation rather than retaining it.
628 NegotiateVersionOnRenego uint16
629
Adam Langleyd9e397b2015-01-22 14:27:53 -0800630 // ExpectFalseStart causes the server to, on full handshakes,
631 // expect the peer to False Start; the server Finished message
632 // isn't sent until we receive an application data record
633 // from the peer.
634 ExpectFalseStart bool
635
Adam Langleye9ada862015-05-11 17:20:37 -0700636 // AlertBeforeFalseStartTest, if non-zero, causes the server to, on full
637 // handshakes, send an alert just before reading the application data
638 // record to test False Start. This can be used in a negative False
639 // Start test to determine whether the peer processed the alert (and
640 // closed the connection) before or after sending app data.
641 AlertBeforeFalseStartTest alert
642
Adam Langleyd9e397b2015-01-22 14:27:53 -0800643 // ExpectServerName, if not empty, is the hostname the client
644 // must specify in the server_name extension.
645 ExpectServerName string
646
Kenny Rootb8494592015-09-25 02:29:14 +0000647 // SwapNPNAndALPN switches the relative order between NPN and ALPN in
648 // both ClientHello and ServerHello.
Adam Langleyd9e397b2015-01-22 14:27:53 -0800649 SwapNPNAndALPN bool
650
Kenny Rootb8494592015-09-25 02:29:14 +0000651 // ALPNProtocol, if not nil, sets the ALPN protocol that a server will
652 // return.
653 ALPNProtocol *string
654
David Benjaminf0c4a6c2016-08-11 13:26:41 -0400655 // AcceptAnySession causes the server to resume sessions regardless of
656 // the version associated with the session or cipher suite. It also
657 // causes the server to look in both TLS 1.2 and 1.3 extensions to
658 // process a ticket.
659 AcceptAnySession bool
660
661 // SendBothTickets, if true, causes the client to send tickets in both
662 // TLS 1.2 and 1.3 extensions.
663 SendBothTickets bool
Adam Langleyd9e397b2015-01-22 14:27:53 -0800664
Steven Valdez909b19f2016-11-21 15:35:44 -0500665 // FilterTicket, if not nil, causes the client to modify a session
666 // ticket before sending it in a resume handshake.
667 FilterTicket func([]byte) ([]byte, error)
Adam Langleyd9e397b2015-01-22 14:27:53 -0800668
Robert Sloan5d625782017-02-13 09:55:39 -0800669 // TicketSessionIDLength, if non-zero, is the length of the session ID
670 // to send with a ticket resumption offer.
671 TicketSessionIDLength int
672
673 // EmptyTicketSessionID, if true, causes the client to send an empty
674 // session ID with a ticket resumption offer. For simplicity, this will
675 // also cause the client to interpret a ServerHello with empty session
676 // ID as a resumption. (A client which sends empty session ID is
677 // normally expected to look ahead for ChangeCipherSpec.)
678 EmptyTicketSessionID bool
Adam Langleyd9e397b2015-01-22 14:27:53 -0800679
David Benjaminf0c4a6c2016-08-11 13:26:41 -0400680 // ExpectNoTLS12Session, if true, causes the server to fail the
681 // connection if either a session ID or TLS 1.2 ticket is offered.
682 ExpectNoTLS12Session bool
683
684 // ExpectNoTLS13PSK, if true, causes the server to fail the connection
685 // if a TLS 1.3 PSK is offered.
686 ExpectNoTLS13PSK bool
687
Adam Langleyd9e397b2015-01-22 14:27:53 -0800688 // RequireExtendedMasterSecret, if true, requires that the peer support
689 // the extended master secret option.
690 RequireExtendedMasterSecret bool
691
692 // NoExtendedMasterSecret causes the client and server to behave as if
David Benjaminf0c4a6c2016-08-11 13:26:41 -0400693 // they didn't support an extended master secret in the initial
694 // handshake.
Adam Langleyd9e397b2015-01-22 14:27:53 -0800695 NoExtendedMasterSecret bool
696
David Benjaminf0c4a6c2016-08-11 13:26:41 -0400697 // NoExtendedMasterSecretOnRenegotiation causes the client and server to
698 // behave as if they didn't support an extended master secret in
699 // renegotiation handshakes.
700 NoExtendedMasterSecretOnRenegotiation bool
701
Adam Langleyd9e397b2015-01-22 14:27:53 -0800702 // EmptyRenegotiationInfo causes the renegotiation extension to be
703 // empty in a renegotiation handshake.
704 EmptyRenegotiationInfo bool
705
706 // BadRenegotiationInfo causes the renegotiation extension value in a
707 // renegotiation handshake to be incorrect.
708 BadRenegotiationInfo bool
709
Adam Langley4139edb2016-01-13 15:00:54 -0800710 // NoRenegotiationInfo disables renegotiation info support in all
711 // handshakes.
Adam Langleyd9e397b2015-01-22 14:27:53 -0800712 NoRenegotiationInfo bool
713
Adam Langley4139edb2016-01-13 15:00:54 -0800714 // NoRenegotiationInfoInInitial disables renegotiation info support in
715 // the initial handshake.
716 NoRenegotiationInfoInInitial bool
717
718 // NoRenegotiationInfoAfterInitial disables renegotiation info support
719 // in renegotiation handshakes.
720 NoRenegotiationInfoAfterInitial bool
721
Kenny Rootb8494592015-09-25 02:29:14 +0000722 // RequireRenegotiationInfo, if true, causes the client to return an
723 // error if the server doesn't reply with the renegotiation extension.
724 RequireRenegotiationInfo bool
725
726 // SequenceNumberMapping, if non-nil, is the mapping function to apply
727 // to the sequence number of outgoing packets. For both TLS and DTLS,
728 // the two most-significant bytes in the resulting sequence number are
729 // ignored so that the DTLS epoch cannot be changed.
730 SequenceNumberMapping func(uint64) uint64
Adam Langleyd9e397b2015-01-22 14:27:53 -0800731
Adam Langleye9ada862015-05-11 17:20:37 -0700732 // RSAEphemeralKey, if true, causes the server to send a
733 // ServerKeyExchange message containing an ephemeral key (as in
734 // RSA_EXPORT) in the plain RSA key exchange.
735 RSAEphemeralKey bool
Adam Langleyd9e397b2015-01-22 14:27:53 -0800736
737 // SRTPMasterKeyIdentifer, if not empty, is the SRTP MKI value that the
738 // client offers when negotiating SRTP. MKI support is still missing so
739 // the peer must still send none.
740 SRTPMasterKeyIdentifer string
741
742 // SendSRTPProtectionProfile, if non-zero, is the SRTP profile that the
743 // server sends in the ServerHello instead of the negotiated one.
744 SendSRTPProtectionProfile uint16
745
David Benjaminc895d6b2016-08-11 13:26:41 -0400746 // NoSignatureAlgorithms, if true, causes the client to omit the
Adam Langleyd9e397b2015-01-22 14:27:53 -0800747 // signature and hashes extension.
748 //
749 // For a server, it will cause an empty list to be sent in the
750 // CertificateRequest message. None the less, the configured set will
751 // still be enforced.
David Benjaminc895d6b2016-08-11 13:26:41 -0400752 NoSignatureAlgorithms bool
Adam Langleyd9e397b2015-01-22 14:27:53 -0800753
Adam Langleye9ada862015-05-11 17:20:37 -0700754 // NoSupportedCurves, if true, causes the client to omit the
755 // supported_curves extension.
756 NoSupportedCurves bool
757
Adam Langleyd9e397b2015-01-22 14:27:53 -0800758 // RequireSameRenegoClientVersion, if true, causes the server
759 // to require that all ClientHellos match in offered version
760 // across a renego.
761 RequireSameRenegoClientVersion bool
762
Steven Valdezbb1ceac2016-10-07 10:34:51 -0400763 // ExpectInitialRecordVersion, if non-zero, is the expected value of
Steven Valdez909b19f2016-11-21 15:35:44 -0500764 // record-layer version field before the protocol version is determined.
Adam Langleyd9e397b2015-01-22 14:27:53 -0800765 ExpectInitialRecordVersion uint16
766
Steven Valdez909b19f2016-11-21 15:35:44 -0500767 // SendRecordVersion, if non-zero, is the value to send as the
768 // record-layer version.
769 SendRecordVersion uint16
770
771 // SendInitialRecordVersion, if non-zero, is the value to send as the
772 // record-layer version before the protocol version is determined.
773 SendInitialRecordVersion uint16
774
Adam Langleyd9e397b2015-01-22 14:27:53 -0800775 // MaxPacketLength, if non-zero, is the maximum acceptable size for a
776 // packet.
777 MaxPacketLength int
778
779 // SendCipherSuite, if non-zero, is the cipher suite value that the
780 // server will send in the ServerHello. This does not affect the cipher
781 // the server believes it has actually negotiated.
782 SendCipherSuite uint16
783
Steven Valdez909b19f2016-11-21 15:35:44 -0500784 // SendCipherSuites, if not nil, is the cipher suite list that the
785 // client will send in the ClientHello. This does not affect the cipher
786 // the client believes it has actually offered.
787 SendCipherSuites []uint16
788
Kenny Rootb8494592015-09-25 02:29:14 +0000789 // AppDataBeforeHandshake, if not nil, causes application data to be
790 // sent immediately before the first handshake message.
791 AppDataBeforeHandshake []byte
792
793 // AppDataAfterChangeCipherSpec, if not nil, causes application data to
Adam Langleyd9e397b2015-01-22 14:27:53 -0800794 // be sent immediately after ChangeCipherSpec.
795 AppDataAfterChangeCipherSpec []byte
Adam Langleye9ada862015-05-11 17:20:37 -0700796
797 // AlertAfterChangeCipherSpec, if non-zero, causes an alert to be sent
798 // immediately after ChangeCipherSpec.
799 AlertAfterChangeCipherSpec alert
800
801 // TimeoutSchedule is the schedule of packet drops and simulated
802 // timeouts for before each handshake leg from the peer.
803 TimeoutSchedule []time.Duration
804
805 // PacketAdaptor is the packetAdaptor to use to simulate timeouts.
806 PacketAdaptor *packetAdaptor
807
808 // ReorderHandshakeFragments, if true, causes handshake fragments in
809 // DTLS to overlap and be sent in the wrong order. It also causes
810 // pre-CCS flights to be sent twice. (Post-CCS flights consist of
811 // Finished and will trigger a spurious retransmit.)
812 ReorderHandshakeFragments bool
813
David Benjaminc895d6b2016-08-11 13:26:41 -0400814 // ReverseHandshakeFragments, if true, causes handshake fragments in
815 // DTLS to be reversed within a flight.
816 ReverseHandshakeFragments bool
817
Adam Langleye9ada862015-05-11 17:20:37 -0700818 // MixCompleteMessageWithFragments, if true, causes handshake
819 // messages in DTLS to redundantly both fragment the message
820 // and include a copy of the full one.
821 MixCompleteMessageWithFragments bool
822
823 // SendInvalidRecordType, if true, causes a record with an invalid
824 // content type to be sent immediately following the handshake.
825 SendInvalidRecordType bool
826
David Benjaminc895d6b2016-08-11 13:26:41 -0400827 // SendWrongMessageType, if non-zero, causes messages of the specified
828 // type to be sent with the wrong value.
829 SendWrongMessageType byte
Adam Langleye9ada862015-05-11 17:20:37 -0700830
David Benjamin7c0d06c2016-08-11 13:26:41 -0400831 // SendTrailingMessageData, if non-zero, causes messages of the
832 // specified type to be sent with trailing data.
833 SendTrailingMessageData byte
834
Adam Langleye9ada862015-05-11 17:20:37 -0700835 // FragmentMessageTypeMismatch, if true, causes all non-initial
836 // handshake fragments in DTLS to have the wrong message type.
837 FragmentMessageTypeMismatch bool
838
839 // FragmentMessageLengthMismatch, if true, causes all non-initial
840 // handshake fragments in DTLS to have the wrong message length.
841 FragmentMessageLengthMismatch bool
842
Kenny Rootb8494592015-09-25 02:29:14 +0000843 // SplitFragments, if non-zero, causes the handshake fragments in DTLS
844 // to be split across two records. The value of |SplitFragments| is the
845 // number of bytes in the first fragment.
846 SplitFragments int
Adam Langleye9ada862015-05-11 17:20:37 -0700847
848 // SendEmptyFragments, if true, causes handshakes to include empty
849 // fragments in DTLS.
850 SendEmptyFragments bool
851
Adam Langleyf4e42722015-06-04 17:45:09 -0700852 // SendSplitAlert, if true, causes an alert to be sent with the header
853 // and record body split across multiple packets. The peer should
854 // discard these packets rather than process it.
855 SendSplitAlert bool
Adam Langleye9ada862015-05-11 17:20:37 -0700856
Adam Langleyf4e42722015-06-04 17:45:09 -0700857 // FailIfResumeOnRenego, if true, causes renegotiations to fail if the
858 // client offers a resumption or the server accepts one.
859 FailIfResumeOnRenego bool
Adam Langleye9ada862015-05-11 17:20:37 -0700860
861 // IgnorePeerCipherPreferences, if true, causes the peer's cipher
862 // preferences to be ignored.
863 IgnorePeerCipherPreferences bool
864
865 // IgnorePeerSignatureAlgorithmPreferences, if true, causes the peer's
866 // signature algorithm preferences to be ignored.
867 IgnorePeerSignatureAlgorithmPreferences bool
868
869 // IgnorePeerCurvePreferences, if true, causes the peer's curve
870 // preferences to be ignored.
871 IgnorePeerCurvePreferences bool
872
Adam Langleye9ada862015-05-11 17:20:37 -0700873 // BadFinished, if true, causes the Finished hash to be broken.
874 BadFinished bool
Adam Langleyf4e42722015-06-04 17:45:09 -0700875
876 // DHGroupPrime, if not nil, is used to define the (finite field)
877 // Diffie-Hellman group. The generator used is always two.
878 DHGroupPrime *big.Int
879
David Benjaminc895d6b2016-08-11 13:26:41 -0400880 // PackHandshakeFragments, if true, causes handshake fragments in DTLS
881 // to be packed into individual handshake records, up to the specified
882 // record size.
Adam Langleyf4e42722015-06-04 17:45:09 -0700883 PackHandshakeFragments int
884
David Benjaminc895d6b2016-08-11 13:26:41 -0400885 // PackHandshakeRecords, if true, causes handshake records in DTLS to be
886 // packed into individual packets, up to the specified packet size.
Adam Langleyf4e42722015-06-04 17:45:09 -0700887 PackHandshakeRecords int
888
David Benjaminc895d6b2016-08-11 13:26:41 -0400889 // PackHandshakeFlight, if true, causes each handshake flight in TLS to
890 // be packed into records, up to the largest size record available.
891 PackHandshakeFlight bool
892
Steven Valdezbb1ceac2016-10-07 10:34:51 -0400893 // AdvertiseAllConfiguredCiphers, if true, causes the client to
894 // advertise all configured cipher suite values.
895 AdvertiseAllConfiguredCiphers bool
Kenny Rootb8494592015-09-25 02:29:14 +0000896
897 // EmptyCertificateList, if true, causes the server to send an empty
898 // certificate list in the Certificate message.
899 EmptyCertificateList bool
900
901 // ExpectNewTicket, if true, causes the client to abort if it does not
902 // receive a new ticket.
903 ExpectNewTicket bool
904
905 // RequireClientHelloSize, if not zero, is the required length in bytes
906 // of the ClientHello /record/. This is checked by the server.
907 RequireClientHelloSize int
908
909 // CustomExtension, if not empty, contains the contents of an extension
910 // that will be added to client/server hellos.
911 CustomExtension string
912
David Benjamin95add822016-10-19 01:09:12 -0400913 // CustomUnencryptedExtension, if not empty, contains the contents of
914 // an extension that will be added to ServerHello in TLS 1.3.
915 CustomUnencryptedExtension string
916
Kenny Rootb8494592015-09-25 02:29:14 +0000917 // ExpectedCustomExtension, if not nil, contains the expected contents
918 // of a custom extension.
919 ExpectedCustomExtension *string
920
David Benjamin95add822016-10-19 01:09:12 -0400921 // CustomTicketExtension, if not empty, contains the contents of an
922 // extension what will be added to NewSessionTicket in TLS 1.3.
923 CustomTicketExtension string
924
925 // CustomTicketExtension, if not empty, contains the contents of an
926 // extension what will be added to HelloRetryRequest in TLS 1.3.
927 CustomHelloRetryRequestExtension string
928
Kenny Rootb8494592015-09-25 02:29:14 +0000929 // NoCloseNotify, if true, causes the close_notify alert to be skipped
930 // on connection shutdown.
931 NoCloseNotify bool
932
David Benjamind316cba2016-06-02 16:17:39 -0400933 // SendAlertOnShutdown, if non-zero, is the alert to send instead of
934 // close_notify on shutdown.
935 SendAlertOnShutdown alert
936
Kenny Rootb8494592015-09-25 02:29:14 +0000937 // ExpectCloseNotify, if true, requires a close_notify from the peer on
938 // shutdown. Records from the peer received after close_notify is sent
939 // are not discard.
940 ExpectCloseNotify bool
941
942 // SendLargeRecords, if true, allows outgoing records to be sent
943 // arbitrarily large.
944 SendLargeRecords bool
945
946 // NegotiateALPNAndNPN, if true, causes the server to negotiate both
947 // ALPN and NPN in the same connetion.
948 NegotiateALPNAndNPN bool
Kenny Roote99801b2015-11-06 15:31:15 -0800949
David Benjaminc895d6b2016-08-11 13:26:41 -0400950 // SendALPN, if non-empty, causes the server to send the specified
951 // string in the ALPN extension regardless of the content or presence of
952 // the client offer.
953 SendALPN string
954
David Benjamin95add822016-10-19 01:09:12 -0400955 // SendUnencryptedALPN, if non-empty, causes the server to send the
956 // specified string in a ServerHello ALPN extension in TLS 1.3.
957 SendUnencryptedALPN string
958
Kenny Roote99801b2015-11-06 15:31:15 -0800959 // SendEmptySessionTicket, if true, causes the server to send an empty
960 // session ticket.
961 SendEmptySessionTicket bool
962
Steven Valdez909b19f2016-11-21 15:35:44 -0500963 // SendPSKKeyExchangeModes, if present, determines the PSK key exchange modes
Steven Valdezbb1ceac2016-10-07 10:34:51 -0400964 // to send.
965 SendPSKKeyExchangeModes []byte
966
Steven Valdez909b19f2016-11-21 15:35:44 -0500967 // ExpectNoNewSessionTicket, if present, means that the client will fail upon
968 // receipt of a NewSessionTicket message.
969 ExpectNoNewSessionTicket bool
970
Robert Sloan69939df2017-01-09 10:53:07 -0800971 // DuplicateTicketEarlyDataInfo causes an extra empty extension of
972 // ticket_early_data_info to be sent in NewSessionTicket.
973 DuplicateTicketEarlyDataInfo bool
974
975 // ExpectTicketEarlyDataInfo, if true, means that the client will fail upon
976 // absence of the ticket_early_data_info extension.
977 ExpectTicketEarlyDataInfo bool
978
Steven Valdez909b19f2016-11-21 15:35:44 -0500979 // ExpectTicketAge, if non-zero, is the expected age of the ticket that the
980 // server receives from the client.
981 ExpectTicketAge time.Duration
Steven Valdezbb1ceac2016-10-07 10:34:51 -0400982
Kenny Roote99801b2015-11-06 15:31:15 -0800983 // FailIfSessionOffered, if true, causes the server to fail any
984 // connections where the client offers a non-empty session ID or session
985 // ticket.
986 FailIfSessionOffered bool
Adam Langleyfad63272015-11-12 12:15:39 -0800987
988 // SendHelloRequestBeforeEveryAppDataRecord, if true, causes a
989 // HelloRequest handshake message to be sent before each application
990 // data record. This only makes sense for a server.
991 SendHelloRequestBeforeEveryAppDataRecord bool
Adam Langley4139edb2016-01-13 15:00:54 -0800992
David Benjaminc895d6b2016-08-11 13:26:41 -0400993 // SendHelloRequestBeforeEveryHandshakeMessage, if true, causes a
994 // HelloRequest handshake message to be sent before each handshake
995 // message. This only makes sense for a server.
996 SendHelloRequestBeforeEveryHandshakeMessage bool
997
Adam Langley4139edb2016-01-13 15:00:54 -0800998 // RequireDHPublicValueLen causes a fatal error if the length (in
999 // bytes) of the server's Diffie-Hellman public value is not equal to
1000 // this.
1001 RequireDHPublicValueLen int
1002
1003 // BadChangeCipherSpec, if not nil, is the body to be sent in
1004 // ChangeCipherSpec records instead of {1}.
1005 BadChangeCipherSpec []byte
1006
1007 // BadHelloRequest, if not nil, is what to send instead of a
1008 // HelloRequest.
1009 BadHelloRequest []byte
David Benjamin4969cc92016-04-22 15:02:23 -04001010
1011 // RequireSessionTickets, if true, causes the client to require new
1012 // sessions use session tickets instead of session IDs.
1013 RequireSessionTickets bool
1014
1015 // NullAllCiphers, if true, causes every cipher to behave like the null
1016 // cipher.
1017 NullAllCiphers bool
David Benjamind316cba2016-06-02 16:17:39 -04001018
1019 // SendSCTListOnResume, if not nil, causes the server to send the
1020 // supplied SCT list in resumption handshakes.
1021 SendSCTListOnResume []byte
David Benjaminc895d6b2016-08-11 13:26:41 -04001022
Steven Valdezbb1ceac2016-10-07 10:34:51 -04001023 // SendOCSPResponseOnResume, if not nil, causes the server to advertise
1024 // OCSP stapling in resumption handshakes and, if applicable, send the
1025 // supplied stapled response.
1026 SendOCSPResponseOnResume []byte
1027
Steven Valdez909b19f2016-11-21 15:35:44 -05001028 // SendExtensionOnCertificate, if not nil, causes the runner to send the
1029 // supplied bytes in the extensions on the Certificate message.
1030 SendExtensionOnCertificate []byte
1031
1032 // SendOCSPOnIntermediates, if not nil, causes the server to send the
1033 // supplied OCSP on intermediate certificates in the Certificate message.
1034 SendOCSPOnIntermediates []byte
1035
1036 // SendSCTOnIntermediates, if not nil, causes the server to send the
1037 // supplied SCT on intermediate certificates in the Certificate message.
1038 SendSCTOnIntermediates []byte
1039
1040 // SendDuplicateCertExtensions, if true, causes the server to send an extra
1041 // copy of the OCSP/SCT extensions in the Certificate message.
1042 SendDuplicateCertExtensions bool
1043
1044 // ExpectNoExtensionsOnIntermediate, if true, causes the client to
1045 // reject extensions on intermediate certificates.
1046 ExpectNoExtensionsOnIntermediate bool
1047
David Benjaminc895d6b2016-08-11 13:26:41 -04001048 // RecordPadding is the number of bytes of padding to add to each
1049 // encrypted record in TLS 1.3.
1050 RecordPadding int
1051
1052 // OmitRecordContents, if true, causes encrypted records in TLS 1.3 to
1053 // be missing their body and content type. Padding, if configured, is
1054 // still added.
1055 OmitRecordContents bool
1056
1057 // OuterRecordType, if non-zero, is the outer record type to use instead
1058 // of application data.
1059 OuterRecordType recordType
1060
1061 // SendSignatureAlgorithm, if non-zero, causes all signatures to be sent
1062 // with the given signature algorithm rather than the one negotiated.
1063 SendSignatureAlgorithm signatureAlgorithm
1064
1065 // SkipECDSACurveCheck, if true, causes all ECDSA curve checks to be
1066 // skipped.
1067 SkipECDSACurveCheck bool
1068
1069 // IgnoreSignatureVersionChecks, if true, causes all signature
1070 // algorithms to be enabled at all TLS versions.
1071 IgnoreSignatureVersionChecks bool
1072
1073 // NegotiateRenegotiationInfoAtAllVersions, if true, causes
1074 // Renegotiation Info to be negotiated at all versions.
1075 NegotiateRenegotiationInfoAtAllVersions bool
1076
David Benjaminc895d6b2016-08-11 13:26:41 -04001077 // NegotiateNPNAtAllVersions, if true, causes NPN to be negotiated at
1078 // all versions.
1079 NegotiateNPNAtAllVersions bool
1080
1081 // NegotiateEMSAtAllVersions, if true, causes EMS to be negotiated at
1082 // all versions.
1083 NegotiateEMSAtAllVersions bool
1084
1085 // AdvertiseTicketExtension, if true, causes the ticket extension to be
1086 // advertised in server extensions
1087 AdvertiseTicketExtension bool
1088
Steven Valdezbb1ceac2016-10-07 10:34:51 -04001089 // NegotiatePSKResumption, if true, causes the server to attempt pure PSK
1090 // resumption.
1091 NegotiatePSKResumption bool
1092
1093 // AlwaysSelectPSKIdentity, if true, causes the server in TLS 1.3 to
1094 // always acknowledge a session, regardless of one was offered.
1095 AlwaysSelectPSKIdentity bool
1096
1097 // SelectPSKIdentityOnResume, if non-zero, causes the server to select
1098 // the specified PSK identity index rather than the actual value.
1099 SelectPSKIdentityOnResume uint16
1100
Steven Valdez909b19f2016-11-21 15:35:44 -05001101 // ExtraPSKIdentity, if true, causes the client to send an extra PSK
1102 // identity.
1103 ExtraPSKIdentity bool
Steven Valdezbb1ceac2016-10-07 10:34:51 -04001104
David Benjaminc895d6b2016-08-11 13:26:41 -04001105 // MissingKeyShare, if true, causes the TLS 1.3 implementation to skip
1106 // sending a key_share extension and use the zero ECDHE secret
1107 // instead.
1108 MissingKeyShare bool
1109
1110 // SecondClientHelloMissingKeyShare, if true, causes the second TLS 1.3
1111 // ClientHello to skip sending a key_share extension and use the zero
1112 // ECDHE secret instead.
1113 SecondClientHelloMissingKeyShare bool
1114
1115 // MisinterpretHelloRetryRequestCurve, if non-zero, causes the TLS 1.3
1116 // client to pretend the server requested a HelloRetryRequest with the
1117 // given curve rather than the actual one.
1118 MisinterpretHelloRetryRequestCurve CurveID
1119
1120 // DuplicateKeyShares, if true, causes the TLS 1.3 client to send two
1121 // copies of each KeyShareEntry.
1122 DuplicateKeyShares bool
1123
David Benjamin1b249672016-12-06 18:25:50 -05001124 // SendEarlyAlert, if true, sends a fatal alert after the ClientHello.
1125 SendEarlyAlert bool
1126
Robert Sloan47f43ed2017-02-06 14:55:15 -08001127 // SendFakeEarlyDataLength, if non-zero, is the amount of early data to
1128 // send after the ClientHello.
1129 SendFakeEarlyDataLength int
David Benjamin1b249672016-12-06 18:25:50 -05001130
1131 // OmitEarlyDataExtension, if true, causes the early data extension to
1132 // be omitted in the ClientHello.
1133 OmitEarlyDataExtension bool
1134
1135 // SendEarlyDataOnSecondClientHello, if true, causes the TLS 1.3 client to
1136 // send early data after the second ClientHello.
1137 SendEarlyDataOnSecondClientHello bool
1138
1139 // InterleaveEarlyData, if true, causes the TLS 1.3 client to send early
1140 // data interleaved with the second ClientHello and the client Finished.
1141 InterleaveEarlyData bool
1142
Robert Sloan47f43ed2017-02-06 14:55:15 -08001143 // SendEarlyData causes a TLS 1.3 client to send the provided data
1144 // in application data records immediately after the ClientHello,
1145 // provided that the client has a PSK that is appropriate for sending
1146 // early data and includes that PSK in its ClientHello.
1147 SendEarlyData [][]byte
1148
1149 // ExpectEarlyData causes a TLS 1.3 server to read application
1150 // data after the ClientHello (assuming the server is able to
1151 // derive the key under which the data is encrypted) before it
1152 // sends a ServerHello. It checks that the application data it
1153 // reads matches what is provided in ExpectEarlyData and errors if
1154 // the number of records or their content do not match.
1155 ExpectEarlyData [][]byte
1156
Robert Sloan4d1ac502017-02-06 08:36:14 -08001157 // SendHalfRTTData causes a TLS 1.3 server to send the provided
1158 // data in application data records before reading the client's
1159 // Finished message.
1160 SendHalfRTTData [][]byte
1161
1162 // ExpectHalfRTTData causes a TLS 1.3 client to read application
1163 // data after reading the server's Finished message and before
1164 // sending any other handshake messages. It checks that the
1165 // application data it reads matches what is provided in
1166 // ExpectHalfRTTData and errors if the number of records or their
1167 // content do not match.
1168 ExpectHalfRTTData [][]byte
1169
David Benjaminc895d6b2016-08-11 13:26:41 -04001170 // EmptyEncryptedExtensions, if true, causes the TLS 1.3 server to
1171 // emit an empty EncryptedExtensions block.
1172 EmptyEncryptedExtensions bool
1173
1174 // EncryptedExtensionsWithKeyShare, if true, causes the TLS 1.3 server to
1175 // include the KeyShare extension in the EncryptedExtensions block.
1176 EncryptedExtensionsWithKeyShare bool
1177
David Benjamin95add822016-10-19 01:09:12 -04001178 // AlwaysSendHelloRetryRequest, if true, causes a HelloRetryRequest to
1179 // be sent by the server, even if empty.
1180 AlwaysSendHelloRetryRequest bool
David Benjaminc895d6b2016-08-11 13:26:41 -04001181
1182 // SecondHelloRetryRequest, if true, causes the TLS 1.3 server to send
1183 // two HelloRetryRequests instead of one.
1184 SecondHelloRetryRequest bool
1185
David Benjamin95add822016-10-19 01:09:12 -04001186 // SendHelloRetryRequestCurve, if non-zero, causes the server to send
1187 // the specified curve in a HelloRetryRequest.
1188 SendHelloRetryRequestCurve CurveID
1189
1190 // SendHelloRetryRequestCookie, if not nil, contains a cookie to be
1191 // sent by the server in HelloRetryRequest.
1192 SendHelloRetryRequestCookie []byte
1193
1194 // DuplicateHelloRetryRequestExtensions, if true, causes all
1195 // HelloRetryRequest extensions to be sent twice.
1196 DuplicateHelloRetryRequestExtensions bool
1197
David Benjaminc895d6b2016-08-11 13:26:41 -04001198 // SendServerHelloVersion, if non-zero, causes the server to send the
Steven Valdezbb1ceac2016-10-07 10:34:51 -04001199 // specified value in ServerHello version field.
David Benjaminc895d6b2016-08-11 13:26:41 -04001200 SendServerHelloVersion uint16
1201
1202 // SkipHelloRetryRequest, if true, causes the TLS 1.3 server to not send
1203 // HelloRetryRequest.
1204 SkipHelloRetryRequest bool
1205
1206 // PackHelloRequestWithFinished, if true, causes the TLS server to send
1207 // HelloRequest in the same record as Finished.
1208 PackHelloRequestWithFinished bool
1209
David Benjaminf0c4a6c2016-08-11 13:26:41 -04001210 // ExpectMissingKeyShare, if true, causes the TLS server to fail the
1211 // connection if the selected curve appears in the client's initial
1212 // ClientHello. That is, it requires that a HelloRetryRequest be sent.
1213 ExpectMissingKeyShare bool
1214
David Benjaminc895d6b2016-08-11 13:26:41 -04001215 // SendExtraFinished, if true, causes an extra Finished message to be
1216 // sent.
1217 SendExtraFinished bool
David Benjaminf0c4a6c2016-08-11 13:26:41 -04001218
1219 // SendRequestContext, if not empty, is the request context to send in
1220 // a TLS 1.3 CertificateRequest.
1221 SendRequestContext []byte
1222
1223 // SendSNIWarningAlert, if true, causes the server to send an
1224 // unrecognized_name alert before the ServerHello.
1225 SendSNIWarningAlert bool
1226
1227 // SendCompressionMethods, if not nil, is the compression method list to
1228 // send in the ClientHello.
1229 SendCompressionMethods []byte
David Benjamin7c0d06c2016-08-11 13:26:41 -04001230
1231 // AlwaysSendPreSharedKeyIdentityHint, if true, causes the server to
1232 // always send a ServerKeyExchange for PSK ciphers, even if the identity
1233 // hint is empty.
1234 AlwaysSendPreSharedKeyIdentityHint bool
1235
1236 // TrailingKeyShareData, if true, causes the client key share list to
1237 // include a trailing byte.
1238 TrailingKeyShareData bool
Steven Valdezbb1ceac2016-10-07 10:34:51 -04001239
1240 // InvalidChannelIDSignature, if true, causes the client to generate an
1241 // invalid Channel ID signature.
1242 InvalidChannelIDSignature bool
1243
David Benjamin95add822016-10-19 01:09:12 -04001244 // ExpectGREASE, if true, causes messages without GREASE values to be
1245 // rejected. See draft-davidben-tls-grease-01.
Steven Valdezbb1ceac2016-10-07 10:34:51 -04001246 ExpectGREASE bool
Steven Valdez909b19f2016-11-21 15:35:44 -05001247
1248 // SendShortPSKBinder, if true, causes the client to send a PSK binder
1249 // that is one byte shorter than it should be.
1250 SendShortPSKBinder bool
1251
1252 // SendInvalidPSKBinder, if true, causes the client to send an invalid
1253 // PSK binder.
1254 SendInvalidPSKBinder bool
1255
1256 // SendNoPSKBinder, if true, causes the client to send no PSK binders.
1257 SendNoPSKBinder bool
1258
David Benjamin1b249672016-12-06 18:25:50 -05001259 // SendExtraPSKBinder, if true, causes the client to send an extra PSK
1260 // binder.
1261 SendExtraPSKBinder bool
1262
Steven Valdez909b19f2016-11-21 15:35:44 -05001263 // PSKBinderFirst, if true, causes the client to send the PSK Binder
1264 // extension as the first extension instead of the last extension.
1265 PSKBinderFirst bool
1266
1267 // NoOCSPStapling, if true, causes the client to not request OCSP
1268 // stapling.
1269 NoOCSPStapling bool
1270
1271 // NoSignedCertificateTimestamps, if true, causes the client to not
1272 // request signed certificate timestamps.
1273 NoSignedCertificateTimestamps bool
Robert Sloan69939df2017-01-09 10:53:07 -08001274
Robert Sloan69939df2017-01-09 10:53:07 -08001275 // SendSupportedPointFormats, if not nil, is the list of supported point
1276 // formats to send in ClientHello or ServerHello. If set to a non-nil
1277 // empty slice, no extension will be sent.
1278 SendSupportedPointFormats []byte
Steven Valdezb0b45c62017-01-17 16:23:54 -05001279
1280 // MaxReceivePlaintext, if non-zero, is the maximum plaintext record
1281 // length accepted from the peer.
1282 MaxReceivePlaintext int
Robert Sloan4d1ac502017-02-06 08:36:14 -08001283
1284 // SendTicketLifetime, if non-zero, is the ticket lifetime to send in
1285 // NewSessionTicket messages.
1286 SendTicketLifetime time.Duration
Robert Sloan5d625782017-02-13 09:55:39 -08001287
1288 // SendServerNameAck, if true, causes the server to acknowledge the SNI
1289 // extension.
1290 SendServerNameAck bool
Robert Sloan7d422bc2017-03-06 10:04:29 -08001291
1292 // ExpectCertificateReqNames, if not nil, contains the list of X.509
1293 // names that must be sent in a CertificateRequest from the server.
1294 ExpectCertificateReqNames [][]byte
1295
1296 // RenegotiationCertificate, if not nil, is the certificate to use on
1297 // renegotiation handshakes.
1298 RenegotiationCertificate *Certificate
Adam Langleyd9e397b2015-01-22 14:27:53 -08001299}
1300
1301func (c *Config) serverInit() {
1302 if c.SessionTicketsDisabled {
1303 return
1304 }
1305
1306 // If the key has already been set then we have nothing to do.
1307 for _, b := range c.SessionTicketKey {
1308 if b != 0 {
1309 return
1310 }
1311 }
1312
1313 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
1314 c.SessionTicketsDisabled = true
1315 }
1316}
1317
1318func (c *Config) rand() io.Reader {
1319 r := c.Rand
1320 if r == nil {
1321 return rand.Reader
1322 }
1323 return r
1324}
1325
1326func (c *Config) time() time.Time {
1327 t := c.Time
1328 if t == nil {
1329 t = time.Now
1330 }
1331 return t()
1332}
1333
1334func (c *Config) cipherSuites() []uint16 {
1335 s := c.CipherSuites
1336 if s == nil {
1337 s = defaultCipherSuites()
1338 }
1339 return s
1340}
1341
David Benjaminc895d6b2016-08-11 13:26:41 -04001342func (c *Config) minVersion(isDTLS bool) uint16 {
1343 ret := uint16(minVersion)
1344 if c != nil && c.MinVersion != 0 {
1345 ret = c.MinVersion
Adam Langleyd9e397b2015-01-22 14:27:53 -08001346 }
David Benjaminc895d6b2016-08-11 13:26:41 -04001347 if isDTLS {
1348 // The lowest version of DTLS is 1.0. There is no DSSL 3.0.
1349 if ret < VersionTLS10 {
1350 return VersionTLS10
1351 }
1352 // There is no such thing as DTLS 1.1.
1353 if ret == VersionTLS11 {
1354 return VersionTLS12
1355 }
1356 }
1357 return ret
Adam Langleyd9e397b2015-01-22 14:27:53 -08001358}
1359
David Benjaminc895d6b2016-08-11 13:26:41 -04001360func (c *Config) maxVersion(isDTLS bool) uint16 {
1361 ret := uint16(maxVersion)
1362 if c != nil && c.MaxVersion != 0 {
1363 ret = c.MaxVersion
Adam Langleyd9e397b2015-01-22 14:27:53 -08001364 }
David Benjaminc895d6b2016-08-11 13:26:41 -04001365 if isDTLS {
1366 // We only implement up to DTLS 1.2.
1367 if ret > VersionTLS12 {
1368 return VersionTLS12
1369 }
1370 // There is no such thing as DTLS 1.1.
1371 if ret == VersionTLS11 {
1372 return VersionTLS10
1373 }
1374 }
1375 return ret
Adam Langleyd9e397b2015-01-22 14:27:53 -08001376}
1377
Adam Langley4139edb2016-01-13 15:00:54 -08001378var defaultCurvePreferences = []CurveID{CurveX25519, CurveP256, CurveP384, CurveP521}
Adam Langleyd9e397b2015-01-22 14:27:53 -08001379
1380func (c *Config) curvePreferences() []CurveID {
1381 if c == nil || len(c.CurvePreferences) == 0 {
1382 return defaultCurvePreferences
1383 }
1384 return c.CurvePreferences
1385}
1386
David Benjaminc895d6b2016-08-11 13:26:41 -04001387func (c *Config) defaultCurves() map[CurveID]bool {
1388 defaultCurves := make(map[CurveID]bool)
1389 curves := c.DefaultCurves
1390 if c == nil || c.DefaultCurves == nil {
1391 curves = c.curvePreferences()
1392 }
1393 for _, curveID := range curves {
1394 defaultCurves[curveID] = true
1395 }
1396 return defaultCurves
1397}
1398
Steven Valdezbb1ceac2016-10-07 10:34:51 -04001399// isSupportedVersion returns true if the specified protocol version is
1400// acceptable.
1401func (c *Config) isSupportedVersion(vers uint16, isDTLS bool) bool {
1402 return c.minVersion(isDTLS) <= vers && vers <= c.maxVersion(isDTLS)
Adam Langleyd9e397b2015-01-22 14:27:53 -08001403}
1404
1405// getCertificateForName returns the best certificate for the given name,
1406// defaulting to the first element of c.Certificates if there are no good
1407// options.
1408func (c *Config) getCertificateForName(name string) *Certificate {
1409 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
1410 // There's only one choice, so no point doing any work.
1411 return &c.Certificates[0]
1412 }
1413
1414 name = strings.ToLower(name)
1415 for len(name) > 0 && name[len(name)-1] == '.' {
1416 name = name[:len(name)-1]
1417 }
1418
1419 if cert, ok := c.NameToCertificate[name]; ok {
1420 return cert
1421 }
1422
1423 // try replacing labels in the name with wildcards until we get a
1424 // match.
1425 labels := strings.Split(name, ".")
1426 for i := range labels {
1427 labels[i] = "*"
1428 candidate := strings.Join(labels, ".")
1429 if cert, ok := c.NameToCertificate[candidate]; ok {
1430 return cert
1431 }
1432 }
1433
1434 // If nothing matches, return the first certificate.
1435 return &c.Certificates[0]
1436}
1437
David Benjaminc895d6b2016-08-11 13:26:41 -04001438func (c *Config) signSignatureAlgorithms() []signatureAlgorithm {
1439 if c != nil && c.SignSignatureAlgorithms != nil {
1440 return c.SignSignatureAlgorithms
Adam Langleyd9e397b2015-01-22 14:27:53 -08001441 }
David Benjaminc895d6b2016-08-11 13:26:41 -04001442 return supportedSignatureAlgorithms
Adam Langleyd9e397b2015-01-22 14:27:53 -08001443}
1444
David Benjaminc895d6b2016-08-11 13:26:41 -04001445func (c *Config) verifySignatureAlgorithms() []signatureAlgorithm {
1446 if c != nil && c.VerifySignatureAlgorithms != nil {
1447 return c.VerifySignatureAlgorithms
Adam Langleyd9e397b2015-01-22 14:27:53 -08001448 }
David Benjaminc895d6b2016-08-11 13:26:41 -04001449 return supportedSignatureAlgorithms
Adam Langleyd9e397b2015-01-22 14:27:53 -08001450}
1451
1452// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
1453// from the CommonName and SubjectAlternateName fields of each of the leaf
1454// certificates.
1455func (c *Config) BuildNameToCertificate() {
1456 c.NameToCertificate = make(map[string]*Certificate)
1457 for i := range c.Certificates {
1458 cert := &c.Certificates[i]
1459 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
1460 if err != nil {
1461 continue
1462 }
1463 if len(x509Cert.Subject.CommonName) > 0 {
1464 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
1465 }
1466 for _, san := range x509Cert.DNSNames {
1467 c.NameToCertificate[san] = cert
1468 }
1469 }
1470}
1471
1472// A Certificate is a chain of one or more certificates, leaf first.
1473type Certificate struct {
1474 Certificate [][]byte
1475 PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
1476 // OCSPStaple contains an optional OCSP response which will be served
1477 // to clients that request it.
1478 OCSPStaple []byte
1479 // SignedCertificateTimestampList contains an optional encoded
1480 // SignedCertificateTimestampList structure which will be
1481 // served to clients that request it.
1482 SignedCertificateTimestampList []byte
1483 // Leaf is the parsed form of the leaf certificate, which may be
1484 // initialized using x509.ParseCertificate to reduce per-handshake
1485 // processing for TLS clients doing client authentication. If nil, the
1486 // leaf certificate will be parsed as needed.
1487 Leaf *x509.Certificate
1488}
1489
1490// A TLS record.
1491type record struct {
1492 contentType recordType
1493 major, minor uint8
1494 payload []byte
1495}
1496
1497type handshakeMessage interface {
1498 marshal() []byte
1499 unmarshal([]byte) bool
1500}
1501
1502// lruSessionCache is a client or server session cache implementation
1503// that uses an LRU caching strategy.
1504type lruSessionCache struct {
1505 sync.Mutex
1506
1507 m map[string]*list.Element
1508 q *list.List
1509 capacity int
1510}
1511
1512type lruSessionCacheEntry struct {
1513 sessionKey string
1514 state interface{}
1515}
1516
1517// Put adds the provided (sessionKey, cs) pair to the cache.
1518func (c *lruSessionCache) Put(sessionKey string, cs interface{}) {
1519 c.Lock()
1520 defer c.Unlock()
1521
1522 if elem, ok := c.m[sessionKey]; ok {
1523 entry := elem.Value.(*lruSessionCacheEntry)
1524 entry.state = cs
1525 c.q.MoveToFront(elem)
1526 return
1527 }
1528
1529 if c.q.Len() < c.capacity {
1530 entry := &lruSessionCacheEntry{sessionKey, cs}
1531 c.m[sessionKey] = c.q.PushFront(entry)
1532 return
1533 }
1534
1535 elem := c.q.Back()
1536 entry := elem.Value.(*lruSessionCacheEntry)
1537 delete(c.m, entry.sessionKey)
1538 entry.sessionKey = sessionKey
1539 entry.state = cs
1540 c.q.MoveToFront(elem)
1541 c.m[sessionKey] = elem
1542}
1543
1544// Get returns the value associated with a given key. It returns (nil,
1545// false) if no value is found.
1546func (c *lruSessionCache) Get(sessionKey string) (interface{}, bool) {
1547 c.Lock()
1548 defer c.Unlock()
1549
1550 if elem, ok := c.m[sessionKey]; ok {
1551 c.q.MoveToFront(elem)
1552 return elem.Value.(*lruSessionCacheEntry).state, true
1553 }
1554 return nil, false
1555}
1556
1557// lruClientSessionCache is a ClientSessionCache implementation that
1558// uses an LRU caching strategy.
1559type lruClientSessionCache struct {
1560 lruSessionCache
1561}
1562
1563func (c *lruClientSessionCache) Put(sessionKey string, cs *ClientSessionState) {
1564 c.lruSessionCache.Put(sessionKey, cs)
1565}
1566
1567func (c *lruClientSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
1568 cs, ok := c.lruSessionCache.Get(sessionKey)
1569 if !ok {
1570 return nil, false
1571 }
1572 return cs.(*ClientSessionState), true
1573}
1574
1575// lruServerSessionCache is a ServerSessionCache implementation that
1576// uses an LRU caching strategy.
1577type lruServerSessionCache struct {
1578 lruSessionCache
1579}
1580
1581func (c *lruServerSessionCache) Put(sessionId string, session *sessionState) {
1582 c.lruSessionCache.Put(sessionId, session)
1583}
1584
1585func (c *lruServerSessionCache) Get(sessionId string) (*sessionState, bool) {
1586 cs, ok := c.lruSessionCache.Get(sessionId)
1587 if !ok {
1588 return nil, false
1589 }
1590 return cs.(*sessionState), true
1591}
1592
1593// NewLRUClientSessionCache returns a ClientSessionCache with the given
1594// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1595// is used instead.
1596func NewLRUClientSessionCache(capacity int) ClientSessionCache {
1597 const defaultSessionCacheCapacity = 64
1598
1599 if capacity < 1 {
1600 capacity = defaultSessionCacheCapacity
1601 }
1602 return &lruClientSessionCache{
1603 lruSessionCache{
1604 m: make(map[string]*list.Element),
1605 q: list.New(),
1606 capacity: capacity,
1607 },
1608 }
1609}
1610
1611// NewLRUServerSessionCache returns a ServerSessionCache with the given
1612// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1613// is used instead.
1614func NewLRUServerSessionCache(capacity int) ServerSessionCache {
1615 const defaultSessionCacheCapacity = 64
1616
1617 if capacity < 1 {
1618 capacity = defaultSessionCacheCapacity
1619 }
1620 return &lruServerSessionCache{
1621 lruSessionCache{
1622 m: make(map[string]*list.Element),
1623 q: list.New(),
1624 capacity: capacity,
1625 },
1626 }
1627}
1628
1629// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
1630type dsaSignature struct {
1631 R, S *big.Int
1632}
1633
1634type ecdsaSignature dsaSignature
1635
1636var emptyConfig Config
1637
1638func defaultConfig() *Config {
1639 return &emptyConfig
1640}
1641
1642var (
1643 once sync.Once
1644 varDefaultCipherSuites []uint16
1645)
1646
1647func defaultCipherSuites() []uint16 {
1648 once.Do(initDefaultCipherSuites)
1649 return varDefaultCipherSuites
1650}
1651
1652func initDefaultCipherSuites() {
1653 for _, suite := range cipherSuites {
1654 if suite.flags&suitePSK == 0 {
1655 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
1656 }
1657 }
1658}
1659
1660func unexpectedMessageError(wanted, got interface{}) error {
1661 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1662}
1663
David Benjaminc895d6b2016-08-11 13:26:41 -04001664func isSupportedSignatureAlgorithm(sigAlg signatureAlgorithm, sigAlgs []signatureAlgorithm) bool {
1665 for _, s := range sigAlgs {
1666 if s == sigAlg {
Adam Langleyd9e397b2015-01-22 14:27:53 -08001667 return true
1668 }
1669 }
1670 return false
1671}
David Benjaminc895d6b2016-08-11 13:26:41 -04001672
1673var (
David Benjamin95add822016-10-19 01:09:12 -04001674 // See draft-ietf-tls-tls13-16, section 6.3.1.2.
David Benjaminc895d6b2016-08-11 13:26:41 -04001675 downgradeTLS13 = []byte{0x44, 0x4f, 0x57, 0x4e, 0x47, 0x52, 0x44, 0x01}
1676 downgradeTLS12 = []byte{0x44, 0x4f, 0x57, 0x4e, 0x47, 0x52, 0x44, 0x00}
1677)