blob: 9812bde5e174b64fda00665c06386e1431cf4d6e [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"
10 "crypto/rand"
11 "crypto/x509"
12 "fmt"
13 "io"
14 "math/big"
15 "strings"
16 "sync"
17 "time"
18)
19
20const (
21 VersionSSL30 = 0x0300
22 VersionTLS10 = 0x0301
23 VersionTLS11 = 0x0302
24 VersionTLS12 = 0x0303
25)
26
27const (
28 maxPlaintext = 16384 // maximum plaintext payload length
29 maxCiphertext = 16384 + 2048 // maximum ciphertext payload length
30 recordHeaderLen = 5 // record header length
31 maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB)
32
33 minVersion = VersionSSL30
34 maxVersion = VersionTLS12
35)
36
37// TLS record types.
38type recordType uint8
39
40const (
41 recordTypeChangeCipherSpec recordType = 20
42 recordTypeAlert recordType = 21
43 recordTypeHandshake recordType = 22
44 recordTypeApplicationData recordType = 23
45)
46
47// TLS handshake message types.
48const (
49 typeClientHello uint8 = 1
50 typeServerHello uint8 = 2
51 typeNewSessionTicket uint8 = 4
52 typeCertificate uint8 = 11
53 typeServerKeyExchange uint8 = 12
54 typeCertificateRequest uint8 = 13
55 typeServerHelloDone uint8 = 14
56 typeCertificateVerify uint8 = 15
57 typeClientKeyExchange uint8 = 16
58 typeFinished uint8 = 20
59 typeCertificateStatus uint8 = 22
60 typeNextProtocol uint8 = 67 // Not IANA assigned
61)
62
63// TLS compression types.
64const (
65 compressionNone uint8 = 0
66)
67
68// TLS extension numbers
69const (
70 extensionServerName uint16 = 0
71 extensionStatusRequest uint16 = 5
72 extensionSupportedCurves uint16 = 10
73 extensionSupportedPoints uint16 = 11
74 extensionSignatureAlgorithms uint16 = 13
75 extensionSessionTicket uint16 = 35
76 extensionNextProtoNeg uint16 = 13172 // not IANA assigned
77 extensionRenegotiationInfo uint16 = 0xff01
78)
79
80// TLS signaling cipher suite values
81const (
82 scsvRenegotiation uint16 = 0x00ff
83)
84
85// CurveID is the type of a TLS identifier for an elliptic curve. See
86// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
87type CurveID uint16
88
89const (
90 CurveP256 CurveID = 23
91 CurveP384 CurveID = 24
92 CurveP521 CurveID = 25
93)
94
95// TLS Elliptic Curve Point Formats
96// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
97const (
98 pointFormatUncompressed uint8 = 0
99)
100
101// TLS CertificateStatusType (RFC 3546)
102const (
103 statusTypeOCSP uint8 = 1
104)
105
106// Certificate types (for certificateRequestMsg)
107const (
108 certTypeRSASign = 1 // A certificate containing an RSA key
109 certTypeDSSSign = 2 // A certificate containing a DSA key
110 certTypeRSAFixedDH = 3 // A certificate containing a static DH key
111 certTypeDSSFixedDH = 4 // A certificate containing a static DH key
112
113 // See RFC4492 sections 3 and 5.5.
114 certTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA.
115 certTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA.
116 certTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA.
117
118 // Rest of these are reserved by the TLS spec
119)
120
121// Hash functions for TLS 1.2 (See RFC 5246, section A.4.1)
122const (
123 hashSHA1 uint8 = 2
124 hashSHA256 uint8 = 4
125)
126
127// Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1)
128const (
129 signatureRSA uint8 = 1
130 signatureECDSA uint8 = 3
131)
132
133// signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See
134// RFC 5246, section A.4.1.
135type signatureAndHash struct {
136 hash, signature uint8
137}
138
139// supportedSKXSignatureAlgorithms contains the signature and hash algorithms
140// that the code advertises as supported in a TLS 1.2 ClientHello.
141var supportedSKXSignatureAlgorithms = []signatureAndHash{
142 {hashSHA256, signatureRSA},
143 {hashSHA256, signatureECDSA},
144 {hashSHA1, signatureRSA},
145 {hashSHA1, signatureECDSA},
146}
147
148// supportedClientCertSignatureAlgorithms contains the signature and hash
149// algorithms that the code advertises as supported in a TLS 1.2
150// CertificateRequest.
151var supportedClientCertSignatureAlgorithms = []signatureAndHash{
152 {hashSHA256, signatureRSA},
153 {hashSHA256, signatureECDSA},
154}
155
156// ConnectionState records basic TLS details about the connection.
157type ConnectionState struct {
158 Version uint16 // TLS version used by the connection (e.g. VersionTLS12)
159 HandshakeComplete bool // TLS handshake is complete
160 DidResume bool // connection resumes a previous TLS connection
161 CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
162 NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos)
163 NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server
164 ServerName string // server name requested by client, if any (server side only)
165 PeerCertificates []*x509.Certificate // certificate chain presented by remote peer
166 VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates
167}
168
169// ClientAuthType declares the policy the server will follow for
170// TLS Client Authentication.
171type ClientAuthType int
172
173const (
174 NoClientCert ClientAuthType = iota
175 RequestClientCert
176 RequireAnyClientCert
177 VerifyClientCertIfGiven
178 RequireAndVerifyClientCert
179)
180
181// ClientSessionState contains the state needed by clients to resume TLS
182// sessions.
183type ClientSessionState struct {
184 sessionTicket []uint8 // Encrypted ticket used for session resumption with server
185 vers uint16 // SSL/TLS version negotiated for the session
186 cipherSuite uint16 // Ciphersuite negotiated for the session
187 masterSecret []byte // MasterSecret generated by client on a full handshake
188 serverCertificates []*x509.Certificate // Certificate chain presented by the server
189}
190
191// ClientSessionCache is a cache of ClientSessionState objects that can be used
192// by a client to resume a TLS session with a given server. ClientSessionCache
193// implementations should expect to be called concurrently from different
194// goroutines.
195type ClientSessionCache interface {
196 // Get searches for a ClientSessionState associated with the given key.
197 // On return, ok is true if one was found.
198 Get(sessionKey string) (session *ClientSessionState, ok bool)
199
200 // Put adds the ClientSessionState to the cache with the given key.
201 Put(sessionKey string, cs *ClientSessionState)
202}
203
204// A Config structure is used to configure a TLS client or server.
205// After one has been passed to a TLS function it must not be
206// modified. A Config may be reused; the tls package will also not
207// modify it.
208type Config struct {
209 // Rand provides the source of entropy for nonces and RSA blinding.
210 // If Rand is nil, TLS uses the cryptographic random reader in package
211 // crypto/rand.
212 // The Reader must be safe for use by multiple goroutines.
213 Rand io.Reader
214
215 // Time returns the current time as the number of seconds since the epoch.
216 // If Time is nil, TLS uses time.Now.
217 Time func() time.Time
218
219 // Certificates contains one or more certificate chains
220 // to present to the other side of the connection.
221 // Server configurations must include at least one certificate.
222 Certificates []Certificate
223
224 // NameToCertificate maps from a certificate name to an element of
225 // Certificates. Note that a certificate name can be of the form
226 // '*.example.com' and so doesn't have to be a domain name as such.
227 // See Config.BuildNameToCertificate
228 // The nil value causes the first element of Certificates to be used
229 // for all connections.
230 NameToCertificate map[string]*Certificate
231
232 // RootCAs defines the set of root certificate authorities
233 // that clients use when verifying server certificates.
234 // If RootCAs is nil, TLS uses the host's root CA set.
235 RootCAs *x509.CertPool
236
237 // NextProtos is a list of supported, application level protocols.
238 NextProtos []string
239
240 // ServerName is used to verify the hostname on the returned
241 // certificates unless InsecureSkipVerify is given. It is also included
242 // in the client's handshake to support virtual hosting.
243 ServerName string
244
245 // ClientAuth determines the server's policy for
246 // TLS Client Authentication. The default is NoClientCert.
247 ClientAuth ClientAuthType
248
249 // ClientCAs defines the set of root certificate authorities
250 // that servers use if required to verify a client certificate
251 // by the policy in ClientAuth.
252 ClientCAs *x509.CertPool
253
254 // InsecureSkipVerify controls whether a client verifies the
255 // server's certificate chain and host name.
256 // If InsecureSkipVerify is true, TLS accepts any certificate
257 // presented by the server and any host name in that certificate.
258 // In this mode, TLS is susceptible to man-in-the-middle attacks.
259 // This should be used only for testing.
260 InsecureSkipVerify bool
261
262 // CipherSuites is a list of supported cipher suites. If CipherSuites
263 // is nil, TLS uses a list of suites supported by the implementation.
264 CipherSuites []uint16
265
266 // PreferServerCipherSuites controls whether the server selects the
267 // client's most preferred ciphersuite, or the server's most preferred
268 // ciphersuite. If true then the server's preference, as expressed in
269 // the order of elements in CipherSuites, is used.
270 PreferServerCipherSuites bool
271
272 // SessionTicketsDisabled may be set to true to disable session ticket
273 // (resumption) support.
274 SessionTicketsDisabled bool
275
276 // SessionTicketKey is used by TLS servers to provide session
277 // resumption. See RFC 5077. If zero, it will be filled with
278 // random data before the first server handshake.
279 //
280 // If multiple servers are terminating connections for the same host
281 // they should all have the same SessionTicketKey. If the
282 // SessionTicketKey leaks, previously recorded and future TLS
283 // connections using that key are compromised.
284 SessionTicketKey [32]byte
285
286 // SessionCache is a cache of ClientSessionState entries for TLS session
287 // resumption.
288 ClientSessionCache ClientSessionCache
289
290 // MinVersion contains the minimum SSL/TLS version that is acceptable.
291 // If zero, then SSLv3 is taken as the minimum.
292 MinVersion uint16
293
294 // MaxVersion contains the maximum SSL/TLS version that is acceptable.
295 // If zero, then the maximum version supported by this package is used,
296 // which is currently TLS 1.2.
297 MaxVersion uint16
298
299 // CurvePreferences contains the elliptic curves that will be used in
300 // an ECDHE handshake, in preference order. If empty, the default will
301 // be used.
302 CurvePreferences []CurveID
303
304 // Bugs specifies optional misbehaviour to be used for testing other
305 // implementations.
306 Bugs ProtocolBugs
307
308 serverInitOnce sync.Once // guards calling (*Config).serverInit
309}
310
311type BadValue int
312
313const (
314 BadValueNone BadValue = iota
315 BadValueNegative
316 BadValueZero
317 BadValueLimit
318 BadValueLarge
319 NumBadValues
320)
321
322type ProtocolBugs struct {
323 // InvalidSKXSignature specifies that the signature in a
324 // ServerKeyExchange message should be invalid.
325 InvalidSKXSignature bool
326
327 // InvalidSKXCurve causes the curve ID in the ServerKeyExchange message
328 // to be wrong.
329 InvalidSKXCurve bool
330
331 // BadECDSAR controls ways in which the 'r' value of an ECDSA signature
332 // can be invalid.
333 BadECDSAR BadValue
334 BadECDSAS BadValue
335}
336
337func (c *Config) serverInit() {
338 if c.SessionTicketsDisabled {
339 return
340 }
341
342 // If the key has already been set then we have nothing to do.
343 for _, b := range c.SessionTicketKey {
344 if b != 0 {
345 return
346 }
347 }
348
349 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
350 c.SessionTicketsDisabled = true
351 }
352}
353
354func (c *Config) rand() io.Reader {
355 r := c.Rand
356 if r == nil {
357 return rand.Reader
358 }
359 return r
360}
361
362func (c *Config) time() time.Time {
363 t := c.Time
364 if t == nil {
365 t = time.Now
366 }
367 return t()
368}
369
370func (c *Config) cipherSuites() []uint16 {
371 s := c.CipherSuites
372 if s == nil {
373 s = defaultCipherSuites()
374 }
375 return s
376}
377
378func (c *Config) minVersion() uint16 {
379 if c == nil || c.MinVersion == 0 {
380 return minVersion
381 }
382 return c.MinVersion
383}
384
385func (c *Config) maxVersion() uint16 {
386 if c == nil || c.MaxVersion == 0 {
387 return maxVersion
388 }
389 return c.MaxVersion
390}
391
392var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
393
394func (c *Config) curvePreferences() []CurveID {
395 if c == nil || len(c.CurvePreferences) == 0 {
396 return defaultCurvePreferences
397 }
398 return c.CurvePreferences
399}
400
401// mutualVersion returns the protocol version to use given the advertised
402// version of the peer.
403func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
404 minVersion := c.minVersion()
405 maxVersion := c.maxVersion()
406
407 if vers < minVersion {
408 return 0, false
409 }
410 if vers > maxVersion {
411 vers = maxVersion
412 }
413 return vers, true
414}
415
416// getCertificateForName returns the best certificate for the given name,
417// defaulting to the first element of c.Certificates if there are no good
418// options.
419func (c *Config) getCertificateForName(name string) *Certificate {
420 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
421 // There's only one choice, so no point doing any work.
422 return &c.Certificates[0]
423 }
424
425 name = strings.ToLower(name)
426 for len(name) > 0 && name[len(name)-1] == '.' {
427 name = name[:len(name)-1]
428 }
429
430 if cert, ok := c.NameToCertificate[name]; ok {
431 return cert
432 }
433
434 // try replacing labels in the name with wildcards until we get a
435 // match.
436 labels := strings.Split(name, ".")
437 for i := range labels {
438 labels[i] = "*"
439 candidate := strings.Join(labels, ".")
440 if cert, ok := c.NameToCertificate[candidate]; ok {
441 return cert
442 }
443 }
444
445 // If nothing matches, return the first certificate.
446 return &c.Certificates[0]
447}
448
449// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
450// from the CommonName and SubjectAlternateName fields of each of the leaf
451// certificates.
452func (c *Config) BuildNameToCertificate() {
453 c.NameToCertificate = make(map[string]*Certificate)
454 for i := range c.Certificates {
455 cert := &c.Certificates[i]
456 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
457 if err != nil {
458 continue
459 }
460 if len(x509Cert.Subject.CommonName) > 0 {
461 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
462 }
463 for _, san := range x509Cert.DNSNames {
464 c.NameToCertificate[san] = cert
465 }
466 }
467}
468
469// A Certificate is a chain of one or more certificates, leaf first.
470type Certificate struct {
471 Certificate [][]byte
472 PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
473 // OCSPStaple contains an optional OCSP response which will be served
474 // to clients that request it.
475 OCSPStaple []byte
476 // Leaf is the parsed form of the leaf certificate, which may be
477 // initialized using x509.ParseCertificate to reduce per-handshake
478 // processing for TLS clients doing client authentication. If nil, the
479 // leaf certificate will be parsed as needed.
480 Leaf *x509.Certificate
481}
482
483// A TLS record.
484type record struct {
485 contentType recordType
486 major, minor uint8
487 payload []byte
488}
489
490type handshakeMessage interface {
491 marshal() []byte
492 unmarshal([]byte) bool
493}
494
495// lruSessionCache is a ClientSessionCache implementation that uses an LRU
496// caching strategy.
497type lruSessionCache struct {
498 sync.Mutex
499
500 m map[string]*list.Element
501 q *list.List
502 capacity int
503}
504
505type lruSessionCacheEntry struct {
506 sessionKey string
507 state *ClientSessionState
508}
509
510// NewLRUClientSessionCache returns a ClientSessionCache with the given
511// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
512// is used instead.
513func NewLRUClientSessionCache(capacity int) ClientSessionCache {
514 const defaultSessionCacheCapacity = 64
515
516 if capacity < 1 {
517 capacity = defaultSessionCacheCapacity
518 }
519 return &lruSessionCache{
520 m: make(map[string]*list.Element),
521 q: list.New(),
522 capacity: capacity,
523 }
524}
525
526// Put adds the provided (sessionKey, cs) pair to the cache.
527func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
528 c.Lock()
529 defer c.Unlock()
530
531 if elem, ok := c.m[sessionKey]; ok {
532 entry := elem.Value.(*lruSessionCacheEntry)
533 entry.state = cs
534 c.q.MoveToFront(elem)
535 return
536 }
537
538 if c.q.Len() < c.capacity {
539 entry := &lruSessionCacheEntry{sessionKey, cs}
540 c.m[sessionKey] = c.q.PushFront(entry)
541 return
542 }
543
544 elem := c.q.Back()
545 entry := elem.Value.(*lruSessionCacheEntry)
546 delete(c.m, entry.sessionKey)
547 entry.sessionKey = sessionKey
548 entry.state = cs
549 c.q.MoveToFront(elem)
550 c.m[sessionKey] = elem
551}
552
553// Get returns the ClientSessionState value associated with a given key. It
554// returns (nil, false) if no value is found.
555func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
556 c.Lock()
557 defer c.Unlock()
558
559 if elem, ok := c.m[sessionKey]; ok {
560 c.q.MoveToFront(elem)
561 return elem.Value.(*lruSessionCacheEntry).state, true
562 }
563 return nil, false
564}
565
566// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
567type dsaSignature struct {
568 R, S *big.Int
569}
570
571type ecdsaSignature dsaSignature
572
573var emptyConfig Config
574
575func defaultConfig() *Config {
576 return &emptyConfig
577}
578
579var (
580 once sync.Once
581 varDefaultCipherSuites []uint16
582)
583
584func defaultCipherSuites() []uint16 {
585 once.Do(initDefaultCipherSuites)
586 return varDefaultCipherSuites
587}
588
589func initDefaultCipherSuites() {
590 varDefaultCipherSuites = make([]uint16, len(cipherSuites))
591 for i, suite := range cipherSuites {
592 varDefaultCipherSuites[i] = suite.id
593 }
594}
595
596func unexpectedMessageError(wanted, got interface{}) error {
597 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
598}