-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdevca.go
297 lines (245 loc) · 8.22 KB
/
devca.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
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package main
import (
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"os"
"regexp"
"strings"
"time"
"github.com/alexflint/go-arg"
)
func main() {
var command rootCommand
parser := arg.MustParse(&command)
if parser.Subcommand() == nil {
parser.WriteHelp(os.Stdout)
os.Exit(-1)
}
err := command.Handle()
if err != nil {
parser.FailSubcommand(err.Error(), parser.SubcommandNames()...)
}
}
type rootCommand struct {
Init *initCommand `arg:"subcommand:init" help:"Initialize Certificate Authority"`
Server *serverCommand `arg:"subcommand:server" help:"Sign Server Certificate"`
}
func (cmd *rootCommand) Description() string {
return "Manages Certificate Authorities and Certificates for development."
}
func (cmd *rootCommand) Handle() error {
switch {
case cmd.Init != nil:
return cmd.Init.Handle()
case cmd.Server != nil:
return cmd.Server.Handle()
default:
return nil
}
}
type initCommand struct {
Name string `arg:"positional" help:"certificate authority name"`
Force bool `arg:"-f,--force" help:"allow overwrite of the authority certificate"`
Domains []string `arg:"-d,--domain" help:"domain name constraints"`
}
func (cmd *initCommand) Handle() error {
if !cmd.Force {
if _, err := os.Stat("ca.crt"); err == nil {
return fmt.Errorf("certificate authority already exist")
}
}
caName := "Local Development CA"
if cmd.Name != "" {
caName = cmd.Name
} else {
hostname, err := os.Hostname()
if err == nil && hostname != "" {
caName = strings.ToUpper(hostname) + " Development CA"
}
}
caCert, caKey, err := createCertificateAuthority(caName, cmd.Domains)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
err = saveCertificateAndPrivateKey(caCert, "ca.crt", caKey, "ca.key")
if err != nil {
return fmt.Errorf("could not save CA certificate: %w", err)
}
return nil
}
type serverCommand struct {
HostName []string `arg:"positional,required" help:"server host names"`
}
func (cmd *serverCommand) Handle() error {
caCert, caKey, err := loadCertificateAndPrivateKey("ca.crt", "ca.key")
if err != nil {
return fmt.Errorf("could not load signer certificate: %w", err)
}
hostNames := cmd.HostName
hostCert, hostKey, err := signHostCertificate(caCert, caKey, hostNames)
if err != nil {
return fmt.Errorf("could not sign server certificate: %w", err)
}
baseFileName := hostNames[0] + "-" + fmt.Sprintf("%x", hostCert.SerialNumber)
err = saveCertificateAndPrivateKey(hostCert, baseFileName+".crt", hostKey, baseFileName+".key")
if err != nil {
return fmt.Errorf("could not save server certificate: %w", err)
}
return nil
}
func createCertificateAuthority(authorityName string, domains []string) (*x509.Certificate, crypto.PrivateKey, error) {
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, nil, fmt.Errorf("create CA private key: %w", err)
}
template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
CommonName: authorityName,
Organization: []string{authorityName},
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Hour * 24 * 365 * 10),
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
IsCA: true,
MaxPathLen: 1,
BasicConstraintsValid: true,
PermittedDNSDomainsCritical: len(domains) > 0,
PermittedDNSDomains: domains,
}
certBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey)
if err != nil {
return nil, nil, fmt.Errorf("create CA certificate: %w", err)
}
cert, err := x509.ParseCertificate(certBytes)
if err != nil {
return nil, nil, fmt.Errorf("parse CA certificate: %w", err)
}
return cert, privateKey, nil
}
func signHostCertificate(caCertificate *x509.Certificate, caPrivateKey crypto.PrivateKey, hostNames []string) (*x509.Certificate, crypto.PrivateKey, error) {
if len(hostNames) < 1 {
return nil, nil, fmt.Errorf("at least on host name should be provided")
}
validHostNameRegexp, _ := regexp.Compile(`^((\*|[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$`)
for _, hostName := range hostNames {
if !validHostNameRegexp.MatchString(hostName) {
return nil, nil, fmt.Errorf("invalid host name: %s", hostName)
}
}
notBefore := time.Now()
notAfter := notBefore.Add(time.Hour * 24 * 365 * 2)
if notBefore.After(caCertificate.NotAfter) || notAfter.After(caCertificate.NotAfter) {
return nil, nil, fmt.Errorf("signer certificate will be expired before host certificate")
}
serialNumber := big.NewInt(notBefore.Unix())
privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, nil, fmt.Errorf("create host private key: %w", err)
}
template := x509.Certificate{
IsCA: false,
BasicConstraintsValid: true,
SerialNumber: serialNumber,
Subject: pkix.Name{
CommonName: hostNames[0],
},
DNSNames: hostNames,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
NotBefore: notBefore,
NotAfter: notAfter,
}
certBytes, err := x509.CreateCertificate(rand.Reader, &template, caCertificate, &privateKey.PublicKey, caPrivateKey)
if err != nil {
return nil, nil, fmt.Errorf("create host certificate: %w", err)
}
cert, err := x509.ParseCertificate(certBytes)
if err != nil {
return nil, nil, fmt.Errorf("parse host certificate: %w", err)
}
return cert, privateKey, nil
}
func loadCertificateAndPrivateKey(certificateFileName, keyFileName string) (*x509.Certificate, crypto.PrivateKey, error) {
pemBytes, err := os.ReadFile(certificateFileName)
if err != nil {
return nil, nil, fmt.Errorf("load certificate: %w", err)
}
certPemBlock, _ := pem.Decode(pemBytes)
if certPemBlock == nil {
return nil, nil, fmt.Errorf("decode certificate")
}
certificate, err := x509.ParseCertificate(certPemBlock.Bytes)
if err != nil {
return nil, nil, fmt.Errorf("parse certificate: %w", err)
}
pemBytes, err = os.ReadFile(keyFileName)
if err != nil {
return nil, nil, fmt.Errorf("load private key: %w", err)
}
keyPemBlock, _ := pem.Decode(pemBytes)
if keyPemBlock == nil {
return nil, nil, fmt.Errorf("decode private key")
}
privateKey, err := parsePrivateKey(keyPemBlock)
if err != nil {
return nil, nil, fmt.Errorf("parse private key: %w", err)
}
return certificate, privateKey, nil
}
func parsePrivateKey(pemBlock *pem.Block) (privateKey crypto.PrivateKey, err error) {
switch pemBlock.Type {
case "RSA PRIVATE KEY":
privateKey, err = x509.ParsePKCS1PrivateKey(pemBlock.Bytes)
case "EC PRIVATE KEY":
privateKey, err = x509.ParseECPrivateKey(pemBlock.Bytes)
default:
privateKey = nil
err = fmt.Errorf("unsupported private key type: %s", pemBlock.Type)
}
return
}
func saveCertificateAndPrivateKey(certificate *x509.Certificate, certificateFileName string, privateKey crypto.PrivateKey, keyFileName string) error {
certificatePEM := &pem.Block{Type: "CERTIFICATE", Bytes: certificate.Raw}
certificateBuffer := &bytes.Buffer{}
pem.Encode(certificateBuffer, certificatePEM)
privateKeyPEM, err := marshalPrivateKey(privateKey)
if err != nil {
return fmt.Errorf("encode private key: %w", err)
}
privateKeyBuffer := &bytes.Buffer{}
pem.Encode(privateKeyBuffer, privateKeyPEM)
err = os.WriteFile(certificateFileName, certificateBuffer.Bytes(), 0640)
if err != nil {
return fmt.Errorf("write certificate: %w", err)
}
err = os.WriteFile(keyFileName, privateKeyBuffer.Bytes(), 0640)
if err != nil {
return fmt.Errorf("write private key: %w", err)
}
return nil
}
func marshalPrivateKey(privateKey interface{}) (*pem.Block, error) {
switch key := privateKey.(type) {
case *rsa.PrivateKey:
return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}, nil
case *ecdsa.PrivateKey:
keyBytes, err := x509.MarshalECPrivateKey(key)
if err != nil {
return nil, fmt.Errorf("marshal ECDSA private key: %w", err)
}
return &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes}, nil
default:
return nil, fmt.Errorf("unsupported private key type")
}
}