blob: a33ad19b930dd7d3439f11a670849627a1fa641f [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 (
100 CurveP256 CurveID = 23
101 CurveP384 CurveID = 24
102 CurveP521 CurveID = 25
103)
104
105// TLS Elliptic Curve Point Formats
106// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
107const (
108 pointFormatUncompressed uint8 = 0
109)
110
111// TLS CertificateStatusType (RFC 3546)
112const (
113 statusTypeOCSP uint8 = 1
114)
115
116// Certificate types (for certificateRequestMsg)
117const (
David Benjamin7b030512014-07-08 17:30:11 -0400118 CertTypeRSASign = 1 // A certificate containing an RSA key
119 CertTypeDSSSign = 2 // A certificate containing a DSA key
120 CertTypeRSAFixedDH = 3 // A certificate containing a static DH key
121 CertTypeDSSFixedDH = 4 // A certificate containing a static DH key
Adam Langley95c29f32014-06-20 12:00:00 -0700122
123 // See RFC4492 sections 3 and 5.5.
David Benjamin7b030512014-07-08 17:30:11 -0400124 CertTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
125 CertTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
126 CertTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
Adam Langley95c29f32014-06-20 12:00:00 -0700127
128 // Rest of these are reserved by the TLS spec
129)
130
131// Hash functions for TLS 1.2 (See RFC 5246, section A.4.1)
132const (
David Benjamin000800a2014-11-14 01:43:59 -0500133 hashMD5 uint8 = 1
Adam Langley95c29f32014-06-20 12:00:00 -0700134 hashSHA1 uint8 = 2
David Benjamin000800a2014-11-14 01:43:59 -0500135 hashSHA224 uint8 = 3
Adam Langley95c29f32014-06-20 12:00:00 -0700136 hashSHA256 uint8 = 4
David Benjamin000800a2014-11-14 01:43:59 -0500137 hashSHA384 uint8 = 5
138 hashSHA512 uint8 = 6
Adam Langley95c29f32014-06-20 12:00:00 -0700139)
140
141// Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
142const (
143 signatureRSA uint8 = 1
144 signatureECDSA uint8 = 3
145)
146
147// signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See
148// RFC 5246, section A.4.1.
149type signatureAndHash struct {
David Benjamine098ec22014-08-27 23:13:20 -0400150 signature, hash uint8
Adam Langley95c29f32014-06-20 12:00:00 -0700151}
152
153// supportedSKXSignatureAlgorithms contains the signature and hash algorithms
154// that the code advertises as supported in a TLS 1.2 ClientHello.
155var supportedSKXSignatureAlgorithms = []signatureAndHash{
David Benjamine098ec22014-08-27 23:13:20 -0400156 {signatureRSA, hashSHA256},
157 {signatureECDSA, hashSHA256},
158 {signatureRSA, hashSHA1},
159 {signatureECDSA, hashSHA1},
Adam Langley95c29f32014-06-20 12:00:00 -0700160}
161
162// supportedClientCertSignatureAlgorithms contains the signature and hash
163// algorithms that the code advertises as supported in a TLS 1.2
164// CertificateRequest.
165var supportedClientCertSignatureAlgorithms = []signatureAndHash{
David Benjamine098ec22014-08-27 23:13:20 -0400166 {signatureRSA, hashSHA256},
167 {signatureECDSA, hashSHA256},
Adam Langley95c29f32014-06-20 12:00:00 -0700168}
169
David Benjaminca6c8262014-11-15 19:06:08 -0500170// SRTP protection profiles (See RFC 5764, section 4.1.2)
171const (
172 SRTP_AES128_CM_HMAC_SHA1_80 uint16 = 0x0001
173 SRTP_AES128_CM_HMAC_SHA1_32 = 0x0002
174)
175
Adam Langley95c29f32014-06-20 12:00:00 -0700176// ConnectionState records basic TLS details about the connection.
177type ConnectionState struct {
178 Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
179 HandshakeComplete bool // TLS handshake is complete
180 DidResume bool // connection resumes a previous TLS connection
181 CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
182 NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos)
183 NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server
David Benjaminfc7b0862014-09-06 13:21:53 -0400184 NegotiatedProtocolFromALPN bool // protocol negotiated with ALPN
Adam Langley95c29f32014-06-20 12:00:00 -0700185 ServerName string // server name requested by client, if any (server side only)
186 PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
187 VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
David Benjamind30a9902014-08-24 01:44:23 -0400188 ChannelID *ecdsa.PublicKey // the channel ID for this connection
David Benjaminca6c8262014-11-15 19:06:08 -0500189 SRTPProtectionProfile uint16 // the negotiated DTLS-SRTP protection profile
Adam Langley95c29f32014-06-20 12:00:00 -0700190}
191
192// ClientAuthType declares the policy the server will follow for
193// TLS Client Authentication.
194type ClientAuthType int
195
196const (
197 NoClientCert ClientAuthType = iota
198 RequestClientCert
199 RequireAnyClientCert
200 VerifyClientCertIfGiven
201 RequireAndVerifyClientCert
202)
203
204// ClientSessionState contains the state needed by clients to resume TLS
205// sessions.
206type ClientSessionState struct {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500207 sessionId []uint8 // Session ID supplied by the server. nil if the session has a ticket.
Adam Langley75712922014-10-10 16:23:43 -0700208 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
209 vers uint16 // SSL/TLS version negotiated for the session
210 cipherSuite uint16 // Ciphersuite negotiated for the session
211 masterSecret []byte // MasterSecret generated by client on a full handshake
212 handshakeHash []byte // Handshake hash for Channel ID purposes.
213 serverCertificates []*x509.Certificate // Certificate chain presented by the server
214 extendedMasterSecret bool // Whether an extended master secret was used to generate the session
Adam Langley95c29f32014-06-20 12:00:00 -0700215}
216
217// ClientSessionCache is a cache of ClientSessionState objects that can be used
218// by a client to resume a TLS session with a given server. ClientSessionCache
219// implementations should expect to be called concurrently from different
220// goroutines.
221type ClientSessionCache interface {
222 // Get searches for a ClientSessionState associated with the given key.
223 // On return, ok is true if one was found.
224 Get(sessionKey string) (session *ClientSessionState, ok bool)
225
226 // Put adds the ClientSessionState to the cache with the given key.
227 Put(sessionKey string, cs *ClientSessionState)
228}
229
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500230// ServerSessionCache is a cache of sessionState objects that can be used by a
231// client to resume a TLS session with a given server. ServerSessionCache
232// implementations should expect to be called concurrently from different
233// goroutines.
234type ServerSessionCache interface {
235 // Get searches for a sessionState associated with the given session
236 // ID. On return, ok is true if one was found.
237 Get(sessionId string) (session *sessionState, ok bool)
238
239 // Put adds the sessionState to the cache with the given session ID.
240 Put(sessionId string, session *sessionState)
241}
242
Adam Langley95c29f32014-06-20 12:00:00 -0700243// A Config structure is used to configure a TLS client or server.
244// After one has been passed to a TLS function it must not be
245// modified. A Config may be reused; the tls package will also not
246// modify it.
247type Config struct {
248 // Rand provides the source of entropy for nonces and RSA blinding.
249 // If Rand is nil, TLS uses the cryptographic random reader in package
250 // crypto/rand.
251 // The Reader must be safe for use by multiple goroutines.
252 Rand io.Reader
253
254 // Time returns the current time as the number of seconds since the epoch.
255 // If Time is nil, TLS uses time.Now.
256 Time func() time.Time
257
258 // Certificates contains one or more certificate chains
259 // to present to the other side of the connection.
260 // Server configurations must include at least one certificate.
261 Certificates []Certificate
262
263 // NameToCertificate maps from a certificate name to an element of
264 // Certificates. Note that a certificate name can be of the form
265 // '*.example.com' and so doesn't have to be a domain name as such.
266 // See Config.BuildNameToCertificate
267 // The nil value causes the first element of Certificates to be used
268 // for all connections.
269 NameToCertificate map[string]*Certificate
270
271 // RootCAs defines the set of root certificate authorities
272 // that clients use when verifying server certificates.
273 // If RootCAs is nil, TLS uses the host's root CA set.
274 RootCAs *x509.CertPool
275
276 // NextProtos is a list of supported, application level protocols.
277 NextProtos []string
278
279 // ServerName is used to verify the hostname on the returned
280 // certificates unless InsecureSkipVerify is given. It is also included
281 // in the client's handshake to support virtual hosting.
282 ServerName string
283
284 // ClientAuth determines the server's policy for
285 // TLS Client Authentication. The default is NoClientCert.
286 ClientAuth ClientAuthType
287
288 // ClientCAs defines the set of root certificate authorities
289 // that servers use if required to verify a client certificate
290 // by the policy in ClientAuth.
291 ClientCAs *x509.CertPool
292
David Benjamin7b030512014-07-08 17:30:11 -0400293 // ClientCertificateTypes defines the set of allowed client certificate
294 // types. The default is CertTypeRSASign and CertTypeECDSASign.
295 ClientCertificateTypes []byte
296
Adam Langley95c29f32014-06-20 12:00:00 -0700297 // InsecureSkipVerify controls whether a client verifies the
298 // server's certificate chain and host name.
299 // If InsecureSkipVerify is true, TLS accepts any certificate
300 // presented by the server and any host name in that certificate.
301 // In this mode, TLS is susceptible to man-in-the-middle attacks.
302 // This should be used only for testing.
303 InsecureSkipVerify bool
304
305 // CipherSuites is a list of supported cipher suites. If CipherSuites
306 // is nil, TLS uses a list of suites supported by the implementation.
307 CipherSuites []uint16
308
309 // PreferServerCipherSuites controls whether the server selects the
310 // client's most preferred ciphersuite, or the server's most preferred
311 // ciphersuite. If true then the server's preference, as expressed in
312 // the order of elements in CipherSuites, is used.
313 PreferServerCipherSuites bool
314
315 // SessionTicketsDisabled may be set to true to disable session ticket
316 // (resumption) support.
317 SessionTicketsDisabled bool
318
319 // SessionTicketKey is used by TLS servers to provide session
320 // resumption. See RFC 5077. If zero, it will be filled with
321 // random data before the first server handshake.
322 //
323 // If multiple servers are terminating connections for the same host
324 // they should all have the same SessionTicketKey. If the
325 // SessionTicketKey leaks, previously recorded and future TLS
326 // connections using that key are compromised.
327 SessionTicketKey [32]byte
328
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500329 // ClientSessionCache is a cache of ClientSessionState entries
330 // for TLS session resumption.
Adam Langley95c29f32014-06-20 12:00:00 -0700331 ClientSessionCache ClientSessionCache
332
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500333 // ServerSessionCache is a cache of sessionState entries for TLS session
334 // resumption.
335 ServerSessionCache ServerSessionCache
336
Adam Langley95c29f32014-06-20 12:00:00 -0700337 // MinVersion contains the minimum SSL/TLS version that is acceptable.
338 // If zero, then SSLv3 is taken as the minimum.
339 MinVersion uint16
340
341 // MaxVersion contains the maximum SSL/TLS version that is acceptable.
342 // If zero, then the maximum version supported by this package is used,
343 // which is currently TLS 1.2.
344 MaxVersion uint16
345
346 // CurvePreferences contains the elliptic curves that will be used in
347 // an ECDHE handshake, in preference order. If empty, the default will
348 // be used.
349 CurvePreferences []CurveID
350
David Benjamind30a9902014-08-24 01:44:23 -0400351 // ChannelID contains the ECDSA key for the client to use as
352 // its TLS Channel ID.
353 ChannelID *ecdsa.PrivateKey
354
355 // RequestChannelID controls whether the server requests a TLS
356 // Channel ID. If negotiated, the client's public key is
357 // returned in the ConnectionState.
358 RequestChannelID bool
359
David Benjamin48cae082014-10-27 01:06:24 -0400360 // PreSharedKey, if not nil, is the pre-shared key to use with
361 // the PSK cipher suites.
362 PreSharedKey []byte
363
364 // PreSharedKeyIdentity, if not empty, is the identity to use
365 // with the PSK cipher suites.
366 PreSharedKeyIdentity string
367
David Benjaminca6c8262014-11-15 19:06:08 -0500368 // SRTPProtectionProfiles, if not nil, is the list of SRTP
369 // protection profiles to offer in DTLS-SRTP.
370 SRTPProtectionProfiles []uint16
371
David Benjamin000800a2014-11-14 01:43:59 -0500372 // SignatureAndHashes, if not nil, overrides the default set of
373 // supported signature and hash algorithms to advertise in
374 // CertificateRequest.
375 SignatureAndHashes []signatureAndHash
376
Adam Langley95c29f32014-06-20 12:00:00 -0700377 // Bugs specifies optional misbehaviour to be used for testing other
378 // implementations.
379 Bugs ProtocolBugs
380
381 serverInitOnce sync.Once // guards calling (*Config).serverInit
382}
383
384type BadValue int
385
386const (
387 BadValueNone BadValue = iota
388 BadValueNegative
389 BadValueZero
390 BadValueLimit
391 BadValueLarge
392 NumBadValues
393)
394
395type ProtocolBugs struct {
396 // InvalidSKXSignature specifies that the signature in a
397 // ServerKeyExchange message should be invalid.
398 InvalidSKXSignature bool
399
400 // InvalidSKXCurve causes the curve ID in the ServerKeyExchange message
401 // to be wrong.
402 InvalidSKXCurve bool
403
404 // BadECDSAR controls ways in which the 'r' value of an ECDSA signature
405 // can be invalid.
406 BadECDSAR BadValue
407 BadECDSAS BadValue
Adam Langley80842bd2014-06-20 12:00:00 -0700408
409 // MaxPadding causes CBC records to have the maximum possible padding.
410 MaxPadding bool
411 // PaddingFirstByteBad causes the first byte of the padding to be
412 // incorrect.
413 PaddingFirstByteBad bool
414 // PaddingFirstByteBadIf255 causes the first byte of padding to be
415 // incorrect if there's a maximum amount of padding (i.e. 255 bytes).
416 PaddingFirstByteBadIf255 bool
Adam Langleyac61fa32014-06-23 12:03:11 -0700417
418 // FailIfNotFallbackSCSV causes a server handshake to fail if the
419 // client doesn't send the fallback SCSV value.
420 FailIfNotFallbackSCSV bool
David Benjamin35a7a442014-07-05 00:23:20 -0400421
422 // DuplicateExtension causes an extra empty extension of bogus type to
423 // be emitted in either the ClientHello or the ServerHello.
424 DuplicateExtension bool
David Benjamin1c375dd2014-07-12 00:48:23 -0400425
426 // UnauthenticatedECDH causes the server to pretend ECDHE_RSA
427 // and ECDHE_ECDSA cipher suites are actually ECDH_anon. No
428 // Certificate message is sent and no signature is added to
429 // ServerKeyExchange.
430 UnauthenticatedECDH bool
David Benjamin9c651c92014-07-12 13:27:45 -0400431
David Benjaminb80168e2015-02-08 18:30:14 -0500432 // SkipHelloVerifyRequest causes a DTLS server to skip the
433 // HelloVerifyRequest message.
434 SkipHelloVerifyRequest bool
435
David Benjamin9c651c92014-07-12 13:27:45 -0400436 // SkipServerKeyExchange causes the server to skip sending
437 // ServerKeyExchange messages.
438 SkipServerKeyExchange bool
David Benjamina0e52232014-07-19 17:39:58 -0400439
David Benjaminb80168e2015-02-08 18:30:14 -0500440 // SkipNewSessionTicket causes the server to skip sending the
441 // NewSessionTicket message despite promising to in ServerHello.
442 SkipNewSessionTicket bool
443
David Benjamina0e52232014-07-19 17:39:58 -0400444 // SkipChangeCipherSpec causes the implementation to skip
445 // sending the ChangeCipherSpec message (and adjusting cipher
446 // state accordingly for the Finished message).
447 SkipChangeCipherSpec bool
David Benjaminf3ec83d2014-07-21 22:42:34 -0400448
David Benjaminb80168e2015-02-08 18:30:14 -0500449 // SkipFinished causes the implementation to skip sending the Finished
450 // message.
451 SkipFinished bool
452
David Benjaminf3ec83d2014-07-21 22:42:34 -0400453 // EarlyChangeCipherSpec causes the client to send an early
454 // ChangeCipherSpec message before the ClientKeyExchange. A value of
455 // zero disables this behavior. One and two configure variants for 0.9.8
456 // and 1.0.1 modes, respectively.
457 EarlyChangeCipherSpec int
David Benjamind23f4122014-07-23 15:09:48 -0400458
David Benjamin86271ee2014-07-21 16:14:03 -0400459 // FragmentAcrossChangeCipherSpec causes the implementation to fragment
460 // the Finished (or NextProto) message around the ChangeCipherSpec
461 // messages.
462 FragmentAcrossChangeCipherSpec bool
463
David Benjamind86c7672014-08-02 04:07:12 -0400464 // SendV2ClientHello causes the client to send a V2ClientHello
465 // instead of a normal ClientHello.
466 SendV2ClientHello bool
David Benjaminbef270a2014-08-02 04:22:02 -0400467
468 // SendFallbackSCSV causes the client to include
469 // TLS_FALLBACK_SCSV in the ClientHello.
470 SendFallbackSCSV bool
David Benjamin43ec06f2014-08-05 02:28:57 -0400471
472 // MaxHandshakeRecordLength, if non-zero, is the maximum size of a
David Benjamin98214542014-08-07 18:02:39 -0400473 // handshake record. Handshake messages will be split into multiple
474 // records at the specified size, except that the client_version will
475 // never be fragmented.
David Benjamin43ec06f2014-08-05 02:28:57 -0400476 MaxHandshakeRecordLength int
David Benjamina8e3e0e2014-08-06 22:11:10 -0400477
David Benjamin98214542014-08-07 18:02:39 -0400478 // FragmentClientVersion will allow MaxHandshakeRecordLength to apply to
479 // the first 6 bytes of the ClientHello.
480 FragmentClientVersion bool
481
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400482 // FragmentAlert will cause all alerts to be fragmented across
483 // two records.
484 FragmentAlert bool
485
David Benjamin3fd1fbd2015-02-03 16:07:32 -0500486 // SendSpuriousAlert, if non-zero, will cause an spurious, unwanted
487 // alert to be sent.
488 SendSpuriousAlert alert
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400489
David Benjamina8e3e0e2014-08-06 22:11:10 -0400490 // RsaClientKeyExchangeVersion, if non-zero, causes the client to send a
491 // ClientKeyExchange with the specified version rather than the
492 // client_version when performing the RSA key exchange.
493 RsaClientKeyExchangeVersion uint16
David Benjaminbed9aae2014-08-07 19:13:38 -0400494
495 // RenewTicketOnResume causes the server to renew the session ticket and
496 // send a NewSessionTicket message during an abbreviated handshake.
497 RenewTicketOnResume bool
David Benjamin98e882e2014-08-08 13:24:34 -0400498
499 // SendClientVersion, if non-zero, causes the client to send a different
500 // TLS version in the ClientHello than the maximum supported version.
501 SendClientVersion uint16
David Benjamin83c0bc92014-08-04 01:23:53 -0400502
David Benjamine58c4f52014-08-24 03:47:07 -0400503 // ExpectFalseStart causes the server to, on full handshakes,
504 // expect the peer to False Start; the server Finished message
505 // isn't sent until we receive an application data record
506 // from the peer.
507 ExpectFalseStart bool
David Benjamin5c24a1d2014-08-31 00:59:27 -0400508
509 // SSL3RSAKeyExchange causes the client to always send an RSA
510 // ClientKeyExchange message without the two-byte length
511 // prefix, as if it were SSL3.
512 SSL3RSAKeyExchange bool
David Benjamin39ebf532014-08-31 02:23:49 -0400513
514 // SkipCipherVersionCheck causes the server to negotiate
515 // TLS 1.2 ciphers in earlier versions of TLS.
516 SkipCipherVersionCheck bool
David Benjamine78bfde2014-09-06 12:45:15 -0400517
518 // ExpectServerName, if not empty, is the hostname the client
519 // must specify in the server_name extension.
520 ExpectServerName string
David Benjaminfc7b0862014-09-06 13:21:53 -0400521
522 // SwapNPNAndALPN switches the relative order between NPN and
523 // ALPN on the server. This is to test that server preference
524 // of ALPN works regardless of their relative order.
525 SwapNPNAndALPN bool
David Benjamin01fe8202014-09-24 15:21:44 -0400526
527 // AllowSessionVersionMismatch causes the server to resume sessions
528 // regardless of the version associated with the session.
529 AllowSessionVersionMismatch bool
Adam Langley38311732014-10-16 19:04:35 -0700530
531 // CorruptTicket causes a client to corrupt a session ticket before
532 // sending it in a resume handshake.
533 CorruptTicket bool
534
535 // OversizedSessionId causes the session id that is sent with a ticket
536 // resumption attempt to be too large (33 bytes).
537 OversizedSessionId bool
Adam Langley75712922014-10-10 16:23:43 -0700538
539 // RequireExtendedMasterSecret, if true, requires that the peer support
540 // the extended master secret option.
541 RequireExtendedMasterSecret bool
542
David Benjaminca6554b2014-11-08 12:31:52 -0500543 // NoExtendedMasterSecret causes the client and server to behave as if
Adam Langley75712922014-10-10 16:23:43 -0700544 // they didn't support an extended master secret.
545 NoExtendedMasterSecret bool
Adam Langley2ae77d22014-10-28 17:29:33 -0700546
547 // EmptyRenegotiationInfo causes the renegotiation extension to be
548 // empty in a renegotiation handshake.
549 EmptyRenegotiationInfo bool
550
551 // BadRenegotiationInfo causes the renegotiation extension value in a
552 // renegotiation handshake to be incorrect.
553 BadRenegotiationInfo bool
David Benjamin5e961c12014-11-07 01:48:35 -0500554
David Benjaminca6554b2014-11-08 12:31:52 -0500555 // NoRenegotiationInfo causes the client to behave as if it
556 // didn't support the renegotiation info extension.
557 NoRenegotiationInfo bool
558
David Benjamin5e961c12014-11-07 01:48:35 -0500559 // SequenceNumberIncrement, if non-zero, causes outgoing sequence
560 // numbers in DTLS to increment by that value rather by 1. This is to
561 // stress the replay bitmap window by simulating extreme packet loss and
562 // retransmit at the record layer.
563 SequenceNumberIncrement uint64
David Benjamin9114fae2014-11-08 11:41:14 -0500564
David Benjamina3e89492015-02-26 15:16:22 -0500565 // RSAEphemeralKey, if true, causes the server to send a
566 // ServerKeyExchange message containing an ephemeral key (as in
567 // RSA_EXPORT) in the plain RSA key exchange.
568 RSAEphemeralKey bool
David Benjaminca6c8262014-11-15 19:06:08 -0500569
570 // SRTPMasterKeyIdentifer, if not empty, is the SRTP MKI value that the
571 // client offers when negotiating SRTP. MKI support is still missing so
572 // the peer must still send none.
573 SRTPMasterKeyIdentifer string
574
575 // SendSRTPProtectionProfile, if non-zero, is the SRTP profile that the
576 // server sends in the ServerHello instead of the negotiated one.
577 SendSRTPProtectionProfile uint16
David Benjamin000800a2014-11-14 01:43:59 -0500578
579 // NoSignatureAndHashes, if true, causes the client to omit the
580 // signature and hashes extension.
581 //
582 // For a server, it will cause an empty list to be sent in the
583 // CertificateRequest message. None the less, the configured set will
584 // still be enforced.
585 NoSignatureAndHashes bool
David Benjaminc44b1df2014-11-23 12:11:01 -0500586
587 // RequireSameRenegoClientVersion, if true, causes the server
588 // to require that all ClientHellos match in offered version
589 // across a renego.
590 RequireSameRenegoClientVersion bool
Feng Lu41aa3252014-11-21 22:47:56 -0800591
592 // RequireFastradioPadding, if true, requires that ClientHello messages
593 // be at least 1000 bytes long.
594 RequireFastradioPadding bool
David Benjamin1e29a6b2014-12-10 02:27:24 -0500595
596 // ExpectInitialRecordVersion, if non-zero, is the expected
597 // version of the records before the version is determined.
598 ExpectInitialRecordVersion uint16
David Benjamin13be1de2015-01-11 16:29:36 -0500599
600 // MaxPacketLength, if non-zero, is the maximum acceptable size for a
601 // packet.
602 MaxPacketLength int
David Benjamin6095de82014-12-27 01:50:38 -0500603
604 // SendCipherSuite, if non-zero, is the cipher suite value that the
605 // server will send in the ServerHello. This does not affect the cipher
606 // the server believes it has actually negotiated.
607 SendCipherSuite uint16
David Benjamin4189bd92015-01-25 23:52:39 -0500608
609 // AppDataAfterChangeCipherSpec, if not null, causes application data to
610 // be sent immediately after ChangeCipherSpec.
611 AppDataAfterChangeCipherSpec []byte
David Benjamin83f90402015-01-27 01:09:43 -0500612
David Benjamindc3da932015-03-12 15:09:02 -0400613 // AlertAfterChangeCipherSpec, if non-zero, causes an alert to be sent
614 // immediately after ChangeCipherSpec.
615 AlertAfterChangeCipherSpec alert
616
David Benjamin83f90402015-01-27 01:09:43 -0500617 // TimeoutSchedule is the schedule of packet drops and simulated
618 // timeouts for before each handshake leg from the peer.
619 TimeoutSchedule []time.Duration
620
621 // PacketAdaptor is the packetAdaptor to use to simulate timeouts.
622 PacketAdaptor *packetAdaptor
David Benjaminb3774b92015-01-31 17:16:01 -0500623
624 // ReorderHandshakeFragments, if true, causes handshake fragments in
625 // DTLS to overlap and be sent in the wrong order. It also causes
626 // pre-CCS flights to be sent twice. (Post-CCS flights consist of
627 // Finished and will trigger a spurious retransmit.)
628 ReorderHandshakeFragments bool
David Benjaminddb9f152015-02-03 15:44:39 -0500629
David Benjamin75381222015-03-02 19:30:30 -0500630 // MixCompleteMessageWithFragments, if true, causes handshake
631 // messages in DTLS to redundantly both fragment the message
632 // and include a copy of the full one.
633 MixCompleteMessageWithFragments bool
634
David Benjaminddb9f152015-02-03 15:44:39 -0500635 // SendInvalidRecordType, if true, causes a record with an invalid
636 // content type to be sent immediately following the handshake.
637 SendInvalidRecordType bool
David Benjaminbcb2d912015-02-24 23:45:43 -0500638
639 // WrongCertificateMessageType, if true, causes Certificate message to
640 // be sent with the wrong message type.
641 WrongCertificateMessageType bool
David Benjamin75381222015-03-02 19:30:30 -0500642
643 // FragmentMessageTypeMismatch, if true, causes all non-initial
644 // handshake fragments in DTLS to have the wrong message type.
645 FragmentMessageTypeMismatch bool
646
647 // FragmentMessageLengthMismatch, if true, causes all non-initial
648 // handshake fragments in DTLS to have the wrong message length.
649 FragmentMessageLengthMismatch bool
650
651 // SplitFragmentHeader, if true, causes the handshake fragments in DTLS
652 // to be split across two records.
653 SplitFragmentHeader bool
654
655 // SplitFragmentBody, if true, causes the handshake bodies in DTLS to be
656 // split across two records.
657 //
658 // TODO(davidben): There's one final split to test: when the header and
659 // body are split across two records. But those are (incorrectly)
660 // accepted right now.
661 SplitFragmentBody bool
662
663 // SendEmptyFragments, if true, causes handshakes to include empty
664 // fragments in DTLS.
665 SendEmptyFragments bool
David Benjamincdea40c2015-03-19 14:09:43 -0400666
667 // NeverResumeOnRenego, if true, causes renegotiations to always be full
668 // handshakes.
669 NeverResumeOnRenego bool
Adam Langley95c29f32014-06-20 12:00:00 -0700670}
671
672func (c *Config) serverInit() {
673 if c.SessionTicketsDisabled {
674 return
675 }
676
677 // If the key has already been set then we have nothing to do.
678 for _, b := range c.SessionTicketKey {
679 if b != 0 {
680 return
681 }
682 }
683
684 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
685 c.SessionTicketsDisabled = true
686 }
687}
688
689func (c *Config) rand() io.Reader {
690 r := c.Rand
691 if r == nil {
692 return rand.Reader
693 }
694 return r
695}
696
697func (c *Config) time() time.Time {
698 t := c.Time
699 if t == nil {
700 t = time.Now
701 }
702 return t()
703}
704
705func (c *Config) cipherSuites() []uint16 {
706 s := c.CipherSuites
707 if s == nil {
708 s = defaultCipherSuites()
709 }
710 return s
711}
712
713func (c *Config) minVersion() uint16 {
714 if c == nil || c.MinVersion == 0 {
715 return minVersion
716 }
717 return c.MinVersion
718}
719
720func (c *Config) maxVersion() uint16 {
721 if c == nil || c.MaxVersion == 0 {
722 return maxVersion
723 }
724 return c.MaxVersion
725}
726
727var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
728
729func (c *Config) curvePreferences() []CurveID {
730 if c == nil || len(c.CurvePreferences) == 0 {
731 return defaultCurvePreferences
732 }
733 return c.CurvePreferences
734}
735
736// mutualVersion returns the protocol version to use given the advertised
737// version of the peer.
738func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
739 minVersion := c.minVersion()
740 maxVersion := c.maxVersion()
741
742 if vers < minVersion {
743 return 0, false
744 }
745 if vers > maxVersion {
746 vers = maxVersion
747 }
748 return vers, true
749}
750
751// getCertificateForName returns the best certificate for the given name,
752// defaulting to the first element of c.Certificates if there are no good
753// options.
754func (c *Config) getCertificateForName(name string) *Certificate {
755 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
756 // There's only one choice, so no point doing any work.
757 return &c.Certificates[0]
758 }
759
760 name = strings.ToLower(name)
761 for len(name) > 0 && name[len(name)-1] == '.' {
762 name = name[:len(name)-1]
763 }
764
765 if cert, ok := c.NameToCertificate[name]; ok {
766 return cert
767 }
768
769 // try replacing labels in the name with wildcards until we get a
770 // match.
771 labels := strings.Split(name, ".")
772 for i := range labels {
773 labels[i] = "*"
774 candidate := strings.Join(labels, ".")
775 if cert, ok := c.NameToCertificate[candidate]; ok {
776 return cert
777 }
778 }
779
780 // If nothing matches, return the first certificate.
781 return &c.Certificates[0]
782}
783
David Benjamin000800a2014-11-14 01:43:59 -0500784func (c *Config) signatureAndHashesForServer() []signatureAndHash {
785 if c != nil && c.SignatureAndHashes != nil {
786 return c.SignatureAndHashes
787 }
788 return supportedClientCertSignatureAlgorithms
789}
790
791func (c *Config) signatureAndHashesForClient() []signatureAndHash {
792 if c != nil && c.SignatureAndHashes != nil {
793 return c.SignatureAndHashes
794 }
795 return supportedSKXSignatureAlgorithms
796}
797
Adam Langley95c29f32014-06-20 12:00:00 -0700798// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
799// from the CommonName and SubjectAlternateName fields of each of the leaf
800// certificates.
801func (c *Config) BuildNameToCertificate() {
802 c.NameToCertificate = make(map[string]*Certificate)
803 for i := range c.Certificates {
804 cert := &c.Certificates[i]
805 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
806 if err != nil {
807 continue
808 }
809 if len(x509Cert.Subject.CommonName) > 0 {
810 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
811 }
812 for _, san := range x509Cert.DNSNames {
813 c.NameToCertificate[san] = cert
814 }
815 }
816}
817
818// A Certificate is a chain of one or more certificates, leaf first.
819type Certificate struct {
820 Certificate [][]byte
821 PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
822 // OCSPStaple contains an optional OCSP response which will be served
823 // to clients that request it.
824 OCSPStaple []byte
David Benjamin61f95272014-11-25 01:55:35 -0500825 // SignedCertificateTimestampList contains an optional encoded
826 // SignedCertificateTimestampList structure which will be
827 // served to clients that request it.
828 SignedCertificateTimestampList []byte
Adam Langley95c29f32014-06-20 12:00:00 -0700829 // Leaf is the parsed form of the leaf certificate, which may be
830 // initialized using x509.ParseCertificate to reduce per-handshake
831 // processing for TLS clients doing client authentication. If nil, the
832 // leaf certificate will be parsed as needed.
833 Leaf *x509.Certificate
834}
835
836// A TLS record.
837type record struct {
838 contentType recordType
839 major, minor uint8
840 payload []byte
841}
842
843type handshakeMessage interface {
844 marshal() []byte
845 unmarshal([]byte) bool
846}
847
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500848// lruSessionCache is a client or server session cache implementation
849// that uses an LRU caching strategy.
Adam Langley95c29f32014-06-20 12:00:00 -0700850type lruSessionCache struct {
851 sync.Mutex
852
853 m map[string]*list.Element
854 q *list.List
855 capacity int
856}
857
858type lruSessionCacheEntry struct {
859 sessionKey string
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500860 state interface{}
Adam Langley95c29f32014-06-20 12:00:00 -0700861}
862
863// Put adds the provided (sessionKey, cs) pair to the cache.
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500864func (c *lruSessionCache) Put(sessionKey string, cs interface{}) {
Adam Langley95c29f32014-06-20 12:00:00 -0700865 c.Lock()
866 defer c.Unlock()
867
868 if elem, ok := c.m[sessionKey]; ok {
869 entry := elem.Value.(*lruSessionCacheEntry)
870 entry.state = cs
871 c.q.MoveToFront(elem)
872 return
873 }
874
875 if c.q.Len() < c.capacity {
876 entry := &lruSessionCacheEntry{sessionKey, cs}
877 c.m[sessionKey] = c.q.PushFront(entry)
878 return
879 }
880
881 elem := c.q.Back()
882 entry := elem.Value.(*lruSessionCacheEntry)
883 delete(c.m, entry.sessionKey)
884 entry.sessionKey = sessionKey
885 entry.state = cs
886 c.q.MoveToFront(elem)
887 c.m[sessionKey] = elem
888}
889
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500890// Get returns the value associated with a given key. It returns (nil,
891// false) if no value is found.
892func (c *lruSessionCache) Get(sessionKey string) (interface{}, bool) {
Adam Langley95c29f32014-06-20 12:00:00 -0700893 c.Lock()
894 defer c.Unlock()
895
896 if elem, ok := c.m[sessionKey]; ok {
897 c.q.MoveToFront(elem)
898 return elem.Value.(*lruSessionCacheEntry).state, true
899 }
900 return nil, false
901}
902
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500903// lruClientSessionCache is a ClientSessionCache implementation that
904// uses an LRU caching strategy.
905type lruClientSessionCache struct {
906 lruSessionCache
907}
908
909func (c *lruClientSessionCache) Put(sessionKey string, cs *ClientSessionState) {
910 c.lruSessionCache.Put(sessionKey, cs)
911}
912
913func (c *lruClientSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
914 cs, ok := c.lruSessionCache.Get(sessionKey)
915 if !ok {
916 return nil, false
917 }
918 return cs.(*ClientSessionState), true
919}
920
921// lruServerSessionCache is a ServerSessionCache implementation that
922// uses an LRU caching strategy.
923type lruServerSessionCache struct {
924 lruSessionCache
925}
926
927func (c *lruServerSessionCache) Put(sessionId string, session *sessionState) {
928 c.lruSessionCache.Put(sessionId, session)
929}
930
931func (c *lruServerSessionCache) Get(sessionId string) (*sessionState, bool) {
932 cs, ok := c.lruSessionCache.Get(sessionId)
933 if !ok {
934 return nil, false
935 }
936 return cs.(*sessionState), true
937}
938
939// NewLRUClientSessionCache returns a ClientSessionCache with the given
940// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
941// is used instead.
942func NewLRUClientSessionCache(capacity int) ClientSessionCache {
943 const defaultSessionCacheCapacity = 64
944
945 if capacity < 1 {
946 capacity = defaultSessionCacheCapacity
947 }
948 return &lruClientSessionCache{
949 lruSessionCache{
950 m: make(map[string]*list.Element),
951 q: list.New(),
952 capacity: capacity,
953 },
954 }
955}
956
957// NewLRUServerSessionCache returns a ServerSessionCache with the given
958// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
959// is used instead.
960func NewLRUServerSessionCache(capacity int) ServerSessionCache {
961 const defaultSessionCacheCapacity = 64
962
963 if capacity < 1 {
964 capacity = defaultSessionCacheCapacity
965 }
966 return &lruServerSessionCache{
967 lruSessionCache{
968 m: make(map[string]*list.Element),
969 q: list.New(),
970 capacity: capacity,
971 },
972 }
973}
974
Adam Langley95c29f32014-06-20 12:00:00 -0700975// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
976type dsaSignature struct {
977 R, S *big.Int
978}
979
980type ecdsaSignature dsaSignature
981
982var emptyConfig Config
983
984func defaultConfig() *Config {
985 return &emptyConfig
986}
987
988var (
989 once sync.Once
990 varDefaultCipherSuites []uint16
991)
992
993func defaultCipherSuites() []uint16 {
994 once.Do(initDefaultCipherSuites)
995 return varDefaultCipherSuites
996}
997
998func initDefaultCipherSuites() {
David Benjamin48cae082014-10-27 01:06:24 -0400999 for _, suite := range cipherSuites {
1000 if suite.flags&suitePSK == 0 {
1001 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
1002 }
Adam Langley95c29f32014-06-20 12:00:00 -07001003 }
1004}
1005
1006func unexpectedMessageError(wanted, got interface{}) error {
1007 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
1008}
David Benjamin000800a2014-11-14 01:43:59 -05001009
1010func isSupportedSignatureAndHash(sigHash signatureAndHash, sigHashes []signatureAndHash) bool {
1011 for _, s := range sigHashes {
1012 if s == sigHash {
1013 return true
1014 }
1015 }
1016 return false
1017}