OSDN Git Service

9184e8e8118483cf97cdf0bdd84fb0c9dec01b9d
[pf3gnuchains/gcc-fork.git] / libgo / go / crypto / tls / tls.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 partially implements the TLS 1.1 protocol, as specified in RFC
6 // 4346.
7 package tls
8
9 import (
10         "crypto/rsa"
11         "crypto/x509"
12         "encoding/pem"
13         "errors"
14         "io/ioutil"
15         "net"
16         "strings"
17 )
18
19 // Server returns a new TLS server side connection
20 // using conn as the underlying transport.
21 // The configuration config must be non-nil and must have
22 // at least one certificate.
23 func Server(conn net.Conn, config *Config) *Conn {
24         return &Conn{conn: conn, config: config}
25 }
26
27 // Client returns a new TLS client side connection
28 // using conn as the underlying transport.
29 // Client interprets a nil configuration as equivalent to
30 // the zero configuration; see the documentation of Config
31 // for the defaults.
32 func Client(conn net.Conn, config *Config) *Conn {
33         return &Conn{conn: conn, config: config, isClient: true}
34 }
35
36 // A listener implements a network listener (net.Listener) for TLS connections.
37 type listener struct {
38         net.Listener
39         config *Config
40 }
41
42 // Accept waits for and returns the next incoming TLS connection.
43 // The returned connection c is a *tls.Conn.
44 func (l *listener) Accept() (c net.Conn, err error) {
45         c, err = l.Listener.Accept()
46         if err != nil {
47                 return
48         }
49         c = Server(c, l.config)
50         return
51 }
52
53 // NewListener creates a Listener which accepts connections from an inner
54 // Listener and wraps each connection with Server.
55 // The configuration config must be non-nil and must have
56 // at least one certificate.
57 func NewListener(inner net.Listener, config *Config) net.Listener {
58         l := new(listener)
59         l.Listener = inner
60         l.config = config
61         return l
62 }
63
64 // Listen creates a TLS listener accepting connections on the
65 // given network address using net.Listen.
66 // The configuration config must be non-nil and must have
67 // at least one certificate.
68 func Listen(network, laddr string, config *Config) (net.Listener, error) {
69         if config == nil || len(config.Certificates) == 0 {
70                 return nil, errors.New("tls.Listen: no certificates in configuration")
71         }
72         l, err := net.Listen(network, laddr)
73         if err != nil {
74                 return nil, err
75         }
76         return NewListener(l, config), nil
77 }
78
79 // Dial connects to the given network address using net.Dial
80 // and then initiates a TLS handshake, returning the resulting
81 // TLS connection.
82 // Dial interprets a nil configuration as equivalent to
83 // the zero configuration; see the documentation of Config
84 // for the defaults.
85 func Dial(network, addr string, config *Config) (*Conn, error) {
86         raddr := addr
87         c, err := net.Dial(network, raddr)
88         if err != nil {
89                 return nil, err
90         }
91
92         colonPos := strings.LastIndex(raddr, ":")
93         if colonPos == -1 {
94                 colonPos = len(raddr)
95         }
96         hostname := raddr[:colonPos]
97
98         if config == nil {
99                 config = defaultConfig()
100         }
101         if config.ServerName != "" {
102                 // Make a copy to avoid polluting argument or default.
103                 c := *config
104                 c.ServerName = hostname
105                 config = &c
106         }
107         conn := Client(c, config)
108         if err = conn.Handshake(); err != nil {
109                 c.Close()
110                 return nil, err
111         }
112         return conn, nil
113 }
114
115 // LoadX509KeyPair reads and parses a public/private key pair from a pair of
116 // files. The files must contain PEM encoded data.
117 func LoadX509KeyPair(certFile, keyFile string) (cert Certificate, err error) {
118         certPEMBlock, err := ioutil.ReadFile(certFile)
119         if err != nil {
120                 return
121         }
122         keyPEMBlock, err := ioutil.ReadFile(keyFile)
123         if err != nil {
124                 return
125         }
126         return X509KeyPair(certPEMBlock, keyPEMBlock)
127 }
128
129 // X509KeyPair parses a public/private key pair from a pair of
130 // PEM encoded data.
131 func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (cert Certificate, err error) {
132         var certDERBlock *pem.Block
133         for {
134                 certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
135                 if certDERBlock == nil {
136                         break
137                 }
138                 if certDERBlock.Type == "CERTIFICATE" {
139                         cert.Certificate = append(cert.Certificate, certDERBlock.Bytes)
140                 }
141         }
142
143         if len(cert.Certificate) == 0 {
144                 err = errors.New("crypto/tls: failed to parse certificate PEM data")
145                 return
146         }
147
148         keyDERBlock, _ := pem.Decode(keyPEMBlock)
149         if keyDERBlock == nil {
150                 err = errors.New("crypto/tls: failed to parse key PEM data")
151                 return
152         }
153
154         // OpenSSL 0.9.8 generates PKCS#1 private keys by default, while
155         // OpenSSL 1.0.0 generates PKCS#8 keys. We try both.
156         var key *rsa.PrivateKey
157         if key, err = x509.ParsePKCS1PrivateKey(keyDERBlock.Bytes); err != nil {
158                 var privKey interface{}
159                 if privKey, err = x509.ParsePKCS8PrivateKey(keyDERBlock.Bytes); err != nil {
160                         err = errors.New("crypto/tls: failed to parse key: " + err.Error())
161                         return
162                 }
163
164                 var ok bool
165                 if key, ok = privKey.(*rsa.PrivateKey); !ok {
166                         err = errors.New("crypto/tls: found non-RSA private key in PKCS#8 wrapping")
167                         return
168                 }
169         }
170
171         cert.PrivateKey = key
172
173         // We don't need to parse the public key for TLS, but we so do anyway
174         // to check that it looks sane and matches the private key.
175         x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
176         if err != nil {
177                 return
178         }
179
180         if x509Cert.PublicKeyAlgorithm != x509.RSA || x509Cert.PublicKey.(*rsa.PublicKey).N.Cmp(key.PublicKey.N) != 0 {
181                 err = errors.New("crypto/tls: private key does not match public key")
182                 return
183         }
184
185         return
186 }