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/mldsa"
32 "crypto/rsa"
33 "crypto/x509"
34 "encoding/pem"
35 "errors"
36 "fmt"
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 var _ error = timeoutError{}
116
117 func (timeoutError) Error() string { return "tls: DialWithDialer timed out" }
118 func (timeoutError) Timeout() bool { return true }
119 func (timeoutError) Temporary() bool { return true }
120
121
122
123
124
125
126
127
128
129
130
131 func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error) {
132 return dial(context.Background(), dialer, network, addr, config)
133 }
134
135 func dial(ctx context.Context, netDialer *net.Dialer, network, addr string, config *Config) (*Conn, error) {
136 if netDialer.Timeout != 0 {
137 var cancel context.CancelFunc
138 ctx, cancel = context.WithTimeout(ctx, netDialer.Timeout)
139 defer cancel()
140 }
141
142 if !netDialer.Deadline.IsZero() {
143 var cancel context.CancelFunc
144 ctx, cancel = context.WithDeadline(ctx, netDialer.Deadline)
145 defer cancel()
146 }
147
148 rawConn, err := netDialer.DialContext(ctx, network, addr)
149 if err != nil {
150 return nil, err
151 }
152
153 colonPos := strings.LastIndex(addr, ":")
154 if colonPos == -1 {
155 colonPos = len(addr)
156 }
157 hostname := addr[:colonPos]
158
159 if config == nil {
160 config = defaultConfig()
161 }
162
163
164 if config.ServerName == "" {
165
166 c := config.Clone()
167 c.ServerName = hostname
168 config = c
169 }
170
171 conn := Client(rawConn, config)
172 if err := conn.HandshakeContext(ctx); err != nil {
173 rawConn.Close()
174 return nil, err
175 }
176 return conn, nil
177 }
178
179
180
181
182
183
184
185 func Dial(network, addr string, config *Config) (*Conn, error) {
186 return DialWithDialer(new(net.Dialer), network, addr, config)
187 }
188
189
190
191 type Dialer struct {
192
193
194
195 NetDialer *net.Dialer
196
197
198
199
200
201 Config *Config
202 }
203
204
205
206
207
208
209
210
211 func (d *Dialer) Dial(network, addr string) (net.Conn, error) {
212 return d.DialContext(context.Background(), network, addr)
213 }
214
215 func (d *Dialer) netDialer() *net.Dialer {
216 if d.NetDialer != nil {
217 return d.NetDialer
218 }
219 return new(net.Dialer)
220 }
221
222
223
224
225
226
227
228
229
230
231 func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
232 c, err := dial(ctx, d.netDialer(), network, addr, d.Config)
233 if err != nil {
234
235 return nil, err
236 }
237 return c, nil
238 }
239
240
241
242
243
244 func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) {
245 certPEMBlock, err := os.ReadFile(certFile)
246 if err != nil {
247 return Certificate{}, err
248 }
249 keyPEMBlock, err := os.ReadFile(keyFile)
250 if err != nil {
251 return Certificate{}, err
252 }
253 return X509KeyPair(certPEMBlock, keyPEMBlock)
254 }
255
256
257
258 func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error) {
259 fail := func(err error) (Certificate, error) { return Certificate{}, err }
260
261 var cert Certificate
262 var skippedBlockTypes []string
263 for {
264 var certDERBlock *pem.Block
265 certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
266 if certDERBlock == nil {
267 break
268 }
269 if certDERBlock.Type == "CERTIFICATE" {
270 cert.Certificate = append(cert.Certificate, certDERBlock.Bytes)
271 } else {
272 skippedBlockTypes = append(skippedBlockTypes, certDERBlock.Type)
273 }
274 }
275
276 if len(cert.Certificate) == 0 {
277 if len(skippedBlockTypes) == 0 {
278 return fail(errors.New("tls: failed to find any PEM data in certificate input"))
279 }
280 if len(skippedBlockTypes) == 1 && strings.HasSuffix(skippedBlockTypes[0], "PRIVATE KEY") {
281 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"))
282 }
283 return fail(fmt.Errorf("tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v", skippedBlockTypes))
284 }
285
286 skippedBlockTypes = skippedBlockTypes[:0]
287 var keyDERBlock *pem.Block
288 for {
289 keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)
290 if keyDERBlock == nil {
291 if len(skippedBlockTypes) == 0 {
292 return fail(errors.New("tls: failed to find any PEM data in key input"))
293 }
294 if len(skippedBlockTypes) == 1 && skippedBlockTypes[0] == "CERTIFICATE" {
295 return fail(errors.New("tls: found a certificate rather than a key in the PEM for the private key"))
296 }
297 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))
298 }
299 if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") {
300 break
301 }
302 skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type)
303 }
304
305
306
307 x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
308 if err != nil {
309 return fail(err)
310 }
311 cert.Leaf = x509Cert
312
313 cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes)
314 if err != nil {
315 return fail(err)
316 }
317
318 switch pub := x509Cert.PublicKey.(type) {
319 case *rsa.PublicKey:
320 priv, ok := cert.PrivateKey.(*rsa.PrivateKey)
321 if !ok {
322 return fail(errors.New("tls: private key type does not match public key type"))
323 }
324 if !priv.PublicKey.Equal(pub) {
325 return fail(errors.New("tls: private key does not match public key"))
326 }
327 case *ecdsa.PublicKey:
328 priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey)
329 if !ok {
330 return fail(errors.New("tls: private key type does not match public key type"))
331 }
332 if !priv.PublicKey.Equal(pub) {
333 return fail(errors.New("tls: private key does not match public key"))
334 }
335 case ed25519.PublicKey:
336 priv, ok := cert.PrivateKey.(ed25519.PrivateKey)
337 if !ok {
338 return fail(errors.New("tls: private key type does not match public key type"))
339 }
340 if !priv.Public().(ed25519.PublicKey).Equal(pub) {
341 return fail(errors.New("tls: private key does not match public key"))
342 }
343 case *mldsa.PublicKey:
344 priv, ok := cert.PrivateKey.(*mldsa.PrivateKey)
345 if !ok {
346 return fail(errors.New("tls: private key type does not match public key type"))
347 }
348 if !priv.PublicKey().Equal(pub) {
349 return fail(errors.New("tls: private key does not match public key"))
350 }
351 default:
352 return fail(errors.New("tls: unknown public key algorithm"))
353 }
354
355 return cert, nil
356 }
357
358
359
360
361 func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
362 key, err := x509.ParsePKCS8PrivateKey(der)
363 pkcs8Err := err
364 if err != nil {
365 key, err = x509.ParsePKCS1PrivateKey(der)
366 }
367 if err != nil {
368 key, err = x509.ParseECPrivateKey(der)
369 }
370 if err != nil {
371 return nil, fmt.Errorf("tls: failed to parse private key: %w", pkcs8Err)
372 }
373 switch key := key.(type) {
374 case *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey, *mldsa.PrivateKey:
375 return key, nil
376 default:
377 return nil, errors.New("tls: found unknown private key type in PKCS#8 wrapping")
378 }
379 }
380
View as plain text