blob: 2e6ddf3c5f65a7d7a12bc526edeeb57a1d524ef7 [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
5package main
6
7import (
8 "container/list"
9 "crypto"
David Benjamind30a9902014-08-24 01:44:23 -040010 "crypto/ecdsa"
Adam Langley95c29f32014-06-20 12:00:00 -070011 "crypto/rand"
12 "crypto/x509"
13 "fmt"
14 "io"
15 "math/big"
16 "strings"
17 "sync"
18 "time"
19)
20
21const (
22 VersionSSL30 = 0x0300
23 VersionTLS10 = 0x0301
24 VersionTLS11 = 0x0302
25 VersionTLS12 = 0x0303
26)
27
28const (
David Benjamin83c0bc92014-08-04 01:23:53 -040029 maxPlaintext = 16384 // maximum plaintext payload length
30 maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
31 tlsRecordHeaderLen = 5 // record header length
32 dtlsRecordHeaderLen = 13
33 maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
Adam Langley95c29f32014-06-20 12:00:00 -070034
35 minVersion = VersionSSL30
36 maxVersion = VersionTLS12
37)
38
39// TLS record types.
40type recordType uint8
41
42const (
43 recordTypeChangeCipherSpec recordType = 20
44 recordTypeAlert recordType = 21
45 recordTypeHandshake recordType = 22
46 recordTypeApplicationData recordType = 23
47)
48
49// TLS handshake message types.
50const (
Adam Langley2ae77d22014-10-28 17:29:33 -070051 typeHelloRequest uint8 = 0
David Benjamind30a9902014-08-24 01:44:23 -040052 typeClientHello uint8 = 1
53 typeServerHello uint8 = 2
54 typeHelloVerifyRequest uint8 = 3
55 typeNewSessionTicket uint8 = 4
56 typeCertificate uint8 = 11
57 typeServerKeyExchange uint8 = 12
58 typeCertificateRequest uint8 = 13
59 typeServerHelloDone uint8 = 14
60 typeCertificateVerify uint8 = 15
61 typeClientKeyExchange uint8 = 16
62 typeFinished uint8 = 20
63 typeCertificateStatus uint8 = 22
64 typeNextProtocol uint8 = 67 // Not IANA assigned
65 typeEncryptedExtensions uint8 = 203 // Not IANA assigned
Adam Langley95c29f32014-06-20 12:00:00 -070066)
67
68// TLS compression types.
69const (
70 compressionNone uint8 = 0
71)
72
73// TLS extension numbers
74const (
David Benjamin61f95272014-11-25 01:55:35 -050075 extensionServerName uint16 = 0
76 extensionStatusRequest uint16 = 5
77 extensionSupportedCurves uint16 = 10
78 extensionSupportedPoints uint16 = 11
79 extensionSignatureAlgorithms uint16 = 13
80 extensionUseSRTP uint16 = 14
81 extensionALPN uint16 = 16
82 extensionSignedCertificateTimestamp uint16 = 18
83 extensionExtendedMasterSecret uint16 = 23
84 extensionSessionTicket uint16 = 35
85 extensionNextProtoNeg uint16 = 13172 // not IANA assigned
86 extensionRenegotiationInfo uint16 = 0xff01
87 extensionChannelID uint16 = 30032 // not IANA assigned
Adam Langley95c29f32014-06-20 12:00:00 -070088)
89
90// TLS signaling cipher suite values
91const (
92 scsvRenegotiation uint16 = 0x00ff
93)
94
95// CurveID is the type of a TLS identifier for an elliptic curve. See
96// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
97type CurveID uint16
98
99const (
David Benjaminc574f412015-04-20 11:13:01 -0400100 CurveP224 CurveID = 21
Adam Langley95c29f32014-06-20 12:00:00 -0700101 CurveP256 CurveID = 23
102 CurveP384 CurveID = 24
103 CurveP521 CurveID = 25
104)
105
106// TLS Elliptic Curve Point Formats
107// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
108const (
109 pointFormatUncompressed uint8 = 0
110)
111
112// TLS CertificateStatusType (RFC 3546)
113const (
114 statusTypeOCSP uint8 = 1
115)
116
117// Certificate types (for certificateRequestMsg)
118const (
David Benjamin7b030512014-07-08 17:30:11 -0400119 CertTypeRSASign = 1 // A certificate containing an RSA key
120 CertTypeDSSSign = 2 // A certificate containing a DSA key
121 CertTypeRSAFixedDH = 3 // A certificate containing a static DH key
122 CertTypeDSSFixedDH = 4 // A certificate containing a static DH key
Adam Langley95c29f32014-06-20 12:00:00 -0700123
124 // See RFC4492 sections 3 and 5.5.
David Benjamin7b030512014-07-08 17:30:11 -0400125 CertTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
126 CertTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
127 CertTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
Adam Langley95c29f32014-06-20 12:00:00 -0700128
129 // Rest of these are reserved by the TLS spec
130)
131
132// Hash functions for TLS 1.2 (See RFC 5246, section A.4.1)
133const (
David Benjamin000800a2014-11-14 01:43:59 -0500134 hashMD5 uint8 = 1
Adam Langley95c29f32014-06-20 12:00:00 -0700135 hashSHA1 uint8 = 2
David Benjamin000800a2014-11-14 01:43:59 -0500136 hashSHA224 uint8 = 3
Adam Langley95c29f32014-06-20 12:00:00 -0700137 hashSHA256 uint8 = 4
David Benjamin000800a2014-11-14 01:43:59 -0500138 hashSHA384 uint8 = 5
139 hashSHA512 uint8 = 6
Adam Langley95c29f32014-06-20 12:00:00 -0700140)
141
142// Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
143const (
144 signatureRSA uint8 = 1
145 signatureECDSA uint8 = 3
146)
147
148// signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See
149// RFC 5246, section A.4.1.
150type signatureAndHash struct {
David Benjamine098ec22014-08-27 23:13:20 -0400151 signature, hash uint8
Adam Langley95c29f32014-06-20 12:00:00 -0700152}
153
154// supportedSKXSignatureAlgorithms contains the signature and hash algorithms
155// that the code advertises as supported in a TLS 1.2 ClientHello.
156var supportedSKXSignatureAlgorithms = []signatureAndHash{
David Benjamine098ec22014-08-27 23:13:20 -0400157 {signatureRSA, hashSHA256},
158 {signatureECDSA, hashSHA256},
159 {signatureRSA, hashSHA1},
160 {signatureECDSA, hashSHA1},
Adam Langley95c29f32014-06-20 12:00:00 -0700161}
162
163// supportedClientCertSignatureAlgorithms contains the signature and hash
164// algorithms that the code advertises as supported in a TLS 1.2
165// CertificateRequest.
166var supportedClientCertSignatureAlgorithms = []signatureAndHash{
David Benjamine098ec22014-08-27 23:13:20 -0400167 {signatureRSA, hashSHA256},
168 {signatureECDSA, hashSHA256},
Adam Langley95c29f32014-06-20 12:00:00 -0700169}
170
David Benjaminca6c8262014-11-15 19:06:08 -0500171// SRTP protection profiles (See RFC 5764, section 4.1.2)
172const (
173 SRTP_AES128_CM_HMAC_SHA1_80 uint16 = 0x0001
174 SRTP_AES128_CM_HMAC_SHA1_32 = 0x0002
175)
176
Adam Langley95c29f32014-06-20 12:00:00 -0700177// ConnectionState records basic TLS details about the connection.
178type ConnectionState struct {
179 Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
180 HandshakeComplete bool // TLS handshake is complete
181 DidResume bool // connection resumes a previous TLS connection
182 CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
183 NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos)
184 NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server
David Benjaminfc7b0862014-09-06 13:21:53 -0400185 NegotiatedProtocolFromALPN bool // protocol negotiated with ALPN
Adam Langley95c29f32014-06-20 12:00:00 -0700186 ServerName string // server name requested by client, if any (server side only)
187 PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
188 VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
David Benjamind30a9902014-08-24 01:44:23 -0400189 ChannelID *ecdsa.PublicKey // the channel ID for this connection
David Benjaminca6c8262014-11-15 19:06:08 -0500190 SRTPProtectionProfile uint16 // the negotiated DTLS-SRTP protection profile
Adam Langley95c29f32014-06-20 12:00:00 -0700191}
192
193// ClientAuthType declares the policy the server will follow for
194// TLS Client Authentication.
195type ClientAuthType int
196
197const (
198 NoClientCert ClientAuthType = iota
199 RequestClientCert
200 RequireAnyClientCert
201 VerifyClientCertIfGiven
202 RequireAndVerifyClientCert
203)
204
205// ClientSessionState contains the state needed by clients to resume TLS
206// sessions.
207type ClientSessionState struct {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500208 sessionId []uint8 // Session ID supplied by the server. nil if the session has a ticket.
Adam Langley75712922014-10-10 16:23:43 -0700209 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
210 vers uint16 // SSL/TLS version negotiated for the session
211 cipherSuite uint16 // Ciphersuite negotiated for the session
212 masterSecret []byte // MasterSecret generated by client on a full handshake
213 handshakeHash []byte // Handshake hash for Channel ID purposes.
214 serverCertificates []*x509.Certificate // Certificate chain presented by the server
215 extendedMasterSecret bool // Whether an extended master secret was used to generate the session
Adam Langley95c29f32014-06-20 12:00:00 -0700216}
217
218// ClientSessionCache is a cache of ClientSessionState objects that can be used
219// by a client to resume a TLS session with a given server. ClientSessionCache
220// implementations should expect to be called concurrently from different
221// goroutines.
222type ClientSessionCache interface {
223 // Get searches for a ClientSessionState associated with the given key.
224 // On return, ok is true if one was found.
225 Get(sessionKey string) (session *ClientSessionState, ok bool)
226
227 // Put adds the ClientSessionState to the cache with the given key.
228 Put(sessionKey string, cs *ClientSessionState)
229}
230
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500231// ServerSessionCache is a cache of sessionState objects that can be used by a
232// client to resume a TLS session with a given server. ServerSessionCache
233// implementations should expect to be called concurrently from different
234// goroutines.
235type ServerSessionCache interface {
236 // Get searches for a sessionState associated with the given session
237 // ID. On return, ok is true if one was found.
238 Get(sessionId string) (session *sessionState, ok bool)
239
240 // Put adds the sessionState to the cache with the given session ID.
241 Put(sessionId string, session *sessionState)
242}
243
Adam Langley95c29f32014-06-20 12:00:00 -0700244// A Config structure is used to configure a TLS client or server.
245// After one has been passed to a TLS function it must not be
246// modified. A Config may be reused; the tls package will also not
247// modify it.
248type Config struct {
249 // Rand provides the source of entropy for nonces and RSA blinding.
250 // If Rand is nil, TLS uses the cryptographic random reader in package
251 // crypto/rand.
252 // The Reader must be safe for use by multiple goroutines.
253 Rand io.Reader
254
255 // Time returns the current time as the number of seconds since the epoch.
256 // If Time is nil, TLS uses time.Now.
257 Time func() time.Time
258
259 // Certificates contains one or more certificate chains
260 // to present to the other side of the connection.
261 // Server configurations must include at least one certificate.
262 Certificates []Certificate
263
264 // NameToCertificate maps from a certificate name to an element of
265 // Certificates. Note that a certificate name can be of the form
266 // '*.example.com' and so doesn't have to be a domain name as such.
267 // See Config.BuildNameToCertificate
268 // The nil value causes the first element of Certificates to be used
269 // for all connections.
270 NameToCertificate map[string]*Certificate
271
272 // RootCAs defines the set of root certificate authorities
273 // that clients use when verifying server certificates.
274 // If RootCAs is nil, TLS uses the host's root CA set.
275 RootCAs *x509.CertPool
276
277 // NextProtos is a list of supported, application level protocols.
278 NextProtos []string
279
280 // ServerName is used to verify the hostname on the returned
281 // certificates unless InsecureSkipVerify is given. It is also included
282 // in the client's handshake to support virtual hosting.
283 ServerName string
284
285 // ClientAuth determines the server's policy for
286 // TLS Client Authentication. The default is NoClientCert.
287 ClientAuth ClientAuthType
288
289 // ClientCAs defines the set of root certificate authorities
290 // that servers use if required to verify a client certificate
291 // by the policy in ClientAuth.
292 ClientCAs *x509.CertPool
293
David Benjamin7b030512014-07-08 17:30:11 -0400294 // ClientCertificateTypes defines the set of allowed client certificate
295 // types. The default is CertTypeRSASign and CertTypeECDSASign.
296 ClientCertificateTypes []byte
297
Adam Langley95c29f32014-06-20 12:00:00 -0700298 // InsecureSkipVerify controls whether a client verifies the
299 // server's certificate chain and host name.
300 // If InsecureSkipVerify is true, TLS accepts any certificate
301 // presented by the server and any host name in that certificate.
302 // In this mode, TLS is susceptible to man-in-the-middle attacks.
303 // This should be used only for testing.
304 InsecureSkipVerify bool
305
306 // CipherSuites is a list of supported cipher suites. If CipherSuites
307 // is nil, TLS uses a list of suites supported by the implementation.
308 CipherSuites []uint16
309
310 // PreferServerCipherSuites controls whether the server selects the
311 // client's most preferred ciphersuite, or the server's most preferred
312 // ciphersuite. If true then the server's preference, as expressed in
313 // the order of elements in CipherSuites, is used.
314 PreferServerCipherSuites bool
315
316 // SessionTicketsDisabled may be set to true to disable session ticket
317 // (resumption) support.
318 SessionTicketsDisabled bool
319
320 // SessionTicketKey is used by TLS servers to provide session
321 // resumption. See RFC 5077. If zero, it will be filled with
322 // random data before the first server handshake.
323 //
324 // If multiple servers are terminating connections for the same host
325 // they should all have the same SessionTicketKey. If the
326 // SessionTicketKey leaks, previously recorded and future TLS
327 // connections using that key are compromised.
328 SessionTicketKey [32]byte
329
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500330 // ClientSessionCache is a cache of ClientSessionState entries
331 // for TLS session resumption.
Adam Langley95c29f32014-06-20 12:00:00 -0700332 ClientSessionCache ClientSessionCache
333
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500334 // ServerSessionCache is a cache of sessionState entries for TLS session
335 // resumption.
336 ServerSessionCache ServerSessionCache
337
Adam Langley95c29f32014-06-20 12:00:00 -0700338 // MinVersion contains the minimum SSL/TLS version that is acceptable.
339 // If zero, then SSLv3 is taken as the minimum.
340 MinVersion uint16
341
342 // MaxVersion contains the maximum SSL/TLS version that is acceptable.
343 // If zero, then the maximum version supported by this package is used,
344 // which is currently TLS 1.2.
345 MaxVersion uint16
346
347 // CurvePreferences contains the elliptic curves that will be used in
348 // an ECDHE handshake, in preference order. If empty, the default will
349 // be used.
350 CurvePreferences []CurveID
351
David Benjamind30a9902014-08-24 01:44:23 -0400352 // ChannelID contains the ECDSA key for the client to use as
353 // its TLS Channel ID.
354 ChannelID *ecdsa.PrivateKey
355
356 // RequestChannelID controls whether the server requests a TLS
357 // Channel ID. If negotiated, the client's public key is
358 // returned in the ConnectionState.
359 RequestChannelID bool
360
David Benjamin48cae082014-10-27 01:06:24 -0400361 // PreSharedKey, if not nil, is the pre-shared key to use with
362 // the PSK cipher suites.
363 PreSharedKey []byte
364
365 // PreSharedKeyIdentity, if not empty, is the identity to use
366 // with the PSK cipher suites.
367 PreSharedKeyIdentity string
368
David Benjaminca6c8262014-11-15 19:06:08 -0500369 // SRTPProtectionProfiles, if not nil, is the list of SRTP
370 // protection profiles to offer in DTLS-SRTP.
371 SRTPProtectionProfiles []uint16
372
David Benjamin000800a2014-11-14 01:43:59 -0500373 // SignatureAndHashes, if not nil, overrides the default set of
374 // supported signature and hash algorithms to advertise in
375 // CertificateRequest.
376 SignatureAndHashes []signatureAndHash
377
Adam Langley95c29f32014-06-20 12:00:00 -0700378 // Bugs specifies optional misbehaviour to be used for testing other
379 // implementations.
380 Bugs ProtocolBugs
381
382 serverInitOnce sync.Once // guards calling (*Config).serverInit
383}
384
385type BadValue int
386
387const (
388 BadValueNone BadValue = iota
389 BadValueNegative
390 BadValueZero
391 BadValueLimit
392 BadValueLarge
393 NumBadValues
394)
395
396type ProtocolBugs struct {
397 // InvalidSKXSignature specifies that the signature in a
398 // ServerKeyExchange message should be invalid.
399 InvalidSKXSignature bool
400
401 // InvalidSKXCurve causes the curve ID in the ServerKeyExchange message
402 // to be wrong.
403 InvalidSKXCurve bool
404
405 // BadECDSAR controls ways in which the 'r' value of an ECDSA signature
406 // can be invalid.
407 BadECDSAR BadValue
408 BadECDSAS BadValue
Adam Langley80842bd2014-06-20 12:00:00 -0700409
410 // MaxPadding causes CBC records to have the maximum possible padding.
411 MaxPadding bool
412 // PaddingFirstByteBad causes the first byte of the padding to be
413 // incorrect.
414 PaddingFirstByteBad bool
415 // PaddingFirstByteBadIf255 causes the first byte of padding to be
416 // incorrect if there's a maximum amount of padding (i.e. 255 bytes).
417 PaddingFirstByteBadIf255 bool
Adam Langleyac61fa32014-06-23 12:03:11 -0700418
419 // FailIfNotFallbackSCSV causes a server handshake to fail if the
420 // client doesn't send the fallback SCSV value.
421 FailIfNotFallbackSCSV bool
David Benjamin35a7a442014-07-05 00:23:20 -0400422
423 // DuplicateExtension causes an extra empty extension of bogus type to
424 // be emitted in either the ClientHello or the ServerHello.
425 DuplicateExtension bool
David Benjamin1c375dd2014-07-12 00:48:23 -0400426
427 // UnauthenticatedECDH causes the server to pretend ECDHE_RSA
428 // and ECDHE_ECDSA cipher suites are actually ECDH_anon. No
429 // Certificate message is sent and no signature is added to
430 // ServerKeyExchange.
431 UnauthenticatedECDH bool
David Benjamin9c651c92014-07-12 13:27:45 -0400432
David Benjaminb80168e2015-02-08 18:30:14 -0500433 // SkipHelloVerifyRequest causes a DTLS server to skip the
434 // HelloVerifyRequest message.
435 SkipHelloVerifyRequest bool
436
David Benjamindcd979f2015-04-20 18:26:52 -0400437 // SkipCertificateStatus, if true, causes the server to skip the
438 // CertificateStatus message. This is legal because CertificateStatus is
439 // optional, even with a status_request in ServerHello.
440 SkipCertificateStatus bool
441
David Benjamin9c651c92014-07-12 13:27:45 -0400442 // SkipServerKeyExchange causes the server to skip sending
443 // ServerKeyExchange messages.
444 SkipServerKeyExchange bool
David Benjamina0e52232014-07-19 17:39:58 -0400445
David Benjaminb80168e2015-02-08 18:30:14 -0500446 // SkipNewSessionTicket causes the server to skip sending the
447 // NewSessionTicket message despite promising to in ServerHello.
448 SkipNewSessionTicket bool
449
David Benjamina0e52232014-07-19 17:39:58 -0400450 // SkipChangeCipherSpec causes the implementation to skip
451 // sending the ChangeCipherSpec message (and adjusting cipher
452 // state accordingly for the Finished message).
453 SkipChangeCipherSpec bool
David Benjaminf3ec83d2014-07-21 22:42:34 -0400454
David Benjaminb80168e2015-02-08 18:30:14 -0500455 // SkipFinished causes the implementation to skip sending the Finished
456 // message.
457 SkipFinished bool
458
David Benjaminf3ec83d2014-07-21 22:42:34 -0400459 // EarlyChangeCipherSpec causes the client to send an early
460 // ChangeCipherSpec message before the ClientKeyExchange. A value of
461 // zero disables this behavior. One and two configure variants for 0.9.8
462 // and 1.0.1 modes, respectively.
463 EarlyChangeCipherSpec int
David Benjamind23f4122014-07-23 15:09:48 -0400464
David Benjamin86271ee2014-07-21 16:14:03 -0400465 // FragmentAcrossChangeCipherSpec causes the implementation to fragment
466 // the Finished (or NextProto) message around the ChangeCipherSpec
467 // messages.
468 FragmentAcrossChangeCipherSpec bool
469
David Benjamind86c7672014-08-02 04:07:12 -0400470 // SendV2ClientHello causes the client to send a V2ClientHello
471 // instead of a normal ClientHello.
472 SendV2ClientHello bool
David Benjaminbef270a2014-08-02 04:22:02 -0400473
474 // SendFallbackSCSV causes the client to include
475 // TLS_FALLBACK_SCSV in the ClientHello.
476 SendFallbackSCSV bool
David Benjamin43ec06f2014-08-05 02:28:57 -0400477
478 // MaxHandshakeRecordLength, if non-zero, is the maximum size of a
David Benjamin98214542014-08-07 18:02:39 -0400479 // handshake record. Handshake messages will be split into multiple
480 // records at the specified size, except that the client_version will
481 // never be fragmented.
David Benjamin43ec06f2014-08-05 02:28:57 -0400482 MaxHandshakeRecordLength int
David Benjamina8e3e0e2014-08-06 22:11:10 -0400483
David Benjamin98214542014-08-07 18:02:39 -0400484 // FragmentClientVersion will allow MaxHandshakeRecordLength to apply to
485 // the first 6 bytes of the ClientHello.
486 FragmentClientVersion bool
487
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400488 // FragmentAlert will cause all alerts to be fragmented across
489 // two records.
490 FragmentAlert bool
491
David Benjamin3fd1fbd2015-02-03 16:07:32 -0500492 // SendSpuriousAlert, if non-zero, will cause an spurious, unwanted
493 // alert to be sent.
494 SendSpuriousAlert alert
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400495
David Benjamina8e3e0e2014-08-06 22:11:10 -0400496 // RsaClientKeyExchangeVersion, if non-zero, causes the client to send a
497 // ClientKeyExchange with the specified version rather than the
498 // client_version when performing the RSA key exchange.
499 RsaClientKeyExchangeVersion uint16
David Benjaminbed9aae2014-08-07 19:13:38 -0400500
501 // RenewTicketOnResume causes the server to renew the session ticket and
502 // send a NewSessionTicket message during an abbreviated handshake.
503 RenewTicketOnResume bool
David Benjamin98e882e2014-08-08 13:24:34 -0400504
505 // SendClientVersion, if non-zero, causes the client to send a different
506 // TLS version in the ClientHello than the maximum supported version.
507 SendClientVersion uint16
David Benjamin83c0bc92014-08-04 01:23:53 -0400508
David Benjamine58c4f52014-08-24 03:47:07 -0400509 // ExpectFalseStart causes the server to, on full handshakes,
510 // expect the peer to False Start; the server Finished message
511 // isn't sent until we receive an application data record
512 // from the peer.
513 ExpectFalseStart bool
David Benjamin5c24a1d2014-08-31 00:59:27 -0400514
David Benjamin1c633152015-04-02 20:19:11 -0400515 // AlertBeforeFalseStartTest, if non-zero, causes the server to, on full
516 // handshakes, send an alert just before reading the application data
517 // record to test False Start. This can be used in a negative False
518 // Start test to determine whether the peer processed the alert (and
519 // closed the connection) before or after sending app data.
520 AlertBeforeFalseStartTest alert
521
David Benjamin5c24a1d2014-08-31 00:59:27 -0400522 // SSL3RSAKeyExchange causes the client to always send an RSA
523 // ClientKeyExchange message without the two-byte length
524 // prefix, as if it were SSL3.
525 SSL3RSAKeyExchange bool
David Benjamin39ebf532014-08-31 02:23:49 -0400526
527 // SkipCipherVersionCheck causes the server to negotiate
528 // TLS 1.2 ciphers in earlier versions of TLS.
529 SkipCipherVersionCheck bool
David Benjamine78bfde2014-09-06 12:45:15 -0400530
531 // ExpectServerName, if not empty, is the hostname the client
532 // must specify in the server_name extension.
533 ExpectServerName string
David Benjaminfc7b0862014-09-06 13:21:53 -0400534
535 // SwapNPNAndALPN switches the relative order between NPN and
536 // ALPN on the server. This is to test that server preference
537 // of ALPN works regardless of their relative order.
538 SwapNPNAndALPN bool
David Benjamin01fe8202014-09-24 15:21:44 -0400539
540 // AllowSessionVersionMismatch causes the server to resume sessions
541 // regardless of the version associated with the session.
542 AllowSessionVersionMismatch bool
Adam Langley38311732014-10-16 19:04:35 -0700543
544 // CorruptTicket causes a client to corrupt a session ticket before
545 // sending it in a resume handshake.
546 CorruptTicket bool
547
548 // OversizedSessionId causes the session id that is sent with a ticket
549 // resumption attempt to be too large (33 bytes).
550 OversizedSessionId bool
Adam Langley75712922014-10-10 16:23:43 -0700551
552 // RequireExtendedMasterSecret, if true, requires that the peer support
553 // the extended master secret option.
554 RequireExtendedMasterSecret bool
555
David Benjaminca6554b2014-11-08 12:31:52 -0500556 // NoExtendedMasterSecret causes the client and server to behave as if
Adam Langley75712922014-10-10 16:23:43 -0700557 // they didn't support an extended master secret.
558 NoExtendedMasterSecret bool
Adam Langley2ae77d22014-10-28 17:29:33 -0700559
560 // EmptyRenegotiationInfo causes the renegotiation extension to be
561 // empty in a renegotiation handshake.
562 EmptyRenegotiationInfo bool
563
564 // BadRenegotiationInfo causes the renegotiation extension value in a
565 // renegotiation handshake to be incorrect.
566 BadRenegotiationInfo bool
David Benjamin5e961c12014-11-07 01:48:35 -0500567
David Benjaminca6554b2014-11-08 12:31:52 -0500568 // NoRenegotiationInfo causes the client to behave as if it
569 // didn't support the renegotiation info extension.
570 NoRenegotiationInfo bool
571
David Benjamin5e961c12014-11-07 01:48:35 -0500572 // SequenceNumberIncrement, if non-zero, causes outgoing sequence
573 // numbers in DTLS to increment by that value rather by 1. This is to
574 // stress the replay bitmap window by simulating extreme packet loss and
575 // retransmit at the record layer.
576 SequenceNumberIncrement uint64
David Benjamin9114fae2014-11-08 11:41:14 -0500577
David Benjamina3e89492015-02-26 15:16:22 -0500578 // RSAEphemeralKey, if true, causes the server to send a
579 // ServerKeyExchange message containing an ephemeral key (as in
580 // RSA_EXPORT) in the plain RSA key exchange.
581 RSAEphemeralKey bool
David Benjaminca6c8262014-11-15 19:06:08 -0500582
583 // SRTPMasterKeyIdentifer, if not empty, is the SRTP MKI value that the
584 // client offers when negotiating SRTP. MKI support is still missing so
585 // the peer must still send none.
586 SRTPMasterKeyIdentifer string
587
588 // SendSRTPProtectionProfile, if non-zero, is the SRTP profile that the
589 // server sends in the ServerHello instead of the negotiated one.
590 SendSRTPProtectionProfile uint16
David Benjamin000800a2014-11-14 01:43:59 -0500591
592 // NoSignatureAndHashes, if true, causes the client to omit the
593 // signature and hashes extension.
594 //
595 // For a server, it will cause an empty list to be sent in the
596 // CertificateRequest message. None the less, the configured set will
597 // still be enforced.
598 NoSignatureAndHashes bool
David Benjaminc44b1df2014-11-23 12:11:01 -0500599
David Benjamin55a43642015-04-20 14:45:55 -0400600 // NoSupportedCurves, if true, causes the client to omit the
601 // supported_curves extension.
602 NoSupportedCurves bool
603
David Benjaminc44b1df2014-11-23 12:11:01 -0500604 // RequireSameRenegoClientVersion, if true, causes the server
605 // to require that all ClientHellos match in offered version
606 // across a renego.
607 RequireSameRenegoClientVersion bool
Feng Lu41aa3252014-11-21 22:47:56 -0800608
609 // RequireFastradioPadding, if true, requires that ClientHello messages
610 // be at least 1000 bytes long.
611 RequireFastradioPadding bool
David Benjamin1e29a6b2014-12-10 02:27:24 -0500612
613 // ExpectInitialRecordVersion, if non-zero, is the expected
614 // version of the records before the version is determined.
615 ExpectInitialRecordVersion uint16
David Benjamin13be1de2015-01-11 16:29:36 -0500616
617 // MaxPacketLength, if non-zero, is the maximum acceptable size for a
618 // packet.
619 MaxPacketLength int
David Benjamin6095de82014-12-27 01:50:38 -0500620
621 // SendCipherSuite, if non-zero, is the cipher suite value that the
622 // server will send in the ServerHello. This does not affect the cipher
623 // the server believes it has actually negotiated.
624 SendCipherSuite uint16
David Benjamin4189bd92015-01-25 23:52:39 -0500625
626 // AppDataAfterChangeCipherSpec, if not null, causes application data to
627 // be sent immediately after ChangeCipherSpec.
628 AppDataAfterChangeCipherSpec []byte
David Benjamin83f90402015-01-27 01:09:43 -0500629
David Benjamindc3da932015-03-12 15:09:02 -0400630 // AlertAfterChangeCipherSpec, if non-zero, causes an alert to be sent
631 // immediately after ChangeCipherSpec.
632 AlertAfterChangeCipherSpec alert
633
David Benjamin83f90402015-01-27 01:09:43 -0500634 // TimeoutSchedule is the schedule of packet drops and simulated
635 // timeouts for before each handshake leg from the peer.
636 TimeoutSchedule []time.Duration
637
638 // PacketAdaptor is the packetAdaptor to use to simulate timeouts.
639 PacketAdaptor *packetAdaptor
David Benjaminb3774b92015-01-31 17:16:01 -0500640
641 // ReorderHandshakeFragments, if true, causes handshake fragments in
642 // DTLS to overlap and be sent in the wrong order. It also causes
643 // pre-CCS flights to be sent twice. (Post-CCS flights consist of
644 // Finished and will trigger a spurious retransmit.)
645 ReorderHandshakeFragments bool
David Benjaminddb9f152015-02-03 15:44:39 -0500646
David Benjamin75381222015-03-02 19:30:30 -0500647 // MixCompleteMessageWithFragments, if true, causes handshake
648 // messages in DTLS to redundantly both fragment the message
649 // and include a copy of the full one.
650 MixCompleteMessageWithFragments bool
651
David Benjaminddb9f152015-02-03 15:44:39 -0500652 // SendInvalidRecordType, if true, causes a record with an invalid
653 // content type to be sent immediately following the handshake.
654 SendInvalidRecordType bool
David Benjaminbcb2d912015-02-24 23:45:43 -0500655
656 // WrongCertificateMessageType, if true, causes Certificate message to
657 // be sent with the wrong message type.
658 WrongCertificateMessageType bool
David Benjamin75381222015-03-02 19:30:30 -0500659
660 // FragmentMessageTypeMismatch, if true, causes all non-initial
661 // handshake fragments in DTLS to have the wrong message type.
662 FragmentMessageTypeMismatch bool
663
664 // FragmentMessageLengthMismatch, if true, causes all non-initial
665 // handshake fragments in DTLS to have the wrong message length.
666 FragmentMessageLengthMismatch bool
667
668 // SplitFragmentHeader, if true, causes the handshake fragments in DTLS
669 // to be split across two records.
670 SplitFragmentHeader bool
671
672 // SplitFragmentBody, if true, causes the handshake bodies in DTLS to be
673 // split across two records.
674 //
675 // TODO(davidben): There's one final split to test: when the header and
676 // body are split across two records. But those are (incorrectly)
677 // accepted right now.
678 SplitFragmentBody bool
679
680 // SendEmptyFragments, if true, causes handshakes to include empty
681 // fragments in DTLS.
682 SendEmptyFragments bool
David Benjamincdea40c2015-03-19 14:09:43 -0400683
David Benjamin4b27d9f2015-05-12 22:42:52 -0400684 // FailIfResumeOnRenego, if true, causes renegotiations to fail if the
685 // client offers a resumption or the server accepts one.
686 FailIfResumeOnRenego bool
David Benjamin3c9746a2015-03-19 15:00:10 -0400687
688 // NoSignatureAlgorithmsOnRenego, if true, causes renegotiations to omit
689 // the signature_algorithms extension.
690 NoSignatureAlgorithmsOnRenego bool
David Benjamin67d1fb52015-03-16 15:16:23 -0400691
692 // IgnorePeerCipherPreferences, if true, causes the peer's cipher
693 // preferences to be ignored.
694 IgnorePeerCipherPreferences bool
David Benjamin72dc7832015-03-16 17:49:43 -0400695
696 // IgnorePeerSignatureAlgorithmPreferences, if true, causes the peer's
697 // signature algorithm preferences to be ignored.
698 IgnorePeerSignatureAlgorithmPreferences bool
David Benjamin340d5ed2015-03-21 02:21:37 -0400699
David Benjaminc574f412015-04-20 11:13:01 -0400700 // IgnorePeerCurvePreferences, if true, causes the peer's curve
701 // preferences to be ignored.
702 IgnorePeerCurvePreferences bool
703
David Benjamin340d5ed2015-03-21 02:21:37 -0400704 // SendWarningAlerts, if non-zero, causes every record to be prefaced by
705 // a warning alert.
706 SendWarningAlerts alert
David Benjamin513f0ea2015-04-02 19:33:31 -0400707
708 // BadFinished, if true, causes the Finished hash to be broken.
709 BadFinished bool
Adam Langley95c29f32014-06-20 12:00:00 -0700710}
711
712func (c *Config) serverInit() {
713 if c.SessionTicketsDisabled {
714 return
715 }
716
717 // If the key has already been set then we have nothing to do.
718 for _, b := range c.SessionTicketKey {
719 if b != 0 {
720 return
721 }
722 }
723
724 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
725 c.SessionTicketsDisabled = true
726 }
727}
728
729func (c *Config) rand() io.Reader {
730 r := c.Rand
731 if r == nil {
732 return rand.Reader
733 }
734 return r
735}
736
737func (c *Config) time() time.Time {
738 t := c.Time
739 if t == nil {
740 t = time.Now
741 }
742 return t()
743}
744
745func (c *Config) cipherSuites() []uint16 {
746 s := c.CipherSuites
747 if s == nil {
748 s = defaultCipherSuites()
749 }
750 return s
751}
752
753func (c *Config) minVersion() uint16 {
754 if c == nil || c.MinVersion == 0 {
755 return minVersion
756 }
757 return c.MinVersion
758}
759
760func (c *Config) maxVersion() uint16 {
761 if c == nil || c.MaxVersion == 0 {
762 return maxVersion
763 }
764 return c.MaxVersion
765}
766
767var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
768
769func (c *Config) curvePreferences() []CurveID {
770 if c == nil || len(c.CurvePreferences) == 0 {
771 return defaultCurvePreferences
772 }
773 return c.CurvePreferences
774}
775
776// mutualVersion returns the protocol version to use given the advertised
777// version of the peer.
778func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
779 minVersion := c.minVersion()
780 maxVersion := c.maxVersion()
781
782 if vers < minVersion {
783 return 0, false
784 }
785 if vers > maxVersion {
786 vers = maxVersion
787 }
788 return vers, true
789}
790
791// getCertificateForName returns the best certificate for the given name,
792// defaulting to the first element of c.Certificates if there are no good
793// options.
794func (c *Config) getCertificateForName(name string) *Certificate {
795 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
796 // There's only one choice, so no point doing any work.
797 return &c.Certificates[0]
798 }
799
800 name = strings.ToLower(name)
801 for len(name) > 0 && name[len(name)-1] == '.' {
802 name = name[:len(name)-1]
803 }
804
805 if cert, ok := c.NameToCertificate[name]; ok {
806 return cert
807 }
808
809 // try replacing labels in the name with wildcards until we get a
810 // match.
811 labels := strings.Split(name, ".")
812 for i := range labels {
813 labels[i] = "*"
814 candidate := strings.Join(labels, ".")
815 if cert, ok := c.NameToCertificate[candidate]; ok {
816 return cert
817 }
818 }
819
820 // If nothing matches, return the first certificate.
821 return &c.Certificates[0]
822}
823
David Benjamin000800a2014-11-14 01:43:59 -0500824func (c *Config) signatureAndHashesForServer() []signatureAndHash {
825 if c != nil && c.SignatureAndHashes != nil {
826 return c.SignatureAndHashes
827 }
828 return supportedClientCertSignatureAlgorithms
829}
830
831func (c *Config) signatureAndHashesForClient() []signatureAndHash {
832 if c != nil && c.SignatureAndHashes != nil {
833 return c.SignatureAndHashes
834 }
835 return supportedSKXSignatureAlgorithms
836}
837
Adam Langley95c29f32014-06-20 12:00:00 -0700838// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
839// from the CommonName and SubjectAlternateName fields of each of the leaf
840// certificates.
841func (c *Config) BuildNameToCertificate() {
842 c.NameToCertificate = make(map[string]*Certificate)
843 for i := range c.Certificates {
844 cert := &c.Certificates[i]
845 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
846 if err != nil {
847 continue
848 }
849 if len(x509Cert.Subject.CommonName) > 0 {
850 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
851 }
852 for _, san := range x509Cert.DNSNames {
853 c.NameToCertificate[san] = cert
854 }
855 }
856}
857
858// A Certificate is a chain of one or more certificates, leaf first.
859type Certificate struct {
860 Certificate [][]byte
861 PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
862 // OCSPStaple contains an optional OCSP response which will be served
863 // to clients that request it.
864 OCSPStaple []byte
David Benjamin61f95272014-11-25 01:55:35 -0500865 // SignedCertificateTimestampList contains an optional encoded
866 // SignedCertificateTimestampList structure which will be
867 // served to clients that request it.
868 SignedCertificateTimestampList []byte
Adam Langley95c29f32014-06-20 12:00:00 -0700869 // Leaf is the parsed form of the leaf certificate, which may be
870 // initialized using x509.ParseCertificate to reduce per-handshake
871 // processing for TLS clients doing client authentication. If nil, the
872 // leaf certificate will be parsed as needed.
873 Leaf *x509.Certificate
874}
875
876// A TLS record.
877type record struct {
878 contentType recordType
879 major, minor uint8
880 payload []byte
881}
882
883type handshakeMessage interface {
884 marshal() []byte
885 unmarshal([]byte) bool
886}
887
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500888// lruSessionCache is a client or server session cache implementation
889// that uses an LRU caching strategy.
Adam Langley95c29f32014-06-20 12:00:00 -0700890type lruSessionCache struct {
891 sync.Mutex
892
893 m map[string]*list.Element
894 q *list.List
895 capacity int
896}
897
898type lruSessionCacheEntry struct {
899 sessionKey string
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500900 state interface{}
Adam Langley95c29f32014-06-20 12:00:00 -0700901}
902
903// Put adds the provided (sessionKey, cs) pair to the cache.
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500904func (c *lruSessionCache) Put(sessionKey string, cs interface{}) {
Adam Langley95c29f32014-06-20 12:00:00 -0700905 c.Lock()
906 defer c.Unlock()
907
908 if elem, ok := c.m[sessionKey]; ok {
909 entry := elem.Value.(*lruSessionCacheEntry)
910 entry.state = cs
911 c.q.MoveToFront(elem)
912 return
913 }
914
915 if c.q.Len() < c.capacity {
916 entry := &lruSessionCacheEntry{sessionKey, cs}
917 c.m[sessionKey] = c.q.PushFront(entry)
918 return
919 }
920
921 elem := c.q.Back()
922 entry := elem.Value.(*lruSessionCacheEntry)
923 delete(c.m, entry.sessionKey)
924 entry.sessionKey = sessionKey
925 entry.state = cs
926 c.q.MoveToFront(elem)
927 c.m[sessionKey] = elem
928}
929
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500930// Get returns the value associated with a given key. It returns (nil,
931// false) if no value is found.
932func (c *lruSessionCache) Get(sessionKey string) (interface{}, bool) {
Adam Langley95c29f32014-06-20 12:00:00 -0700933 c.Lock()
934 defer c.Unlock()
935
936 if elem, ok := c.m[sessionKey]; ok {
937 c.q.MoveToFront(elem)
938 return elem.Value.(*lruSessionCacheEntry).state, true
939 }
940 return nil, false
941}
942
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500943// lruClientSessionCache is a ClientSessionCache implementation that
944// uses an LRU caching strategy.
945type lruClientSessionCache struct {
946 lruSessionCache
947}
948
949func (c *lruClientSessionCache) Put(sessionKey string, cs *ClientSessionState) {
950 c.lruSessionCache.Put(sessionKey, cs)
951}
952
953func (c *lruClientSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
954 cs, ok := c.lruSessionCache.Get(sessionKey)
955 if !ok {
956 return nil, false
957 }
958 return cs.(*ClientSessionState), true
959}
960
961// lruServerSessionCache is a ServerSessionCache implementation that
962// uses an LRU caching strategy.
963type lruServerSessionCache struct {
964 lruSessionCache
965}
966
967func (c *lruServerSessionCache) Put(sessionId string, session *sessionState) {
968 c.lruSessionCache.Put(sessionId, session)
969}
970
971func (c *lruServerSessionCache) Get(sessionId string) (*sessionState, bool) {
972 cs, ok := c.lruSessionCache.Get(sessionId)
973 if !ok {
974 return nil, false
975 }
976 return cs.(*sessionState), true
977}
978
979// NewLRUClientSessionCache returns a ClientSessionCache with the given
980// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
981// is used instead.
982func NewLRUClientSessionCache(capacity int) ClientSessionCache {
983 const defaultSessionCacheCapacity = 64
984
985 if capacity < 1 {
986 capacity = defaultSessionCacheCapacity
987 }
988 return &lruClientSessionCache{
989 lruSessionCache{
990 m: make(map[string]*list.Element),
991 q: list.New(),
992 capacity: capacity,
993 },
994 }
995}
996
997// NewLRUServerSessionCache returns a ServerSessionCache with the given
998// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
999// is used instead.
1000func NewLRUServerSessionCache(capacity int) ServerSessionCache {
1001 const defaultSessionCacheCapacity = 64
1002
1003 if capacity < 1 {
1004 capacity = defaultSessionCacheCapacity
1005 }
1006 return &lruServerSessionCache{
1007 lruSessionCache{
1008 m: make(map[string]*list.Element),
1009 q: list.New(),
1010 capacity: capacity,
1011 },
1012 }
1013}
1014
Adam Langley95c29f32014-06-20 12:00:00 -07001015// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
1016type dsaSignature struct {
1017 R, S *big.Int
1018}
1019
1020type ecdsaSignature dsaSignature
1021
1022var emptyConfig Config
1023
1024func defaultConfig() *Config {
1025 return &emptyConfig
1026}
1027
1028var (
1029 once sync.Once
1030 varDefaultCipherSuites []uint16
1031)
1032
1033func defaultCipherSuites() []uint16 {
1034 once.Do(initDefaultCipherSuites)
1035 return varDefaultCipherSuites
1036}
1037
1038func initDefaultCipherSuites() {
David Benjamin48cae082014-10-27 01:06:24 -04001039 for _, suite := range cipherSuites {
1040 if suite.flags&suitePSK == 0 {
1041 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
1042 }
Adam Langley95c29f32014-06-20 12:00:00 -07001043 }
1044}
1045
1046func unexpectedMessageError(wanted, got interface{}) error {
1047 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1048}
David Benjamin000800a2014-11-14 01:43:59 -05001049
1050func isSupportedSignatureAndHash(sigHash signatureAndHash, sigHashes []signatureAndHash) bool {
1051 for _, s := range sigHashes {
1052 if s == sigHash {
1053 return true
1054 }
1055 }
1056 return false
1057}