forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 0
/
path_root.go
465 lines (385 loc) · 13.1 KB
/
path_root.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
package pki
import (
"crypto/rand"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"reflect"
"time"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/vault/helper/errutil"
"github.com/hashicorp/vault/logical"
"github.com/hashicorp/vault/logical/framework"
)
func pathGenerateRoot(b *backend) *framework.Path {
ret := &framework.Path{
Pattern: "root/generate/" + framework.GenericNameRegex("exported"),
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathCAGenerateRoot,
},
HelpSynopsis: pathGenerateRootHelpSyn,
HelpDescription: pathGenerateRootHelpDesc,
}
ret.Fields = addCACommonFields(map[string]*framework.FieldSchema{})
ret.Fields = addCAKeyGenerationFields(ret.Fields)
ret.Fields = addCAIssueFields(ret.Fields)
return ret
}
func pathDeleteRoot(b *backend) *framework.Path {
ret := &framework.Path{
Pattern: "root",
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.DeleteOperation: b.pathCADeleteRoot,
},
HelpSynopsis: pathDeleteRootHelpSyn,
HelpDescription: pathDeleteRootHelpDesc,
}
return ret
}
func pathSignIntermediate(b *backend) *framework.Path {
ret := &framework.Path{
Pattern: "root/sign-intermediate",
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathCASignIntermediate,
},
HelpSynopsis: pathSignIntermediateHelpSyn,
HelpDescription: pathSignIntermediateHelpDesc,
}
ret.Fields = addCACommonFields(map[string]*framework.FieldSchema{})
ret.Fields = addCAIssueFields(ret.Fields)
ret.Fields["csr"] = &framework.FieldSchema{
Type: framework.TypeString,
Default: "",
Description: `PEM-format CSR to be signed.`,
}
ret.Fields["use_csr_values"] = &framework.FieldSchema{
Type: framework.TypeBool,
Default: false,
Description: `If true, then:
1) Subject information, including names and alternate
names, will be preserved from the CSR rather than
using values provided in the other parameters to
this path;
2) Any key usages requested in the CSR will be
added to the basic set of key usages used for CA
certs signed by this path; for instance,
the non-repudiation flag.`,
}
return ret
}
func pathSignSelfIssued(b *backend) *framework.Path {
ret := &framework.Path{
Pattern: "root/sign-self-issued",
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathCASignSelfIssued,
},
Fields: map[string]*framework.FieldSchema{
"certificate": &framework.FieldSchema{
Type: framework.TypeString,
Description: `PEM-format self-issued certificate to be signed.`,
},
},
HelpSynopsis: pathSignSelfIssuedHelpSyn,
HelpDescription: pathSignSelfIssuedHelpDesc,
}
return ret
}
func (b *backend) pathCADeleteRoot(
req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
return nil, req.Storage.Delete("config/ca_bundle")
}
func (b *backend) pathCAGenerateRoot(
req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
var err error
entry, err := req.Storage.Get("config/ca_bundle")
if err != nil {
return nil, err
}
if entry != nil {
return nil, nil
}
exported, format, role, errorResp := b.getGenerationParams(data)
if errorResp != nil {
return errorResp, nil
}
maxPathLengthIface, ok := data.GetOk("max_path_length")
if ok {
maxPathLength := maxPathLengthIface.(int)
role.MaxPathLength = &maxPathLength
}
parsedBundle, err := generateCert(b, role, nil, true, req, data)
if err != nil {
switch err.(type) {
case errutil.UserError:
return logical.ErrorResponse(err.Error()), nil
case errutil.InternalError:
return nil, err
}
}
cb, err := parsedBundle.ToCertBundle()
if err != nil {
return nil, errwrap.Wrapf("error converting raw cert bundle to cert bundle: {{err}}", err)
}
resp := &logical.Response{
Data: map[string]interface{}{
"expiration": int64(parsedBundle.Certificate.NotAfter.Unix()),
"serial_number": cb.SerialNumber,
},
}
switch format {
case "pem":
resp.Data["certificate"] = cb.Certificate
resp.Data["issuing_ca"] = cb.Certificate
if exported {
resp.Data["private_key"] = cb.PrivateKey
resp.Data["private_key_type"] = cb.PrivateKeyType
}
case "pem_bundle":
resp.Data["issuing_ca"] = cb.Certificate
if exported {
resp.Data["private_key"] = cb.PrivateKey
resp.Data["private_key_type"] = cb.PrivateKeyType
resp.Data["certificate"] = fmt.Sprintf("%s\n%s", cb.PrivateKey, cb.Certificate)
} else {
resp.Data["certificate"] = cb.Certificate
}
case "der":
resp.Data["certificate"] = base64.StdEncoding.EncodeToString(parsedBundle.CertificateBytes)
resp.Data["issuing_ca"] = base64.StdEncoding.EncodeToString(parsedBundle.CertificateBytes)
if exported {
resp.Data["private_key"] = base64.StdEncoding.EncodeToString(parsedBundle.PrivateKeyBytes)
resp.Data["private_key_type"] = cb.PrivateKeyType
}
}
if data.Get("private_key_format").(string) == "pkcs8" {
err = convertRespToPKCS8(resp)
if err != nil {
return nil, err
}
}
// Store it as the CA bundle
entry, err = logical.StorageEntryJSON("config/ca_bundle", cb)
if err != nil {
return nil, err
}
err = req.Storage.Put(entry)
if err != nil {
return nil, err
}
// Also store it as just the certificate identified by serial number, so it
// can be revoked
err = req.Storage.Put(&logical.StorageEntry{
Key: "certs/" + normalizeSerial(cb.SerialNumber),
Value: parsedBundle.CertificateBytes,
})
if err != nil {
return nil, errwrap.Wrapf("unable to store certificate locally: {{err}}", err)
}
// For ease of later use, also store just the certificate at a known
// location
entry.Key = "ca"
entry.Value = parsedBundle.CertificateBytes
err = req.Storage.Put(entry)
if err != nil {
return nil, err
}
// Build a fresh CRL
err = buildCRL(b, req)
if err != nil {
return nil, err
}
if parsedBundle.Certificate.MaxPathLen == 0 {
resp.AddWarning("Max path length of the generated certificate is zero. This certificate cannot be used to issue intermediate CA certificates.")
}
return resp, nil
}
func (b *backend) pathCASignIntermediate(
req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
var err error
format := getFormat(data)
if format == "" {
return logical.ErrorResponse(
`The "format" path parameter must be "pem" or "der"`,
), nil
}
role := &roleEntry{
TTL: (time.Duration(data.Get("ttl").(int)) * time.Second).String(),
AllowLocalhost: true,
AllowAnyName: true,
AllowIPSANs: true,
EnforceHostnames: false,
KeyType: "any",
AllowExpirationPastCA: true,
}
if cn := data.Get("common_name").(string); len(cn) == 0 {
role.UseCSRCommonName = true
}
var caErr error
signingBundle, caErr := fetchCAInfo(req)
switch caErr.(type) {
case errutil.UserError:
return nil, errutil.UserError{Err: fmt.Sprintf(
"could not fetch the CA certificate (was one set?): %s", caErr)}
case errutil.InternalError:
return nil, errutil.InternalError{Err: fmt.Sprintf(
"error fetching CA certificate: %s", caErr)}
}
useCSRValues := data.Get("use_csr_values").(bool)
maxPathLengthIface, ok := data.GetOk("max_path_length")
if ok {
maxPathLength := maxPathLengthIface.(int)
role.MaxPathLength = &maxPathLength
}
parsedBundle, err := signCert(b, role, signingBundle, true, useCSRValues, req, data)
if err != nil {
switch err.(type) {
case errutil.UserError:
return logical.ErrorResponse(err.Error()), nil
case errutil.InternalError:
return nil, err
}
}
if err := parsedBundle.Verify(); err != nil {
return nil, fmt.Errorf("verification of parsed bundle failed: %s", err)
}
signingCB, err := signingBundle.ToCertBundle()
if err != nil {
return nil, fmt.Errorf("Error converting raw signing bundle to cert bundle: %s", err)
}
cb, err := parsedBundle.ToCertBundle()
if err != nil {
return nil, fmt.Errorf("Error converting raw cert bundle to cert bundle: %s", err)
}
resp := &logical.Response{
Data: map[string]interface{}{
"expiration": int64(parsedBundle.Certificate.NotAfter.Unix()),
"serial_number": cb.SerialNumber,
},
}
if signingBundle.Certificate.NotAfter.Before(parsedBundle.Certificate.NotAfter) {
resp.AddWarning("The expiration time for the signed certificate is after the CA's expiration time. If the new certificate is not treated as a root, validation paths with the certificate past the issuing CA's expiration time will fail.")
}
switch format {
case "pem":
resp.Data["certificate"] = cb.Certificate
resp.Data["issuing_ca"] = signingCB.Certificate
if cb.CAChain != nil && len(cb.CAChain) > 0 {
resp.Data["ca_chain"] = cb.CAChain
}
case "pem_bundle":
resp.Data["certificate"] = cb.ToPEMBundle()
resp.Data["issuing_ca"] = signingCB.Certificate
if cb.CAChain != nil && len(cb.CAChain) > 0 {
resp.Data["ca_chain"] = cb.CAChain
}
case "der":
resp.Data["certificate"] = base64.StdEncoding.EncodeToString(parsedBundle.CertificateBytes)
resp.Data["issuing_ca"] = base64.StdEncoding.EncodeToString(signingBundle.CertificateBytes)
var caChain []string
for _, caCert := range parsedBundle.CAChain {
caChain = append(caChain, base64.StdEncoding.EncodeToString(caCert.Bytes))
}
if caChain != nil && len(caChain) > 0 {
resp.Data["ca_chain"] = cb.CAChain
}
}
err = req.Storage.Put(&logical.StorageEntry{
Key: "certs/" + normalizeSerial(cb.SerialNumber),
Value: parsedBundle.CertificateBytes,
})
if err != nil {
return nil, fmt.Errorf("Unable to store certificate locally: %v", err)
}
if parsedBundle.Certificate.MaxPathLen == 0 {
resp.AddWarning("Max path length of the signed certificate is zero. This certificate cannot be used to issue intermediate CA certificates.")
}
return resp, nil
}
func (b *backend) pathCASignSelfIssued(
req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
var err error
certPem := data.Get("certificate").(string)
block, _ := pem.Decode([]byte(certPem))
if block == nil || len(block.Bytes) == 0 {
return logical.ErrorResponse("certificate could not be PEM-decoded"), nil
}
certs, err := x509.ParseCertificates(block.Bytes)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf("error parsing certificate: %s", err)), nil
}
if len(certs) != 1 {
return logical.ErrorResponse(fmt.Sprintf("%d certificates found in PEM file, expected 1", len(certs))), nil
}
cert := certs[0]
if !cert.IsCA {
return logical.ErrorResponse("given certificate is not a CA certificate"), nil
}
if !reflect.DeepEqual(cert.Issuer, cert.Subject) {
return logical.ErrorResponse("given certificate is not self-issued"), nil
}
var caErr error
signingBundle, caErr := fetchCAInfo(req)
switch caErr.(type) {
case errutil.UserError:
return nil, errutil.UserError{Err: fmt.Sprintf(
"could not fetch the CA certificate (was one set?): %s", caErr)}
case errutil.InternalError:
return nil, errutil.InternalError{Err: fmt.Sprintf(
"error fetching CA certificate: %s", caErr)}
}
signingCB, err := signingBundle.ToCertBundle()
if err != nil {
return nil, fmt.Errorf("Error converting raw signing bundle to cert bundle: %s", err)
}
urls := &urlEntries{}
if signingBundle.URLs != nil {
urls = signingBundle.URLs
}
cert.IssuingCertificateURL = urls.IssuingCertificates
cert.CRLDistributionPoints = urls.CRLDistributionPoints
cert.OCSPServer = urls.OCSPServers
newCert, err := x509.CreateCertificate(rand.Reader, cert, signingBundle.Certificate, cert.PublicKey, signingBundle.PrivateKey)
if err != nil {
return nil, errwrap.Wrapf("error signing self-issued certificate: {{err}}", err)
}
if len(newCert) == 0 {
return nil, fmt.Errorf("nil cert was created when signing self-issued certificate")
}
pemCert := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: newCert,
})
return &logical.Response{
Data: map[string]interface{}{
"certificate": string(pemCert),
"issuing_ca": signingCB.Certificate,
},
}, nil
}
const pathGenerateRootHelpSyn = `
Generate a new CA certificate and private key used for signing.
`
const pathGenerateRootHelpDesc = `
See the API documentation for more information.
`
const pathDeleteRootHelpSyn = `
Deletes the root CA key to allow a new one to be generated.
`
const pathDeleteRootHelpDesc = `
See the API documentation for more information.
`
const pathSignIntermediateHelpSyn = `
Issue an intermediate CA certificate based on the provided CSR.
`
const pathSignIntermediateHelpDesc = `
see the API documentation for more information.
`
const pathSignSelfIssuedHelpSyn = `
Signs another CA's self-issued certificate.
`
const pathSignSelfIssuedHelpDesc = `
Signs another CA's self-issued certificate. This is most often used for rolling roots; unless you know you need this you probably want to use sign-intermediate instead.
Note that this is a very privileged operation and should be extremely restricted in terms of who is allowed to use it. All values will be taken directly from the incoming certificate and only verification that it is self-issued will be performed.
Configured URLs for CRLs/OCSP/etc. will be copied over and the issuer will be this mount's CA cert. Other than that, all other values will be used verbatim.
`