-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcerts.go
410 lines (334 loc) · 9.2 KB
/
certs.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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
// Package certs provides helpful methods for generating test certificates.
package certs
import (
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"math/big"
rand2 "math/rand"
"strconv"
"testing"
"time"
)
// Config can be provided to override the default values. The default values used are equivalent
// to a zero Config value (e.g. Config{}).
type Config struct {
// CertPath specifies where to store the certificate. An empty string
// disables output. Files are PEM-encoded for New and NewPEM and DER-encoded
// for NewDER.
CertPath string
// CertPath specifies where to store the key. An empty string disables
// output. Files are PEM-encoded for New and NewPEM and DER-encoded for
// NewDER. Key files are unencrypted.
KeyPath string
// CACert specifies the CA certificate that signs the generated cert. Pass
// nil to create a self-signed certificate.
CACert *x509.Certificate
// CAKey specifies the CA key that signs the generated cert. Pass nil to
// create a self-signed certificate.
CAKey crypto.Signer
// DN is the distinguished name of the certificate. If nil, a DN is
// generated of the form 'CN=<random number>'.
DN *pkix.Name
// Expiry is the expiry time of the certificate. If zero, the expiry is set
// one year in the future.
Expiry time.Time
// SerialNumber specifies the certificate serial. If nil, a random
// SerialNumber is generated.
SerialNumber *big.Int
// KeyType indicates the type of key to generate.
KeyType KeyType
// KeySize indicates the size of the key to generate for RSA keys. If zero,
// RSA keys will be 2048 bits long.
RSAKeySize int
// Curve indicates the type of ECDSA key to generate. If nil, a P256 curve
// is used.
Curve elliptic.Curve
// IsCA indicates whether to set CA flags on the certificate.
IsCA bool
// Algorithm specifies the signature algorithm to use. If zero,
// SHA256WithRSA or ECDSAWithSHA256 is used (according to the issuing key
// type).
Algorithm x509.SignatureAlgorithm
// nowTime is used by tests
nowTime time.Time
}
// KeyType defines the type of key to generate.
type KeyType int
const (
RSA KeyType = iota
ECDSA
)
var maxSerial = big.NewInt(100000)
const (
pemCertType = "CERTIFICATE"
pemKeyType = "PRIVATE KEY"
coreKeyUsage = x509.KeyUsageDataEncipherment |
x509.KeyUsageDigitalSignature |
x509.KeyUsageKeyEncipherment |
x509.KeyUsageKeyAgreement
caKeyUsage = coreKeyUsage | x509.KeyUsageCertSign
)
func genCertAndKey(cfg Config, pem bool) (*x509.Certificate, crypto.Signer, error) {
err := validateConfig(cfg)
if err != nil {
return nil, nil, err
}
signingKeyType := cfg.KeyType
selfSigned := true
if cfg.CACert != nil && cfg.CAKey != nil {
selfSigned = false
switch cfg.CAKey.(type) {
case *rsa.PrivateKey:
signingKeyType = RSA
case *ecdsa.PrivateKey:
signingKeyType = RSA
default:
return nil, nil, errors.New("only RSA and ECDSA CA keys supported")
}
}
var subjectKey crypto.Signer
switch cfg.KeyType {
case RSA:
keySize := cfg.RSAKeySize
if keySize == 0 {
keySize = 2048
}
subjectKey, err = rsa.GenerateKey(rand.Reader, keySize)
case ECDSA:
curve := cfg.Curve
if curve == nil {
curve = elliptic.P256()
}
subjectKey, err = ecdsa.GenerateKey(curve, rand.Reader)
}
if err != nil {
return nil, nil, wrapError(err, "failed to generate key")
}
serial := cfg.SerialNumber
if serial == nil {
serial, err = rand.Int(rand.Reader, maxSerial)
if err != nil {
return nil, nil, wrapError(err, "failed to generate serial")
}
}
dn := cfg.DN
if dn == nil {
dn = &pkix.Name{CommonName: strconv.Itoa(rand2.Int())}
}
now := cfg.nowTime
if now.IsZero() {
now = time.Now()
}
expiry := cfg.Expiry
if expiry.IsZero() {
expiry = now.AddDate(1, 0, 0)
}
certUsage := coreKeyUsage
if cfg.IsCA {
certUsage = caKeyUsage
}
algorithm := cfg.Algorithm
if algorithm == x509.UnknownSignatureAlgorithm {
switch signingKeyType {
case RSA:
algorithm = x509.SHA256WithRSA
case ECDSA:
algorithm = x509.ECDSAWithSHA256
}
}
template := &x509.Certificate{
// Config settings
SerialNumber: serial,
Subject: *dn,
NotAfter: expiry,
IsCA: cfg.IsCA,
// Things we set ourselves
NotBefore: now,
KeyUsage: certUsage,
BasicConstraintsValid: true,
SignatureAlgorithm: algorithm,
}
var parent *x509.Certificate
if selfSigned {
parent = template
} else {
parent = cfg.CACert
}
issuerKey := cfg.CAKey
if issuerKey == nil {
issuerKey = subjectKey
}
certBytes, err := x509.CreateCertificate(rand.Reader, template, parent, subjectKey.Public(), issuerKey)
if err != nil {
return nil, nil, wrapError(err, "failed to generate certificate")
}
cert, err := x509.ParseCertificate(certBytes)
if err != nil {
return nil, nil, wrapError(err, "failed to generate certificate")
}
if cfg.CertPath != "" {
var outBytes []byte
if pem {
outBytes, err = pemEncodeCert(certBytes)
if err != nil {
return nil, nil, wrapError(err, "failed to encode certificate")
}
} else {
outBytes = certBytes
}
err = ioutil.WriteFile(cfg.CertPath, outBytes, 0644)
if err != nil {
return nil, nil, wrapError(err, "failed to write certificate")
}
}
if cfg.KeyPath != "" {
var keyBytes []byte
switch cfg.KeyType {
case RSA:
keyBytes, err = x509.MarshalPKCS8PrivateKey(subjectKey.(*rsa.PrivateKey))
if err != nil {
return nil, nil, wrapError(err, "failed to encode key")
}
case ECDSA:
keyBytes, err = x509.MarshalECPrivateKey(subjectKey.(*ecdsa.PrivateKey))
if err != nil {
return nil, nil, wrapError(err, "failed to encode key")
}
}
if pem {
keyBytes, err = pemEncodeKey(keyBytes)
if err != nil {
return nil, nil, wrapError(err, "failed to encode certificate")
}
}
err = ioutil.WriteFile(cfg.KeyPath, keyBytes, 0644)
if err != nil {
return nil, nil, wrapError(err, "failed to write key")
}
}
return cert, subjectKey, nil
}
func getConfig(cfgs []Config) Config {
if len(cfgs) > 0 {
return cfgs[0]
}
return Config{}
}
// New generates a certificate and private key. To override default values, pass
// a Config value.
func New(cfg ...Config) (*x509.Certificate, crypto.Signer, error) {
cert, key, err := genCertAndKey(getConfig(cfg), true)
if err != nil {
return nil, nil, err
}
return cert, key, nil
}
// TNew generates a certificate and private key. To override default values, pass
// a Config value. If an error occurs, t.Error is called.
func TNew(t *testing.T, cfg ...Config) (*x509.Certificate, crypto.Signer) {
c, k, err := New(cfg...)
if err != nil {
t.Error(err)
}
return c, k
}
// NewDER generates a certificate and private key in DER format. To override default values, pass
// a Config value.
func NewDER(cfg ...Config) (certificate []byte, key []byte, err error) {
cert, signerKey, err := genCertAndKey(getConfig(cfg), false)
if err != nil {
return nil, nil, err
}
certificate = cert.Raw
switch k := signerKey.(type) {
case *rsa.PrivateKey:
key, err = x509.MarshalPKCS8PrivateKey(k)
case *ecdsa.PrivateKey:
key, err = x509.MarshalECPrivateKey(k)
}
if err != nil {
return nil, nil, err
}
return
}
// TNewDER generates a certificate and private key in DER format. To override default values, pass
// a Config value. If an error occurs, t.Error is called.
func TNewDER(t *testing.T, cfg ...Config) (certificate []byte, key []byte) {
c, k, err := NewDER(cfg...)
if err != nil {
t.Error(err)
}
return c, k
}
// NewPEM generates a certificate and private key in PEM format. To override default values, pass
// a Config value.
func NewPEM(cfg ...Config) (certificate []byte, key []byte, err error) {
certBytes, keyBytes, err := NewDER(getConfig(cfg))
if err != nil {
return nil, nil, err
}
c, err := pemEncodeCert(certBytes)
if err != nil {
return nil, nil, err
}
k, err := pemEncodeKey(keyBytes)
if err != nil {
return nil, nil, err
}
return c, k, nil
}
// TNewPEM generates a certificate and private key in PEM format. To override default values, pass
// a Config value. If an error occurs, t.Error is called.
func TNewPEM(t *testing.T, cfg ...Config) (certificate []byte, key []byte) {
c, k, err := NewPEM(cfg...)
if err != nil {
t.Error(err)
}
return c, k
}
func pemEncodeCert(certBytes []byte) ([]byte, error) {
return pemEncode(certBytes, pemCertType)
}
func pemEncodeKey(keyBytes []byte) ([]byte, error) {
return pemEncode(keyBytes, pemKeyType)
}
func pemEncode(obj []byte, pemType string) ([]byte, error) {
block := &pem.Block{
Type: pemType,
Bytes: obj,
}
b := new(bytes.Buffer)
if err := pem.Encode(b, block); err != nil {
return nil, err
}
return b.Bytes(), nil
}
func validateConfig(cfg Config) error {
// We reject only the most grievous errors
switch cfg.KeyType {
case RSA, ECDSA:
// this is fine
default:
return errors.New("bad KeyType in config")
}
if cfg.SerialNumber != nil && cfg.SerialNumber.Cmp(big.NewInt(1)) == -1 {
return errors.New("SerialNumber must be positive")
}
if cfg.RSAKeySize < 0 {
return errors.New("RSAKeySize must be positive (or zero)")
}
return nil
}
func wrapError(err error, msg string) error {
return errors.New(fmt.Sprintf("%s: %s", msg, err))
}