blob: fd78eb650ff7366daf19ef15f2597faceb50c5e3 [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
Adam Langley80842bd2014-06-20 12:00:00 -0700335
336 // MaxPadding causes CBC records to have the maximum possible padding.
337 MaxPadding bool
338 // PaddingFirstByteBad causes the first byte of the padding to be
339 // incorrect.
340 PaddingFirstByteBad bool
341 // PaddingFirstByteBadIf255 causes the first byte of padding to be
342 // incorrect if there's a maximum amount of padding (i.e. 255 bytes).
343 PaddingFirstByteBadIf255 bool
Adam Langleyac61fa32014-06-23 12:03:11 -0700344
345 // FailIfNotFallbackSCSV causes a server handshake to fail if the
346 // client doesn't send the fallback SCSV value.
347 FailIfNotFallbackSCSV bool
Adam Langley95c29f32014-06-20 12:00:00 -0700348}
349
350func (c *Config) serverInit() {
351 if c.SessionTicketsDisabled {
352 return
353 }
354
355 // If the key has already been set then we have nothing to do.
356 for _, b := range c.SessionTicketKey {
357 if b != 0 {
358 return
359 }
360 }
361
362 if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil {
363 c.SessionTicketsDisabled = true
364 }
365}
366
367func (c *Config) rand() io.Reader {
368 r := c.Rand
369 if r == nil {
370 return rand.Reader
371 }
372 return r
373}
374
375func (c *Config) time() time.Time {
376 t := c.Time
377 if t == nil {
378 t = time.Now
379 }
380 return t()
381}
382
383func (c *Config) cipherSuites() []uint16 {
384 s := c.CipherSuites
385 if s == nil {
386 s = defaultCipherSuites()
387 }
388 return s
389}
390
391func (c *Config) minVersion() uint16 {
392 if c == nil || c.MinVersion == 0 {
393 return minVersion
394 }
395 return c.MinVersion
396}
397
398func (c *Config) maxVersion() uint16 {
399 if c == nil || c.MaxVersion == 0 {
400 return maxVersion
401 }
402 return c.MaxVersion
403}
404
405var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521}
406
407func (c *Config) curvePreferences() []CurveID {
408 if c == nil || len(c.CurvePreferences) == 0 {
409 return defaultCurvePreferences
410 }
411 return c.CurvePreferences
412}
413
414// mutualVersion returns the protocol version to use given the advertised
415// version of the peer.
416func (c *Config) mutualVersion(vers uint16) (uint16, bool) {
417 minVersion := c.minVersion()
418 maxVersion := c.maxVersion()
419
420 if vers < minVersion {
421 return 0, false
422 }
423 if vers > maxVersion {
424 vers = maxVersion
425 }
426 return vers, true
427}
428
429// getCertificateForName returns the best certificate for the given name,
430// defaulting to the first element of c.Certificates if there are no good
431// options.
432func (c *Config) getCertificateForName(name string) *Certificate {
433 if len(c.Certificates) == 1 || c.NameToCertificate == nil {
434 // There's only one choice, so no point doing any work.
435 return &c.Certificates[0]
436 }
437
438 name = strings.ToLower(name)
439 for len(name) > 0 && name[len(name)-1] == '.' {
440 name = name[:len(name)-1]
441 }
442
443 if cert, ok := c.NameToCertificate[name]; ok {
444 return cert
445 }
446
447 // try replacing labels in the name with wildcards until we get a
448 // match.
449 labels := strings.Split(name, ".")
450 for i := range labels {
451 labels[i] = "*"
452 candidate := strings.Join(labels, ".")
453 if cert, ok := c.NameToCertificate[candidate]; ok {
454 return cert
455 }
456 }
457
458 // If nothing matches, return the first certificate.
459 return &c.Certificates[0]
460}
461
462// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
463// from the CommonName and SubjectAlternateName fields of each of the leaf
464// certificates.
465func (c *Config) BuildNameToCertificate() {
466 c.NameToCertificate = make(map[string]*Certificate)
467 for i := range c.Certificates {
468 cert := &c.Certificates[i]
469 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
470 if err != nil {
471 continue
472 }
473 if len(x509Cert.Subject.CommonName) > 0 {
474 c.NameToCertificate[x509Cert.Subject.CommonName] = cert
475 }
476 for _, san := range x509Cert.DNSNames {
477 c.NameToCertificate[san] = cert
478 }
479 }
480}
481
482// A Certificate is a chain of one or more certificates, leaf first.
483type Certificate struct {
484 Certificate [][]byte
485 PrivateKey crypto.PrivateKey // supported types: *rsa.PrivateKey, *ecdsa.PrivateKey
486 // OCSPStaple contains an optional OCSP response which will be served
487 // to clients that request it.
488 OCSPStaple []byte
489 // Leaf is the parsed form of the leaf certificate, which may be
490 // initialized using x509.ParseCertificate to reduce per-handshake
491 // processing for TLS clients doing client authentication. If nil, the
492 // leaf certificate will be parsed as needed.
493 Leaf *x509.Certificate
494}
495
496// A TLS record.
497type record struct {
498 contentType recordType
499 major, minor uint8
500 payload []byte
501}
502
503type handshakeMessage interface {
504 marshal() []byte
505 unmarshal([]byte) bool
506}
507
508// lruSessionCache is a ClientSessionCache implementation that uses an LRU
509// caching strategy.
510type lruSessionCache struct {
511 sync.Mutex
512
513 m map[string]*list.Element
514 q *list.List
515 capacity int
516}
517
518type lruSessionCacheEntry struct {
519 sessionKey string
520 state *ClientSessionState
521}
522
523// NewLRUClientSessionCache returns a ClientSessionCache with the given
524// capacity that uses an LRU strategy. If capacity is < 1, a default capacity
525// is used instead.
526func NewLRUClientSessionCache(capacity int) ClientSessionCache {
527 const defaultSessionCacheCapacity = 64
528
529 if capacity < 1 {
530 capacity = defaultSessionCacheCapacity
531 }
532 return &lruSessionCache{
533 m: make(map[string]*list.Element),
534 q: list.New(),
535 capacity: capacity,
536 }
537}
538
539// Put adds the provided (sessionKey, cs) pair to the cache.
540func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) {
541 c.Lock()
542 defer c.Unlock()
543
544 if elem, ok := c.m[sessionKey]; ok {
545 entry := elem.Value.(*lruSessionCacheEntry)
546 entry.state = cs
547 c.q.MoveToFront(elem)
548 return
549 }
550
551 if c.q.Len() < c.capacity {
552 entry := &lruSessionCacheEntry{sessionKey, cs}
553 c.m[sessionKey] = c.q.PushFront(entry)
554 return
555 }
556
557 elem := c.q.Back()
558 entry := elem.Value.(*lruSessionCacheEntry)
559 delete(c.m, entry.sessionKey)
560 entry.sessionKey = sessionKey
561 entry.state = cs
562 c.q.MoveToFront(elem)
563 c.m[sessionKey] = elem
564}
565
566// Get returns the ClientSessionState value associated with a given key. It
567// returns (nil, false) if no value is found.
568func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) {
569 c.Lock()
570 defer c.Unlock()
571
572 if elem, ok := c.m[sessionKey]; ok {
573 c.q.MoveToFront(elem)
574 return elem.Value.(*lruSessionCacheEntry).state, true
575 }
576 return nil, false
577}
578
579// TODO(jsing): Make these available to both crypto/x509 and crypto/tls.
580type dsaSignature struct {
581 R, S *big.Int
582}
583
584type ecdsaSignature dsaSignature
585
586var emptyConfig Config
587
588func defaultConfig() *Config {
589 return &emptyConfig
590}
591
592var (
593 once sync.Once
594 varDefaultCipherSuites []uint16
595)
596
597func defaultCipherSuites() []uint16 {
598 once.Do(initDefaultCipherSuites)
599 return varDefaultCipherSuites
600}
601
602func initDefaultCipherSuites() {
603 varDefaultCipherSuites = make([]uint16, len(cipherSuites))
604 for i, suite := range cipherSuites {
605 varDefaultCipherSuites[i] = suite.id
606 }
607}
608
609func unexpectedMessageError(wanted, got interface{}) error {
610 return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted)
611}