OSDN Git Service

libgo: Update to weekly.2011-12-22.
[pf3gnuchains/gcc-fork.git] / libgo / go / crypto / tls / common.go
1 // 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
5 package tls
6
7 import (
8         "crypto"
9         "crypto/rand"
10         "crypto/x509"
11         "io"
12         "strings"
13         "sync"
14         "time"
15 )
16
17 const (
18         maxPlaintext    = 16384        // maximum plaintext payload length
19         maxCiphertext   = 16384 + 2048 // maximum ciphertext payload length
20         recordHeaderLen = 5            // record header length
21         maxHandshake    = 65536        // maximum handshake we support (protocol max is 16 MB)
22
23         versionSSL30 = 0x0300
24         versionTLS10 = 0x0301
25
26         minVersion = versionSSL30
27         maxVersion = versionTLS10
28 )
29
30 // TLS record types.
31 type recordType uint8
32
33 const (
34         recordTypeChangeCipherSpec recordType = 20
35         recordTypeAlert            recordType = 21
36         recordTypeHandshake        recordType = 22
37         recordTypeApplicationData  recordType = 23
38 )
39
40 // TLS handshake message types.
41 const (
42         typeClientHello        uint8 = 1
43         typeServerHello        uint8 = 2
44         typeCertificate        uint8 = 11
45         typeServerKeyExchange  uint8 = 12
46         typeCertificateRequest uint8 = 13
47         typeServerHelloDone    uint8 = 14
48         typeCertificateVerify  uint8 = 15
49         typeClientKeyExchange  uint8 = 16
50         typeFinished           uint8 = 20
51         typeCertificateStatus  uint8 = 22
52         typeNextProtocol       uint8 = 67 // Not IANA assigned
53 )
54
55 // TLS compression types.
56 const (
57         compressionNone uint8 = 0
58 )
59
60 // TLS extension numbers
61 var (
62         extensionServerName      uint16 = 0
63         extensionStatusRequest   uint16 = 5
64         extensionSupportedCurves uint16 = 10
65         extensionSupportedPoints uint16 = 11
66         extensionNextProtoNeg    uint16 = 13172 // not IANA assigned
67 )
68
69 // TLS Elliptic Curves
70 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
71 var (
72         curveP256 uint16 = 23
73         curveP384 uint16 = 24
74         curveP521 uint16 = 25
75 )
76
77 // TLS Elliptic Curve Point Formats
78 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9
79 var (
80         pointFormatUncompressed uint8 = 0
81 )
82
83 // TLS CertificateStatusType (RFC 3546)
84 const (
85         statusTypeOCSP uint8 = 1
86 )
87
88 // Certificate types (for certificateRequestMsg)
89 const (
90         certTypeRSASign    = 1 // A certificate containing an RSA key
91         certTypeDSSSign    = 2 // A certificate containing a DSA key
92         certTypeRSAFixedDH = 3 // A certificate containing a static DH key
93         certTypeDSSFixedDH = 4 // A certificate containing a static DH key
94         // Rest of these are reserved by the TLS spec
95 )
96
97 // ConnectionState records basic TLS details about the connection.
98 type ConnectionState struct {
99         HandshakeComplete          bool
100         CipherSuite                uint16
101         NegotiatedProtocol         string
102         NegotiatedProtocolIsMutual bool
103
104         // ServerName contains the server name indicated by the client, if any.
105         // (Only valid for server connections.)
106         ServerName string
107
108         // the certificate chain that was presented by the other side
109         PeerCertificates []*x509.Certificate
110         // the verified certificate chains built from PeerCertificates.
111         VerifiedChains [][]*x509.Certificate
112 }
113
114 // A Config structure is used to configure a TLS client or server. After one
115 // has been passed to a TLS function it must not be modified.
116 type Config struct {
117         // Rand provides the source of entropy for nonces and RSA blinding.
118         // If Rand is nil, TLS uses the cryptographic random reader in package
119         // crypto/rand.
120         Rand io.Reader
121
122         // Time returns the current time as the number of seconds since the epoch.
123         // If Time is nil, TLS uses the system time.Seconds.
124         Time func() time.Time
125
126         // Certificates contains one or more certificate chains
127         // to present to the other side of the connection.
128         // Server configurations must include at least one certificate.
129         Certificates []Certificate
130
131         // NameToCertificate maps from a certificate name to an element of
132         // Certificates. Note that a certificate name can be of the form
133         // '*.example.com' and so doesn't have to be a domain name as such.
134         // See Config.BuildNameToCertificate
135         // The nil value causes the first element of Certificates to be used
136         // for all connections.
137         NameToCertificate map[string]*Certificate
138
139         // RootCAs defines the set of root certificate authorities
140         // that clients use when verifying server certificates.
141         // If RootCAs is nil, TLS uses the host's root CA set.
142         RootCAs *x509.CertPool
143
144         // NextProtos is a list of supported, application level protocols.
145         NextProtos []string
146
147         // ServerName is included in the client's handshake to support virtual
148         // hosting.
149         ServerName string
150
151         // AuthenticateClient controls whether a server will request a certificate
152         // from the client. It does not require that the client send a
153         // certificate nor does it require that the certificate sent be
154         // anything more than self-signed.
155         AuthenticateClient bool
156
157         // InsecureSkipVerify controls whether a client verifies the
158         // server's certificate chain and host name.
159         // If InsecureSkipVerify is true, TLS accepts any certificate
160         // presented by the server and any host name in that certificate.
161         // In this mode, TLS is susceptible to man-in-the-middle attacks.
162         // This should be used only for testing.
163         InsecureSkipVerify bool
164
165         // CipherSuites is a list of supported cipher suites. If CipherSuites
166         // is nil, TLS uses a list of suites supported by the implementation.
167         CipherSuites []uint16
168 }
169
170 func (c *Config) rand() io.Reader {
171         r := c.Rand
172         if r == nil {
173                 return rand.Reader
174         }
175         return r
176 }
177
178 func (c *Config) time() time.Time {
179         t := c.Time
180         if t == nil {
181                 t = time.Now
182         }
183         return t()
184 }
185
186 func (c *Config) rootCAs() *x509.CertPool {
187         s := c.RootCAs
188         if s == nil {
189                 s = defaultRoots()
190         }
191         return s
192 }
193
194 func (c *Config) cipherSuites() []uint16 {
195         s := c.CipherSuites
196         if s == nil {
197                 s = defaultCipherSuites()
198         }
199         return s
200 }
201
202 // getCertificateForName returns the best certificate for the given name,
203 // defaulting to the first element of c.Certificates if there are no good
204 // options.
205 func (c *Config) getCertificateForName(name string) *Certificate {
206         if len(c.Certificates) == 1 || c.NameToCertificate == nil {
207                 // There's only one choice, so no point doing any work.
208                 return &c.Certificates[0]
209         }
210
211         name = strings.ToLower(name)
212         for len(name) > 0 && name[len(name)-1] == '.' {
213                 name = name[:len(name)-1]
214         }
215
216         if cert, ok := c.NameToCertificate[name]; ok {
217                 return cert
218         }
219
220         // try replacing labels in the name with wildcards until we get a
221         // match.
222         labels := strings.Split(name, ".")
223         for i := range labels {
224                 labels[i] = "*"
225                 candidate := strings.Join(labels, ".")
226                 if cert, ok := c.NameToCertificate[candidate]; ok {
227                         return cert
228                 }
229         }
230
231         // If nothing matches, return the first certificate.
232         return &c.Certificates[0]
233 }
234
235 // BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
236 // from the CommonName and SubjectAlternateName fields of each of the leaf
237 // certificates.
238 func (c *Config) BuildNameToCertificate() {
239         c.NameToCertificate = make(map[string]*Certificate)
240         for i := range c.Certificates {
241                 cert := &c.Certificates[i]
242                 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
243                 if err != nil {
244                         continue
245                 }
246                 if len(x509Cert.Subject.CommonName) > 0 {
247                         c.NameToCertificate[x509Cert.Subject.CommonName] = cert
248                 }
249                 for _, san := range x509Cert.DNSNames {
250                         c.NameToCertificate[san] = cert
251                 }
252         }
253 }
254
255 // A Certificate is a chain of one or more certificates, leaf first.
256 type Certificate struct {
257         Certificate [][]byte
258         PrivateKey  crypto.PrivateKey // supported types: *rsa.PrivateKey
259         // OCSPStaple contains an optional OCSP response which will be served
260         // to clients that request it.
261         OCSPStaple []byte
262 }
263
264 // A TLS record.
265 type record struct {
266         contentType  recordType
267         major, minor uint8
268         payload      []byte
269 }
270
271 type handshakeMessage interface {
272         marshal() []byte
273         unmarshal([]byte) bool
274 }
275
276 // mutualVersion returns the protocol version to use given the advertised
277 // version of the peer.
278 func mutualVersion(vers uint16) (uint16, bool) {
279         if vers < minVersion {
280                 return 0, false
281         }
282         if vers > maxVersion {
283                 vers = maxVersion
284         }
285         return vers, true
286 }
287
288 var emptyConfig Config
289
290 func defaultConfig() *Config {
291         return &emptyConfig
292 }
293
294 var once sync.Once
295
296 func defaultRoots() *x509.CertPool {
297         once.Do(initDefaults)
298         return varDefaultRoots
299 }
300
301 func defaultCipherSuites() []uint16 {
302         once.Do(initDefaults)
303         return varDefaultCipherSuites
304 }
305
306 func initDefaults() {
307         initDefaultRoots()
308         initDefaultCipherSuites()
309 }
310
311 var (
312         varDefaultRoots        *x509.CertPool
313         varDefaultCipherSuites []uint16
314 )
315
316 func initDefaultCipherSuites() {
317         varDefaultCipherSuites = make([]uint16, len(cipherSuites))
318         for i, suite := range cipherSuites {
319                 varDefaultCipherSuites[i] = suite.id
320         }
321 }