-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcert_authority.go
More file actions
261 lines (218 loc) · 6.49 KB
/
cert_authority.go
File metadata and controls
261 lines (218 loc) · 6.49 KB
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io/ioutil"
"math/big"
"net"
"os"
"sync"
"time"
)
type rootCA struct {
cert *x509.Certificate
key *ecdsa.PrivateKey
tlsCerts map[string]*tls.Certificate
sync.RWMutex
}
func (ca *rootCA) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
ca.RLock()
tlsCert, found := ca.tlsCerts[hello.ServerName]
ca.RUnlock()
if found {
return tlsCert, nil
}
cert, priv := ca.Cert(hello.ServerName)
tlsCert = &tls.Certificate{
Certificate: [][]byte{cert.Raw, ca.cert.Raw},
PrivateKey: priv,
}
ca.Lock()
ca.tlsCerts[hello.ServerName] = tlsCert
ca.Unlock()
return tlsCert, nil
}
func (ca *rootCA) Cert(domain string) (*x509.Certificate, *ecdsa.PrivateKey) {
privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
fmt.Fprintf(os.Stderr, "unable to generate ecdsa key: %v\n", err)
os.Exit(2)
}
publicKey := &privKey.PublicKey
commonSubject := dummySubject(domain)
cert := x509.Certificate{
SerialNumber: randSerial(),
Subject: commonSubject,
NotAfter: time.Now().AddDate(20, 0, 0),
BasicConstraintsValid: true,
IsCA: false,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
DNSNames: []string{domain},
}
derBytes, err := x509.CreateCertificate(rand.Reader, &cert, ca.cert, publicKey, ca.key)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to create certificate: %v\n", err)
os.Exit(2)
}
finalCert, err := x509.ParseCertificate(derBytes)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to parse created certificate: %v\n", err)
os.Exit(2)
}
return finalCert, privKey
}
func LoadOrCreateRootCA(certFile, keyFile string) *rootCA {
certExists := false
keyExists := false
if _, err := os.Stat(certFile); err == nil {
certExists = true
}
if _, err := os.Stat(keyFile); err == nil {
keyExists = true
}
if certExists && keyExists {
return loadCA(certFile, keyFile)
}
// Clean up either file if it exists
_ = os.Remove(certFile)
_ = os.Remove(keyFile)
return createCA(certFile, keyFile)
}
func loadCA(certFile string, keyFile string) *rootCA {
certBytes, err := ioutil.ReadFile(certFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Error reading root cert file: %v\n", err)
os.Exit(2)
}
certBlock, _ := pem.Decode(certBytes)
if certBlock == nil {
fmt.Fprintf(os.Stderr, "Error decoding PEM of root cert file: %v\n", err)
os.Exit(2)
}
cert, err := x509.ParseCertificate(certBlock.Bytes)
if err != nil {
fmt.Fprintf(os.Stderr, "Error parsing root cert file: %v\n", err)
os.Exit(2)
}
keyBytes, err := ioutil.ReadFile(keyFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Error reading root private key file: %v\n", err)
os.Exit(2)
}
keyBlock, _ := pem.Decode(keyBytes)
if keyBlock == nil {
fmt.Fprintf(os.Stderr, "Error decoding PEM of root private key file: %v\n", err)
os.Exit(2)
}
key, err := x509.ParseECPrivateKey(keyBlock.Bytes)
if err != nil {
fmt.Fprintf(os.Stderr, "Error parsing root private key file: %v\n", err)
os.Exit(2)
}
return &rootCA{
cert: cert,
tlsCerts: make(map[string]*tls.Certificate, 10),
key: key,
}
}
func createCA(certFile string, keyFile string) *rootCA {
privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to generate ecdsa key for root cert: %v\n", err)
os.Exit(2)
}
publicKey := &privKey.PublicKey
commonSubject := dummySubject("tlself.root")
cert := x509.Certificate{
SerialNumber: randSerial(),
Subject: commonSubject,
NotAfter: time.Now().AddDate(20, 0, 0),
NotBefore: time.Now().AddDate(0, 0, -1),
MaxPathLen: 0,
MaxPathLenZero: true,
BasicConstraintsValid: true,
IsCA: true,
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
}
derBytes, err := x509.CreateCertificate(rand.Reader, &cert, &cert, publicKey, privKey)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to create root certificate: %v\n", err)
os.Exit(2)
}
finalCert, err := x509.ParseCertificate(derBytes)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to parse created root certificate: %v\n", err)
os.Exit(2)
}
certOut, err := os.Create(certFile)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to open cert.pem for writing root cert: %v\n", err)
os.Exit(2)
}
err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
if err != nil {
fmt.Fprintf(os.Stderr, "error encoding root cert to pem block: %v\n", err)
os.Exit(2)
}
err = certOut.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "error closing root cert file: %v\n", err)
os.Exit(2)
}
keyOut, err := os.OpenFile(keyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to open key.pem for writing root key: %v\n", err)
os.Exit(2)
}
err = pem.Encode(keyOut, pemBlockForKey(privKey))
if err != nil {
fmt.Fprintf(os.Stderr, "error encoding root private key to pem block: %v\n", err)
os.Exit(2)
}
err = keyOut.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "error closing root private key file: %v\n", err)
os.Exit(2)
}
return &rootCA{
cert: finalCert,
tlsCerts: make(map[string]*tls.Certificate, 10),
key: privKey,
}
}
func pemBlockForKey(priv *ecdsa.PrivateKey) *pem.Block {
b, err := x509.MarshalECPrivateKey(priv)
if err != nil {
fmt.Fprintf(os.Stderr, "unable to marshal ECDSA private key: %v\n", err)
os.Exit(2)
}
return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}
}
func dummySubject(common string) pkix.Name {
return pkix.Name{
CommonName: common,
Organization: []string{"No Corp"},
OrganizationalUnit: []string{"WWW"},
Locality: []string{"YYY"},
Country: []string{"QQQ"},
Province: []string{"ZZZ"},
}
}
func randSerial() *big.Int {
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to generate serial number: %s\n", err)
os.Exit(2)
}
return serialNumber
}