-
Notifications
You must be signed in to change notification settings - Fork 4
/
certmanager.go
180 lines (166 loc) · 5.57 KB
/
certmanager.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
// MIT License
//
// Copyright (c) 2023 TTBT Enterprises LLC
// Copyright (c) 2023 Robin Thellend <rthellend@rthellend.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Package certmanager implements an X509 certificate manager that can replace
// https://pkg.go.dev/golang.org/x/crypto/acme/autocert#Manager for testing
// purposes.
// This certificate manager is a self-signed certificate authority that is not
// and should not be trusted for securing any real life communication.
package certmanager
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"net/http"
"sync"
"time"
"golang.org/x/net/idna"
)
// CertManager is an X509 certificate manager that also acts as a certificate
// authority for testing purposes.
type CertManager struct {
name string
key *rsa.PrivateKey
caCert *x509.Certificate
caCertPEM []byte
pool *x509.CertPool
logger func(string, ...interface{})
mu sync.Mutex
certs map[string]*tls.Certificate
}
// New returns a new ephemeral certificate manager.
func New(name string, logger func(string, ...interface{})) (*CertManager, error) {
if logger == nil {
logger = func(string, ...interface{}) {}
}
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, fmt.Errorf("rsa.GenerateKey: %w", err)
}
sn, _ := rand.Int(rand.Reader, big.NewInt(1<<32))
now := time.Now()
templ := &x509.Certificate{
PublicKeyAlgorithm: x509.RSA,
SerialNumber: sn,
Issuer: pkix.Name{CommonName: name},
Subject: pkix.Name{CommonName: name},
NotBefore: now,
NotAfter: now.Add(time.Hour),
KeyUsage: x509.KeyUsageCertSign,
BasicConstraintsValid: true,
IsCA: true,
DNSNames: []string{name},
}
b, err := x509.CreateCertificate(rand.Reader, templ, templ, key.Public(), key)
if err != nil {
return nil, fmt.Errorf("x509.CreateCertificate: %w", err)
}
caCert, err := x509.ParseCertificate(b)
if err != nil {
return nil, fmt.Errorf("x509.ParseCertificate: %w", err)
}
caCertPEM := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: b,
})
pool := x509.NewCertPool()
pool.AddCert(caCert)
return &CertManager{
name: name,
key: key,
caCert: caCert,
caCertPEM: caCertPEM,
pool: pool,
logger: logger,
certs: make(map[string]*tls.Certificate),
}, nil
}
// RootCAPEM returns the root certificate in PEM format.
func (cm *CertManager) RootCAPEM() string {
return string(cm.caCertPEM)
}
// RootCACertPool returns a CertPool that contains the root certificate.
func (cm *CertManager) RootCACertPool() *x509.CertPool {
return cm.pool
}
// TLSConfig returns a tls.Config that uses this certificate manager.
func (cm *CertManager) TLSConfig() *tls.Config {
return &tls.Config{
GetCertificate: cm.GetCertificate,
}
}
// GetCertificate can be used in tls.Config.
func (cm *CertManager) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
return cm.GetCert(hello.ServerName)
}
// GetCert returns a new tls.Certificate with name as the subject's common name.
func (cm *CertManager) GetCert(name string) (*tls.Certificate, error) {
if n, err := idna.Lookup.ToASCII(name); err == nil {
name = n
}
cm.mu.Lock()
defer cm.mu.Unlock()
if c := cm.certs[name]; c != nil {
return c, nil
}
cm.logger("[%s] GetCert(%q)", cm.name, name)
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, fmt.Errorf("rsa.GenerateKey: %w", err)
}
sn, _ := rand.Int(rand.Reader, big.NewInt(1<<32))
now := time.Now()
templ := &x509.Certificate{
PublicKeyAlgorithm: x509.RSA,
SerialNumber: sn,
Subject: pkix.Name{CommonName: name},
NotBefore: now,
NotAfter: now.Add(time.Hour),
KeyUsage: x509.KeyUsageDataEncipherment | x509.KeyUsageDigitalSignature,
BasicConstraintsValid: true,
DNSNames: []string{name},
}
b, err := x509.CreateCertificate(rand.Reader, templ, cm.caCert, key.Public(), cm.key)
if err != nil {
return nil, fmt.Errorf("x509.CreateCertificate: %v", err)
}
cert, err := x509.ParseCertificate(b)
if err != nil {
return nil, fmt.Errorf("x509.ParseCertificate: %v", err)
}
cm.certs[name] = &tls.Certificate{
Certificate: [][]byte{b},
PrivateKey: key,
Leaf: cert,
}
return cm.certs[name], nil
}
// HTTPHandler returns its fallback arguments. It exists only to mimic the
// autocert API.
func (cm *CertManager) HTTPHandler(fallback http.Handler) http.Handler {
return fallback
}