blob: 9f79778f430b9a9d6abb79c1138f82874b2b95a4 [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
80 extensionALPN uint16 = 16
81 extensionExtendedMasterSecret uint16 = 23
82 extensionSessionTicket uint16 = 35
83 extensionNextProtoNeg uint16 = 13172 // not IANA assigned
84 extensionRenegotiationInfo uint16 = 0xff01
85 extensionChannelID uint16 = 30032 // not IANA assigned
Adam Langley95c29f32014-06-20 12:00:00 -070086)
87
88// TLS signaling cipher suite values
89const (
90 scsvRenegotiation uint16 = 0x00ff
91)
92
93// CurveID is the type of a TLS identifier for an elliptic curve. See
94// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
95type CurveID uint16
96
97const (
98 CurveP256 CurveID = 23
99 CurveP384 CurveID = 24
100 CurveP521 CurveID = 25
101)
102
103// TLS Elliptic Curve Point Formats
104// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
105const (
106 pointFormatUncompressed uint8 = 0
107)
108
109// TLS CertificateStatusType (RFC 3546)
110const (
111 statusTypeOCSP uint8 = 1
112)
113
114// Certificate types (for certificateRequestMsg)
115const (
David Benjamin7b030512014-07-08 17:30:11 -0400116 CertTypeRSASign = 1 // A certificate containing an RSA key
117 CertTypeDSSSign = 2 // A certificate containing a DSA key
118 CertTypeRSAFixedDH = 3 // A certificate containing a static DH key
119 CertTypeDSSFixedDH = 4 // A certificate containing a static DH key
Adam Langley95c29f32014-06-20 12:00:00 -0700120
121 // See RFC4492 sections 3 and 5.5.
David Benjamin7b030512014-07-08 17:30:11 -0400122 CertTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
123 CertTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
124 CertTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
Adam Langley95c29f32014-06-20 12:00:00 -0700125
126 // Rest of these are reserved by the TLS spec
127)
128
129// Hash functions for TLS 1.2 (See RFC 5246, section A.4.1)
130const (
131 hashSHA1 uint8 = 2
132 hashSHA256 uint8 = 4
133)
134
135// Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
136const (
137 signatureRSA uint8 = 1
138 signatureECDSA uint8 = 3
139)
140
141// signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See
142// RFC 5246, section A.4.1.
143type signatureAndHash struct {
David Benjamine098ec22014-08-27 23:13:20 -0400144 signature, hash uint8
Adam Langley95c29f32014-06-20 12:00:00 -0700145}
146
147// supportedSKXSignatureAlgorithms contains the signature and hash algorithms
148// that the code advertises as supported in a TLS 1.2 ClientHello.
149var supportedSKXSignatureAlgorithms = []signatureAndHash{
David Benjamine098ec22014-08-27 23:13:20 -0400150 {signatureRSA, hashSHA256},
151 {signatureECDSA, hashSHA256},
152 {signatureRSA, hashSHA1},
153 {signatureECDSA, hashSHA1},
Adam Langley95c29f32014-06-20 12:00:00 -0700154}
155
156// supportedClientCertSignatureAlgorithms contains the signature and hash
157// algorithms that the code advertises as supported in a TLS 1.2
158// CertificateRequest.
159var supportedClientCertSignatureAlgorithms = []signatureAndHash{
David Benjamine098ec22014-08-27 23:13:20 -0400160 {signatureRSA, hashSHA256},
161 {signatureECDSA, hashSHA256},
Adam Langley95c29f32014-06-20 12:00:00 -0700162}
163
164// ConnectionState records basic TLS details about the connection.
165type ConnectionState struct {
166 Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
167 HandshakeComplete bool // TLS handshake is complete
168 DidResume bool // connection resumes a previous TLS connection
169 CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
170 NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos)
171 NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server
David Benjaminfc7b0862014-09-06 13:21:53 -0400172 NegotiatedProtocolFromALPN bool // protocol negotiated with ALPN
Adam Langley95c29f32014-06-20 12:00:00 -0700173 ServerName string // server name requested by client, if any (server side only)
174 PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
175 VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
David Benjamind30a9902014-08-24 01:44:23 -0400176 ChannelID *ecdsa.PublicKey // the channel ID for this connection
Adam Langley95c29f32014-06-20 12:00:00 -0700177}
178
179// ClientAuthType declares the policy the server will follow for
180// TLS Client Authentication.
181type ClientAuthType int
182
183const (
184 NoClientCert ClientAuthType = iota
185 RequestClientCert
186 RequireAnyClientCert
187 VerifyClientCertIfGiven
188 RequireAndVerifyClientCert
189)
190
191// ClientSessionState contains the state needed by clients to resume TLS
192// sessions.
193type ClientSessionState struct {
Adam Langley75712922014-10-10 16:23:43 -0700194 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
195 vers uint16 // SSL/TLS version negotiated for the session
196 cipherSuite uint16 // Ciphersuite negotiated for the session
197 masterSecret []byte // MasterSecret generated by client on a full handshake
198 handshakeHash []byte // Handshake hash for Channel ID purposes.
199 serverCertificates []*x509.Certificate // Certificate chain presented by the server
200 extendedMasterSecret bool // Whether an extended master secret was used to generate the session
Adam Langley95c29f32014-06-20 12:00:00 -0700201}
202
203// ClientSessionCache is a cache of ClientSessionState objects that can be used
204// by a client to resume a TLS session with a given server. ClientSessionCache
205// implementations should expect to be called concurrently from different
206// goroutines.
207type ClientSessionCache interface {
208 // Get searches for a ClientSessionState associated with the given key.
209 // On return, ok is true if one was found.
210 Get(sessionKey string) (session *ClientSessionState, ok bool)
211
212 // Put adds the ClientSessionState to the cache with the given key.
213 Put(sessionKey string, cs *ClientSessionState)
214}
215
216// A Config structure is used to configure a TLS client or server.
217// After one has been passed to a TLS function it must not be
218// modified. A Config may be reused; the tls package will also not
219// modify it.
220type Config struct {
221 // Rand provides the source of entropy for nonces and RSA blinding.
222 // If Rand is nil, TLS uses the cryptographic random reader in package
223 // crypto/rand.
224 // The Reader must be safe for use by multiple goroutines.
225 Rand io.Reader
226
227 // Time returns the current time as the number of seconds since the epoch.
228 // If Time is nil, TLS uses time.Now.
229 Time func() time.Time
230
231 // Certificates contains one or more certificate chains
232 // to present to the other side of the connection.
233 // Server configurations must include at least one certificate.
234 Certificates []Certificate
235
236 // NameToCertificate maps from a certificate name to an element of
237 // Certificates. Note that a certificate name can be of the form
238 // '*.example.com' and so doesn't have to be a domain name as such.
239 // See Config.BuildNameToCertificate
240 // The nil value causes the first element of Certificates to be used
241 // for all connections.
242 NameToCertificate map[string]*Certificate
243
244 // RootCAs defines the set of root certificate authorities
245 // that clients use when verifying server certificates.
246 // If RootCAs is nil, TLS uses the host's root CA set.
247 RootCAs *x509.CertPool
248
249 // NextProtos is a list of supported, application level protocols.
250 NextProtos []string
251
252 // ServerName is used to verify the hostname on the returned
253 // certificates unless InsecureSkipVerify is given. It is also included
254 // in the client's handshake to support virtual hosting.
255 ServerName string
256
257 // ClientAuth determines the server's policy for
258 // TLS Client Authentication. The default is NoClientCert.
259 ClientAuth ClientAuthType
260
261 // ClientCAs defines the set of root certificate authorities
262 // that servers use if required to verify a client certificate
263 // by the policy in ClientAuth.
264 ClientCAs *x509.CertPool
265
David Benjamin7b030512014-07-08 17:30:11 -0400266 // ClientCertificateTypes defines the set of allowed client certificate
267 // types. The default is CertTypeRSASign and CertTypeECDSASign.
268 ClientCertificateTypes []byte
269
Adam Langley95c29f32014-06-20 12:00:00 -0700270 // InsecureSkipVerify controls whether a client verifies the
271 // server's certificate chain and host name.
272 // If InsecureSkipVerify is true, TLS accepts any certificate
273 // presented by the server and any host name in that certificate.
274 // In this mode, TLS is susceptible to man-in-the-middle attacks.
275 // This should be used only for testing.
276 InsecureSkipVerify bool
277
278 // CipherSuites is a list of supported cipher suites. If CipherSuites
279 // is nil, TLS uses a list of suites supported by the implementation.
280 CipherSuites []uint16
281
282 // PreferServerCipherSuites controls whether the server selects the
283 // client's most preferred ciphersuite, or the server's most preferred
284 // ciphersuite. If true then the server's preference, as expressed in
285 // the order of elements in CipherSuites, is used.
286 PreferServerCipherSuites bool
287
288 // SessionTicketsDisabled may be set to true to disable session ticket
289 // (resumption) support.
290 SessionTicketsDisabled bool
291
292 // SessionTicketKey is used by TLS servers to provide session
293 // resumption. See RFC 5077. If zero, it will be filled with
294 // random data before the first server handshake.
295 //
296 // If multiple servers are terminating connections for the same host
297 // they should all have the same SessionTicketKey. If the
298 // SessionTicketKey leaks, previously recorded and future TLS
299 // connections using that key are compromised.
300 SessionTicketKey [32]byte
301
302 // SessionCache is a cache of ClientSessionState entries for TLS session
303 // resumption.
304 ClientSessionCache ClientSessionCache
305
306 // MinVersion contains the minimum SSL/TLS version that is acceptable.
307 // If zero, then SSLv3 is taken as the minimum.
308 MinVersion uint16
309
310 // MaxVersion contains the maximum SSL/TLS version that is acceptable.
311 // If zero, then the maximum version supported by this package is used,
312 // which is currently TLS 1.2.
313 MaxVersion uint16
314
315 // CurvePreferences contains the elliptic curves that will be used in
316 // an ECDHE handshake, in preference order. If empty, the default will
317 // be used.
318 CurvePreferences []CurveID
319
David Benjamind30a9902014-08-24 01:44:23 -0400320 // ChannelID contains the ECDSA key for the client to use as
321 // its TLS Channel ID.
322 ChannelID *ecdsa.PrivateKey
323
324 // RequestChannelID controls whether the server requests a TLS
325 // Channel ID. If negotiated, the client's public key is
326 // returned in the ConnectionState.
327 RequestChannelID bool
328
David Benjamin48cae082014-10-27 01:06:24 -0400329 // PreSharedKey, if not nil, is the pre-shared key to use with
330 // the PSK cipher suites.
331 PreSharedKey []byte
332
333 // PreSharedKeyIdentity, if not empty, is the identity to use
334 // with the PSK cipher suites.
335 PreSharedKeyIdentity string
336
Adam Langley95c29f32014-06-20 12:00:00 -0700337 // Bugs specifies optional misbehaviour to be used for testing other
338 // implementations.
339 Bugs ProtocolBugs
340
341 serverInitOnce sync.Once // guards calling (*Config).serverInit
342}
343
344type BadValue int
345
346const (
347 BadValueNone BadValue = iota
348 BadValueNegative
349 BadValueZero
350 BadValueLimit
351 BadValueLarge
352 NumBadValues
353)
354
355type ProtocolBugs struct {
356 // InvalidSKXSignature specifies that the signature in a
357 // ServerKeyExchange message should be invalid.
358 InvalidSKXSignature bool
359
360 // InvalidSKXCurve causes the curve ID in the ServerKeyExchange message
361 // to be wrong.
362 InvalidSKXCurve bool
363
364 // BadECDSAR controls ways in which the 'r' value of an ECDSA signature
365 // can be invalid.
366 BadECDSAR BadValue
367 BadECDSAS BadValue
Adam Langley80842bd2014-06-20 12:00:00 -0700368
369 // MaxPadding causes CBC records to have the maximum possible padding.
370 MaxPadding bool
371 // PaddingFirstByteBad causes the first byte of the padding to be
372 // incorrect.
373 PaddingFirstByteBad bool
374 // PaddingFirstByteBadIf255 causes the first byte of padding to be
375 // incorrect if there's a maximum amount of padding (i.e. 255 bytes).
376 PaddingFirstByteBadIf255 bool
Adam Langleyac61fa32014-06-23 12:03:11 -0700377
378 // FailIfNotFallbackSCSV causes a server handshake to fail if the
379 // client doesn't send the fallback SCSV value.
380 FailIfNotFallbackSCSV bool
David Benjamin35a7a442014-07-05 00:23:20 -0400381
382 // DuplicateExtension causes an extra empty extension of bogus type to
383 // be emitted in either the ClientHello or the ServerHello.
384 DuplicateExtension bool
David Benjamin1c375dd2014-07-12 00:48:23 -0400385
386 // UnauthenticatedECDH causes the server to pretend ECDHE_RSA
387 // and ECDHE_ECDSA cipher suites are actually ECDH_anon. No
388 // Certificate message is sent and no signature is added to
389 // ServerKeyExchange.
390 UnauthenticatedECDH bool
David Benjamin9c651c92014-07-12 13:27:45 -0400391
392 // SkipServerKeyExchange causes the server to skip sending
393 // ServerKeyExchange messages.
394 SkipServerKeyExchange bool
David Benjamina0e52232014-07-19 17:39:58 -0400395
396 // SkipChangeCipherSpec causes the implementation to skip
397 // sending the ChangeCipherSpec message (and adjusting cipher
398 // state accordingly for the Finished message).
399 SkipChangeCipherSpec bool
David Benjaminf3ec83d2014-07-21 22:42:34 -0400400
401 // EarlyChangeCipherSpec causes the client to send an early
402 // ChangeCipherSpec message before the ClientKeyExchange. A value of
403 // zero disables this behavior. One and two configure variants for 0.9.8
404 // and 1.0.1 modes, respectively.
405 EarlyChangeCipherSpec int
David Benjamind23f4122014-07-23 15:09:48 -0400406
David Benjamin86271ee2014-07-21 16:14:03 -0400407 // FragmentAcrossChangeCipherSpec causes the implementation to fragment
408 // the Finished (or NextProto) message around the ChangeCipherSpec
409 // messages.
410 FragmentAcrossChangeCipherSpec bool
411
David Benjamind23f4122014-07-23 15:09:48 -0400412 // SkipNewSessionTicket causes the server to skip sending the
413 // NewSessionTicket message despite promising to in ServerHello.
414 SkipNewSessionTicket bool
David Benjamind86c7672014-08-02 04:07:12 -0400415
416 // SendV2ClientHello causes the client to send a V2ClientHello
417 // instead of a normal ClientHello.
418 SendV2ClientHello bool
David Benjaminbef270a2014-08-02 04:22:02 -0400419
420 // SendFallbackSCSV causes the client to include
421 // TLS_FALLBACK_SCSV in the ClientHello.
422 SendFallbackSCSV bool
David Benjamin43ec06f2014-08-05 02:28:57 -0400423
424 // MaxHandshakeRecordLength, if non-zero, is the maximum size of a
David Benjamin98214542014-08-07 18:02:39 -0400425 // handshake record. Handshake messages will be split into multiple
426 // records at the specified size, except that the client_version will
427 // never be fragmented.
David Benjamin43ec06f2014-08-05 02:28:57 -0400428 MaxHandshakeRecordLength int
David Benjamina8e3e0e2014-08-06 22:11:10 -0400429
David Benjamin98214542014-08-07 18:02:39 -0400430 // FragmentClientVersion will allow MaxHandshakeRecordLength to apply to
431 // the first 6 bytes of the ClientHello.
432 FragmentClientVersion bool
433
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400434 // FragmentAlert will cause all alerts to be fragmented across
435 // two records.
436 FragmentAlert bool
437
438 // SendSpuriousAlert will cause an spurious, unwanted alert to be sent.
439 SendSpuriousAlert bool
440
David Benjamina8e3e0e2014-08-06 22:11:10 -0400441 // RsaClientKeyExchangeVersion, if non-zero, causes the client to send a
442 // ClientKeyExchange with the specified version rather than the
443 // client_version when performing the RSA key exchange.
444 RsaClientKeyExchangeVersion uint16
David Benjaminbed9aae2014-08-07 19:13:38 -0400445
446 // RenewTicketOnResume causes the server to renew the session ticket and
447 // send a NewSessionTicket message during an abbreviated handshake.
448 RenewTicketOnResume bool
David Benjamin98e882e2014-08-08 13:24:34 -0400449
450 // SendClientVersion, if non-zero, causes the client to send a different
451 // TLS version in the ClientHello than the maximum supported version.
452 SendClientVersion uint16
David Benjamin83c0bc92014-08-04 01:23:53 -0400453
454 // SkipHelloVerifyRequest causes a DTLS server to skip the
455 // HelloVerifyRequest message.
456 SkipHelloVerifyRequest bool
David Benjamine58c4f52014-08-24 03:47:07 -0400457
458 // ExpectFalseStart causes the server to, on full handshakes,
459 // expect the peer to False Start; the server Finished message
460 // isn't sent until we receive an application data record
461 // from the peer.
462 ExpectFalseStart bool
David Benjamin5c24a1d2014-08-31 00:59:27 -0400463
464 // SSL3RSAKeyExchange causes the client to always send an RSA
465 // ClientKeyExchange message without the two-byte length
466 // prefix, as if it were SSL3.
467 SSL3RSAKeyExchange bool
David Benjamin39ebf532014-08-31 02:23:49 -0400468
469 // SkipCipherVersionCheck causes the server to negotiate
470 // TLS 1.2 ciphers in earlier versions of TLS.
471 SkipCipherVersionCheck bool
David Benjamine78bfde2014-09-06 12:45:15 -0400472
473 // ExpectServerName, if not empty, is the hostname the client
474 // must specify in the server_name extension.
475 ExpectServerName string
David Benjaminfc7b0862014-09-06 13:21:53 -0400476
477 // SwapNPNAndALPN switches the relative order between NPN and
478 // ALPN on the server. This is to test that server preference
479 // of ALPN works regardless of their relative order.
480 SwapNPNAndALPN bool
David Benjamin01fe8202014-09-24 15:21:44 -0400481
482 // AllowSessionVersionMismatch causes the server to resume sessions
483 // regardless of the version associated with the session.
484 AllowSessionVersionMismatch bool
Adam Langley38311732014-10-16 19:04:35 -0700485
486 // CorruptTicket causes a client to corrupt a session ticket before
487 // sending it in a resume handshake.
488 CorruptTicket bool
489
490 // OversizedSessionId causes the session id that is sent with a ticket
491 // resumption attempt to be too large (33 bytes).
492 OversizedSessionId bool
Adam Langley75712922014-10-10 16:23:43 -0700493
494 // RequireExtendedMasterSecret, if true, requires that the peer support
495 // the extended master secret option.
496 RequireExtendedMasterSecret bool
497
David Benjaminca6554b2014-11-08 12:31:52 -0500498 // NoExtendedMasterSecret causes the client and server to behave as if
Adam Langley75712922014-10-10 16:23:43 -0700499 // they didn't support an extended master secret.
500 NoExtendedMasterSecret bool
Adam Langley2ae77d22014-10-28 17:29:33 -0700501
502 // EmptyRenegotiationInfo causes the renegotiation extension to be
503 // empty in a renegotiation handshake.
504 EmptyRenegotiationInfo bool
505
506 // BadRenegotiationInfo causes the renegotiation extension value in a
507 // renegotiation handshake to be incorrect.
508 BadRenegotiationInfo bool
David Benjamin5e961c12014-11-07 01:48:35 -0500509
David Benjaminca6554b2014-11-08 12:31:52 -0500510 // NoRenegotiationInfo causes the client to behave as if it
511 // didn't support the renegotiation info extension.
512 NoRenegotiationInfo bool
513
David Benjamin5e961c12014-11-07 01:48:35 -0500514 // SequenceNumberIncrement, if non-zero, causes outgoing sequence
515 // numbers in DTLS to increment by that value rather by 1. This is to
516 // stress the replay bitmap window by simulating extreme packet loss and
517 // retransmit at the record layer.
518 SequenceNumberIncrement uint64
David Benjamin9114fae2014-11-08 11:41:14 -0500519
520 // RSAServerKeyExchange, if true, causes the server to send a
521 // ServerKeyExchange message in the plain RSA key exchange.
522 RSAServerKeyExchange bool
Adam Langley95c29f32014-06-20 12:00:00 -0700523}
524
525func (c *Config) serverInit() {
526 if c.SessionTicketsDisabled {
527 return
528 }
529
530 // If the key has already been set then we have nothing to do.
531 for _, b := range c.SessionTicketKey {
532 if b != 0 {
533 return
534 }
535 }
536
537 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
538 c.SessionTicketsDisabled = true
539 }
540}
541
542func (c *Config) rand() io.Reader {
543 r := c.Rand
544 if r == nil {
545 return rand.Reader
546 }
547 return r
548}
549
550func (c *Config) time() time.Time {
551 t := c.Time
552 if t == nil {
553 t = time.Now
554 }
555 return t()
556}
557
558func (c *Config) cipherSuites() []uint16 {
559 s := c.CipherSuites
560 if s == nil {
561 s = defaultCipherSuites()
562 }
563 return s
564}
565
566func (c *Config) minVersion() uint16 {
567 if c == nil || c.MinVersion == 0 {
568 return minVersion
569 }
570 return c.MinVersion
571}
572
573func (c *Config) maxVersion() uint16 {
574 if c == nil || c.MaxVersion == 0 {
575 return maxVersion
576 }
577 return c.MaxVersion
578}
579
580var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
581
582func (c *Config) curvePreferences() []CurveID {
583 if c == nil || len(c.CurvePreferences) == 0 {
584 return defaultCurvePreferences
585 }
586 return c.CurvePreferences
587}
588
589// mutualVersion returns the protocol version to use given the advertised
590// version of the peer.
591func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
592 minVersion := c.minVersion()
593 maxVersion := c.maxVersion()
594
595 if vers < minVersion {
596 return 0, false
597 }
598 if vers > maxVersion {
599 vers = maxVersion
600 }
601 return vers, true
602}
603
604// getCertificateForName returns the best certificate for the given name,
605// defaulting to the first element of c.Certificates if there are no good
606// options.
607func (c *Config) getCertificateForName(name string) *Certificate {
608 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
609 // There's only one choice, so no point doing any work.
610 return &c.Certificates[0]
611 }
612
613 name = strings.ToLower(name)
614 for len(name) > 0 && name[len(name)-1] == '.' {
615 name = name[:len(name)-1]
616 }
617
618 if cert, ok := c.NameToCertificate[name]; ok {
619 return cert
620 }
621
622 // try replacing labels in the name with wildcards until we get a
623 // match.
624 labels := strings.Split(name, ".")
625 for i := range labels {
626 labels[i] = "*"
627 candidate := strings.Join(labels, ".")
628 if cert, ok := c.NameToCertificate[candidate]; ok {
629 return cert
630 }
631 }
632
633 // If nothing matches, return the first certificate.
634 return &c.Certificates[0]
635}
636
637// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
638// from the CommonName and SubjectAlternateName fields of each of the leaf
639// certificates.
640func (c *Config) BuildNameToCertificate() {
641 c.NameToCertificate = make(map[string]*Certificate)
642 for i := range c.Certificates {
643 cert := &c.Certificates[i]
644 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
645 if err != nil {
646 continue
647 }
648 if len(x509Cert.Subject.CommonName) > 0 {
649 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
650 }
651 for _, san := range x509Cert.DNSNames {
652 c.NameToCertificate[san] = cert
653 }
654 }
655}
656
657// A Certificate is a chain of one or more certificates, leaf first.
658type Certificate struct {
659 Certificate [][]byte
660 PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
661 // OCSPStaple contains an optional OCSP response which will be served
662 // to clients that request it.
663 OCSPStaple []byte
664 // Leaf is the parsed form of the leaf certificate, which may be
665 // initialized using x509.ParseCertificate to reduce per-handshake
666 // processing for TLS clients doing client authentication. If nil, the
667 // leaf certificate will be parsed as needed.
668 Leaf *x509.Certificate
669}
670
671// A TLS record.
672type record struct {
673 contentType recordType
674 major, minor uint8
675 payload []byte
676}
677
678type handshakeMessage interface {
679 marshal() []byte
680 unmarshal([]byte) bool
681}
682
683// lruSessionCache is a ClientSessionCache implementation that uses an LRU
684// caching strategy.
685type lruSessionCache struct {
686 sync.Mutex
687
688 m map[string]*list.Element
689 q *list.List
690 capacity int
691}
692
693type lruSessionCacheEntry struct {
694 sessionKey string
695 state *ClientSessionState
696}
697
698// NewLRUClientSessionCache returns a ClientSessionCache with the given
699// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
700// is used instead.
701func NewLRUClientSessionCache(capacity int) ClientSessionCache {
702 const defaultSessionCacheCapacity = 64
703
704 if capacity < 1 {
705 capacity = defaultSessionCacheCapacity
706 }
707 return &lruSessionCache{
708 m: make(map[string]*list.Element),
709 q: list.New(),
710 capacity: capacity,
711 }
712}
713
714// Put adds the provided (sessionKey, cs) pair to the cache.
715func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
716 c.Lock()
717 defer c.Unlock()
718
719 if elem, ok := c.m[sessionKey]; ok {
720 entry := elem.Value.(*lruSessionCacheEntry)
721 entry.state = cs
722 c.q.MoveToFront(elem)
723 return
724 }
725
726 if c.q.Len() < c.capacity {
727 entry := &lruSessionCacheEntry{sessionKey, cs}
728 c.m[sessionKey] = c.q.PushFront(entry)
729 return
730 }
731
732 elem := c.q.Back()
733 entry := elem.Value.(*lruSessionCacheEntry)
734 delete(c.m, entry.sessionKey)
735 entry.sessionKey = sessionKey
736 entry.state = cs
737 c.q.MoveToFront(elem)
738 c.m[sessionKey] = elem
739}
740
741// Get returns the ClientSessionState value associated with a given key. It
742// returns (nil, false) if no value is found.
743func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
744 c.Lock()
745 defer c.Unlock()
746
747 if elem, ok := c.m[sessionKey]; ok {
748 c.q.MoveToFront(elem)
749 return elem.Value.(*lruSessionCacheEntry).state, true
750 }
751 return nil, false
752}
753
754// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
755type dsaSignature struct {
756 R, S *big.Int
757}
758
759type ecdsaSignature dsaSignature
760
761var emptyConfig Config
762
763func defaultConfig() *Config {
764 return &emptyConfig
765}
766
767var (
768 once sync.Once
769 varDefaultCipherSuites []uint16
770)
771
772func defaultCipherSuites() []uint16 {
773 once.Do(initDefaultCipherSuites)
774 return varDefaultCipherSuites
775}
776
777func initDefaultCipherSuites() {
David Benjamin48cae082014-10-27 01:06:24 -0400778 for _, suite := range cipherSuites {
779 if suite.flags&suitePSK == 0 {
780 varDefaultCipherSuites = append(varDefaultCipherSuites, suite.id)
781 }
Adam Langley95c29f32014-06-20 12:00:00 -0700782 }
783}
784
785func unexpectedMessageError(wanted, got interface{}) error {
786 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
787}