blob: 01b7581d89cee74caf1e6249a43fc082e5ef9cf4 [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 {
Adam Langley75712922014-10-10 16:23:43 -0700206 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
207 vers uint16 // SSL/TLS version negotiated for the session
208 cipherSuite uint16 // Ciphersuite negotiated for the session
209 masterSecret []byte // MasterSecret generated by client on a full handshake
210 handshakeHash []byte // Handshake hash for Channel ID purposes.
211 serverCertificates []*x509.Certificate // Certificate chain presented by the server
212 extendedMasterSecret bool // Whether an extended master secret was used to generate the session
Adam Langley95c29f32014-06-20 12:00:00 -0700213}
214
215// ClientSessionCache is a cache of ClientSessionState objects that can be used
216// by a client to resume a TLS session with a given server. ClientSessionCache
217// implementations should expect to be called concurrently from different
218// goroutines.
219type ClientSessionCache interface {
220 // Get searches for a ClientSessionState associated with the given key.
221 // On return, ok is true if one was found.
222 Get(sessionKey string) (session *ClientSessionState, ok bool)
223
224 // Put adds the ClientSessionState to the cache with the given key.
225 Put(sessionKey string, cs *ClientSessionState)
226}
227
228// A Config structure is used to configure a TLS client or server.
229// After one has been passed to a TLS function it must not be
230// modified. A Config may be reused; the tls package will also not
231// modify it.
232type Config struct {
233 // Rand provides the source of entropy for nonces and RSA blinding.
234 // If Rand is nil, TLS uses the cryptographic random reader in package
235 // crypto/rand.
236 // The Reader must be safe for use by multiple goroutines.
237 Rand io.Reader
238
239 // Time returns the current time as the number of seconds since the epoch.
240 // If Time is nil, TLS uses time.Now.
241 Time func() time.Time
242
243 // Certificates contains one or more certificate chains
244 // to present to the other side of the connection.
245 // Server configurations must include at least one certificate.
246 Certificates []Certificate
247
248 // NameToCertificate maps from a certificate name to an element of
249 // Certificates. Note that a certificate name can be of the form
250 // '*.example.com' and so doesn't have to be a domain name as such.
251 // See Config.BuildNameToCertificate
252 // The nil value causes the first element of Certificates to be used
253 // for all connections.
254 NameToCertificate map[string]*Certificate
255
256 // RootCAs defines the set of root certificate authorities
257 // that clients use when verifying server certificates.
258 // If RootCAs is nil, TLS uses the host's root CA set.
259 RootCAs *x509.CertPool
260
261 // NextProtos is a list of supported, application level protocols.
262 NextProtos []string
263
264 // ServerName is used to verify the hostname on the returned
265 // certificates unless InsecureSkipVerify is given. It is also included
266 // in the client's handshake to support virtual hosting.
267 ServerName string
268
269 // ClientAuth determines the server's policy for
270 // TLS Client Authentication. The default is NoClientCert.
271 ClientAuth ClientAuthType
272
273 // ClientCAs defines the set of root certificate authorities
274 // that servers use if required to verify a client certificate
275 // by the policy in ClientAuth.
276 ClientCAs *x509.CertPool
277
David Benjamin7b030512014-07-08 17:30:11 -0400278 // ClientCertificateTypes defines the set of allowed client certificate
279 // types. The default is CertTypeRSASign and CertTypeECDSASign.
280 ClientCertificateTypes []byte
281
Adam Langley95c29f32014-06-20 12:00:00 -0700282 // InsecureSkipVerify controls whether a client verifies the
283 // server's certificate chain and host name.
284 // If InsecureSkipVerify is true, TLS accepts any certificate
285 // presented by the server and any host name in that certificate.
286 // In this mode, TLS is susceptible to man-in-the-middle attacks.
287 // This should be used only for testing.
288 InsecureSkipVerify bool
289
290 // CipherSuites is a list of supported cipher suites. If CipherSuites
291 // is nil, TLS uses a list of suites supported by the implementation.
292 CipherSuites []uint16
293
294 // PreferServerCipherSuites controls whether the server selects the
295 // client's most preferred ciphersuite, or the server's most preferred
296 // ciphersuite. If true then the server's preference, as expressed in
297 // the order of elements in CipherSuites, is used.
298 PreferServerCipherSuites bool
299
300 // SessionTicketsDisabled may be set to true to disable session ticket
301 // (resumption) support.
302 SessionTicketsDisabled bool
303
304 // SessionTicketKey is used by TLS servers to provide session
305 // resumption. See RFC 5077. If zero, it will be filled with
306 // random data before the first server handshake.
307 //
308 // If multiple servers are terminating connections for the same host
309 // they should all have the same SessionTicketKey. If the
310 // SessionTicketKey leaks, previously recorded and future TLS
311 // connections using that key are compromised.
312 SessionTicketKey [32]byte
313
314 // SessionCache is a cache of ClientSessionState entries for TLS session
315 // resumption.
316 ClientSessionCache ClientSessionCache
317
318 // MinVersion contains the minimum SSL/TLS version that is acceptable.
319 // If zero, then SSLv3 is taken as the minimum.
320 MinVersion uint16
321
322 // MaxVersion contains the maximum SSL/TLS version that is acceptable.
323 // If zero, then the maximum version supported by this package is used,
324 // which is currently TLS 1.2.
325 MaxVersion uint16
326
327 // CurvePreferences contains the elliptic curves that will be used in
328 // an ECDHE handshake, in preference order. If empty, the default will
329 // be used.
330 CurvePreferences []CurveID
331
David Benjamind30a9902014-08-24 01:44:23 -0400332 // ChannelID contains the ECDSA key for the client to use as
333 // its TLS Channel ID.
334 ChannelID *ecdsa.PrivateKey
335
336 // RequestChannelID controls whether the server requests a TLS
337 // Channel ID. If negotiated, the client's public key is
338 // returned in the ConnectionState.
339 RequestChannelID bool
340
David Benjamin48cae082014-10-27 01:06:24 -0400341 // PreSharedKey, if not nil, is the pre-shared key to use with
342 // the PSK cipher suites.
343 PreSharedKey []byte
344
345 // PreSharedKeyIdentity, if not empty, is the identity to use
346 // with the PSK cipher suites.
347 PreSharedKeyIdentity string
348
David Benjaminca6c8262014-11-15 19:06:08 -0500349 // SRTPProtectionProfiles, if not nil, is the list of SRTP
350 // protection profiles to offer in DTLS-SRTP.
351 SRTPProtectionProfiles []uint16
352
David Benjamin000800a2014-11-14 01:43:59 -0500353 // SignatureAndHashes, if not nil, overrides the default set of
354 // supported signature and hash algorithms to advertise in
355 // CertificateRequest.
356 SignatureAndHashes []signatureAndHash
357
Adam Langley95c29f32014-06-20 12:00:00 -0700358 // Bugs specifies optional misbehaviour to be used for testing other
359 // implementations.
360 Bugs ProtocolBugs
361
362 serverInitOnce sync.Once // guards calling (*Config).serverInit
363}
364
365type BadValue int
366
367const (
368 BadValueNone BadValue = iota
369 BadValueNegative
370 BadValueZero
371 BadValueLimit
372 BadValueLarge
373 NumBadValues
374)
375
376type ProtocolBugs struct {
377 // InvalidSKXSignature specifies that the signature in a
378 // ServerKeyExchange message should be invalid.
379 InvalidSKXSignature bool
380
381 // InvalidSKXCurve causes the curve ID in the ServerKeyExchange message
382 // to be wrong.
383 InvalidSKXCurve bool
384
385 // BadECDSAR controls ways in which the 'r' value of an ECDSA signature
386 // can be invalid.
387 BadECDSAR BadValue
388 BadECDSAS BadValue
Adam Langley80842bd2014-06-20 12:00:00 -0700389
390 // MaxPadding causes CBC records to have the maximum possible padding.
391 MaxPadding bool
392 // PaddingFirstByteBad causes the first byte of the padding to be
393 // incorrect.
394 PaddingFirstByteBad bool
395 // PaddingFirstByteBadIf255 causes the first byte of padding to be
396 // incorrect if there's a maximum amount of padding (i.e. 255 bytes).
397 PaddingFirstByteBadIf255 bool
Adam Langleyac61fa32014-06-23 12:03:11 -0700398
399 // FailIfNotFallbackSCSV causes a server handshake to fail if the
400 // client doesn't send the fallback SCSV value.
401 FailIfNotFallbackSCSV bool
David Benjamin35a7a442014-07-05 00:23:20 -0400402
403 // DuplicateExtension causes an extra empty extension of bogus type to
404 // be emitted in either the ClientHello or the ServerHello.
405 DuplicateExtension bool
David Benjamin1c375dd2014-07-12 00:48:23 -0400406
407 // UnauthenticatedECDH causes the server to pretend ECDHE_RSA
408 // and ECDHE_ECDSA cipher suites are actually ECDH_anon. No
409 // Certificate message is sent and no signature is added to
410 // ServerKeyExchange.
411 UnauthenticatedECDH bool
David Benjamin9c651c92014-07-12 13:27:45 -0400412
413 // SkipServerKeyExchange causes the server to skip sending
414 // ServerKeyExchange messages.
415 SkipServerKeyExchange bool
David Benjamina0e52232014-07-19 17:39:58 -0400416
417 // SkipChangeCipherSpec causes the implementation to skip
418 // sending the ChangeCipherSpec message (and adjusting cipher
419 // state accordingly for the Finished message).
420 SkipChangeCipherSpec bool
David Benjaminf3ec83d2014-07-21 22:42:34 -0400421
422 // EarlyChangeCipherSpec causes the client to send an early
423 // ChangeCipherSpec message before the ClientKeyExchange. A value of
424 // zero disables this behavior. One and two configure variants for 0.9.8
425 // and 1.0.1 modes, respectively.
426 EarlyChangeCipherSpec int
David Benjamind23f4122014-07-23 15:09:48 -0400427
David Benjamin86271ee2014-07-21 16:14:03 -0400428 // FragmentAcrossChangeCipherSpec causes the implementation to fragment
429 // the Finished (or NextProto) message around the ChangeCipherSpec
430 // messages.
431 FragmentAcrossChangeCipherSpec bool
432
David Benjamind23f4122014-07-23 15:09:48 -0400433 // SkipNewSessionTicket causes the server to skip sending the
434 // NewSessionTicket message despite promising to in ServerHello.
435 SkipNewSessionTicket bool
David Benjamind86c7672014-08-02 04:07:12 -0400436
437 // SendV2ClientHello causes the client to send a V2ClientHello
438 // instead of a normal ClientHello.
439 SendV2ClientHello bool
David Benjaminbef270a2014-08-02 04:22:02 -0400440
441 // SendFallbackSCSV causes the client to include
442 // TLS_FALLBACK_SCSV in the ClientHello.
443 SendFallbackSCSV bool
David Benjamin43ec06f2014-08-05 02:28:57 -0400444
445 // MaxHandshakeRecordLength, if non-zero, is the maximum size of a
David Benjamin98214542014-08-07 18:02:39 -0400446 // handshake record. Handshake messages will be split into multiple
447 // records at the specified size, except that the client_version will
448 // never be fragmented.
David Benjamin43ec06f2014-08-05 02:28:57 -0400449 MaxHandshakeRecordLength int
David Benjamina8e3e0e2014-08-06 22:11:10 -0400450
David Benjamin98214542014-08-07 18:02:39 -0400451 // FragmentClientVersion will allow MaxHandshakeRecordLength to apply to
452 // the first 6 bytes of the ClientHello.
453 FragmentClientVersion bool
454
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400455 // FragmentAlert will cause all alerts to be fragmented across
456 // two records.
457 FragmentAlert bool
458
459 // SendSpuriousAlert will cause an spurious, unwanted alert to be sent.
460 SendSpuriousAlert bool
461
David Benjamina8e3e0e2014-08-06 22:11:10 -0400462 // RsaClientKeyExchangeVersion, if non-zero, causes the client to send a
463 // ClientKeyExchange with the specified version rather than the
464 // client_version when performing the RSA key exchange.
465 RsaClientKeyExchangeVersion uint16
David Benjaminbed9aae2014-08-07 19:13:38 -0400466
467 // RenewTicketOnResume causes the server to renew the session ticket and
468 // send a NewSessionTicket message during an abbreviated handshake.
469 RenewTicketOnResume bool
David Benjamin98e882e2014-08-08 13:24:34 -0400470
471 // SendClientVersion, if non-zero, causes the client to send a different
472 // TLS version in the ClientHello than the maximum supported version.
473 SendClientVersion uint16
David Benjamin83c0bc92014-08-04 01:23:53 -0400474
475 // SkipHelloVerifyRequest causes a DTLS server to skip the
476 // HelloVerifyRequest message.
477 SkipHelloVerifyRequest bool
David Benjamine58c4f52014-08-24 03:47:07 -0400478
479 // ExpectFalseStart causes the server to, on full handshakes,
480 // expect the peer to False Start; the server Finished message
481 // isn't sent until we receive an application data record
482 // from the peer.
483 ExpectFalseStart bool
David Benjamin5c24a1d2014-08-31 00:59:27 -0400484
485 // SSL3RSAKeyExchange causes the client to always send an RSA
486 // ClientKeyExchange message without the two-byte length
487 // prefix, as if it were SSL3.
488 SSL3RSAKeyExchange bool
David Benjamin39ebf532014-08-31 02:23:49 -0400489
490 // SkipCipherVersionCheck causes the server to negotiate
491 // TLS 1.2 ciphers in earlier versions of TLS.
492 SkipCipherVersionCheck bool
David Benjamine78bfde2014-09-06 12:45:15 -0400493
494 // ExpectServerName, if not empty, is the hostname the client
495 // must specify in the server_name extension.
496 ExpectServerName string
David Benjaminfc7b0862014-09-06 13:21:53 -0400497
498 // SwapNPNAndALPN switches the relative order between NPN and
499 // ALPN on the server. This is to test that server preference
500 // of ALPN works regardless of their relative order.
501 SwapNPNAndALPN bool
David Benjamin01fe8202014-09-24 15:21:44 -0400502
503 // AllowSessionVersionMismatch causes the server to resume sessions
504 // regardless of the version associated with the session.
505 AllowSessionVersionMismatch bool
Adam Langley38311732014-10-16 19:04:35 -0700506
507 // CorruptTicket causes a client to corrupt a session ticket before
508 // sending it in a resume handshake.
509 CorruptTicket bool
510
511 // OversizedSessionId causes the session id that is sent with a ticket
512 // resumption attempt to be too large (33 bytes).
513 OversizedSessionId bool
Adam Langley75712922014-10-10 16:23:43 -0700514
515 // RequireExtendedMasterSecret, if true, requires that the peer support
516 // the extended master secret option.
517 RequireExtendedMasterSecret bool
518
David Benjaminca6554b2014-11-08 12:31:52 -0500519 // NoExtendedMasterSecret causes the client and server to behave as if
Adam Langley75712922014-10-10 16:23:43 -0700520 // they didn't support an extended master secret.
521 NoExtendedMasterSecret bool
Adam Langley2ae77d22014-10-28 17:29:33 -0700522
523 // EmptyRenegotiationInfo causes the renegotiation extension to be
524 // empty in a renegotiation handshake.
525 EmptyRenegotiationInfo bool
526
527 // BadRenegotiationInfo causes the renegotiation extension value in a
528 // renegotiation handshake to be incorrect.
529 BadRenegotiationInfo bool
David Benjamin5e961c12014-11-07 01:48:35 -0500530
David Benjaminca6554b2014-11-08 12:31:52 -0500531 // NoRenegotiationInfo causes the client to behave as if it
532 // didn't support the renegotiation info extension.
533 NoRenegotiationInfo bool
534
David Benjamin5e961c12014-11-07 01:48:35 -0500535 // SequenceNumberIncrement, if non-zero, causes outgoing sequence
536 // numbers in DTLS to increment by that value rather by 1. This is to
537 // stress the replay bitmap window by simulating extreme packet loss and
538 // retransmit at the record layer.
539 SequenceNumberIncrement uint64
David Benjamin9114fae2014-11-08 11:41:14 -0500540
541 // RSAServerKeyExchange, if true, causes the server to send a
542 // ServerKeyExchange message in the plain RSA key exchange.
543 RSAServerKeyExchange bool
David Benjaminca6c8262014-11-15 19:06:08 -0500544
545 // SRTPMasterKeyIdentifer, if not empty, is the SRTP MKI value that the
546 // client offers when negotiating SRTP. MKI support is still missing so
547 // the peer must still send none.
548 SRTPMasterKeyIdentifer string
549
550 // SendSRTPProtectionProfile, if non-zero, is the SRTP profile that the
551 // server sends in the ServerHello instead of the negotiated one.
552 SendSRTPProtectionProfile uint16
David Benjamin000800a2014-11-14 01:43:59 -0500553
554 // NoSignatureAndHashes, if true, causes the client to omit the
555 // signature and hashes extension.
556 //
557 // For a server, it will cause an empty list to be sent in the
558 // CertificateRequest message. None the less, the configured set will
559 // still be enforced.
560 NoSignatureAndHashes bool
Adam Langley95c29f32014-06-20 12:00:00 -0700561}
562
563func (c *Config) serverInit() {
564 if c.SessionTicketsDisabled {
565 return
566 }
567
568 // If the key has already been set then we have nothing to do.
569 for _, b := range c.SessionTicketKey {
570 if b != 0 {
571 return
572 }
573 }
574
575 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
576 c.SessionTicketsDisabled = true
577 }
578}
579
580func (c *Config) rand() io.Reader {
581 r := c.Rand
582 if r == nil {
583 return rand.Reader
584 }
585 return r
586}
587
588func (c *Config) time() time.Time {
589 t := c.Time
590 if t == nil {
591 t = time.Now
592 }
593 return t()
594}
595
596func (c *Config) cipherSuites() []uint16 {
597 s := c.CipherSuites
598 if s == nil {
599 s = defaultCipherSuites()
600 }
601 return s
602}
603
604func (c *Config) minVersion() uint16 {
605 if c == nil || c.MinVersion == 0 {
606 return minVersion
607 }
608 return c.MinVersion
609}
610
611func (c *Config) maxVersion() uint16 {
612 if c == nil || c.MaxVersion == 0 {
613 return maxVersion
614 }
615 return c.MaxVersion
616}
617
618var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
619
620func (c *Config) curvePreferences() []CurveID {
621 if c == nil || len(c.CurvePreferences) == 0 {
622 return defaultCurvePreferences
623 }
624 return c.CurvePreferences
625}
626
627// mutualVersion returns the protocol version to use given the advertised
628// version of the peer.
629func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
630 minVersion := c.minVersion()
631 maxVersion := c.maxVersion()
632
633 if vers < minVersion {
634 return 0, false
635 }
636 if vers > maxVersion {
637 vers = maxVersion
638 }
639 return vers, true
640}
641
642// getCertificateForName returns the best certificate for the given name,
643// defaulting to the first element of c.Certificates if there are no good
644// options.
645func (c *Config) getCertificateForName(name string) *Certificate {
646 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
647 // There's only one choice, so no point doing any work.
648 return &c.Certificates[0]
649 }
650
651 name = strings.ToLower(name)
652 for len(name) > 0 && name[len(name)-1] == '.' {
653 name = name[:len(name)-1]
654 }
655
656 if cert, ok := c.NameToCertificate[name]; ok {
657 return cert
658 }
659
660 // try replacing labels in the name with wildcards until we get a
661 // match.
662 labels := strings.Split(name, ".")
663 for i := range labels {
664 labels[i] = "*"
665 candidate := strings.Join(labels, ".")
666 if cert, ok := c.NameToCertificate[candidate]; ok {
667 return cert
668 }
669 }
670
671 // If nothing matches, return the first certificate.
672 return &c.Certificates[0]
673}
674
David Benjamin000800a2014-11-14 01:43:59 -0500675func (c *Config) signatureAndHashesForServer() []signatureAndHash {
676 if c != nil && c.SignatureAndHashes != nil {
677 return c.SignatureAndHashes
678 }
679 return supportedClientCertSignatureAlgorithms
680}
681
682func (c *Config) signatureAndHashesForClient() []signatureAndHash {
683 if c != nil && c.SignatureAndHashes != nil {
684 return c.SignatureAndHashes
685 }
686 return supportedSKXSignatureAlgorithms
687}
688
Adam Langley95c29f32014-06-20 12:00:00 -0700689// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
690// from the CommonName and SubjectAlternateName fields of each of the leaf
691// certificates.
692func (c *Config) BuildNameToCertificate() {
693 c.NameToCertificate = make(map[string]*Certificate)
694 for i := range c.Certificates {
695 cert := &c.Certificates[i]
696 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
697 if err != nil {
698 continue
699 }
700 if len(x509Cert.Subject.CommonName) > 0 {
701 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
702 }
703 for _, san := range x509Cert.DNSNames {
704 c.NameToCertificate[san] = cert
705 }
706 }
707}
708
709// A Certificate is a chain of one or more certificates, leaf first.
710type Certificate struct {
711 Certificate [][]byte
712 PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
713 // OCSPStaple contains an optional OCSP response which will be served
714 // to clients that request it.
715 OCSPStaple []byte
716 // Leaf is the parsed form of the leaf certificate, which may be
717 // initialized using x509.ParseCertificate to reduce per-handshake
718 // processing for TLS clients doing client authentication. If nil, the
719 // leaf certificate will be parsed as needed.
720 Leaf *x509.Certificate
721}
722
723// A TLS record.
724type record struct {
725 contentType recordType
726 major, minor uint8
727 payload []byte
728}
729
730type handshakeMessage interface {
731 marshal() []byte
732 unmarshal([]byte) bool
733}
734
735// lruSessionCache is a ClientSessionCache implementation that uses an LRU
736// caching strategy.
737type lruSessionCache struct {
738 sync.Mutex
739
740 m map[string]*list.Element
741 q *list.List
742 capacity int
743}
744
745type lruSessionCacheEntry struct {
746 sessionKey string
747 state *ClientSessionState
748}
749
750// NewLRUClientSessionCache returns a ClientSessionCache with the given
751// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
752// is used instead.
753func NewLRUClientSessionCache(capacity int) ClientSessionCache {
754 const defaultSessionCacheCapacity = 64
755
756 if capacity < 1 {
757 capacity = defaultSessionCacheCapacity
758 }
759 return &lruSessionCache{
760 m: make(map[string]*list.Element),
761 q: list.New(),
762 capacity: capacity,
763 }
764}
765
766// Put adds the provided (sessionKey, cs) pair to the cache.
767func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
768 c.Lock()
769 defer c.Unlock()
770
771 if elem, ok := c.m[sessionKey]; ok {
772 entry := elem.Value.(*lruSessionCacheEntry)
773 entry.state = cs
774 c.q.MoveToFront(elem)
775 return
776 }
777
778 if c.q.Len() < c.capacity {
779 entry := &lruSessionCacheEntry{sessionKey, cs}
780 c.m[sessionKey] = c.q.PushFront(entry)
781 return
782 }
783
784 elem := c.q.Back()
785 entry := elem.Value.(*lruSessionCacheEntry)
786 delete(c.m, entry.sessionKey)
787 entry.sessionKey = sessionKey
788 entry.state = cs
789 c.q.MoveToFront(elem)
790 c.m[sessionKey] = elem
791}
792
793// Get returns the ClientSessionState value associated with a given key. It
794// returns (nil, false) if no value is found.
795func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
796 c.Lock()
797 defer c.Unlock()
798
799 if elem, ok := c.m[sessionKey]; ok {
800 c.q.MoveToFront(elem)
801 return elem.Value.(*lruSessionCacheEntry).state, true
802 }
803 return nil, false
804}
805
806// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
807type dsaSignature struct {
808 R, S *big.Int
809}
810
811type ecdsaSignature dsaSignature
812
813var emptyConfig Config
814
815func defaultConfig() *Config {
816 return &emptyConfig
817}
818
819var (
820 once sync.Once
821 varDefaultCipherSuites []uint16
822)
823
824func defaultCipherSuites() []uint16 {
825 once.Do(initDefaultCipherSuites)
826 return varDefaultCipherSuites
827}
828
829func initDefaultCipherSuites() {
David Benjamin48cae082014-10-27 01:06:24 -0400830 for _, suite := range cipherSuites {
831 if suite.flags&suitePSK == 0 {
832 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
833 }
Adam Langley95c29f32014-06-20 12:00:00 -0700834 }
835}
836
837func unexpectedMessageError(wanted, got interface{}) error {
838 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
839}
David Benjamin000800a2014-11-14 01:43:59 -0500840
841func isSupportedSignatureAndHash(sigHash signatureAndHash, sigHashes []signatureAndHash) bool {
842 for _, s := range sigHashes {
843 if s == sigHash {
844 return true
845 }
846 }
847 return false
848}