blob: 476a2a4fb485d18155d46ae27dcdcb9aac0d446f [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 (
Adam Langley75712922014-10-10 16:23:43 -070075 extensionServerName uint16 = 0
76 extensionStatusRequest uint16 = 5
77 extensionSupportedCurves uint16 = 10
78 extensionSupportedPoints uint16 = 11
79 extensionSignatureAlgorithms uint16 = 13
David Benjaminca6c8262014-11-15 19:06:08 -050080 extensionUseSRTP uint16 = 14
Adam Langley75712922014-10-10 16:23:43 -070081 extensionALPN uint16 = 16
82 extensionExtendedMasterSecret uint16 = 23
83 extensionSessionTicket uint16 = 35
84 extensionNextProtoNeg uint16 = 13172 // not IANA assigned
85 extensionRenegotiationInfo uint16 = 0xff01
86 extensionChannelID uint16 = 30032 // not IANA assigned
Adam Langley95c29f32014-06-20 12:00:00 -070087)
88
89// TLS signaling cipher suite values
90const (
91 scsvRenegotiation uint16 = 0x00ff
92)
93
94// CurveID is the type of a TLS identifier for an elliptic curve. See
95// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
96type CurveID uint16
97
98const (
99 CurveP256 CurveID = 23
100 CurveP384 CurveID = 24
101 CurveP521 CurveID = 25
102)
103
104// TLS Elliptic Curve Point Formats
105// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
106const (
107 pointFormatUncompressed uint8 = 0
108)
109
110// TLS CertificateStatusType (RFC 3546)
111const (
112 statusTypeOCSP uint8 = 1
113)
114
115// Certificate types (for certificateRequestMsg)
116const (
David Benjamin7b030512014-07-08 17:30:11 -0400117 CertTypeRSASign = 1 // A certificate containing an RSA key
118 CertTypeDSSSign = 2 // A certificate containing a DSA key
119 CertTypeRSAFixedDH = 3 // A certificate containing a static DH key
120 CertTypeDSSFixedDH = 4 // A certificate containing a static DH key
Adam Langley95c29f32014-06-20 12:00:00 -0700121
122 // See RFC4492 sections 3 and 5.5.
David Benjamin7b030512014-07-08 17:30:11 -0400123 CertTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
124 CertTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
125 CertTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
Adam Langley95c29f32014-06-20 12:00:00 -0700126
127 // Rest of these are reserved by the TLS spec
128)
129
130// Hash functions for TLS 1.2 (See RFC 5246, section A.4.1)
131const (
David Benjamin000800a2014-11-14 01:43:59 -0500132 hashMD5 uint8 = 1
Adam Langley95c29f32014-06-20 12:00:00 -0700133 hashSHA1 uint8 = 2
David Benjamin000800a2014-11-14 01:43:59 -0500134 hashSHA224 uint8 = 3
Adam Langley95c29f32014-06-20 12:00:00 -0700135 hashSHA256 uint8 = 4
David Benjamin000800a2014-11-14 01:43:59 -0500136 hashSHA384 uint8 = 5
137 hashSHA512 uint8 = 6
Adam Langley95c29f32014-06-20 12:00:00 -0700138)
139
140// Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
141const (
142 signatureRSA uint8 = 1
143 signatureECDSA uint8 = 3
144)
145
146// signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See
147// RFC 5246, section A.4.1.
148type signatureAndHash struct {
David Benjamine098ec22014-08-27 23:13:20 -0400149 signature, hash uint8
Adam Langley95c29f32014-06-20 12:00:00 -0700150}
151
152// supportedSKXSignatureAlgorithms contains the signature and hash algorithms
153// that the code advertises as supported in a TLS 1.2 ClientHello.
154var supportedSKXSignatureAlgorithms = []signatureAndHash{
David Benjamine098ec22014-08-27 23:13:20 -0400155 {signatureRSA, hashSHA256},
156 {signatureECDSA, hashSHA256},
157 {signatureRSA, hashSHA1},
158 {signatureECDSA, hashSHA1},
Adam Langley95c29f32014-06-20 12:00:00 -0700159}
160
161// supportedClientCertSignatureAlgorithms contains the signature and hash
162// algorithms that the code advertises as supported in a TLS 1.2
163// CertificateRequest.
164var supportedClientCertSignatureAlgorithms = []signatureAndHash{
David Benjamine098ec22014-08-27 23:13:20 -0400165 {signatureRSA, hashSHA256},
166 {signatureECDSA, hashSHA256},
Adam Langley95c29f32014-06-20 12:00:00 -0700167}
168
David Benjaminca6c8262014-11-15 19:06:08 -0500169// SRTP protection profiles (See RFC 5764, section 4.1.2)
170const (
171 SRTP_AES128_CM_HMAC_SHA1_80 uint16 = 0x0001
172 SRTP_AES128_CM_HMAC_SHA1_32 = 0x0002
173)
174
Adam Langley95c29f32014-06-20 12:00:00 -0700175// ConnectionState records basic TLS details about the connection.
176type ConnectionState struct {
177 Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
178 HandshakeComplete bool // TLS handshake is complete
179 DidResume bool // connection resumes a previous TLS connection
180 CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
181 NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos)
182 NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server
David Benjaminfc7b0862014-09-06 13:21:53 -0400183 NegotiatedProtocolFromALPN bool // protocol negotiated with ALPN
Adam Langley95c29f32014-06-20 12:00:00 -0700184 ServerName string // server name requested by client, if any (server side only)
185 PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
186 VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
David Benjamind30a9902014-08-24 01:44:23 -0400187 ChannelID *ecdsa.PublicKey // the channel ID for this connection
David Benjaminca6c8262014-11-15 19:06:08 -0500188 SRTPProtectionProfile uint16 // the negotiated DTLS-SRTP protection profile
Adam Langley95c29f32014-06-20 12:00:00 -0700189}
190
191// ClientAuthType declares the policy the server will follow for
192// TLS Client Authentication.
193type ClientAuthType int
194
195const (
196 NoClientCert ClientAuthType = iota
197 RequestClientCert
198 RequireAnyClientCert
199 VerifyClientCertIfGiven
200 RequireAndVerifyClientCert
201)
202
203// ClientSessionState contains the state needed by clients to resume TLS
204// sessions.
205type ClientSessionState struct {
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500206 sessionId []uint8 // Session ID supplied by the server. nil if the session has a ticket.
Adam Langley75712922014-10-10 16:23:43 -0700207 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
208 vers uint16 // SSL/TLS version negotiated for the session
209 cipherSuite uint16 // Ciphersuite negotiated for the session
210 masterSecret []byte // MasterSecret generated by client on a full handshake
211 handshakeHash []byte // Handshake hash for Channel ID purposes.
212 serverCertificates []*x509.Certificate // Certificate chain presented by the server
213 extendedMasterSecret bool // Whether an extended master secret was used to generate the session
Adam Langley95c29f32014-06-20 12:00:00 -0700214}
215
216// ClientSessionCache is a cache of ClientSessionState objects that can be used
217// by a client to resume a TLS session with a given server. ClientSessionCache
218// implementations should expect to be called concurrently from different
219// goroutines.
220type ClientSessionCache interface {
221 // Get searches for a ClientSessionState associated with the given key.
222 // On return, ok is true if one was found.
223 Get(sessionKey string) (session *ClientSessionState, ok bool)
224
225 // Put adds the ClientSessionState to the cache with the given key.
226 Put(sessionKey string, cs *ClientSessionState)
227}
228
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500229// ServerSessionCache is a cache of sessionState objects that can be used by a
230// client to resume a TLS session with a given server. ServerSessionCache
231// implementations should expect to be called concurrently from different
232// goroutines.
233type ServerSessionCache interface {
234 // Get searches for a sessionState associated with the given session
235 // ID. On return, ok is true if one was found.
236 Get(sessionId string) (session *sessionState, ok bool)
237
238 // Put adds the sessionState to the cache with the given session ID.
239 Put(sessionId string, session *sessionState)
240}
241
Adam Langley95c29f32014-06-20 12:00:00 -0700242// A Config structure is used to configure a TLS client or server.
243// After one has been passed to a TLS function it must not be
244// modified. A Config may be reused; the tls package will also not
245// modify it.
246type Config struct {
247 // Rand provides the source of entropy for nonces and RSA blinding.
248 // If Rand is nil, TLS uses the cryptographic random reader in package
249 // crypto/rand.
250 // The Reader must be safe for use by multiple goroutines.
251 Rand io.Reader
252
253 // Time returns the current time as the number of seconds since the epoch.
254 // If Time is nil, TLS uses time.Now.
255 Time func() time.Time
256
257 // Certificates contains one or more certificate chains
258 // to present to the other side of the connection.
259 // Server configurations must include at least one certificate.
260 Certificates []Certificate
261
262 // NameToCertificate maps from a certificate name to an element of
263 // Certificates. Note that a certificate name can be of the form
264 // '*.example.com' and so doesn't have to be a domain name as such.
265 // See Config.BuildNameToCertificate
266 // The nil value causes the first element of Certificates to be used
267 // for all connections.
268 NameToCertificate map[string]*Certificate
269
270 // RootCAs defines the set of root certificate authorities
271 // that clients use when verifying server certificates.
272 // If RootCAs is nil, TLS uses the host's root CA set.
273 RootCAs *x509.CertPool
274
275 // NextProtos is a list of supported, application level protocols.
276 NextProtos []string
277
278 // ServerName is used to verify the hostname on the returned
279 // certificates unless InsecureSkipVerify is given. It is also included
280 // in the client's handshake to support virtual hosting.
281 ServerName string
282
283 // ClientAuth determines the server's policy for
284 // TLS Client Authentication. The default is NoClientCert.
285 ClientAuth ClientAuthType
286
287 // ClientCAs defines the set of root certificate authorities
288 // that servers use if required to verify a client certificate
289 // by the policy in ClientAuth.
290 ClientCAs *x509.CertPool
291
David Benjamin7b030512014-07-08 17:30:11 -0400292 // ClientCertificateTypes defines the set of allowed client certificate
293 // types. The default is CertTypeRSASign and CertTypeECDSASign.
294 ClientCertificateTypes []byte
295
Adam Langley95c29f32014-06-20 12:00:00 -0700296 // InsecureSkipVerify controls whether a client verifies the
297 // server's certificate chain and host name.
298 // If InsecureSkipVerify is true, TLS accepts any certificate
299 // presented by the server and any host name in that certificate.
300 // In this mode, TLS is susceptible to man-in-the-middle attacks.
301 // This should be used only for testing.
302 InsecureSkipVerify bool
303
304 // CipherSuites is a list of supported cipher suites. If CipherSuites
305 // is nil, TLS uses a list of suites supported by the implementation.
306 CipherSuites []uint16
307
308 // PreferServerCipherSuites controls whether the server selects the
309 // client's most preferred ciphersuite, or the server's most preferred
310 // ciphersuite. If true then the server's preference, as expressed in
311 // the order of elements in CipherSuites, is used.
312 PreferServerCipherSuites bool
313
314 // SessionTicketsDisabled may be set to true to disable session ticket
315 // (resumption) support.
316 SessionTicketsDisabled bool
317
318 // SessionTicketKey is used by TLS servers to provide session
319 // resumption. See RFC 5077. If zero, it will be filled with
320 // random data before the first server handshake.
321 //
322 // If multiple servers are terminating connections for the same host
323 // they should all have the same SessionTicketKey. If the
324 // SessionTicketKey leaks, previously recorded and future TLS
325 // connections using that key are compromised.
326 SessionTicketKey [32]byte
327
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500328 // ClientSessionCache is a cache of ClientSessionState entries
329 // for TLS session resumption.
Adam Langley95c29f32014-06-20 12:00:00 -0700330 ClientSessionCache ClientSessionCache
331
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500332 // ServerSessionCache is a cache of sessionState entries for TLS session
333 // resumption.
334 ServerSessionCache ServerSessionCache
335
Adam Langley95c29f32014-06-20 12:00:00 -0700336 // MinVersion contains the minimum SSL/TLS version that is acceptable.
337 // If zero, then SSLv3 is taken as the minimum.
338 MinVersion uint16
339
340 // MaxVersion contains the maximum SSL/TLS version that is acceptable.
341 // If zero, then the maximum version supported by this package is used,
342 // which is currently TLS 1.2.
343 MaxVersion uint16
344
345 // CurvePreferences contains the elliptic curves that will be used in
346 // an ECDHE handshake, in preference order. If empty, the default will
347 // be used.
348 CurvePreferences []CurveID
349
David Benjamind30a9902014-08-24 01:44:23 -0400350 // ChannelID contains the ECDSA key for the client to use as
351 // its TLS Channel ID.
352 ChannelID *ecdsa.PrivateKey
353
354 // RequestChannelID controls whether the server requests a TLS
355 // Channel ID. If negotiated, the client's public key is
356 // returned in the ConnectionState.
357 RequestChannelID bool
358
David Benjamin48cae082014-10-27 01:06:24 -0400359 // PreSharedKey, if not nil, is the pre-shared key to use with
360 // the PSK cipher suites.
361 PreSharedKey []byte
362
363 // PreSharedKeyIdentity, if not empty, is the identity to use
364 // with the PSK cipher suites.
365 PreSharedKeyIdentity string
366
David Benjaminca6c8262014-11-15 19:06:08 -0500367 // SRTPProtectionProfiles, if not nil, is the list of SRTP
368 // protection profiles to offer in DTLS-SRTP.
369 SRTPProtectionProfiles []uint16
370
David Benjamin000800a2014-11-14 01:43:59 -0500371 // SignatureAndHashes, if not nil, overrides the default set of
372 // supported signature and hash algorithms to advertise in
373 // CertificateRequest.
374 SignatureAndHashes []signatureAndHash
375
Adam Langley95c29f32014-06-20 12:00:00 -0700376 // Bugs specifies optional misbehaviour to be used for testing other
377 // implementations.
378 Bugs ProtocolBugs
379
380 serverInitOnce sync.Once // guards calling (*Config).serverInit
381}
382
383type BadValue int
384
385const (
386 BadValueNone BadValue = iota
387 BadValueNegative
388 BadValueZero
389 BadValueLimit
390 BadValueLarge
391 NumBadValues
392)
393
394type ProtocolBugs struct {
395 // InvalidSKXSignature specifies that the signature in a
396 // ServerKeyExchange message should be invalid.
397 InvalidSKXSignature bool
398
399 // InvalidSKXCurve causes the curve ID in the ServerKeyExchange message
400 // to be wrong.
401 InvalidSKXCurve bool
402
403 // BadECDSAR controls ways in which the 'r' value of an ECDSA signature
404 // can be invalid.
405 BadECDSAR BadValue
406 BadECDSAS BadValue
Adam Langley80842bd2014-06-20 12:00:00 -0700407
408 // MaxPadding causes CBC records to have the maximum possible padding.
409 MaxPadding bool
410 // PaddingFirstByteBad causes the first byte of the padding to be
411 // incorrect.
412 PaddingFirstByteBad bool
413 // PaddingFirstByteBadIf255 causes the first byte of padding to be
414 // incorrect if there's a maximum amount of padding (i.e. 255 bytes).
415 PaddingFirstByteBadIf255 bool
Adam Langleyac61fa32014-06-23 12:03:11 -0700416
417 // FailIfNotFallbackSCSV causes a server handshake to fail if the
418 // client doesn't send the fallback SCSV value.
419 FailIfNotFallbackSCSV bool
David Benjamin35a7a442014-07-05 00:23:20 -0400420
421 // DuplicateExtension causes an extra empty extension of bogus type to
422 // be emitted in either the ClientHello or the ServerHello.
423 DuplicateExtension bool
David Benjamin1c375dd2014-07-12 00:48:23 -0400424
425 // UnauthenticatedECDH causes the server to pretend ECDHE_RSA
426 // and ECDHE_ECDSA cipher suites are actually ECDH_anon. No
427 // Certificate message is sent and no signature is added to
428 // ServerKeyExchange.
429 UnauthenticatedECDH bool
David Benjamin9c651c92014-07-12 13:27:45 -0400430
431 // SkipServerKeyExchange causes the server to skip sending
432 // ServerKeyExchange messages.
433 SkipServerKeyExchange bool
David Benjamina0e52232014-07-19 17:39:58 -0400434
435 // SkipChangeCipherSpec causes the implementation to skip
436 // sending the ChangeCipherSpec message (and adjusting cipher
437 // state accordingly for the Finished message).
438 SkipChangeCipherSpec bool
David Benjaminf3ec83d2014-07-21 22:42:34 -0400439
440 // EarlyChangeCipherSpec causes the client to send an early
441 // ChangeCipherSpec message before the ClientKeyExchange. A value of
442 // zero disables this behavior. One and two configure variants for 0.9.8
443 // and 1.0.1 modes, respectively.
444 EarlyChangeCipherSpec int
David Benjamind23f4122014-07-23 15:09:48 -0400445
David Benjamin86271ee2014-07-21 16:14:03 -0400446 // FragmentAcrossChangeCipherSpec causes the implementation to fragment
447 // the Finished (or NextProto) message around the ChangeCipherSpec
448 // messages.
449 FragmentAcrossChangeCipherSpec bool
450
David Benjamind23f4122014-07-23 15:09:48 -0400451 // SkipNewSessionTicket causes the server to skip sending the
452 // NewSessionTicket message despite promising to in ServerHello.
453 SkipNewSessionTicket bool
David Benjamind86c7672014-08-02 04:07:12 -0400454
455 // SendV2ClientHello causes the client to send a V2ClientHello
456 // instead of a normal ClientHello.
457 SendV2ClientHello bool
David Benjaminbef270a2014-08-02 04:22:02 -0400458
459 // SendFallbackSCSV causes the client to include
460 // TLS_FALLBACK_SCSV in the ClientHello.
461 SendFallbackSCSV bool
David Benjamin43ec06f2014-08-05 02:28:57 -0400462
463 // MaxHandshakeRecordLength, if non-zero, is the maximum size of a
David Benjamin98214542014-08-07 18:02:39 -0400464 // handshake record. Handshake messages will be split into multiple
465 // records at the specified size, except that the client_version will
466 // never be fragmented.
David Benjamin43ec06f2014-08-05 02:28:57 -0400467 MaxHandshakeRecordLength int
David Benjamina8e3e0e2014-08-06 22:11:10 -0400468
David Benjamin98214542014-08-07 18:02:39 -0400469 // FragmentClientVersion will allow MaxHandshakeRecordLength to apply to
470 // the first 6 bytes of the ClientHello.
471 FragmentClientVersion bool
472
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400473 // FragmentAlert will cause all alerts to be fragmented across
474 // two records.
475 FragmentAlert bool
476
477 // SendSpuriousAlert will cause an spurious, unwanted alert to be sent.
478 SendSpuriousAlert bool
479
David Benjamina8e3e0e2014-08-06 22:11:10 -0400480 // RsaClientKeyExchangeVersion, if non-zero, causes the client to send a
481 // ClientKeyExchange with the specified version rather than the
482 // client_version when performing the RSA key exchange.
483 RsaClientKeyExchangeVersion uint16
David Benjaminbed9aae2014-08-07 19:13:38 -0400484
485 // RenewTicketOnResume causes the server to renew the session ticket and
486 // send a NewSessionTicket message during an abbreviated handshake.
487 RenewTicketOnResume bool
David Benjamin98e882e2014-08-08 13:24:34 -0400488
489 // SendClientVersion, if non-zero, causes the client to send a different
490 // TLS version in the ClientHello than the maximum supported version.
491 SendClientVersion uint16
David Benjamin83c0bc92014-08-04 01:23:53 -0400492
493 // SkipHelloVerifyRequest causes a DTLS server to skip the
494 // HelloVerifyRequest message.
495 SkipHelloVerifyRequest bool
David Benjamine58c4f52014-08-24 03:47:07 -0400496
497 // ExpectFalseStart causes the server to, on full handshakes,
498 // expect the peer to False Start; the server Finished message
499 // isn't sent until we receive an application data record
500 // from the peer.
501 ExpectFalseStart bool
David Benjamin5c24a1d2014-08-31 00:59:27 -0400502
503 // SSL3RSAKeyExchange causes the client to always send an RSA
504 // ClientKeyExchange message without the two-byte length
505 // prefix, as if it were SSL3.
506 SSL3RSAKeyExchange bool
David Benjamin39ebf532014-08-31 02:23:49 -0400507
508 // SkipCipherVersionCheck causes the server to negotiate
509 // TLS 1.2 ciphers in earlier versions of TLS.
510 SkipCipherVersionCheck bool
David Benjamine78bfde2014-09-06 12:45:15 -0400511
512 // ExpectServerName, if not empty, is the hostname the client
513 // must specify in the server_name extension.
514 ExpectServerName string
David Benjaminfc7b0862014-09-06 13:21:53 -0400515
516 // SwapNPNAndALPN switches the relative order between NPN and
517 // ALPN on the server. This is to test that server preference
518 // of ALPN works regardless of their relative order.
519 SwapNPNAndALPN bool
David Benjamin01fe8202014-09-24 15:21:44 -0400520
521 // AllowSessionVersionMismatch causes the server to resume sessions
522 // regardless of the version associated with the session.
523 AllowSessionVersionMismatch bool
Adam Langley38311732014-10-16 19:04:35 -0700524
525 // CorruptTicket causes a client to corrupt a session ticket before
526 // sending it in a resume handshake.
527 CorruptTicket bool
528
529 // OversizedSessionId causes the session id that is sent with a ticket
530 // resumption attempt to be too large (33 bytes).
531 OversizedSessionId bool
Adam Langley75712922014-10-10 16:23:43 -0700532
533 // RequireExtendedMasterSecret, if true, requires that the peer support
534 // the extended master secret option.
535 RequireExtendedMasterSecret bool
536
David Benjaminca6554b2014-11-08 12:31:52 -0500537 // NoExtendedMasterSecret causes the client and server to behave as if
Adam Langley75712922014-10-10 16:23:43 -0700538 // they didn't support an extended master secret.
539 NoExtendedMasterSecret bool
Adam Langley2ae77d22014-10-28 17:29:33 -0700540
541 // EmptyRenegotiationInfo causes the renegotiation extension to be
542 // empty in a renegotiation handshake.
543 EmptyRenegotiationInfo bool
544
545 // BadRenegotiationInfo causes the renegotiation extension value in a
546 // renegotiation handshake to be incorrect.
547 BadRenegotiationInfo bool
David Benjamin5e961c12014-11-07 01:48:35 -0500548
David Benjaminca6554b2014-11-08 12:31:52 -0500549 // NoRenegotiationInfo causes the client to behave as if it
550 // didn't support the renegotiation info extension.
551 NoRenegotiationInfo bool
552
David Benjamin5e961c12014-11-07 01:48:35 -0500553 // SequenceNumberIncrement, if non-zero, causes outgoing sequence
554 // numbers in DTLS to increment by that value rather by 1. This is to
555 // stress the replay bitmap window by simulating extreme packet loss and
556 // retransmit at the record layer.
557 SequenceNumberIncrement uint64
David Benjamin9114fae2014-11-08 11:41:14 -0500558
559 // RSAServerKeyExchange, if true, causes the server to send a
560 // ServerKeyExchange message in the plain RSA key exchange.
561 RSAServerKeyExchange bool
David Benjaminca6c8262014-11-15 19:06:08 -0500562
563 // SRTPMasterKeyIdentifer, if not empty, is the SRTP MKI value that the
564 // client offers when negotiating SRTP. MKI support is still missing so
565 // the peer must still send none.
566 SRTPMasterKeyIdentifer string
567
568 // SendSRTPProtectionProfile, if non-zero, is the SRTP profile that the
569 // server sends in the ServerHello instead of the negotiated one.
570 SendSRTPProtectionProfile uint16
David Benjamin000800a2014-11-14 01:43:59 -0500571
572 // NoSignatureAndHashes, if true, causes the client to omit the
573 // signature and hashes extension.
574 //
575 // For a server, it will cause an empty list to be sent in the
576 // CertificateRequest message. None the less, the configured set will
577 // still be enforced.
578 NoSignatureAndHashes bool
Adam Langley95c29f32014-06-20 12:00:00 -0700579}
580
581func (c *Config) serverInit() {
582 if c.SessionTicketsDisabled {
583 return
584 }
585
586 // If the key has already been set then we have nothing to do.
587 for _, b := range c.SessionTicketKey {
588 if b != 0 {
589 return
590 }
591 }
592
593 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
594 c.SessionTicketsDisabled = true
595 }
596}
597
598func (c *Config) rand() io.Reader {
599 r := c.Rand
600 if r == nil {
601 return rand.Reader
602 }
603 return r
604}
605
606func (c *Config) time() time.Time {
607 t := c.Time
608 if t == nil {
609 t = time.Now
610 }
611 return t()
612}
613
614func (c *Config) cipherSuites() []uint16 {
615 s := c.CipherSuites
616 if s == nil {
617 s = defaultCipherSuites()
618 }
619 return s
620}
621
622func (c *Config) minVersion() uint16 {
623 if c == nil || c.MinVersion == 0 {
624 return minVersion
625 }
626 return c.MinVersion
627}
628
629func (c *Config) maxVersion() uint16 {
630 if c == nil || c.MaxVersion == 0 {
631 return maxVersion
632 }
633 return c.MaxVersion
634}
635
636var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
637
638func (c *Config) curvePreferences() []CurveID {
639 if c == nil || len(c.CurvePreferences) == 0 {
640 return defaultCurvePreferences
641 }
642 return c.CurvePreferences
643}
644
645// mutualVersion returns the protocol version to use given the advertised
646// version of the peer.
647func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
648 minVersion := c.minVersion()
649 maxVersion := c.maxVersion()
650
651 if vers < minVersion {
652 return 0, false
653 }
654 if vers > maxVersion {
655 vers = maxVersion
656 }
657 return vers, true
658}
659
660// getCertificateForName returns the best certificate for the given name,
661// defaulting to the first element of c.Certificates if there are no good
662// options.
663func (c *Config) getCertificateForName(name string) *Certificate {
664 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
665 // There's only one choice, so no point doing any work.
666 return &c.Certificates[0]
667 }
668
669 name = strings.ToLower(name)
670 for len(name) > 0 && name[len(name)-1] == '.' {
671 name = name[:len(name)-1]
672 }
673
674 if cert, ok := c.NameToCertificate[name]; ok {
675 return cert
676 }
677
678 // try replacing labels in the name with wildcards until we get a
679 // match.
680 labels := strings.Split(name, ".")
681 for i := range labels {
682 labels[i] = "*"
683 candidate := strings.Join(labels, ".")
684 if cert, ok := c.NameToCertificate[candidate]; ok {
685 return cert
686 }
687 }
688
689 // If nothing matches, return the first certificate.
690 return &c.Certificates[0]
691}
692
David Benjamin000800a2014-11-14 01:43:59 -0500693func (c *Config) signatureAndHashesForServer() []signatureAndHash {
694 if c != nil && c.SignatureAndHashes != nil {
695 return c.SignatureAndHashes
696 }
697 return supportedClientCertSignatureAlgorithms
698}
699
700func (c *Config) signatureAndHashesForClient() []signatureAndHash {
701 if c != nil && c.SignatureAndHashes != nil {
702 return c.SignatureAndHashes
703 }
704 return supportedSKXSignatureAlgorithms
705}
706
Adam Langley95c29f32014-06-20 12:00:00 -0700707// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
708// from the CommonName and SubjectAlternateName fields of each of the leaf
709// certificates.
710func (c *Config) BuildNameToCertificate() {
711 c.NameToCertificate = make(map[string]*Certificate)
712 for i := range c.Certificates {
713 cert := &c.Certificates[i]
714 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
715 if err != nil {
716 continue
717 }
718 if len(x509Cert.Subject.CommonName) > 0 {
719 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
720 }
721 for _, san := range x509Cert.DNSNames {
722 c.NameToCertificate[san] = cert
723 }
724 }
725}
726
727// A Certificate is a chain of one or more certificates, leaf first.
728type Certificate struct {
729 Certificate [][]byte
730 PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
731 // OCSPStaple contains an optional OCSP response which will be served
732 // to clients that request it.
733 OCSPStaple []byte
734 // Leaf is the parsed form of the leaf certificate, which may be
735 // initialized using x509.ParseCertificate to reduce per-handshake
736 // processing for TLS clients doing client authentication. If nil, the
737 // leaf certificate will be parsed as needed.
738 Leaf *x509.Certificate
739}
740
741// A TLS record.
742type record struct {
743 contentType recordType
744 major, minor uint8
745 payload []byte
746}
747
748type handshakeMessage interface {
749 marshal() []byte
750 unmarshal([]byte) bool
751}
752
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500753// lruSessionCache is a client or server session cache implementation
754// that uses an LRU caching strategy.
Adam Langley95c29f32014-06-20 12:00:00 -0700755type lruSessionCache struct {
756 sync.Mutex
757
758 m map[string]*list.Element
759 q *list.List
760 capacity int
761}
762
763type lruSessionCacheEntry struct {
764 sessionKey string
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500765 state interface{}
Adam Langley95c29f32014-06-20 12:00:00 -0700766}
767
768// Put adds the provided (sessionKey, cs) pair to the cache.
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500769func (c *lruSessionCache) Put(sessionKey string, cs interface{}) {
Adam Langley95c29f32014-06-20 12:00:00 -0700770 c.Lock()
771 defer c.Unlock()
772
773 if elem, ok := c.m[sessionKey]; ok {
774 entry := elem.Value.(*lruSessionCacheEntry)
775 entry.state = cs
776 c.q.MoveToFront(elem)
777 return
778 }
779
780 if c.q.Len() < c.capacity {
781 entry := &lruSessionCacheEntry{sessionKey, cs}
782 c.m[sessionKey] = c.q.PushFront(entry)
783 return
784 }
785
786 elem := c.q.Back()
787 entry := elem.Value.(*lruSessionCacheEntry)
788 delete(c.m, entry.sessionKey)
789 entry.sessionKey = sessionKey
790 entry.state = cs
791 c.q.MoveToFront(elem)
792 c.m[sessionKey] = elem
793}
794
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500795// Get returns the value associated with a given key. It returns (nil,
796// false) if no value is found.
797func (c *lruSessionCache) Get(sessionKey string) (interface{}, bool) {
Adam Langley95c29f32014-06-20 12:00:00 -0700798 c.Lock()
799 defer c.Unlock()
800
801 if elem, ok := c.m[sessionKey]; ok {
802 c.q.MoveToFront(elem)
803 return elem.Value.(*lruSessionCacheEntry).state, true
804 }
805 return nil, false
806}
807
David Benjaminfe8eb9a2014-11-17 03:19:02 -0500808// lruClientSessionCache is a ClientSessionCache implementation that
809// uses an LRU caching strategy.
810type lruClientSessionCache struct {
811 lruSessionCache
812}
813
814func (c *lruClientSessionCache) Put(sessionKey string, cs *ClientSessionState) {
815 c.lruSessionCache.Put(sessionKey, cs)
816}
817
818func (c *lruClientSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
819 cs, ok := c.lruSessionCache.Get(sessionKey)
820 if !ok {
821 return nil, false
822 }
823 return cs.(*ClientSessionState), true
824}
825
826// lruServerSessionCache is a ServerSessionCache implementation that
827// uses an LRU caching strategy.
828type lruServerSessionCache struct {
829 lruSessionCache
830}
831
832func (c *lruServerSessionCache) Put(sessionId string, session *sessionState) {
833 c.lruSessionCache.Put(sessionId, session)
834}
835
836func (c *lruServerSessionCache) Get(sessionId string) (*sessionState, bool) {
837 cs, ok := c.lruSessionCache.Get(sessionId)
838 if !ok {
839 return nil, false
840 }
841 return cs.(*sessionState), true
842}
843
844// NewLRUClientSessionCache returns a ClientSessionCache with the given
845// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
846// is used instead.
847func NewLRUClientSessionCache(capacity int) ClientSessionCache {
848 const defaultSessionCacheCapacity = 64
849
850 if capacity < 1 {
851 capacity = defaultSessionCacheCapacity
852 }
853 return &lruClientSessionCache{
854 lruSessionCache{
855 m: make(map[string]*list.Element),
856 q: list.New(),
857 capacity: capacity,
858 },
859 }
860}
861
862// NewLRUServerSessionCache returns a ServerSessionCache with the given
863// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
864// is used instead.
865func NewLRUServerSessionCache(capacity int) ServerSessionCache {
866 const defaultSessionCacheCapacity = 64
867
868 if capacity < 1 {
869 capacity = defaultSessionCacheCapacity
870 }
871 return &lruServerSessionCache{
872 lruSessionCache{
873 m: make(map[string]*list.Element),
874 q: list.New(),
875 capacity: capacity,
876 },
877 }
878}
879
Adam Langley95c29f32014-06-20 12:00:00 -0700880// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
881type dsaSignature struct {
882 R, S *big.Int
883}
884
885type ecdsaSignature dsaSignature
886
887var emptyConfig Config
888
889func defaultConfig() *Config {
890 return &emptyConfig
891}
892
893var (
894 once sync.Once
895 varDefaultCipherSuites []uint16
896)
897
898func defaultCipherSuites() []uint16 {
899 once.Do(initDefaultCipherSuites)
900 return varDefaultCipherSuites
901}
902
903func initDefaultCipherSuites() {
David Benjamin48cae082014-10-27 01:06:24 -0400904 for _, suite := range cipherSuites {
905 if suite.flags&suitePSK == 0 {
906 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
907 }
Adam Langley95c29f32014-06-20 12:00:00 -0700908 }
909}
910
911func unexpectedMessageError(wanted, got interface{}) error {
912 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
913}
David Benjamin000800a2014-11-14 01:43:59 -0500914
915func isSupportedSignatureAndHash(sigHash signatureAndHash, sigHashes []signatureAndHash) bool {
916 for _, s := range sigHashes {
917 if s == sigHash {
918 return true
919 }
920 }
921 return false
922}