blob: 95c546199c284584e1ae6663fd0ef4ceef6bb1cc [file] [log] [blame]
Adam Langley95c29f32014-06-20 12:00:00 -07001// Copyright 2009 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
Adam Langleydc7e9c42015-09-29 15:21:04 -07005package runner
Adam Langley95c29f32014-06-20 12:00:00 -07006
7import (
8 "container/list"
9 "crypto"
David Benjamind30a9902014-08-24 01:44:23 -040010 "crypto/ecdsa"
Adam Langley95c29f32014-06-20 12:00:00 -070011 "crypto/rand"
12 "crypto/x509"
13 "fmt"
14 "io"
15 "math/big"
16 "strings"
17 "sync"
18 "time"
19)
20
21const (
22 VersionSSL30 = 0x0300
23 VersionTLS10 = 0x0301
24 VersionTLS11 = 0x0302
25 VersionTLS12 = 0x0303
Nick Harper1fd39d82016-06-14 18:14:35 -070026 VersionTLS13 = 0x0304
Adam Langley95c29f32014-06-20 12:00:00 -070027)
28
29const (
David Benjamin83c0bc92014-08-04 01:23:53 -040030 maxPlaintext = 16384 // maximum plaintext payload length
31 maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
32 tlsRecordHeaderLen = 5 // record header length
33 dtlsRecordHeaderLen = 13
34 maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
Adam Langley95c29f32014-06-20 12:00:00 -070035
36 minVersion = VersionSSL30
Nick Harper1fd39d82016-06-14 18:14:35 -070037 maxVersion = VersionTLS13
Adam Langley95c29f32014-06-20 12:00:00 -070038)
39
40// TLS record types.
41type recordType uint8
42
43const (
44 recordTypeChangeCipherSpec recordType = 20
45 recordTypeAlert recordType = 21
46 recordTypeHandshake recordType = 22
47 recordTypeApplicationData recordType = 23
48)
49
50// TLS handshake message types.
51const (
Adam Langley2ae77d22014-10-28 17:29:33 -070052 typeHelloRequest uint8 = 0
David Benjamind30a9902014-08-24 01:44:23 -040053 typeClientHello uint8 = 1
54 typeServerHello uint8 = 2
55 typeHelloVerifyRequest uint8 = 3
56 typeNewSessionTicket uint8 = 4
57 typeCertificate uint8 = 11
58 typeServerKeyExchange uint8 = 12
59 typeCertificateRequest uint8 = 13
60 typeServerHelloDone uint8 = 14
61 typeCertificateVerify uint8 = 15
62 typeClientKeyExchange uint8 = 16
63 typeFinished uint8 = 20
64 typeCertificateStatus uint8 = 22
65 typeNextProtocol uint8 = 67 // Not IANA assigned
66 typeEncryptedExtensions uint8 = 203 // Not IANA assigned
Adam Langley95c29f32014-06-20 12:00:00 -070067)
68
69// TLS compression types.
70const (
71 compressionNone uint8 = 0
72)
73
74// TLS extension numbers
75const (
David Benjamin61f95272014-11-25 01:55:35 -050076 extensionServerName uint16 = 0
77 extensionStatusRequest uint16 = 5
78 extensionSupportedCurves uint16 = 10
79 extensionSupportedPoints uint16 = 11
80 extensionSignatureAlgorithms uint16 = 13
81 extensionUseSRTP uint16 = 14
82 extensionALPN uint16 = 16
83 extensionSignedCertificateTimestamp uint16 = 18
84 extensionExtendedMasterSecret uint16 = 23
85 extensionSessionTicket uint16 = 35
David Benjamin399e7c92015-07-30 23:01:27 -040086 extensionCustom uint16 = 1234 // not IANA assigned
David Benjamin61f95272014-11-25 01:55:35 -050087 extensionNextProtoNeg uint16 = 13172 // not IANA assigned
88 extensionRenegotiationInfo uint16 = 0xff01
89 extensionChannelID uint16 = 30032 // not IANA assigned
Adam Langley95c29f32014-06-20 12:00:00 -070090)
91
92// TLS signaling cipher suite values
93const (
94 scsvRenegotiation uint16 = 0x00ff
95)
96
97// CurveID is the type of a TLS identifier for an elliptic curve. See
98// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
99type CurveID uint16
100
101const (
David Benjamincba2b622015-12-18 22:13:41 -0500102 CurveP224 CurveID = 21
103 CurveP256 CurveID = 23
104 CurveP384 CurveID = 24
105 CurveP521 CurveID = 25
106 CurveX25519 CurveID = 29
Adam Langley95c29f32014-06-20 12:00:00 -0700107)
108
109// TLS Elliptic Curve Point Formats
110// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
111const (
112 pointFormatUncompressed uint8 = 0
113)
114
115// TLS CertificateStatusType (RFC 3546)
116const (
117 statusTypeOCSP uint8 = 1
118)
119
120// Certificate types (for certificateRequestMsg)
121const (
David Benjamin7b030512014-07-08 17:30:11 -0400122 CertTypeRSASign = 1 // A certificate containing an RSA key
123 CertTypeDSSSign = 2 // A certificate containing a DSA key
124 CertTypeRSAFixedDH = 3 // A certificate containing a static DH key
125 CertTypeDSSFixedDH = 4 // A certificate containing a static DH key
Adam Langley95c29f32014-06-20 12:00:00 -0700126
127 // See RFC4492 sections 3 and 5.5.
David Benjamin7b030512014-07-08 17:30:11 -0400128 CertTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
129 CertTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
130 CertTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
Adam Langley95c29f32014-06-20 12:00:00 -0700131
132 // Rest of these are reserved by the TLS spec
133)
134
Nick Harper60edffd2016-06-21 15:19:24 -0700135// signatureAlgorithm corresponds to a SignatureScheme value from TLS 1.3. Note
136// that TLS 1.3 names the production 'SignatureScheme' to avoid colliding with
137// TLS 1.2's SignatureAlgorithm but otherwise refers to them as 'signature
138// algorithms' throughout. We match the latter.
139type signatureAlgorithm uint16
Adam Langley95c29f32014-06-20 12:00:00 -0700140
Adam Langley95c29f32014-06-20 12:00:00 -0700141const (
Nick Harper60edffd2016-06-21 15:19:24 -0700142 // RSASSA-PKCS1-v1_5 algorithms
143 signatureRSAPKCS1WithMD5 signatureAlgorithm = 0x0101
144 signatureRSAPKCS1WithSHA1 signatureAlgorithm = 0x0201
145 signatureRSAPKCS1WithSHA256 signatureAlgorithm = 0x0401
146 signatureRSAPKCS1WithSHA384 signatureAlgorithm = 0x0501
147 signatureRSAPKCS1WithSHA512 signatureAlgorithm = 0x0601
Adam Langley95c29f32014-06-20 12:00:00 -0700148
Nick Harper60edffd2016-06-21 15:19:24 -0700149 // ECDSA algorithms
150 signatureECDSAWithSHA1 signatureAlgorithm = 0x0203
151 signatureECDSAWithP256AndSHA256 signatureAlgorithm = 0x0403
152 signatureECDSAWithP384AndSHA384 signatureAlgorithm = 0x0503
153 signatureECDSAWithP521AndSHA512 signatureAlgorithm = 0x0603
154
155 // RSASSA-PSS algorithms
156 signatureRSAPSSWithSHA256 signatureAlgorithm = 0x0700
157 signatureRSAPSSWithSHA384 signatureAlgorithm = 0x0701
158 signatureRSAPSSWithSHA512 signatureAlgorithm = 0x0702
159
160 // EdDSA algorithms
161 signatureEd25519 signatureAlgorithm = 0x0703
162 signatureEd448 signatureAlgorithm = 0x0704
163)
Adam Langley95c29f32014-06-20 12:00:00 -0700164
165// supportedSKXSignatureAlgorithms contains the signature and hash algorithms
166// that the code advertises as supported in a TLS 1.2 ClientHello.
Nick Harper60edffd2016-06-21 15:19:24 -0700167var supportedSKXSignatureAlgorithms = []signatureAlgorithm{
168 signatureRSAPKCS1WithSHA256,
169 signatureECDSAWithP256AndSHA256,
170 signatureRSAPKCS1WithSHA1,
171 signatureECDSAWithSHA1,
Adam Langley95c29f32014-06-20 12:00:00 -0700172}
173
Nick Harper60edffd2016-06-21 15:19:24 -0700174// supportedPeerSignatureAlgorithms contains the signature and hash
Adam Langley95c29f32014-06-20 12:00:00 -0700175// algorithms that the code advertises as supported in a TLS 1.2
176// CertificateRequest.
Nick Harper60edffd2016-06-21 15:19:24 -0700177var supportedPeerSignatureAlgorithms = []signatureAlgorithm{
178 signatureRSAPKCS1WithSHA256,
179 signatureECDSAWithP256AndSHA256,
Adam Langley95c29f32014-06-20 12:00:00 -0700180}
181
David Benjaminca6c8262014-11-15 19:06:08 -0500182// SRTP protection profiles (See RFC 5764, section 4.1.2)
183const (
184 SRTP_AES128_CM_HMAC_SHA1_80 uint16 = 0x0001
185 SRTP_AES128_CM_HMAC_SHA1_32 = 0x0002
186)
187
Adam Langley95c29f32014-06-20 12:00:00 -0700188// ConnectionState records basic TLS details about the connection.
189type ConnectionState struct {
190 Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
191 HandshakeComplete bool // TLS handshake is complete
192 DidResume bool // connection resumes a previous TLS connection
193 CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
194 NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos)
195 NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server
David Benjaminfc7b0862014-09-06 13:21:53 -0400196 NegotiatedProtocolFromALPN bool // protocol negotiated with ALPN
Adam Langley95c29f32014-06-20 12:00:00 -0700197 ServerName string // server name requested by client, if any (server side only)
198 PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
199 VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
David Benjamind30a9902014-08-24 01:44:23 -0400200 ChannelID *ecdsa.PublicKey // the channel ID for this connection
David Benjaminca6c8262014-11-15 19:06:08 -0500201 SRTPProtectionProfile uint16 // the negotiated DTLS-SRTP protection profile
David Benjaminc0577622015-09-12 18:28:38 -0400202 TLSUnique []byte // the tls-unique channel binding
Paul Lietar4fac72e2015-09-09 13:44:55 +0100203 SCTList []byte // signed certificate timestamp list
Nick Harper60edffd2016-06-21 15:19:24 -0700204 PeerSignatureAlgorithm signatureAlgorithm // algorithm used by the peer in the handshake
Adam Langley95c29f32014-06-20 12:00:00 -0700205}
206
207// ClientAuthType declares the policy the server will follow for
208// TLS Client Authentication.
209type ClientAuthType int
210
211const (
212 NoClientCert ClientAuthType = iota
213 RequestClientCert
214 RequireAnyClientCert
215 VerifyClientCertIfGiven
216 RequireAndVerifyClientCert
217)
218
219// ClientSessionState contains the state needed by clients to resume TLS
220// sessions.
221type ClientSessionState struct {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500222 sessionId []uint8 // Session ID supplied by the server. nil if the session has a ticket.
Adam Langley75712922014-10-10 16:23:43 -0700223 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
224 vers uint16 // SSL/TLS version negotiated for the session
225 cipherSuite uint16 // Ciphersuite negotiated for the session
226 masterSecret []byte // MasterSecret generated by client on a full handshake
227 handshakeHash []byte // Handshake hash for Channel ID purposes.
228 serverCertificates []*x509.Certificate // Certificate chain presented by the server
229 extendedMasterSecret bool // Whether an extended master secret was used to generate the session
Paul Lietar62be8ac2015-09-16 10:03:30 +0100230 sctList []byte
231 ocspResponse []byte
Adam Langley95c29f32014-06-20 12:00:00 -0700232}
233
234// ClientSessionCache is a cache of ClientSessionState objects that can be used
235// by a client to resume a TLS session with a given server. ClientSessionCache
236// implementations should expect to be called concurrently from different
237// goroutines.
238type ClientSessionCache interface {
239 // Get searches for a ClientSessionState associated with the given key.
240 // On return, ok is true if one was found.
241 Get(sessionKey string) (session *ClientSessionState, ok bool)
242
243 // Put adds the ClientSessionState to the cache with the given key.
244 Put(sessionKey string, cs *ClientSessionState)
245}
246
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500247// ServerSessionCache is a cache of sessionState objects that can be used by a
248// client to resume a TLS session with a given server. ServerSessionCache
249// implementations should expect to be called concurrently from different
250// goroutines.
251type ServerSessionCache interface {
252 // Get searches for a sessionState associated with the given session
253 // ID. On return, ok is true if one was found.
254 Get(sessionId string) (session *sessionState, ok bool)
255
256 // Put adds the sessionState to the cache with the given session ID.
257 Put(sessionId string, session *sessionState)
258}
259
Adam Langley95c29f32014-06-20 12:00:00 -0700260// A Config structure is used to configure a TLS client or server.
261// After one has been passed to a TLS function it must not be
262// modified. A Config may be reused; the tls package will also not
263// modify it.
264type Config struct {
265 // Rand provides the source of entropy for nonces and RSA blinding.
266 // If Rand is nil, TLS uses the cryptographic random reader in package
267 // crypto/rand.
268 // The Reader must be safe for use by multiple goroutines.
269 Rand io.Reader
270
271 // Time returns the current time as the number of seconds since the epoch.
272 // If Time is nil, TLS uses time.Now.
273 Time func() time.Time
274
275 // Certificates contains one or more certificate chains
276 // to present to the other side of the connection.
277 // Server configurations must include at least one certificate.
278 Certificates []Certificate
279
280 // NameToCertificate maps from a certificate name to an element of
281 // Certificates. Note that a certificate name can be of the form
282 // '*.example.com' and so doesn't have to be a domain name as such.
283 // See Config.BuildNameToCertificate
284 // The nil value causes the first element of Certificates to be used
285 // for all connections.
286 NameToCertificate map[string]*Certificate
287
288 // RootCAs defines the set of root certificate authorities
289 // that clients use when verifying server certificates.
290 // If RootCAs is nil, TLS uses the host's root CA set.
291 RootCAs *x509.CertPool
292
293 // NextProtos is a list of supported, application level protocols.
294 NextProtos []string
295
296 // ServerName is used to verify the hostname on the returned
297 // certificates unless InsecureSkipVerify is given. It is also included
298 // in the client's handshake to support virtual hosting.
299 ServerName string
300
301 // ClientAuth determines the server's policy for
302 // TLS Client Authentication. The default is NoClientCert.
303 ClientAuth ClientAuthType
304
305 // ClientCAs defines the set of root certificate authorities
306 // that servers use if required to verify a client certificate
307 // by the policy in ClientAuth.
308 ClientCAs *x509.CertPool
309
David Benjamin7b030512014-07-08 17:30:11 -0400310 // ClientCertificateTypes defines the set of allowed client certificate
311 // types. The default is CertTypeRSASign and CertTypeECDSASign.
312 ClientCertificateTypes []byte
313
Adam Langley95c29f32014-06-20 12:00:00 -0700314 // InsecureSkipVerify controls whether a client verifies the
315 // server's certificate chain and host name.
316 // If InsecureSkipVerify is true, TLS accepts any certificate
317 // presented by the server and any host name in that certificate.
318 // In this mode, TLS is susceptible to man-in-the-middle attacks.
319 // This should be used only for testing.
320 InsecureSkipVerify bool
321
322 // CipherSuites is a list of supported cipher suites. If CipherSuites
323 // is nil, TLS uses a list of suites supported by the implementation.
324 CipherSuites []uint16
325
326 // PreferServerCipherSuites controls whether the server selects the
327 // client's most preferred ciphersuite, or the server's most preferred
328 // ciphersuite. If true then the server's preference, as expressed in
329 // the order of elements in CipherSuites, is used.
330 PreferServerCipherSuites bool
331
332 // SessionTicketsDisabled may be set to true to disable session ticket
333 // (resumption) support.
334 SessionTicketsDisabled bool
335
336 // SessionTicketKey is used by TLS servers to provide session
337 // resumption. See RFC 5077. If zero, it will be filled with
338 // random data before the first server handshake.
339 //
340 // If multiple servers are terminating connections for the same host
341 // they should all have the same SessionTicketKey. If the
342 // SessionTicketKey leaks, previously recorded and future TLS
343 // connections using that key are compromised.
344 SessionTicketKey [32]byte
345
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500346 // ClientSessionCache is a cache of ClientSessionState entries
347 // for TLS session resumption.
Adam Langley95c29f32014-06-20 12:00:00 -0700348 ClientSessionCache ClientSessionCache
349
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500350 // ServerSessionCache is a cache of sessionState entries for TLS session
351 // resumption.
352 ServerSessionCache ServerSessionCache
353
Adam Langley95c29f32014-06-20 12:00:00 -0700354 // MinVersion contains the minimum SSL/TLS version that is acceptable.
355 // If zero, then SSLv3 is taken as the minimum.
356 MinVersion uint16
357
358 // MaxVersion contains the maximum SSL/TLS version that is acceptable.
359 // If zero, then the maximum version supported by this package is used,
360 // which is currently TLS 1.2.
361 MaxVersion uint16
362
363 // CurvePreferences contains the elliptic curves that will be used in
364 // an ECDHE handshake, in preference order. If empty, the default will
365 // be used.
366 CurvePreferences []CurveID
367
David Benjamind30a9902014-08-24 01:44:23 -0400368 // ChannelID contains the ECDSA key for the client to use as
369 // its TLS Channel ID.
370 ChannelID *ecdsa.PrivateKey
371
372 // RequestChannelID controls whether the server requests a TLS
373 // Channel ID. If negotiated, the client's public key is
374 // returned in the ConnectionState.
375 RequestChannelID bool
376
David Benjamin48cae082014-10-27 01:06:24 -0400377 // PreSharedKey, if not nil, is the pre-shared key to use with
378 // the PSK cipher suites.
379 PreSharedKey []byte
380
381 // PreSharedKeyIdentity, if not empty, is the identity to use
382 // with the PSK cipher suites.
383 PreSharedKeyIdentity string
384
David Benjaminca6c8262014-11-15 19:06:08 -0500385 // SRTPProtectionProfiles, if not nil, is the list of SRTP
386 // protection profiles to offer in DTLS-SRTP.
387 SRTPProtectionProfiles []uint16
388
Nick Harper60edffd2016-06-21 15:19:24 -0700389 // SignatureAlgorithms, if not nil, overrides the default set of
David Benjamin000800a2014-11-14 01:43:59 -0500390 // supported signature and hash algorithms to advertise in
391 // CertificateRequest.
Nick Harper60edffd2016-06-21 15:19:24 -0700392 SignatureAlgorithms []signatureAlgorithm
David Benjamin000800a2014-11-14 01:43:59 -0500393
Adam Langley95c29f32014-06-20 12:00:00 -0700394 // Bugs specifies optional misbehaviour to be used for testing other
395 // implementations.
396 Bugs ProtocolBugs
397
398 serverInitOnce sync.Once // guards calling (*Config).serverInit
399}
400
401type BadValue int
402
403const (
404 BadValueNone BadValue = iota
405 BadValueNegative
406 BadValueZero
407 BadValueLimit
408 BadValueLarge
409 NumBadValues
410)
411
David Benjaminb36a3952015-12-01 18:53:13 -0500412type RSABadValue int
413
414const (
415 RSABadValueNone RSABadValue = iota
416 RSABadValueCorrupt
417 RSABadValueTooLong
418 RSABadValueTooShort
419 RSABadValueWrongVersion
420 NumRSABadValues
421)
422
Adam Langley95c29f32014-06-20 12:00:00 -0700423type ProtocolBugs struct {
424 // InvalidSKXSignature specifies that the signature in a
425 // ServerKeyExchange message should be invalid.
426 InvalidSKXSignature bool
427
David Benjamin6de0e532015-07-28 22:43:19 -0400428 // InvalidCertVerifySignature specifies that the signature in a
429 // CertificateVerify message should be invalid.
430 InvalidCertVerifySignature bool
431
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 Benjamind86c7672014-08-02 04:07:12 -0400514 // SendV2ClientHello causes the client to send a V2ClientHello
515 // instead of a normal ClientHello.
516 SendV2ClientHello bool
David Benjaminbef270a2014-08-02 04:22:02 -0400517
518 // SendFallbackSCSV causes the client to include
519 // TLS_FALLBACK_SCSV in the ClientHello.
520 SendFallbackSCSV bool
David Benjamin43ec06f2014-08-05 02:28:57 -0400521
Adam Langley5021b222015-06-12 18:27:58 -0700522 // SendRenegotiationSCSV causes the client to include the renegotiation
523 // SCSV in the ClientHello.
524 SendRenegotiationSCSV bool
525
David Benjamin43ec06f2014-08-05 02:28:57 -0400526 // MaxHandshakeRecordLength, if non-zero, is the maximum size of a
David Benjamin98214542014-08-07 18:02:39 -0400527 // handshake record. Handshake messages will be split into multiple
528 // records at the specified size, except that the client_version will
David Benjaminbd15a8e2015-05-29 18:48:16 -0400529 // never be fragmented. For DTLS, it is the maximum handshake fragment
530 // size, not record size; DTLS allows multiple handshake fragments in a
531 // single handshake record. See |PackHandshakeFragments|.
David Benjamin43ec06f2014-08-05 02:28:57 -0400532 MaxHandshakeRecordLength int
David Benjamina8e3e0e2014-08-06 22:11:10 -0400533
David Benjamin98214542014-08-07 18:02:39 -0400534 // FragmentClientVersion will allow MaxHandshakeRecordLength to apply to
535 // the first 6 bytes of the ClientHello.
536 FragmentClientVersion bool
537
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400538 // FragmentAlert will cause all alerts to be fragmented across
539 // two records.
540 FragmentAlert bool
541
David Benjamin0d3a8c62016-03-11 22:25:18 -0500542 // DoubleAlert will cause all alerts to be sent as two copies packed
543 // within one record.
544 DoubleAlert bool
545
David Benjamin3fd1fbd2015-02-03 16:07:32 -0500546 // SendSpuriousAlert, if non-zero, will cause an spurious, unwanted
547 // alert to be sent.
548 SendSpuriousAlert alert
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400549
David Benjaminb36a3952015-12-01 18:53:13 -0500550 // BadRSAClientKeyExchange causes the client to send a corrupted RSA
551 // ClientKeyExchange which would not pass padding checks.
552 BadRSAClientKeyExchange RSABadValue
David Benjaminbed9aae2014-08-07 19:13:38 -0400553
554 // RenewTicketOnResume causes the server to renew the session ticket and
555 // send a NewSessionTicket message during an abbreviated handshake.
556 RenewTicketOnResume bool
David Benjamin98e882e2014-08-08 13:24:34 -0400557
558 // SendClientVersion, if non-zero, causes the client to send a different
559 // TLS version in the ClientHello than the maximum supported version.
560 SendClientVersion uint16
David Benjamin83c0bc92014-08-04 01:23:53 -0400561
David Benjamine58c4f52014-08-24 03:47:07 -0400562 // ExpectFalseStart causes the server to, on full handshakes,
563 // expect the peer to False Start; the server Finished message
564 // isn't sent until we receive an application data record
565 // from the peer.
566 ExpectFalseStart bool
David Benjamin5c24a1d2014-08-31 00:59:27 -0400567
David Benjamin1c633152015-04-02 20:19:11 -0400568 // AlertBeforeFalseStartTest, if non-zero, causes the server to, on full
569 // handshakes, send an alert just before reading the application data
570 // record to test False Start. This can be used in a negative False
571 // Start test to determine whether the peer processed the alert (and
572 // closed the connection) before or after sending app data.
573 AlertBeforeFalseStartTest alert
574
David Benjamine78bfde2014-09-06 12:45:15 -0400575 // ExpectServerName, if not empty, is the hostname the client
576 // must specify in the server_name extension.
577 ExpectServerName string
David Benjaminfc7b0862014-09-06 13:21:53 -0400578
David Benjamin76c2efc2015-08-31 14:24:29 -0400579 // SwapNPNAndALPN switches the relative order between NPN and ALPN in
580 // both ClientHello and ServerHello.
David Benjaminfc7b0862014-09-06 13:21:53 -0400581 SwapNPNAndALPN bool
David Benjamin01fe8202014-09-24 15:21:44 -0400582
Adam Langleyefb0e162015-07-09 11:35:04 -0700583 // ALPNProtocol, if not nil, sets the ALPN protocol that a server will
584 // return.
585 ALPNProtocol *string
586
David Benjamin01fe8202014-09-24 15:21:44 -0400587 // AllowSessionVersionMismatch causes the server to resume sessions
588 // regardless of the version associated with the session.
589 AllowSessionVersionMismatch bool
Adam Langley38311732014-10-16 19:04:35 -0700590
591 // CorruptTicket causes a client to corrupt a session ticket before
592 // sending it in a resume handshake.
593 CorruptTicket bool
594
595 // OversizedSessionId causes the session id that is sent with a ticket
596 // resumption attempt to be too large (33 bytes).
597 OversizedSessionId bool
Adam Langley75712922014-10-10 16:23:43 -0700598
599 // RequireExtendedMasterSecret, if true, requires that the peer support
600 // the extended master secret option.
601 RequireExtendedMasterSecret bool
602
David Benjaminca6554b2014-11-08 12:31:52 -0500603 // NoExtendedMasterSecret causes the client and server to behave as if
Adam Langley75712922014-10-10 16:23:43 -0700604 // they didn't support an extended master secret.
605 NoExtendedMasterSecret bool
Adam Langley2ae77d22014-10-28 17:29:33 -0700606
607 // EmptyRenegotiationInfo causes the renegotiation extension to be
608 // empty in a renegotiation handshake.
609 EmptyRenegotiationInfo bool
610
611 // BadRenegotiationInfo causes the renegotiation extension value in a
612 // renegotiation handshake to be incorrect.
613 BadRenegotiationInfo bool
David Benjamin5e961c12014-11-07 01:48:35 -0500614
David Benjamin3e052de2015-11-25 20:10:31 -0500615 // NoRenegotiationInfo disables renegotiation info support in all
616 // handshakes.
David Benjaminca6554b2014-11-08 12:31:52 -0500617 NoRenegotiationInfo bool
618
David Benjamin3e052de2015-11-25 20:10:31 -0500619 // NoRenegotiationInfoInInitial disables renegotiation info support in
620 // the initial handshake.
621 NoRenegotiationInfoInInitial bool
622
623 // NoRenegotiationInfoAfterInitial disables renegotiation info support
624 // in renegotiation handshakes.
625 NoRenegotiationInfoAfterInitial bool
626
Adam Langley5021b222015-06-12 18:27:58 -0700627 // RequireRenegotiationInfo, if true, causes the client to return an
628 // error if the server doesn't reply with the renegotiation extension.
629 RequireRenegotiationInfo bool
630
David Benjamin8e6db492015-07-25 18:29:23 -0400631 // SequenceNumberMapping, if non-nil, is the mapping function to apply
632 // to the sequence number of outgoing packets. For both TLS and DTLS,
633 // the two most-significant bytes in the resulting sequence number are
634 // ignored so that the DTLS epoch cannot be changed.
635 SequenceNumberMapping func(uint64) uint64
David Benjamin9114fae2014-11-08 11:41:14 -0500636
David Benjamina3e89492015-02-26 15:16:22 -0500637 // RSAEphemeralKey, if true, causes the server to send a
638 // ServerKeyExchange message containing an ephemeral key (as in
639 // RSA_EXPORT) in the plain RSA key exchange.
640 RSAEphemeralKey bool
David Benjaminca6c8262014-11-15 19:06:08 -0500641
642 // SRTPMasterKeyIdentifer, if not empty, is the SRTP MKI value that the
643 // client offers when negotiating SRTP. MKI support is still missing so
644 // the peer must still send none.
645 SRTPMasterKeyIdentifer string
646
647 // SendSRTPProtectionProfile, if non-zero, is the SRTP profile that the
648 // server sends in the ServerHello instead of the negotiated one.
649 SendSRTPProtectionProfile uint16
David Benjamin000800a2014-11-14 01:43:59 -0500650
Nick Harper60edffd2016-06-21 15:19:24 -0700651 // NoSignatureAlgorithms, if true, causes the client to omit the
David Benjamin000800a2014-11-14 01:43:59 -0500652 // signature and hashes extension.
653 //
654 // For a server, it will cause an empty list to be sent in the
655 // CertificateRequest message. None the less, the configured set will
656 // still be enforced.
Nick Harper60edffd2016-06-21 15:19:24 -0700657 NoSignatureAlgorithms bool
David Benjaminc44b1df2014-11-23 12:11:01 -0500658
David Benjamin55a43642015-04-20 14:45:55 -0400659 // NoSupportedCurves, if true, causes the client to omit the
660 // supported_curves extension.
661 NoSupportedCurves bool
662
David Benjaminc44b1df2014-11-23 12:11:01 -0500663 // RequireSameRenegoClientVersion, if true, causes the server
664 // to require that all ClientHellos match in offered version
665 // across a renego.
666 RequireSameRenegoClientVersion bool
Feng Lu41aa3252014-11-21 22:47:56 -0800667
David Benjamin1e29a6b2014-12-10 02:27:24 -0500668 // ExpectInitialRecordVersion, if non-zero, is the expected
669 // version of the records before the version is determined.
670 ExpectInitialRecordVersion uint16
David Benjamin13be1de2015-01-11 16:29:36 -0500671
672 // MaxPacketLength, if non-zero, is the maximum acceptable size for a
673 // packet.
674 MaxPacketLength int
David Benjamin6095de82014-12-27 01:50:38 -0500675
676 // SendCipherSuite, if non-zero, is the cipher suite value that the
677 // server will send in the ServerHello. This does not affect the cipher
678 // the server believes it has actually negotiated.
679 SendCipherSuite uint16
David Benjamin4189bd92015-01-25 23:52:39 -0500680
David Benjamin4cf369b2015-08-22 01:35:43 -0400681 // AppDataBeforeHandshake, if not nil, causes application data to be
682 // sent immediately before the first handshake message.
683 AppDataBeforeHandshake []byte
684
685 // AppDataAfterChangeCipherSpec, if not nil, causes application data to
David Benjamin4189bd92015-01-25 23:52:39 -0500686 // be sent immediately after ChangeCipherSpec.
687 AppDataAfterChangeCipherSpec []byte
David Benjamin83f90402015-01-27 01:09:43 -0500688
David Benjamindc3da932015-03-12 15:09:02 -0400689 // AlertAfterChangeCipherSpec, if non-zero, causes an alert to be sent
690 // immediately after ChangeCipherSpec.
691 AlertAfterChangeCipherSpec alert
692
David Benjamin83f90402015-01-27 01:09:43 -0500693 // TimeoutSchedule is the schedule of packet drops and simulated
694 // timeouts for before each handshake leg from the peer.
695 TimeoutSchedule []time.Duration
696
697 // PacketAdaptor is the packetAdaptor to use to simulate timeouts.
698 PacketAdaptor *packetAdaptor
David Benjaminb3774b92015-01-31 17:16:01 -0500699
700 // ReorderHandshakeFragments, if true, causes handshake fragments in
701 // DTLS to overlap and be sent in the wrong order. It also causes
702 // pre-CCS flights to be sent twice. (Post-CCS flights consist of
703 // Finished and will trigger a spurious retransmit.)
704 ReorderHandshakeFragments bool
David Benjaminddb9f152015-02-03 15:44:39 -0500705
David Benjamin75381222015-03-02 19:30:30 -0500706 // MixCompleteMessageWithFragments, if true, causes handshake
707 // messages in DTLS to redundantly both fragment the message
708 // and include a copy of the full one.
709 MixCompleteMessageWithFragments bool
710
David Benjaminddb9f152015-02-03 15:44:39 -0500711 // SendInvalidRecordType, if true, causes a record with an invalid
712 // content type to be sent immediately following the handshake.
713 SendInvalidRecordType bool
David Benjaminbcb2d912015-02-24 23:45:43 -0500714
715 // WrongCertificateMessageType, if true, causes Certificate message to
716 // be sent with the wrong message type.
717 WrongCertificateMessageType bool
David Benjamin75381222015-03-02 19:30:30 -0500718
719 // FragmentMessageTypeMismatch, if true, causes all non-initial
720 // handshake fragments in DTLS to have the wrong message type.
721 FragmentMessageTypeMismatch bool
722
723 // FragmentMessageLengthMismatch, if true, causes all non-initial
724 // handshake fragments in DTLS to have the wrong message length.
725 FragmentMessageLengthMismatch bool
726
David Benjamin11fc66a2015-06-16 11:40:24 -0400727 // SplitFragments, if non-zero, causes the handshake fragments in DTLS
728 // to be split across two records. The value of |SplitFragments| is the
729 // number of bytes in the first fragment.
730 SplitFragments int
David Benjamin75381222015-03-02 19:30:30 -0500731
732 // SendEmptyFragments, if true, causes handshakes to include empty
733 // fragments in DTLS.
734 SendEmptyFragments bool
David Benjamincdea40c2015-03-19 14:09:43 -0400735
David Benjamin9a41d1b2015-05-16 01:30:09 -0400736 // SendSplitAlert, if true, causes an alert to be sent with the header
737 // and record body split across multiple packets. The peer should
738 // discard these packets rather than process it.
739 SendSplitAlert bool
740
David Benjamin4b27d9f2015-05-12 22:42:52 -0400741 // FailIfResumeOnRenego, if true, causes renegotiations to fail if the
742 // client offers a resumption or the server accepts one.
743 FailIfResumeOnRenego bool
David Benjamin3c9746a2015-03-19 15:00:10 -0400744
David Benjamin67d1fb52015-03-16 15:16:23 -0400745 // IgnorePeerCipherPreferences, if true, causes the peer's cipher
746 // preferences to be ignored.
747 IgnorePeerCipherPreferences bool
David Benjamin72dc7832015-03-16 17:49:43 -0400748
749 // IgnorePeerSignatureAlgorithmPreferences, if true, causes the peer's
750 // signature algorithm preferences to be ignored.
751 IgnorePeerSignatureAlgorithmPreferences bool
David Benjamin340d5ed2015-03-21 02:21:37 -0400752
David Benjaminc574f412015-04-20 11:13:01 -0400753 // IgnorePeerCurvePreferences, if true, causes the peer's curve
754 // preferences to be ignored.
755 IgnorePeerCurvePreferences bool
756
David Benjamin513f0ea2015-04-02 19:33:31 -0400757 // BadFinished, if true, causes the Finished hash to be broken.
758 BadFinished bool
Adam Langleya7997f12015-05-14 17:38:50 -0700759
760 // DHGroupPrime, if not nil, is used to define the (finite field)
761 // Diffie-Hellman group. The generator used is always two.
762 DHGroupPrime *big.Int
David Benjaminbd15a8e2015-05-29 18:48:16 -0400763
764 // PackHandshakeFragments, if true, causes handshake fragments to be
765 // packed into individual handshake records, up to the specified record
766 // size.
767 PackHandshakeFragments int
768
769 // PackHandshakeRecords, if true, causes handshake records to be packed
770 // into individual packets, up to the specified packet size.
771 PackHandshakeRecords int
David Benjamin0fa40122015-05-30 17:13:12 -0400772
David Benjamin0407e762016-06-17 16:41:18 -0400773 // EnableAllCiphers, if true, causes all configured ciphers to be
774 // enabled.
775 EnableAllCiphers bool
David Benjamin8923c0b2015-06-07 11:42:34 -0400776
777 // EmptyCertificateList, if true, causes the server to send an empty
778 // certificate list in the Certificate message.
779 EmptyCertificateList bool
David Benjamind98452d2015-06-16 14:16:23 -0400780
781 // ExpectNewTicket, if true, causes the client to abort if it does not
782 // receive a new ticket.
783 ExpectNewTicket bool
Adam Langley33ad2b52015-07-20 17:43:53 -0700784
785 // RequireClientHelloSize, if not zero, is the required length in bytes
786 // of the ClientHello /record/. This is checked by the server.
787 RequireClientHelloSize int
Adam Langley09505632015-07-30 18:10:13 -0700788
789 // CustomExtension, if not empty, contains the contents of an extension
790 // that will be added to client/server hellos.
791 CustomExtension string
792
793 // ExpectedCustomExtension, if not nil, contains the expected contents
794 // of a custom extension.
795 ExpectedCustomExtension *string
David Benjamin30789da2015-08-29 22:56:45 -0400796
797 // NoCloseNotify, if true, causes the close_notify alert to be skipped
798 // on connection shutdown.
799 NoCloseNotify bool
800
David Benjaminfa214e42016-05-10 17:03:10 -0400801 // SendAlertOnShutdown, if non-zero, is the alert to send instead of
802 // close_notify on shutdown.
803 SendAlertOnShutdown alert
804
David Benjamin30789da2015-08-29 22:56:45 -0400805 // ExpectCloseNotify, if true, requires a close_notify from the peer on
806 // shutdown. Records from the peer received after close_notify is sent
807 // are not discard.
808 ExpectCloseNotify bool
David Benjamin2c99d282015-09-01 10:23:00 -0400809
810 // SendLargeRecords, if true, allows outgoing records to be sent
811 // arbitrarily large.
812 SendLargeRecords bool
David Benjamin76c2efc2015-08-31 14:24:29 -0400813
814 // NegotiateALPNAndNPN, if true, causes the server to negotiate both
815 // ALPN and NPN in the same connetion.
816 NegotiateALPNAndNPN bool
David Benjamindd6fed92015-10-23 17:41:12 -0400817
818 // SendEmptySessionTicket, if true, causes the server to send an empty
819 // session ticket.
820 SendEmptySessionTicket bool
821
822 // FailIfSessionOffered, if true, causes the server to fail any
823 // connections where the client offers a non-empty session ID or session
824 // ticket.
825 FailIfSessionOffered bool
Adam Langley27a0d082015-11-03 13:34:10 -0800826
827 // SendHelloRequestBeforeEveryAppDataRecord, if true, causes a
828 // HelloRequest handshake message to be sent before each application
829 // data record. This only makes sense for a server.
830 SendHelloRequestBeforeEveryAppDataRecord bool
Adam Langleyc4f25ce2015-11-26 16:39:08 -0800831
832 // RequireDHPublicValueLen causes a fatal error if the length (in
833 // bytes) of the server's Diffie-Hellman public value is not equal to
834 // this.
835 RequireDHPublicValueLen int
David Benjamin8411b242015-11-26 12:07:28 -0500836
837 // BadChangeCipherSpec, if not nil, is the body to be sent in
838 // ChangeCipherSpec records instead of {1}.
839 BadChangeCipherSpec []byte
David Benjaminef5dfd22015-12-06 13:17:07 -0500840
841 // BadHelloRequest, if not nil, is what to send instead of a
842 // HelloRequest.
843 BadHelloRequest []byte
David Benjaminef1b0092015-11-21 14:05:44 -0500844
845 // RequireSessionTickets, if true, causes the client to require new
846 // sessions use session tickets instead of session IDs.
847 RequireSessionTickets bool
David Benjaminf2b83632016-03-01 22:57:46 -0500848
849 // NullAllCiphers, if true, causes every cipher to behave like the null
850 // cipher.
851 NullAllCiphers bool
David Benjamin80d1b352016-05-04 19:19:06 -0400852
853 // SendSCTListOnResume, if not nil, causes the server to send the
854 // supplied SCT list in resumption handshakes.
855 SendSCTListOnResume []byte
Matt Braithwaite54217e42016-06-13 13:03:47 -0700856
857 // CECPQ1BadX25519Part corrupts the X25519 part of a CECPQ1 key exchange, as
858 // a trivial proof that it is actually used.
859 CECPQ1BadX25519Part bool
860
861 // CECPQ1BadNewhopePart corrupts the Newhope part of a CECPQ1 key exchange,
862 // as a trivial proof that it is actually used.
863 CECPQ1BadNewhopePart bool
David Benjaminc9ae27c2016-06-24 22:56:37 -0400864
865 // RecordPadding is the number of bytes of padding to add to each
866 // encrypted record in TLS 1.3.
867 RecordPadding int
868
869 // OmitRecordContents, if true, causes encrypted records in TLS 1.3 to
870 // be missing their body and content type. Padding, if configured, is
871 // still added.
872 OmitRecordContents bool
873
874 // OuterRecordType, if non-zero, is the outer record type to use instead
875 // of application data.
876 OuterRecordType recordType
Adam Langley95c29f32014-06-20 12:00:00 -0700877}
878
879func (c *Config) serverInit() {
880 if c.SessionTicketsDisabled {
881 return
882 }
883
884 // If the key has already been set then we have nothing to do.
885 for _, b := range c.SessionTicketKey {
886 if b != 0 {
887 return
888 }
889 }
890
891 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
892 c.SessionTicketsDisabled = true
893 }
894}
895
896func (c *Config) rand() io.Reader {
897 r := c.Rand
898 if r == nil {
899 return rand.Reader
900 }
901 return r
902}
903
904func (c *Config) time() time.Time {
905 t := c.Time
906 if t == nil {
907 t = time.Now
908 }
909 return t()
910}
911
912func (c *Config) cipherSuites() []uint16 {
913 s := c.CipherSuites
914 if s == nil {
915 s = defaultCipherSuites()
916 }
917 return s
918}
919
David Benjamincecee272016-06-30 13:33:47 -0400920func (c *Config) minVersion(isDTLS bool) uint16 {
921 ret := uint16(minVersion)
922 if c != nil && c.MinVersion != 0 {
923 ret = c.MinVersion
Adam Langley95c29f32014-06-20 12:00:00 -0700924 }
David Benjamincecee272016-06-30 13:33:47 -0400925 if isDTLS {
926 // The lowest version of DTLS is 1.0. There is no DSSL 3.0.
927 if ret < VersionTLS10 {
928 return VersionTLS10
929 }
930 // There is no such thing as DTLS 1.1.
931 if ret == VersionTLS11 {
932 return VersionTLS12
933 }
934 }
935 return ret
Adam Langley95c29f32014-06-20 12:00:00 -0700936}
937
David Benjamincecee272016-06-30 13:33:47 -0400938func (c *Config) maxVersion(isDTLS bool) uint16 {
939 ret := uint16(maxVersion)
940 if c != nil && c.MaxVersion != 0 {
941 ret = c.MaxVersion
Adam Langley95c29f32014-06-20 12:00:00 -0700942 }
David Benjamincecee272016-06-30 13:33:47 -0400943 if isDTLS {
944 // We only implement up to DTLS 1.2.
945 if ret > VersionTLS12 {
946 return VersionTLS12
947 }
948 // There is no such thing as DTLS 1.1.
949 if ret == VersionTLS11 {
950 return VersionTLS10
951 }
952 }
953 return ret
Adam Langley95c29f32014-06-20 12:00:00 -0700954}
955
David Benjamincba2b622015-12-18 22:13:41 -0500956var defaultCurvePreferences = []CurveID{CurveX25519, CurveP256, CurveP384, CurveP521}
Adam Langley95c29f32014-06-20 12:00:00 -0700957
958func (c *Config) curvePreferences() []CurveID {
959 if c == nil || len(c.CurvePreferences) == 0 {
960 return defaultCurvePreferences
961 }
962 return c.CurvePreferences
963}
964
965// mutualVersion returns the protocol version to use given the advertised
966// version of the peer.
David Benjamincecee272016-06-30 13:33:47 -0400967func (c *Config) mutualVersion(vers uint16, isDTLS bool) (uint16, bool) {
968 // There is no such thing as DTLS 1.1.
969 if isDTLS && vers == VersionTLS11 {
970 vers = VersionTLS10
971 }
972
973 minVersion := c.minVersion(isDTLS)
974 maxVersion := c.maxVersion(isDTLS)
Adam Langley95c29f32014-06-20 12:00:00 -0700975
976 if vers < minVersion {
977 return 0, false
978 }
979 if vers > maxVersion {
980 vers = maxVersion
981 }
982 return vers, true
983}
984
985// getCertificateForName returns the best certificate for the given name,
986// defaulting to the first element of c.Certificates if there are no good
987// options.
988func (c *Config) getCertificateForName(name string) *Certificate {
989 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
990 // There's only one choice, so no point doing any work.
991 return &c.Certificates[0]
992 }
993
994 name = strings.ToLower(name)
995 for len(name) > 0 && name[len(name)-1] == '.' {
996 name = name[:len(name)-1]
997 }
998
999 if cert, ok := c.NameToCertificate[name]; ok {
1000 return cert
1001 }
1002
1003 // try replacing labels in the name with wildcards until we get a
1004 // match.
1005 labels := strings.Split(name, ".")
1006 for i := range labels {
1007 labels[i] = "*"
1008 candidate := strings.Join(labels, ".")
1009 if cert, ok := c.NameToCertificate[candidate]; ok {
1010 return cert
1011 }
1012 }
1013
1014 // If nothing matches, return the first certificate.
1015 return &c.Certificates[0]
1016}
1017
Nick Harper60edffd2016-06-21 15:19:24 -07001018func (c *Config) signatureAlgorithmsForServer() []signatureAlgorithm {
1019 if c != nil && c.SignatureAlgorithms != nil {
1020 return c.SignatureAlgorithms
David Benjamin000800a2014-11-14 01:43:59 -05001021 }
Nick Harper60edffd2016-06-21 15:19:24 -07001022 return supportedPeerSignatureAlgorithms
David Benjamin000800a2014-11-14 01:43:59 -05001023}
1024
Nick Harper60edffd2016-06-21 15:19:24 -07001025func (c *Config) signatureAlgorithmsForClient() []signatureAlgorithm {
1026 if c != nil && c.SignatureAlgorithms != nil {
1027 return c.SignatureAlgorithms
David Benjamin000800a2014-11-14 01:43:59 -05001028 }
1029 return supportedSKXSignatureAlgorithms
1030}
1031
Adam Langley95c29f32014-06-20 12:00:00 -07001032// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
1033// from the CommonName and SubjectAlternateName fields of each of the leaf
1034// certificates.
1035func (c *Config) BuildNameToCertificate() {
1036 c.NameToCertificate = make(map[string]*Certificate)
1037 for i := range c.Certificates {
1038 cert := &c.Certificates[i]
1039 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
1040 if err != nil {
1041 continue
1042 }
1043 if len(x509Cert.Subject.CommonName) > 0 {
1044 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
1045 }
1046 for _, san := range x509Cert.DNSNames {
1047 c.NameToCertificate[san] = cert
1048 }
1049 }
1050}
1051
1052// A Certificate is a chain of one or more certificates, leaf first.
1053type Certificate struct {
1054 Certificate [][]byte
1055 PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
1056 // OCSPStaple contains an optional OCSP response which will be served
1057 // to clients that request it.
1058 OCSPStaple []byte
David Benjamin61f95272014-11-25 01:55:35 -05001059 // SignedCertificateTimestampList contains an optional encoded
1060 // SignedCertificateTimestampList structure which will be
1061 // served to clients that request it.
1062 SignedCertificateTimestampList []byte
Adam Langley95c29f32014-06-20 12:00:00 -07001063 // Leaf is the parsed form of the leaf certificate, which may be
1064 // initialized using x509.ParseCertificate to reduce per-handshake
1065 // processing for TLS clients doing client authentication. If nil, the
1066 // leaf certificate will be parsed as needed.
1067 Leaf *x509.Certificate
1068}
1069
1070// A TLS record.
1071type record struct {
1072 contentType recordType
1073 major, minor uint8
1074 payload []byte
1075}
1076
1077type handshakeMessage interface {
1078 marshal() []byte
1079 unmarshal([]byte) bool
1080}
1081
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001082// lruSessionCache is a client or server session cache implementation
1083// that uses an LRU caching strategy.
Adam Langley95c29f32014-06-20 12:00:00 -07001084type lruSessionCache struct {
1085 sync.Mutex
1086
1087 m map[string]*list.Element
1088 q *list.List
1089 capacity int
1090}
1091
1092type lruSessionCacheEntry struct {
1093 sessionKey string
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001094 state interface{}
Adam Langley95c29f32014-06-20 12:00:00 -07001095}
1096
1097// Put adds the provided (sessionKey, cs) pair to the cache.
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001098func (c *lruSessionCache) Put(sessionKey string, cs interface{}) {
Adam Langley95c29f32014-06-20 12:00:00 -07001099 c.Lock()
1100 defer c.Unlock()
1101
1102 if elem, ok := c.m[sessionKey]; ok {
1103 entry := elem.Value.(*lruSessionCacheEntry)
1104 entry.state = cs
1105 c.q.MoveToFront(elem)
1106 return
1107 }
1108
1109 if c.q.Len() < c.capacity {
1110 entry := &lruSessionCacheEntry{sessionKey, cs}
1111 c.m[sessionKey] = c.q.PushFront(entry)
1112 return
1113 }
1114
1115 elem := c.q.Back()
1116 entry := elem.Value.(*lruSessionCacheEntry)
1117 delete(c.m, entry.sessionKey)
1118 entry.sessionKey = sessionKey
1119 entry.state = cs
1120 c.q.MoveToFront(elem)
1121 c.m[sessionKey] = elem
1122}
1123
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001124// Get returns the value associated with a given key. It returns (nil,
1125// false) if no value is found.
1126func (c *lruSessionCache) Get(sessionKey string) (interface{}, bool) {
Adam Langley95c29f32014-06-20 12:00:00 -07001127 c.Lock()
1128 defer c.Unlock()
1129
1130 if elem, ok := c.m[sessionKey]; ok {
1131 c.q.MoveToFront(elem)
1132 return elem.Value.(*lruSessionCacheEntry).state, true
1133 }
1134 return nil, false
1135}
1136
David Benjaminfe8eb9a2014-11-17 03:19:02 -05001137// lruClientSessionCache is a ClientSessionCache implementation that
1138// uses an LRU caching strategy.
1139type lruClientSessionCache struct {
1140 lruSessionCache
1141}
1142
1143func (c *lruClientSessionCache) Put(sessionKey string, cs *ClientSessionState) {
1144 c.lruSessionCache.Put(sessionKey, cs)
1145}
1146
1147func (c *lruClientSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
1148 cs, ok := c.lruSessionCache.Get(sessionKey)
1149 if !ok {
1150 return nil, false
1151 }
1152 return cs.(*ClientSessionState), true
1153}
1154
1155// lruServerSessionCache is a ServerSessionCache implementation that
1156// uses an LRU caching strategy.
1157type lruServerSessionCache struct {
1158 lruSessionCache
1159}
1160
1161func (c *lruServerSessionCache) Put(sessionId string, session *sessionState) {
1162 c.lruSessionCache.Put(sessionId, session)
1163}
1164
1165func (c *lruServerSessionCache) Get(sessionId string) (*sessionState, bool) {
1166 cs, ok := c.lruSessionCache.Get(sessionId)
1167 if !ok {
1168 return nil, false
1169 }
1170 return cs.(*sessionState), true
1171}
1172
1173// NewLRUClientSessionCache returns a ClientSessionCache with the given
1174// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1175// is used instead.
1176func NewLRUClientSessionCache(capacity int) ClientSessionCache {
1177 const defaultSessionCacheCapacity = 64
1178
1179 if capacity < 1 {
1180 capacity = defaultSessionCacheCapacity
1181 }
1182 return &lruClientSessionCache{
1183 lruSessionCache{
1184 m: make(map[string]*list.Element),
1185 q: list.New(),
1186 capacity: capacity,
1187 },
1188 }
1189}
1190
1191// NewLRUServerSessionCache returns a ServerSessionCache with the given
1192// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
1193// is used instead.
1194func NewLRUServerSessionCache(capacity int) ServerSessionCache {
1195 const defaultSessionCacheCapacity = 64
1196
1197 if capacity < 1 {
1198 capacity = defaultSessionCacheCapacity
1199 }
1200 return &lruServerSessionCache{
1201 lruSessionCache{
1202 m: make(map[string]*list.Element),
1203 q: list.New(),
1204 capacity: capacity,
1205 },
1206 }
1207}
1208
Adam Langley95c29f32014-06-20 12:00:00 -07001209// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
1210type dsaSignature struct {
1211 R, S *big.Int
1212}
1213
1214type ecdsaSignature dsaSignature
1215
1216var emptyConfig Config
1217
1218func defaultConfig() *Config {
1219 return &emptyConfig
1220}
1221
1222var (
1223 once sync.Once
1224 varDefaultCipherSuites []uint16
1225)
1226
1227func defaultCipherSuites() []uint16 {
1228 once.Do(initDefaultCipherSuites)
1229 return varDefaultCipherSuites
1230}
1231
1232func initDefaultCipherSuites() {
David Benjamin48cae082014-10-27 01:06:24 -04001233 for _, suite := range cipherSuites {
1234 if suite.flags&suitePSK == 0 {
1235 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
1236 }
Adam Langley95c29f32014-06-20 12:00:00 -07001237 }
1238}
1239
1240func unexpectedMessageError(wanted, got interface{}) error {
1241 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1242}
David Benjamin000800a2014-11-14 01:43:59 -05001243
Nick Harper60edffd2016-06-21 15:19:24 -07001244func isSupportedSignatureAlgorithm(sigAlg signatureAlgorithm, sigAlgs []signatureAlgorithm) bool {
1245 for _, s := range sigAlgs {
1246 if s == sigAlg {
David Benjamin000800a2014-11-14 01:43:59 -05001247 return true
1248 }
1249 }
1250 return false
1251}