OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [libgo/] [go/] [crypto/] [tls/] [common.go] - Blame information for rev 747

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 747 jeremybenn
// 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
// ClientAuthType declares the policy the server will follow for
115
// TLS Client Authentication.
116
type ClientAuthType int
117
 
118
const (
119
        NoClientCert ClientAuthType = iota
120
        RequestClientCert
121
        RequireAnyClientCert
122
        VerifyClientCertIfGiven
123
        RequireAndVerifyClientCert
124
)
125
 
126
// A Config structure is used to configure a TLS client or server. After one
127
// has been passed to a TLS function it must not be modified.
128
type Config struct {
129
        // Rand provides the source of entropy for nonces and RSA blinding.
130
        // If Rand is nil, TLS uses the cryptographic random reader in package
131
        // crypto/rand.
132
        Rand io.Reader
133
 
134
        // Time returns the current time as the number of seconds since the epoch.
135
        // If Time is nil, TLS uses time.Now.
136
        Time func() time.Time
137
 
138
        // Certificates contains one or more certificate chains
139
        // to present to the other side of the connection.
140
        // Server configurations must include at least one certificate.
141
        Certificates []Certificate
142
 
143
        // NameToCertificate maps from a certificate name to an element of
144
        // Certificates. Note that a certificate name can be of the form
145
        // '*.example.com' and so doesn't have to be a domain name as such.
146
        // See Config.BuildNameToCertificate
147
        // The nil value causes the first element of Certificates to be used
148
        // for all connections.
149
        NameToCertificate map[string]*Certificate
150
 
151
        // RootCAs defines the set of root certificate authorities
152
        // that clients use when verifying server certificates.
153
        // If RootCAs is nil, TLS uses the host's root CA set.
154
        RootCAs *x509.CertPool
155
 
156
        // NextProtos is a list of supported, application level protocols.
157
        NextProtos []string
158
 
159
        // ServerName is included in the client's handshake to support virtual
160
        // hosting.
161
        ServerName string
162
 
163
        // ClientAuth determines the server's policy for
164
        // TLS Client Authentication. The default is NoClientCert.
165
        ClientAuth ClientAuthType
166
 
167
        // ClientCAs defines the set of root certificate authorities
168
        // that servers use if required to verify a client certificate
169
        // by the policy in ClientAuth.
170
        ClientCAs *x509.CertPool
171
 
172
        // InsecureSkipVerify controls whether a client verifies the
173
        // server's certificate chain and host name.
174
        // If InsecureSkipVerify is true, TLS accepts any certificate
175
        // presented by the server and any host name in that certificate.
176
        // In this mode, TLS is susceptible to man-in-the-middle attacks.
177
        // This should be used only for testing.
178
        InsecureSkipVerify bool
179
 
180
        // CipherSuites is a list of supported cipher suites. If CipherSuites
181
        // is nil, TLS uses a list of suites supported by the implementation.
182
        CipherSuites []uint16
183
}
184
 
185
func (c *Config) rand() io.Reader {
186
        r := c.Rand
187
        if r == nil {
188
                return rand.Reader
189
        }
190
        return r
191
}
192
 
193
func (c *Config) time() time.Time {
194
        t := c.Time
195
        if t == nil {
196
                t = time.Now
197
        }
198
        return t()
199
}
200
 
201
func (c *Config) rootCAs() *x509.CertPool {
202
        s := c.RootCAs
203
        if s == nil {
204
                s = defaultRoots()
205
        }
206
        return s
207
}
208
 
209
func (c *Config) cipherSuites() []uint16 {
210
        s := c.CipherSuites
211
        if s == nil {
212
                s = defaultCipherSuites()
213
        }
214
        return s
215
}
216
 
