-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathpath_fetch.go
528 lines (461 loc) · 14.8 KB
/
path_fetch.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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package pki
import (
"context"
"encoding/pem"
"fmt"
"net/http"
"strings"
"time"
"github.com/hashicorp/vault/builtin/logical/pki/issuing"
"github.com/hashicorp/vault/builtin/logical/pki/revocation"
"github.com/hashicorp/vault/helper/constants"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/errutil"
"github.com/hashicorp/vault/sdk/logical"
)
var pathFetchReadSchema = map[int][]framework.Response{
http.StatusOK: {{
Description: "OK",
Fields: map[string]*framework.FieldSchema{
"certificate": {
Type: framework.TypeString,
Description: `Certificate`,
Required: false,
},
"revocation_time": {
Type: framework.TypeInt64,
Description: `Revocation time`,
Required: false,
},
"revocation_time_rfc3339": {
Type: framework.TypeString,
Description: `Revocation time RFC 3339 formatted`,
Required: false,
},
"issuer_id": {
Type: framework.TypeString,
Description: `ID of the issuer`,
Required: false,
},
"ca_chain": {
Type: framework.TypeString,
Description: `Issuing CA Chain`,
Required: false,
},
},
}},
}
// Returns the CA in raw format
func pathFetchCA(b *backend) *framework.Path {
return &framework.Path{
Pattern: `ca(/pem)?`,
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixPKI,
OperationSuffix: "ca-der|ca-pem",
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathFetchRead,
Responses: pathFetchReadSchema,
},
},
HelpSynopsis: pathFetchHelpSyn,
HelpDescription: pathFetchHelpDesc,
}
}
// Returns the CA chain
func pathFetchCAChain(b *backend) *framework.Path {
return &framework.Path{
Pattern: `(cert/)?ca_chain`,
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixPKI,
OperationSuffix: "ca-chain-pem|cert-ca-chain",
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathFetchRead,
Responses: pathFetchReadSchema,
},
},
HelpSynopsis: pathFetchHelpSyn,
HelpDescription: pathFetchHelpDesc,
}
}
// Returns the CRL in raw format
func pathFetchCRL(b *backend) *framework.Path {
return &framework.Path{
Pattern: `crl(/pem|/delta(/pem)?)?`,
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixPKI,
OperationSuffix: "crl-der|crl-pem|crl-delta|crl-delta-pem",
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathFetchRead,
Responses: pathFetchReadSchema,
},
},
HelpSynopsis: pathFetchHelpSyn,
HelpDescription: pathFetchHelpDesc,
}
}
// Returns the CRL in raw format
func pathFetchUnifiedCRL(b *backend) *framework.Path {
return &framework.Path{
Pattern: `unified-crl(/pem|/delta(/pem)?)?`,
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixPKI,
OperationSuffix: "unified-crl-der|unified-crl-pem|unified-crl-delta|unified-crl-delta-pem",
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathFetchRead,
},
},
HelpSynopsis: pathFetchHelpSyn,
HelpDescription: pathFetchHelpDesc,
}
}
// Returns any valid (non-revoked) cert in raw format.
func pathFetchValidRaw(b *backend) *framework.Path {
return &framework.Path{
Pattern: `cert/(?P<serial>[0-9A-Fa-f-:]+)/raw(/pem)?`,
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixPKI,
OperationSuffix: "cert-raw-der|cert-raw-pem",
},
Fields: map[string]*framework.FieldSchema{
"serial": {
Type: framework.TypeString,
Description: `Certificate serial number, in colon- or
hyphen-separated octal`,
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathFetchRead,
Responses: pathFetchReadSchema,
},
},
HelpSynopsis: pathFetchHelpSyn,
HelpDescription: pathFetchHelpDesc,
}
}
// Returns any valid (non-revoked) cert. Since "ca" fits the pattern, this path
// also handles returning the CA cert in a non-raw format.
func pathFetchValid(b *backend) *framework.Path {
return &framework.Path{
Pattern: `cert/(?P<serial>[0-9A-Fa-f-:]+)`,
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixPKI,
OperationSuffix: "cert",
},
Fields: map[string]*framework.FieldSchema{
"serial": {
Type: framework.TypeString,
Description: `Certificate serial number, in colon- or
hyphen-separated octal`,
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathFetchRead,
Responses: pathFetchReadSchema,
},
},
HelpSynopsis: pathFetchHelpSyn,
HelpDescription: pathFetchHelpDesc,
}
}
// This returns the CRL in a non-raw format
func pathFetchCRLViaCertPath(b *backend) *framework.Path {
pattern := `cert/(crl|delta-crl)`
if constants.IsEnterprise {
pattern = `cert/(crl|delta-crl|unified-crl|unified-delta-crl)`
}
return &framework.Path{
Pattern: pattern,
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixPKI,
OperationSuffix: "cert-crl|cert-delta-crl|cert-unified-crl|cert-unified-delta-crl",
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathFetchRead,
Responses: pathFetchReadSchema,
},
},
HelpSynopsis: pathFetchHelpSyn,
HelpDescription: pathFetchHelpDesc,
}
}
// This returns the list of serial numbers for certs
func pathFetchListCerts(b *backend) *framework.Path {
return &framework.Path{
Pattern: "certs/?$",
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixPKI,
OperationSuffix: "certs",
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ListOperation: &framework.PathOperation{
Callback: b.pathFetchCertList,
},
},
HelpSynopsis: pathFetchHelpSyn,
HelpDescription: pathFetchHelpDesc,
}
}
func (b *backend) pathFetchCertList(ctx context.Context, req *logical.Request, _ *framework.FieldData) (response *logical.Response, retErr error) {
entries, err := req.Storage.List(ctx, issuing.PathCerts)
if err != nil {
return nil, err
}
for i := range entries {
entries[i] = denormalizeSerial(entries[i])
}
return logical.ListResponse(entries), nil
}
func (b *backend) pathFetchRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (response *logical.Response, retErr error) {
var serial, pemType, contentType string
var certEntry, revokedEntry *logical.StorageEntry
var funcErr error
var certificate []byte
var fullChain []byte
var revocationTime int64
var revocationIssuerId string
var revocationTimeRfc3339 string
response = &logical.Response{
Data: map[string]interface{}{},
}
sc := b.makeStorageContext(ctx, req.Storage)
// Some of these need to return raw and some non-raw;
// this is basically handled by setting contentType or not.
// Errors don't cause an immediate exit, because the raw
// paths still need to return raw output.
modifiedCtx := &IfModifiedSinceHelper{
req: req,
issuerRef: defaultRef,
}
switch {
case req.Path == "ca" || req.Path == "ca/pem" || req.Path == "cert/ca" || req.Path == "cert/ca/raw" || req.Path == "cert/ca/raw/pem":
modifiedCtx.reqType = ifModifiedCA
ret, err := sendNotModifiedResponseIfNecessary(modifiedCtx, sc, response)
if err != nil || ret {
retErr = err
goto reply
}
serial = "ca"
contentType = "application/pkix-cert"
if req.Path == "ca/pem" || req.Path == "cert/ca/raw/pem" {
pemType = "CERTIFICATE"
contentType = "application/pem-certificate-chain"
} else if req.Path == "cert/ca" {
pemType = "CERTIFICATE"
contentType = ""
}
case req.Path == "ca_chain" || req.Path == "cert/ca_chain":
serial = "ca_chain"
if req.Path == "ca_chain" {
contentType = "application/pkix-cert"
}
case req.Path == "crl" || req.Path == "crl/pem" || req.Path == "crl/delta" || req.Path == "crl/delta/pem" || req.Path == "cert/crl" || req.Path == "cert/crl/raw" || req.Path == "cert/crl/raw/pem" || req.Path == "cert/delta-crl" || req.Path == "cert/delta-crl/raw" || req.Path == "cert/delta-crl/raw/pem" || req.Path == "unified-crl" || req.Path == "unified-crl/pem" || req.Path == "unified-crl/delta" || req.Path == "unified-crl/delta/pem" || req.Path == "cert/unified-crl" || req.Path == "cert/unified-crl/raw" || req.Path == "cert/unified-crl/raw/pem" || req.Path == "cert/unified-delta-crl" || req.Path == "cert/unified-delta-crl/raw" || req.Path == "cert/unified-delta-crl/raw/pem":
config, err := b.CrlBuilder().GetConfigWithUpdate(sc)
if err != nil {
retErr = err
goto reply
}
var isDelta bool
var isUnified bool
if strings.Contains(req.Path, "delta") {
isDelta = true
}
if strings.Contains(req.Path, "unified") || shouldLocalPathsUseUnified(config) {
isUnified = true
}
modifiedCtx.reqType = ifModifiedCRL
if !isUnified && isDelta {
modifiedCtx.reqType = ifModifiedDeltaCRL
} else if isUnified && !isDelta {
modifiedCtx.reqType = ifModifiedUnifiedCRL
} else if isUnified && isDelta {
modifiedCtx.reqType = ifModifiedUnifiedDeltaCRL
}
ret, err := sendNotModifiedResponseIfNecessary(modifiedCtx, sc, response)
if err != nil || ret {
retErr = err
goto reply
}
serial = legacyCRLPath
if !isUnified && isDelta {
serial = deltaCRLPath
} else if isUnified && !isDelta {
serial = unifiedCRLPath
} else if isUnified && isDelta {
serial = unifiedDeltaCRLPath
}
contentType = "application/pkix-crl"
if strings.Contains(req.Path, "pem") {
pemType = "X509 CRL"
contentType = "application/x-pem-file"
} else if req.Path == "cert/crl" || req.Path == "cert/delta-crl" || req.Path == "cert/unified-crl" || req.Path == "cert/unified-delta-crl" {
pemType = "X509 CRL"
contentType = ""
}
case strings.HasSuffix(req.Path, "/pem") || strings.HasSuffix(req.Path, "/raw"):
serial = data.Get("serial").(string)
contentType = "application/pkix-cert"
if strings.HasSuffix(req.Path, "/pem") {
pemType = "CERTIFICATE"
contentType = "application/pem-certificate-chain"
}
default:
if ser, ok := data.GetOk("serial"); ok {
serial = ser.(string)
}
pemType = "CERTIFICATE"
}
if len(serial) == 0 {
response = logical.ErrorResponse("The serial number must be provided")
goto reply
}
// Prefer fetchCAInfo to fetchCertBySerial for CA certificates.
if serial == "ca_chain" || serial == "ca" {
caInfo, err := sc.fetchCAInfo(defaultRef, issuing.ReadOnlyUsage)
if err != nil {
switch err.(type) {
case errutil.UserError:
response = logical.ErrorResponse(err.Error())
goto reply
default:
retErr = err
goto reply
}
}
if serial == "ca_chain" {
rawChain := caInfo.GetFullChain()
var chainStr string
for _, ca := range rawChain {
block := pem.Block{
Type: "CERTIFICATE",
Bytes: ca.Bytes,
}
chainStr = strings.Join([]string{chainStr, strings.TrimSpace(string(pem.EncodeToMemory(&block)))}, "\n")
}
fullChain = []byte(strings.TrimSpace(chainStr))
certificate = fullChain
} else if serial == "ca" {
certificate = caInfo.Certificate.Raw
if len(pemType) != 0 {
block := pem.Block{
Type: pemType,
Bytes: certificate,
}
// This is convoluted on purpose to ensure that we don't have trailing
// newlines via various paths
certificate = []byte(strings.TrimSpace(string(pem.EncodeToMemory(&block))))
}
}
goto reply
}
certEntry, funcErr = fetchCertBySerial(sc, req.Path, serial)
if funcErr != nil {
switch funcErr.(type) {
case errutil.UserError:
response = logical.ErrorResponse(funcErr.Error())
goto reply
default:
retErr = funcErr
goto reply
}
}
if certEntry == nil {
response = nil
goto reply
}
certificate = certEntry.Value
if len(pemType) != 0 {
block := pem.Block{
Type: pemType,
Bytes: certEntry.Value,
}
// This is convoluted on purpose to ensure that we don't have trailing
// newlines via various paths
certificate = []byte(strings.TrimSpace(string(pem.EncodeToMemory(&block))))
}
revokedEntry, funcErr = fetchCertBySerial(sc, "revoked/", serial)
if funcErr != nil {
switch funcErr.(type) {
case errutil.UserError:
response = logical.ErrorResponse(funcErr.Error())
goto reply
default:
retErr = funcErr
goto reply
}
}
if revokedEntry != nil {
var revInfo revocation.RevocationInfo
err := revokedEntry.DecodeJSON(&revInfo)
if err != nil {
return logical.ErrorResponse(fmt.Sprintf("Error decoding revocation entry for serial %s: %s", serial, err)), nil
}
revocationTime = revInfo.RevocationTime
revocationIssuerId = revInfo.CertificateIssuer.String()
if !revInfo.RevocationTimeUTC.IsZero() {
revocationTimeRfc3339 = revInfo.RevocationTimeUTC.Format(time.RFC3339Nano)
}
}
reply:
switch {
case len(contentType) != 0:
response = &logical.Response{
Data: map[string]interface{}{
logical.HTTPContentType: contentType,
logical.HTTPRawBody: certificate,
},
}
if retErr != nil {
if b.Logger().IsWarn() {
b.Logger().Warn("possible error, but cannot return in raw response. Note that an empty CA probably means none was configured, and an empty CRL is possibly correct", "error", retErr)
}
}
retErr = nil
if len(certificate) > 0 {
response.Data[logical.HTTPStatusCode] = 200
} else {
response.Data[logical.HTTPStatusCode] = 204
}
case retErr != nil:
response = nil
return
case response == nil:
return
case response.IsError():
return response, nil
default:
response.Data["certificate"] = string(certificate)
response.Data["revocation_time"] = revocationTime
response.Data["revocation_time_rfc3339"] = revocationTimeRfc3339
// Only output this field if we have a value for it as it doesn't make sense for a
// bunch of code paths that go through here
if revocationIssuerId != "" {
response.Data["issuer_id"] = revocationIssuerId
}
if len(fullChain) > 0 {
response.Data["ca_chain"] = string(fullChain)
}
}
return
}
const pathFetchHelpSyn = `
Fetch a CA, CRL, CA Chain, or non-revoked certificate.
`
const pathFetchHelpDesc = `
This allows certificates to be fetched. Use /cert/:serial for JSON responses.
Using "ca" or "crl" as the value fetches the appropriate information in DER encoding. Add "/pem" to either to get PEM encoding.
Using "ca_chain" as the value fetches the certificate authority trust chain in PEM encoding.
Otherwise, specify a serial number to fetch the specified certificate. Add "/raw" to get just the certificate in DER form, "/raw/pem" to get the PEM encoded certificate.
`