1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package tls
20
21
22
23
24
25
26 import (
27 "context"
28 "crypto"
29 "crypto/ecdsa"
30 "crypto/ed25519"
31 "crypto/rsa"
32 "crypto/x509"
33 "encoding/pem"
34 "errors"
35 "fmt"
36 "internal/godebug"
37 "net"
38 "os"
39 "strings"
40 )
41
42
43
44
45
46 func Server(conn net.Conn, config *Config) *Conn {
47 c := &Conn{
48 conn: conn,
49 config: config,
50 }
51 c.handshakeFn = c.serverHandshake
52 return c
53 }
54
55
56
57
58
59 func Client(conn net.Conn, config *Config) *Conn {
60 c := &Conn{
61 conn: conn,
62 config: config,
63 isClient: true,
64 }
65 c.handshakeFn = c.clientHandshake
66 return c
67 }
68
69
70 type listener struct {
71 net.Listener
72 config *Config
73 }
74
75
76
77 func (l *listener) Accept() (net.Conn, error) {
78 c, err := l.Listener.Accept()
79 if err != nil {
80 return nil, err
81 }
82 return Server(c, l.config), nil
83 }
84
85
86
87
88
89 func NewListener(inner net.Listener, config *Config) net.Listener {
90 l := new(listener)
91 l.Listener = inner
92 l.config = config
93 return l
94 }
95
96
97
98
99
100 func Listen(network, laddr string, config *Config) (net.Listener, error) {
101
102 if config == nil || len(config.Certificates) == 0 &&
103 config.GetCertificate == nil && config.GetConfigForClient == nil {
104 return nil, errors.New("tls: neither Certificates, GetCertificate, nor GetConfigForClient set in Config")
105 }
106 l, err := net.Listen(network, laddr)
107 if err != nil {
108 return nil, err
109 }
110 return NewListener(l, config), nil
111 }
112
113 type timeoutError struct{}
114
115 func (timeoutError) Error() string { return "tls: DialWithDialer timed out" }
116 func (timeoutError) Timeout() bool { return true }
117 func (timeoutError) Temporary() bool { return true }
118
119
120
121
122
123
124
125
126
127
128
129 func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error) {
130 return dial(context.Background(), dialer, network, addr, config)
131 }
132
133 func dial(ctx context.Context, netDialer *net.Dialer, network, addr string, config *Config) (*Conn, error) {
134 if netDialer.Timeout != 0 {
135 var cancel context.CancelFunc
136 ctx, cancel = context.WithTimeout(ctx, netDialer.Timeout)
137 defer cancel()
138 }
139
140 if !netDialer.Deadline.IsZero() {
141 var cancel context.CancelFunc
142 ctx, cancel = context.WithDeadline(ctx, netDialer.Deadline)
143 defer cancel()
144 }
145
146 rawConn, err := netDialer.DialContext(ctx, network, addr)
147 if err != nil {
148 return nil, err
149 }
150
151 colonPos := strings.LastIndex(addr, ":")
152 if colonPos == -1 {
153 colonPos = len(addr)
154 }
155 hostname := addr[:colonPos]
156
157 if config == nil {
158 config = defaultConfig()
159 }
160
161
162 if config.ServerName == "" {
163
164 c := config.Clone()
165 c.ServerName = hostname
166 config = c
167 }
168
169 conn := Client(rawConn, config)
170 if err := conn.HandshakeContext(ctx); err != nil {
171 rawConn.Close()
172 return nil, err
173 }
174 return conn, nil
175 }
176
177
178
179
180
181
182
183 func Dial(network, addr string, config *Config) (*Conn, error) {
184 return DialWithDialer(new(net.Dialer), network, addr, config)
185 }
186
187
188
189 type Dialer struct {
190
191
192
193 NetDialer *net.Dialer
194
195
196
197
198
199 Config *Config
200 }
201
202
203
204
205
206
207
208
209 func (d *Dialer) Dial(network, addr string) (net.Conn, error) {
210 return d.DialContext(context.Background(), network, addr)
211 }
212
213 func (d *Dialer) netDialer() *net.Dialer {
214 if d.NetDialer != nil {
215 return d.NetDialer
216 }
217 return new(net.Dialer)
218 }
219
220
221
222
223
224
225
226
227
228
229 func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
230 c, err := dial(ctx, d.netDialer(), network, addr, d.Config)
231 if err != nil {
232
233 return nil, err
234 }
235 return c, nil
236 }
237
238
239
240
241
242
243
244
245
246 func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) {
247 certPEMBlock, err := os.ReadFile(certFile)
248 if err != nil {
249 return Certificate{}, err
250 }
251 keyPEMBlock, err := os.ReadFile(keyFile)
252 if err != nil {
253 return Certificate{}, err
254 }
255 return X509KeyPair(certPEMBlock, keyPEMBlock)
256 }
257
258 var x509keypairleaf = godebug.New("x509keypairleaf")
259
260
261
262
263
264
265
266 func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error) {
267 fail := func(err error) (Certificate, error) { return Certificate{}, err }
268
269 var cert Certificate
270 var skippedBlockTypes []string
271 for {
272 var certDERBlock *pem.Block
273 certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
274 if certDERBlock == nil {
275 break
276 }
277 if certDERBlock.Type == "CERTIFICATE" {
278 cert.Certificate = append(cert.Certificate, certDERBlock.Bytes)
279 } else {
280 skippedBlockTypes = append(skippedBlockTypes, certDERBlock.Type)
281 }
282 }
283
284 if len(cert.Certificate) == 0 {
285 if len(skippedBlockTypes) == 0 {
286 return fail(errors.New("tls: failed to find any PEM data in certificate input"))
287 }
288 if len(skippedBlockTypes) == 1 && strings.HasSuffix(skippedBlockTypes[0], "PRIVATE KEY") {
289 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"))
290 }
291 return fail(fmt.Errorf("tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v", skippedBlockTypes))
292 }
293
294 skippedBlockTypes = skippedBlockTypes[:0]
295 var keyDERBlock *pem.Block
296 for {
297 keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)
298 if keyDERBlock == nil {
299 if len(skippedBlockTypes) == 0 {
300 return fail(errors.New("tls: failed to find any PEM data in key input"))
301 }
302 if len(skippedBlockTypes) == 1 && skippedBlockTypes[0] == "CERTIFICATE" {
303 return fail(errors.New("tls: found a certificate rather than a key in the PEM for the private key"))
304 }
305 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))
306 }
307 if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
308 break
309 }
310 skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type)
311 }
312
313
314
315 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
316 if err != nil {
317 return fail(err)
318 }
319
320 if x509keypairleaf.Value() != "0" {
321 cert.Leaf = x509Cert
322 } else {
323 x509keypairleaf.IncNonDefault()
324 }
325
326 cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes)
327 if err != nil {
328 return fail(err)
329 }
330
331 switch pub := x509Cert.PublicKey.(type) {
332 case *rsa.PublicKey:
333 priv, ok := cert.PrivateKey.(*rsa.PrivateKey)
334 if !ok {
335 return fail(errors.New("tls: private key type does not match public key type"))
336 }
337 if !priv.PublicKey.Equal(pub) {
338 return fail(errors.New("tls: private key does not match public key"))
339 }
340 case *ecdsa.PublicKey:
341 priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey)
342 if !ok {
343 return fail(errors.New("tls: private key type does not match public key type"))
344 }
345 if !priv.PublicKey.Equal(pub) {
346 return fail(errors.New("tls: private key does not match public key"))
347 }
348 case ed25519.PublicKey:
349 priv, ok := cert.PrivateKey.(ed25519.PrivateKey)
350 if !ok {
351 return fail(errors.New("tls: private key type does not match public key type"))
352 }
353 if !priv.Public().(ed25519.PublicKey).Equal(pub) {
354 return fail(errors.New("tls: private key does not match public key"))
355 }
356 default:
357 return fail(errors.New("tls: unknown public key algorithm"))
358 }
359
360 return cert, nil
361 }
362
363
364
365
366 func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
367 if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
368 return key, nil
369 }
370 if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
371 switch key := key.(type) {
372 case *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey:
373 return key, nil
374 default:
375 return nil, errors.New("tls: found unknown private key type in PKCS#8 wrapping")
376 }
377 }
378 if key, err := x509.ParseECPrivateKey(der); err == nil {
379 return key, nil
380 }
381
382 return nil, errors.New("tls: failed to parse private key")
383 }
384
View as plain text