217
// getCertificateForName returns the best certificate for the given name,
218
// defaulting to the first element of c.Certificates if there are no good
219
// options.
220
func (c *Config) getCertificateForName(name string) *Certificate {
221
        if len(c.Certificates) == 1 || c.NameToCertificate == nil {
222
                // There's only one choice, so no point doing any work.
223
                return &c.Certificates[0]
224
        }
225
 
226
        name = strings.ToLower(name)
227
        for len(name) > 0 && name[len(name)-1] == '.' {
228
                name = name[:len(name)-1]
229
        }
230
 
231
        if cert, ok := c.NameToCertificate[name]; ok {
232
                return cert
233
        }
234
 
235
        // try replacing labels in the name with wildcards until we get a
236
        // match.
237
        labels := strings.Split(name, ".")
238
        for i := range labels {
239
                labels[i] = "*"
240
                candidate := strings.Join(labels, ".")
241
                if cert, ok := c.NameToCertificate[candidate]; ok {
242
                        return cert
243
                }
244
        }
245
 
246
        // If nothing matches, return the first certificate.
247
        return &c.Certificates[0]
248
}
249
 
250
// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate
251
// from the CommonName and SubjectAlternateName fields of each of the leaf
252
// certificates.
253
func (c *Config) BuildNameToCertificate() {
254
        c.NameToCertificate = make(map[string]*Certificate)
255
        for i := range c.Certificates {
256
                cert := &c.Certificates[i]
257
                x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
258
                if err != nil {
259
                        continue
260
                }
261
                if len(x509Cert.Subject.CommonName) > 0 {
262
                        c.NameToCertificate[x509Cert.Subject.CommonName] = cert
263
                }
264
                for _, san := range x509Cert.DNSNames {
265
                        c.NameToCertificate[san] = cert
266
                }
267
        }
268
}
269
 
270
// A Certificate is a chain of one or more certificates, leaf first.
271
type Certificate struct {
272
        Certificate [][]byte
273
        PrivateKey  crypto.PrivateKey // supported types: *rsa.PrivateKey
274
        // OCSPStaple contains an optional OCSP response which will be served
275
        // to clients that request it.
276
        OCSPStaple []byte
277
        // Leaf is the parsed form of the leaf certificate, which may be
278
        // initialized using x509.ParseCertificate to reduce per-handshake
279
        // processing for TLS clients doing client authentication. If nil, the
280
        // leaf certificate will be parsed as needed.
281
        Leaf *x509.Certificate
282
}
283
 
284
// A TLS record.
285
type record struct {
286
        contentType  recordType
287
        major, minor uint8
288
        payload      []byte
289
}
290
 
291
type handshakeMessage interface {
292
        marshal() []byte
293
        unmarshal([]byte) bool
294
}
295
 
296
// mutualVersion returns the protocol version to use given the advertised
297
// version of the peer.
298
func mutualVersion(vers uint16) (uint16, bool) {
299
        if vers < minVersion {
300
                return 0, false
301
        }
302
        if vers > maxVersion {
303
                vers = maxVersion
304
        }
305
        return vers, true
306
}
307
 
308
var emptyConfig Config
309
 
310
func defaultConfig() *Config {
311
        return &emptyConfig
312
}
313
 
314
var once sync.Once
315
 
316
func defaultRoots() *x509.CertPool {
317
        once.Do(initDefaults)
318
        return varDefaultRoots
319
}
320
 
321
func defaultCipherSuites() []uint16 {
322
        once.Do(initDefaults)
323
        return varDefaultCipherSuites
324
}
325
 
326
func initDefaults() {
327
        initDefaultRoots()
328
        initDefaultCipherSuites()
329
}
330
 
331
var (
332
        varDefaultRoots        *x509.CertPool
333
        varDefaultCipherSuites []uint16
334
)
335
 
336
func initDefaultCipherSuites() {
337
        varDefaultCipherSuites = make([]uint16, len(cipherSuites))
338
        for i, suite := range cipherSuites {
339
                varDefaultCipherSuites[i] = suite.id
340
        }
341
}

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.