1
2
3
4
5
6 package tls
7
8
9
10
11
12
13 import (
14 "crypto"
15 "crypto/ecdsa"
16 "crypto/rsa"
17 "crypto/x509"
18 "encoding/pem"
19 "errors"
20 "fmt"
21 "io/ioutil"
22 "net"
23 "strings"
24 "time"
25 )
26
27
28
29
30
31 func Server(conn net.Conn, config *Config) *Conn {
32 return &Conn{conn: conn, config: config}
33 }
34
35
36
37
38
39 func Client(conn net.Conn, config *Config) *Conn {
40 return &Conn{conn: conn, config: config, isClient: true}
41 }
42
43
44 type listener struct {
45 net.Listener
46 config *Config
47 }
48
49
50
51 func (l *listener) Accept() (net.Conn, error) {
52 c, err := l.Listener.Accept()
53 if err != nil {
54 return nil, err
55 }
56 return Server(c, l.config), nil
57 }
58
59
60
61
62
63 func NewListener(inner net.Listener, config *Config) net.Listener {
64 l := new(listener)
65 l.Listener = inner
66 l.config = config
67 return l
68 }
69
70
71
72
73
74 func Listen(network, laddr string, config *Config) (net.Listener, error) {
75 if config == nil || (len(config.Certificates) == 0 && config.GetCertificate == nil) {
76 return nil, errors.New("tls: neither Certificates nor GetCertificate set in Config")
77 }
78 l, err := net.Listen(network, laddr)
79 if err != nil {
80 return nil, err
81 }
82 return NewListener(l, config), nil
83 }
84
85 type timeoutError struct{}
86
87 func (timeoutError) Error() string { return "tls: DialWithDialer timed out" }
88 func (timeoutError) Timeout() bool { return true }
89 func (timeoutError) Temporary() bool { return true }
90
91
92
93
94
95
96
97
98 func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error) {
99
100
101
102 timeout := dialer.Timeout
103
104 if !dialer.Deadline.IsZero() {
105 deadlineTimeout := time.Until(dialer.Deadline)
106 if timeout == 0 || deadlineTimeout < timeout {
107 timeout = deadlineTimeout
108 }
109 }
110
111 var errChannel chan error
112
113 if timeout != 0 {
114 errChannel = make(chan error, 2)
115 time.AfterFunc(timeout, func() {
116 errChannel <- timeoutError{}
117 })
118 }
119
120 rawConn, err := dialer.Dial(network, addr)
121 if err != nil {
122 return nil, err
123 }
124
125 colonPos := strings.LastIndex(addr, ":")
126 if colonPos == -1 {
127 colonPos = len(addr)
128 }
129 hostname := addr[:colonPos]
130
131 if config == nil {
132 config = defaultConfig()
133 }
134
135
136 if config.ServerName == "" {
137
138 c := config.Clone()
139 c.ServerName = hostname
140 config = c
141 }
142
143 conn := Client(rawConn, config)
144
145 if timeout == 0 {
146 err = conn.Handshake()
147 } else {
148 go func() {
149 errChannel <- conn.Handshake()
150 }()
151
152 err = <-errChannel
153 }
154
155 if err != nil {
156 rawConn.Close()
157 return nil, err
158 }
159
160 return conn, nil
161 }
162
163
164
165
166
167
168
169 func Dial(network, addr string, config *Config) (*Conn, error) {
170 return DialWithDialer(new(net.Dialer), network, addr, config)
171 }
172
173
174
175
176
177
178 func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) {
179 certPEMBlock, err := ioutil.ReadFile(certFile)
180 if err != nil {
181 return Certificate{}, err
182 }
183 keyPEMBlock, err := ioutil.ReadFile(keyFile)
184 if err != nil {
185 return Certificate{}, err
186 }
187 return X509KeyPair(certPEMBlock, keyPEMBlock)
188 }
189
190
191
192
193 func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error) {
194 fail := func(err error) (Certificate, error) { return Certificate{}, err }
195
196 var cert Certificate
197 var skippedBlockTypes []string
198 for {
199 var certDERBlock *pem.Block
200 certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
201 if certDERBlock == nil {
202 break
203 }
204 if certDERBlock.Type == "CERTIFICATE" {
205 cert.Certificate = append(cert.Certificate, certDERBlock.Bytes)
206 } else {
207 skippedBlockTypes = append(skippedBlockTypes, certDERBlock.Type)
208 }
209 }
210
211 if len(cert.Certificate) == 0 {
212 if len(skippedBlockTypes) == 0 {
213 return fail(errors.New("tls: failed to find any PEM data in certificate input"))
214 }
215 if len(skippedBlockTypes) == 1 && strings.HasSuffix(skippedBlockTypes[0], "PRIVATE KEY") {
216 return fail(errors.New("tls: failed to find certificate PEM data in certificate input, but did find a private key; PEM inputs may have been switched"))
217 }
218 return fail(fmt.Errorf("tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v", skippedBlockTypes))
219 }
220
221 skippedBlockTypes = skippedBlockTypes[:0]
222 var keyDERBlock *pem.Block
223 for {
224 keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)
225 if keyDERBlock == nil {
226 if len(skippedBlockTypes) == 0 {
227 return fail(errors.New("tls: failed to find any PEM data in key input"))
228 }
229 if len(skippedBlockTypes) == 1 && skippedBlockTypes[0] == "CERTIFICATE" {
230 return fail(errors.New("tls: found a certificate rather than a key in the PEM for the private key"))
231 }
232 return fail(fmt.Errorf("tls: failed to find PEM block with type ending in \"PRIVATE KEY\" in key input after skipping PEM blocks of the following types: %v", skippedBlockTypes))
233 }
234 if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
235 break
236 }
237 skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type)
238 }
239
240 var err error
241 cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes)
242 if err != nil {
243 return fail(err)
244 }
245
246
247
248 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
249 if err != nil {
250 return fail(err)
251 }
252
253 switch pub := x509Cert.PublicKey.(type) {
254 case *rsa.PublicKey:
255 priv, ok := cert.PrivateKey.(*rsa.PrivateKey)
256 if !ok {
257 return fail(errors.New("tls: private key type does not match public key type"))
258 }
259 if pub.N.Cmp(priv.N) != 0 {
260 return fail(errors.New("tls: private key does not match public key"))
261 }
262 case *ecdsa.PublicKey:
263 priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey)
264 if !ok {
265 return fail(errors.New("tls: private key type does not match public key type"))
266 }
267 if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 {
268 return fail(errors.New("tls: private key does not match public key"))
269 }
270 default:
271 return fail(errors.New("tls: unknown public key algorithm"))
272 }
273
274 return cert, nil
275 }
276
277
278
279
280 func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
281 if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
282 return key, nil
283 }
284 if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
285 switch key := key.(type) {
286 case *rsa.PrivateKey, *ecdsa.PrivateKey:
287 return key, nil
288 default:
289 return nil, errors.New("tls: found unknown private key type in PKCS#8 wrapping")
290 }
291 }
292 if key, err := x509.ParseECPrivateKey(der); err == nil {
293 return key, nil
294 }
295
296 return nil, errors.New("tls: failed to parse private key")
297 }
298
View as plain text