blob: a4bdef8021226014f723749db6fdf2ff9442d000 [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 (
132 hashSHA1 uint8 = 2
133 hashSHA256 uint8 = 4
134)
135
136// Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
137const (
138 signatureRSA uint8 = 1
139 signatureECDSA uint8 = 3
140)
141
142// signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See
143// RFC 5246, section A.4.1.
144type signatureAndHash struct {
David Benjamine098ec22014-08-27 23:13:20 -0400145 signature, hash uint8
Adam Langley95c29f32014-06-20 12:00:00 -0700146}
147
148// supportedSKXSignatureAlgorithms contains the signature and hash algorithms
149// that the code advertises as supported in a TLS 1.2 ClientHello.
150var supportedSKXSignatureAlgorithms = []signatureAndHash{
David Benjamine098ec22014-08-27 23:13:20 -0400151 {signatureRSA, hashSHA256},
152 {signatureECDSA, hashSHA256},
153 {signatureRSA, hashSHA1},
154 {signatureECDSA, hashSHA1},
Adam Langley95c29f32014-06-20 12:00:00 -0700155}
156
157// supportedClientCertSignatureAlgorithms contains the signature and hash
158// algorithms that the code advertises as supported in a TLS 1.2
159// CertificateRequest.
160var supportedClientCertSignatureAlgorithms = []signatureAndHash{
David Benjamine098ec22014-08-27 23:13:20 -0400161 {signatureRSA, hashSHA256},
162 {signatureECDSA, hashSHA256},
Adam Langley95c29f32014-06-20 12:00:00 -0700163}
164
David Benjaminca6c8262014-11-15 19:06:08 -0500165// SRTP protection profiles (See RFC 5764, section 4.1.2)
166const (
167 SRTP_AES128_CM_HMAC_SHA1_80 uint16 = 0x0001
168 SRTP_AES128_CM_HMAC_SHA1_32 = 0x0002
169)
170
Adam Langley95c29f32014-06-20 12:00:00 -0700171// ConnectionState records basic TLS details about the connection.
172type ConnectionState struct {
173 Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
174 HandshakeComplete bool // TLS handshake is complete
175 DidResume bool // connection resumes a previous TLS connection
176 CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
177 NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos)
178 NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server
David Benjaminfc7b0862014-09-06 13:21:53 -0400179 NegotiatedProtocolFromALPN bool // protocol negotiated with ALPN
Adam Langley95c29f32014-06-20 12:00:00 -0700180 ServerName string // server name requested by client, if any (server side only)
181 PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
182 VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
David Benjamind30a9902014-08-24 01:44:23 -0400183 ChannelID *ecdsa.PublicKey // the channel ID for this connection
David Benjaminca6c8262014-11-15 19:06:08 -0500184 SRTPProtectionProfile uint16 // the negotiated DTLS-SRTP protection profile
Adam Langley95c29f32014-06-20 12:00:00 -0700185}
186
187// ClientAuthType declares the policy the server will follow for
188// TLS Client Authentication.
189type ClientAuthType int
190
191const (
192 NoClientCert ClientAuthType = iota
193 RequestClientCert
194 RequireAnyClientCert
195 VerifyClientCertIfGiven
196 RequireAndVerifyClientCert
197)
198
199// ClientSessionState contains the state needed by clients to resume TLS
200// sessions.
201type ClientSessionState struct {
Adam Langley75712922014-10-10 16:23:43 -0700202 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
203 vers uint16 // SSL/TLS version negotiated for the session
204 cipherSuite uint16 // Ciphersuite negotiated for the session
205 masterSecret []byte // MasterSecret generated by client on a full handshake
206 handshakeHash []byte // Handshake hash for Channel ID purposes.
207 serverCertificates []*x509.Certificate // Certificate chain presented by the server
208 extendedMasterSecret bool // Whether an extended master secret was used to generate the session
Adam Langley95c29f32014-06-20 12:00:00 -0700209}
210
211// ClientSessionCache is a cache of ClientSessionState objects that can be used
212// by a client to resume a TLS session with a given server. ClientSessionCache
213// implementations should expect to be called concurrently from different
214// goroutines.
215type ClientSessionCache interface {
216 // Get searches for a ClientSessionState associated with the given key.
217 // On return, ok is true if one was found.
218 Get(sessionKey string) (session *ClientSessionState, ok bool)
219
220 // Put adds the ClientSessionState to the cache with the given key.
221 Put(sessionKey string, cs *ClientSessionState)
222}
223
224// A Config structure is used to configure a TLS client or server.
225// After one has been passed to a TLS function it must not be
226// modified. A Config may be reused; the tls package will also not
227// modify it.
228type Config struct {
229 // Rand provides the source of entropy for nonces and RSA blinding.
230 // If Rand is nil, TLS uses the cryptographic random reader in package
231 // crypto/rand.
232 // The Reader must be safe for use by multiple goroutines.
233 Rand io.Reader
234
235 // Time returns the current time as the number of seconds since the epoch.
236 // If Time is nil, TLS uses time.Now.
237 Time func() time.Time
238
239 // Certificates contains one or more certificate chains
240 // to present to the other side of the connection.
241 // Server configurations must include at least one certificate.
242 Certificates []Certificate
243
244 // NameToCertificate maps from a certificate name to an element of
245 // Certificates. Note that a certificate name can be of the form
246 // '*.example.com' and so doesn't have to be a domain name as such.
247 // See Config.BuildNameToCertificate
248 // The nil value causes the first element of Certificates to be used
249 // for all connections.
250 NameToCertificate map[string]*Certificate
251
252 // RootCAs defines the set of root certificate authorities
253 // that clients use when verifying server certificates.
254 // If RootCAs is nil, TLS uses the host's root CA set.
255 RootCAs *x509.CertPool
256
257 // NextProtos is a list of supported, application level protocols.
258 NextProtos []string
259
260 // ServerName is used to verify the hostname on the returned
261 // certificates unless InsecureSkipVerify is given. It is also included
262 // in the client's handshake to support virtual hosting.
263 ServerName string
264
265 // ClientAuth determines the server's policy for
266 // TLS Client Authentication. The default is NoClientCert.
267 ClientAuth ClientAuthType
268
269 // ClientCAs defines the set of root certificate authorities
270 // that servers use if required to verify a client certificate
271 // by the policy in ClientAuth.
272 ClientCAs *x509.CertPool
273
David Benjamin7b030512014-07-08 17:30:11 -0400274 // ClientCertificateTypes defines the set of allowed client certificate
275 // types. The default is CertTypeRSASign and CertTypeECDSASign.
276 ClientCertificateTypes []byte
277
Adam Langley95c29f32014-06-20 12:00:00 -0700278 // InsecureSkipVerify controls whether a client verifies the
279 // server's certificate chain and host name.
280 // If InsecureSkipVerify is true, TLS accepts any certificate
281 // presented by the server and any host name in that certificate.
282 // In this mode, TLS is susceptible to man-in-the-middle attacks.
283 // This should be used only for testing.
284 InsecureSkipVerify bool
285
286 // CipherSuites is a list of supported cipher suites. If CipherSuites
287 // is nil, TLS uses a list of suites supported by the implementation.
288 CipherSuites []uint16
289
290 // PreferServerCipherSuites controls whether the server selects the
291 // client's most preferred ciphersuite, or the server's most preferred
292 // ciphersuite. If true then the server's preference, as expressed in
293 // the order of elements in CipherSuites, is used.
294 PreferServerCipherSuites bool
295
296 // SessionTicketsDisabled may be set to true to disable session ticket
297 // (resumption) support.
298 SessionTicketsDisabled bool
299
300 // SessionTicketKey is used by TLS servers to provide session
301 // resumption. See RFC 5077. If zero, it will be filled with
302 // random data before the first server handshake.
303 //
304 // If multiple servers are terminating connections for the same host
305 // they should all have the same SessionTicketKey. If the
306 // SessionTicketKey leaks, previously recorded and future TLS
307 // connections using that key are compromised.
308 SessionTicketKey [32]byte
309
310 // SessionCache is a cache of ClientSessionState entries for TLS session
311 // resumption.
312 ClientSessionCache ClientSessionCache
313
314 // MinVersion contains the minimum SSL/TLS version that is acceptable.
315 // If zero, then SSLv3 is taken as the minimum.
316 MinVersion uint16
317
318 // MaxVersion contains the maximum SSL/TLS version that is acceptable.
319 // If zero, then the maximum version supported by this package is used,
320 // which is currently TLS 1.2.
321 MaxVersion uint16
322
323 // CurvePreferences contains the elliptic curves that will be used in
324 // an ECDHE handshake, in preference order. If empty, the default will
325 // be used.
326 CurvePreferences []CurveID
327
David Benjamind30a9902014-08-24 01:44:23 -0400328 // ChannelID contains the ECDSA key for the client to use as
329 // its TLS Channel ID.
330 ChannelID *ecdsa.PrivateKey
331
332 // RequestChannelID controls whether the server requests a TLS
333 // Channel ID. If negotiated, the client's public key is
334 // returned in the ConnectionState.
335 RequestChannelID bool
336
David Benjamin48cae082014-10-27 01:06:24 -0400337 // PreSharedKey, if not nil, is the pre-shared key to use with
338 // the PSK cipher suites.
339 PreSharedKey []byte
340
341 // PreSharedKeyIdentity, if not empty, is the identity to use
342 // with the PSK cipher suites.
343 PreSharedKeyIdentity string
344
David Benjaminca6c8262014-11-15 19:06:08 -0500345 // SRTPProtectionProfiles, if not nil, is the list of SRTP
346 // protection profiles to offer in DTLS-SRTP.
347 SRTPProtectionProfiles []uint16
348
Adam Langley95c29f32014-06-20 12:00:00 -0700349 // Bugs specifies optional misbehaviour to be used for testing other
350 // implementations.
351 Bugs ProtocolBugs
352
353 serverInitOnce sync.Once // guards calling (*Config).serverInit
354}
355
356type BadValue int
357
358const (
359 BadValueNone BadValue = iota
360 BadValueNegative
361 BadValueZero
362 BadValueLimit
363 BadValueLarge
364 NumBadValues
365)
366
367type ProtocolBugs struct {
368 // InvalidSKXSignature specifies that the signature in a
369 // ServerKeyExchange message should be invalid.
370 InvalidSKXSignature bool
371
372 // InvalidSKXCurve causes the curve ID in the ServerKeyExchange message
373 // to be wrong.
374 InvalidSKXCurve bool
375
376 // BadECDSAR controls ways in which the 'r' value of an ECDSA signature
377 // can be invalid.
378 BadECDSAR BadValue
379 BadECDSAS BadValue
Adam Langley80842bd2014-06-20 12:00:00 -0700380
381 // MaxPadding causes CBC records to have the maximum possible padding.
382 MaxPadding bool
383 // PaddingFirstByteBad causes the first byte of the padding to be
384 // incorrect.
385 PaddingFirstByteBad bool
386 // PaddingFirstByteBadIf255 causes the first byte of padding to be
387 // incorrect if there's a maximum amount of padding (i.e. 255 bytes).
388 PaddingFirstByteBadIf255 bool
Adam Langleyac61fa32014-06-23 12:03:11 -0700389
390 // FailIfNotFallbackSCSV causes a server handshake to fail if the
391 // client doesn't send the fallback SCSV value.
392 FailIfNotFallbackSCSV bool
David Benjamin35a7a442014-07-05 00:23:20 -0400393
394 // DuplicateExtension causes an extra empty extension of bogus type to
395 // be emitted in either the ClientHello or the ServerHello.
396 DuplicateExtension bool
David Benjamin1c375dd2014-07-12 00:48:23 -0400397
398 // UnauthenticatedECDH causes the server to pretend ECDHE_RSA
399 // and ECDHE_ECDSA cipher suites are actually ECDH_anon. No
400 // Certificate message is sent and no signature is added to
401 // ServerKeyExchange.
402 UnauthenticatedECDH bool
David Benjamin9c651c92014-07-12 13:27:45 -0400403
404 // SkipServerKeyExchange causes the server to skip sending
405 // ServerKeyExchange messages.
406 SkipServerKeyExchange bool
David Benjamina0e52232014-07-19 17:39:58 -0400407
408 // SkipChangeCipherSpec causes the implementation to skip
409 // sending the ChangeCipherSpec message (and adjusting cipher
410 // state accordingly for the Finished message).
411 SkipChangeCipherSpec bool
David Benjaminf3ec83d2014-07-21 22:42:34 -0400412
413 // EarlyChangeCipherSpec causes the client to send an early
414 // ChangeCipherSpec message before the ClientKeyExchange. A value of
415 // zero disables this behavior. One and two configure variants for 0.9.8
416 // and 1.0.1 modes, respectively.
417 EarlyChangeCipherSpec int
David Benjamind23f4122014-07-23 15:09:48 -0400418
David Benjamin86271ee2014-07-21 16:14:03 -0400419 // FragmentAcrossChangeCipherSpec causes the implementation to fragment
420 // the Finished (or NextProto) message around the ChangeCipherSpec
421 // messages.
422 FragmentAcrossChangeCipherSpec bool
423
David Benjamind23f4122014-07-23 15:09:48 -0400424 // SkipNewSessionTicket causes the server to skip sending the
425 // NewSessionTicket message despite promising to in ServerHello.
426 SkipNewSessionTicket bool
David Benjamind86c7672014-08-02 04:07:12 -0400427
428 // SendV2ClientHello causes the client to send a V2ClientHello
429 // instead of a normal ClientHello.
430 SendV2ClientHello bool
David Benjaminbef270a2014-08-02 04:22:02 -0400431
432 // SendFallbackSCSV causes the client to include
433 // TLS_FALLBACK_SCSV in the ClientHello.
434 SendFallbackSCSV bool
David Benjamin43ec06f2014-08-05 02:28:57 -0400435
436 // MaxHandshakeRecordLength, if non-zero, is the maximum size of a
David Benjamin98214542014-08-07 18:02:39 -0400437 // handshake record. Handshake messages will be split into multiple
438 // records at the specified size, except that the client_version will
439 // never be fragmented.
David Benjamin43ec06f2014-08-05 02:28:57 -0400440 MaxHandshakeRecordLength int
David Benjamina8e3e0e2014-08-06 22:11:10 -0400441
David Benjamin98214542014-08-07 18:02:39 -0400442 // FragmentClientVersion will allow MaxHandshakeRecordLength to apply to
443 // the first 6 bytes of the ClientHello.
444 FragmentClientVersion bool
445
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400446 // FragmentAlert will cause all alerts to be fragmented across
447 // two records.
448 FragmentAlert bool
449
450 // SendSpuriousAlert will cause an spurious, unwanted alert to be sent.
451 SendSpuriousAlert bool
452
David Benjamina8e3e0e2014-08-06 22:11:10 -0400453 // RsaClientKeyExchangeVersion, if non-zero, causes the client to send a
454 // ClientKeyExchange with the specified version rather than the
455 // client_version when performing the RSA key exchange.
456 RsaClientKeyExchangeVersion uint16
David Benjaminbed9aae2014-08-07 19:13:38 -0400457
458 // RenewTicketOnResume causes the server to renew the session ticket and
459 // send a NewSessionTicket message during an abbreviated handshake.
460 RenewTicketOnResume bool
David Benjamin98e882e2014-08-08 13:24:34 -0400461
462 // SendClientVersion, if non-zero, causes the client to send a different
463 // TLS version in the ClientHello than the maximum supported version.
464 SendClientVersion uint16
David Benjamin83c0bc92014-08-04 01:23:53 -0400465
466 // SkipHelloVerifyRequest causes a DTLS server to skip the
467 // HelloVerifyRequest message.
468 SkipHelloVerifyRequest bool
David Benjamine58c4f52014-08-24 03:47:07 -0400469
470 // ExpectFalseStart causes the server to, on full handshakes,
471 // expect the peer to False Start; the server Finished message
472 // isn't sent until we receive an application data record
473 // from the peer.
474 ExpectFalseStart bool
David Benjamin5c24a1d2014-08-31 00:59:27 -0400475
476 // SSL3RSAKeyExchange causes the client to always send an RSA
477 // ClientKeyExchange message without the two-byte length
478 // prefix, as if it were SSL3.
479 SSL3RSAKeyExchange bool
David Benjamin39ebf532014-08-31 02:23:49 -0400480
481 // SkipCipherVersionCheck causes the server to negotiate
482 // TLS 1.2 ciphers in earlier versions of TLS.
483 SkipCipherVersionCheck bool
David Benjamine78bfde2014-09-06 12:45:15 -0400484
485 // ExpectServerName, if not empty, is the hostname the client
486 // must specify in the server_name extension.
487 ExpectServerName string
David Benjaminfc7b0862014-09-06 13:21:53 -0400488
489 // SwapNPNAndALPN switches the relative order between NPN and
490 // ALPN on the server. This is to test that server preference
491 // of ALPN works regardless of their relative order.
492 SwapNPNAndALPN bool
David Benjamin01fe8202014-09-24 15:21:44 -0400493
494 // AllowSessionVersionMismatch causes the server to resume sessions
495 // regardless of the version associated with the session.
496 AllowSessionVersionMismatch bool
Adam Langley38311732014-10-16 19:04:35 -0700497
498 // CorruptTicket causes a client to corrupt a session ticket before
499 // sending it in a resume handshake.
500 CorruptTicket bool
501
502 // OversizedSessionId causes the session id that is sent with a ticket
503 // resumption attempt to be too large (33 bytes).
504 OversizedSessionId bool
Adam Langley75712922014-10-10 16:23:43 -0700505
506 // RequireExtendedMasterSecret, if true, requires that the peer support
507 // the extended master secret option.
508 RequireExtendedMasterSecret bool
509
David Benjaminca6554b2014-11-08 12:31:52 -0500510 // NoExtendedMasterSecret causes the client and server to behave as if
Adam Langley75712922014-10-10 16:23:43 -0700511 // they didn't support an extended master secret.
512 NoExtendedMasterSecret bool
Adam Langley2ae77d22014-10-28 17:29:33 -0700513
514 // EmptyRenegotiationInfo causes the renegotiation extension to be
515 // empty in a renegotiation handshake.
516 EmptyRenegotiationInfo bool
517
518 // BadRenegotiationInfo causes the renegotiation extension value in a
519 // renegotiation handshake to be incorrect.
520 BadRenegotiationInfo bool
David Benjamin5e961c12014-11-07 01:48:35 -0500521
David Benjaminca6554b2014-11-08 12:31:52 -0500522 // NoRenegotiationInfo causes the client to behave as if it
523 // didn't support the renegotiation info extension.
524 NoRenegotiationInfo bool
525
David Benjamin5e961c12014-11-07 01:48:35 -0500526 // SequenceNumberIncrement, if non-zero, causes outgoing sequence
527 // numbers in DTLS to increment by that value rather by 1. This is to
528 // stress the replay bitmap window by simulating extreme packet loss and
529 // retransmit at the record layer.
530 SequenceNumberIncrement uint64
David Benjamin9114fae2014-11-08 11:41:14 -0500531
532 // RSAServerKeyExchange, if true, causes the server to send a
533 // ServerKeyExchange message in the plain RSA key exchange.
534 RSAServerKeyExchange bool
David Benjaminca6c8262014-11-15 19:06:08 -0500535
536 // SRTPMasterKeyIdentifer, if not empty, is the SRTP MKI value that the
537 // client offers when negotiating SRTP. MKI support is still missing so
538 // the peer must still send none.
539 SRTPMasterKeyIdentifer string
540
541 // SendSRTPProtectionProfile, if non-zero, is the SRTP profile that the
542 // server sends in the ServerHello instead of the negotiated one.
543 SendSRTPProtectionProfile uint16
Adam Langley95c29f32014-06-20 12:00:00 -0700544}
545
546func (c *Config) serverInit() {
547 if c.SessionTicketsDisabled {
548 return
549 }
550
551 // If the key has already been set then we have nothing to do.
552 for _, b := range c.SessionTicketKey {
553 if b != 0 {
554 return
555 }
556 }
557
558 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
559 c.SessionTicketsDisabled = true
560 }
561}
562
563func (c *Config) rand() io.Reader {
564 r := c.Rand
565 if r == nil {
566 return rand.Reader
567 }
568 return r
569}
570
571func (c *Config) time() time.Time {
572 t := c.Time
573 if t == nil {
574 t = time.Now
575 }
576 return t()
577}
578
579func (c *Config) cipherSuites() []uint16 {
580 s := c.CipherSuites
581 if s == nil {
582 s = defaultCipherSuites()
583 }
584 return s
585}
586
587func (c *Config) minVersion() uint16 {
588 if c == nil || c.MinVersion == 0 {
589 return minVersion
590 }
591 return c.MinVersion
592}
593
594func (c *Config) maxVersion() uint16 {
595 if c == nil || c.MaxVersion == 0 {
596 return maxVersion
597 }
598 return c.MaxVersion
599}
600
601var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
602
603func (c *Config) curvePreferences() []CurveID {
604 if c == nil || len(c.CurvePreferences) == 0 {
605 return defaultCurvePreferences
606 }
607 return c.CurvePreferences
608}
609
610// mutualVersion returns the protocol version to use given the advertised
611// version of the peer.
612func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
613 minVersion := c.minVersion()
614 maxVersion := c.maxVersion()
615
616 if vers < minVersion {
617 return 0, false
618 }
619 if vers > maxVersion {
620 vers = maxVersion
621 }
622 return vers, true
623}
624
625// getCertificateForName returns the best certificate for the given name,
626// defaulting to the first element of c.Certificates if there are no good
627// options.
628func (c *Config) getCertificateForName(name string) *Certificate {
629 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
630 // There's only one choice, so no point doing any work.
631 return &c.Certificates[0]
632 }
633
634 name = strings.ToLower(name)
635 for len(name) > 0 && name[len(name)-1] == '.' {
636 name = name[:len(name)-1]
637 }
638
639 if cert, ok := c.NameToCertificate[name]; ok {
640 return cert
641 }
642
643 // try replacing labels in the name with wildcards until we get a
644 // match.
645 labels := strings.Split(name, ".")
646 for i := range labels {
647 labels[i] = "*"
648 candidate := strings.Join(labels, ".")
649 if cert, ok := c.NameToCertificate[candidate]; ok {
650 return cert
651 }
652 }
653
654 // If nothing matches, return the first certificate.
655 return &c.Certificates[0]
656}
657
658// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
659// from the CommonName and SubjectAlternateName fields of each of the leaf
660// certificates.
661func (c *Config) BuildNameToCertificate() {
662 c.NameToCertificate = make(map[string]*Certificate)
663 for i := range c.Certificates {
664 cert := &c.Certificates[i]
665 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
666 if err != nil {
667 continue
668 }
669 if len(x509Cert.Subject.CommonName) > 0 {
670 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
671 }
672 for _, san := range x509Cert.DNSNames {
673 c.NameToCertificate[san] = cert
674 }
675 }
676}
677
678// A Certificate is a chain of one or more certificates, leaf first.
679type Certificate struct {
680 Certificate [][]byte
681 PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
682 // OCSPStaple contains an optional OCSP response which will be served
683 // to clients that request it.
684 OCSPStaple []byte
685 // Leaf is the parsed form of the leaf certificate, which may be
686 // initialized using x509.ParseCertificate to reduce per-handshake
687 // processing for TLS clients doing client authentication. If nil, the
688 // leaf certificate will be parsed as needed.
689 Leaf *x509.Certificate
690}
691
692// A TLS record.
693type record struct {
694 contentType recordType
695 major, minor uint8
696 payload []byte
697}
698
699type handshakeMessage interface {
700 marshal() []byte
701 unmarshal([]byte) bool
702}
703
704// lruSessionCache is a ClientSessionCache implementation that uses an LRU
705// caching strategy.
706type lruSessionCache struct {
707 sync.Mutex
708
709 m map[string]*list.Element
710 q *list.List
711 capacity int
712}
713
714type lruSessionCacheEntry struct {
715 sessionKey string
716 state *ClientSessionState
717}
718
719// NewLRUClientSessionCache returns a ClientSessionCache with the given
720// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
721// is used instead.
722func NewLRUClientSessionCache(capacity int) ClientSessionCache {
723 const defaultSessionCacheCapacity = 64
724
725 if capacity < 1 {
726 capacity = defaultSessionCacheCapacity
727 }
728 return &lruSessionCache{
729 m: make(map[string]*list.Element),
730 q: list.New(),
731 capacity: capacity,
732 }
733}
734
735// Put adds the provided (sessionKey, cs) pair to the cache.
736func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
737 c.Lock()
738 defer c.Unlock()
739
740 if elem, ok := c.m[sessionKey]; ok {
741 entry := elem.Value.(*lruSessionCacheEntry)
742 entry.state = cs
743 c.q.MoveToFront(elem)
744 return
745 }
746
747 if c.q.Len() < c.capacity {
748 entry := &lruSessionCacheEntry{sessionKey, cs}
749 c.m[sessionKey] = c.q.PushFront(entry)
750 return
751 }
752
753 elem := c.q.Back()
754 entry := elem.Value.(*lruSessionCacheEntry)
755 delete(c.m, entry.sessionKey)
756 entry.sessionKey = sessionKey
757 entry.state = cs
758 c.q.MoveToFront(elem)
759 c.m[sessionKey] = elem
760}
761
762// Get returns the ClientSessionState value associated with a given key. It
763// returns (nil, false) if no value is found.
764func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
765 c.Lock()
766 defer c.Unlock()
767
768 if elem, ok := c.m[sessionKey]; ok {
769 c.q.MoveToFront(elem)
770 return elem.Value.(*lruSessionCacheEntry).state, true
771 }
772 return nil, false
773}
774
775// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
776type dsaSignature struct {
777 R, S *big.Int
778}
779
780type ecdsaSignature dsaSignature
781
782var emptyConfig Config
783
784func defaultConfig() *Config {
785 return &emptyConfig
786}
787
788var (
789 once sync.Once
790 varDefaultCipherSuites []uint16
791)
792
793func defaultCipherSuites() []uint16 {
794 once.Do(initDefaultCipherSuites)
795 return varDefaultCipherSuites
796}
797
798func initDefaultCipherSuites() {
David Benjamin48cae082014-10-27 01:06:24 -0400799 for _, suite := range cipherSuites {
800 if suite.flags&suitePSK == 0 {
801 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
802 }
Adam Langley95c29f32014-06-20 12:00:00 -0700803 }
804}
805
806func unexpectedMessageError(wanted, got interface{}) error {
807 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
808}