/
target_secret_pki_sign.go
553 lines (503 loc) · 20.3 KB
/
target_secret_pki_sign.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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package benchmarktests
import (
"crypto/x509"
"crypto/x509/pkix"
"encoding/json"
"encoding/pem"
"flag"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/gohcl"
"github.com/hashicorp/vault/api"
"github.com/hashicorp/vault/sdk/helper/certutil"
vegeta "github.com/tsenart/vegeta/v12/lib"
)
const (
PKISignTestType = "pki_sign"
PKISignTestMethod = "POST"
)
func init() {
TestList[PKISignTestType] = func() BenchmarkBuilder { return &PKISignTest{} }
}
type PKISignTest struct {
pathPrefix string
cn string
intpath string
rootpath string
config *pkiSecretIssueTestConfig
body []byte
header http.Header
logger hclog.Logger
}
type pkiSecretIssueTestConfig struct {
SetupDelay string `hcl:"setup_delay,optional"`
RootCAConfig *pkiSignRootConfig `hcl:"root_ca,block"`
IntermediateCSRConfig *pkiSignIntCSRConfig `hcl:"intermediate_csr,block"`
IntermediateCAConfig *pkiSignIntCAConfig `hcl:"intermediate_ca,block"`
RoleConfig *pkiSignRoleConfig `hcl:"role,block"`
SignConfig *pkiSignCSRConfig `hcl:"sign,block"`
}
// PKISignCertConfig is the configuration
// for the cert to be signed
//
// /pki/sign/:name
type pkiSignCSRConfig struct {
Name string `hcl:"name,optional"`
CSR *string `hcl:"csr,optional"`
CommonName string `hcl:"common_name,optional"`
AltNames string `hcl:"alt_names,optional"`
IPSANS string `hcl:"ip_sans,optional"`
URISANS string `hcl:"uri_sans,optional"`
OtherSANS string `hcli:"other_sans,optional"`
TTL string `hcl:"ttl,optional"`
Format string `hcl:"format,optional"`
ExcludeCNFromSANS bool `hcl:"exclude_cn_from_sans,optional"`
NotAfter string `hcl:"not_after,optional"`
RemoveRootsFromChain bool `hcl:"remove_root_from_chain,optional"`
UserIDs string `hcl:"user_ids,optional"`
}
// PKISignCAConfig is the configuration
// for the root CA cert to be generated
// for the test
//
// /pki/root/generate/:type
type pkiSignRootConfig struct {
Type string `hcl:"type,optional"`
IssuerName string `hcl:"issuer_name,optional"`
KeyName string `hcl:"key_name,optional"`
KeyRef string `hcl:"key_ref,optional"`
CommonName string `hcl:"common_name,optional"`
AltNames string `hcl:"alt_names,optional"`
IPSANS string `hcl:"ip_sans,optional"`
URISANS string `hcl:"uri_sans,optional"`
OtherSANS string `hcl:"other_sans,optional"`
TTL string `hcl:"ttl,optional"`
Format string `hcl:"format,optional"`
PrivateKeyFormat string `hcl:"private_key_format,optional"`
KeyType string `hcl:"key_type,optional"`
KeyBits int `hcl:"key_bits,optional"`
MaxPathLength int `hcl:"max_path_length,optional"`
ExcludeCNFromSANS bool `hcl:"exclude_cn_from_sans,optional"`
PermittedDNSDomains string `hcl:"permitted_dns_domains,optional"`
OU string `hcl:"ou,optional"`
Organization string `hcl:"organization,optional"`
Country string `hcl:"countrty,optional"`
Locality string `hcl:"locality,optional"`
Province string `hcl:"province,optional"`
StreetAddress string `hcl:"street_address,optional"`
PostalCode string `hcl:"postal_code,optional"`
SerialNumber string `hcl:"serial_number,optional"`
NotBeforeDuration string `hcl:"not_before_duration,optional"`
NotAfter string `hcl:"not_after,optional"`
ManagedKeyName string `hcl:"managed_key_name,optional"`
ManagedKeyID string `hcl:"managed_key_id,optional"`
}
// PKISignIntConfig is the configuratio
// for the intermediate CSR to be
// generated for the test
//
// /pki/intermediate/generate/:type
type pkiSignIntCSRConfig struct {
Type string `hcl:"type,optional"`
CommonName string `hcl:"common_name,optional"`
AltNames string `hcl:"alt_names,optional"`
IPSANS string `hcl:"ip_sans,optional"`
URISANS string `hcl:"uri_sans,optional"`
OtherSANS string `hcl:"other_sans,optional"`
Format string `hcl:"format,optional"`
PrivateKeyFormat string `hcl:"private_key_format,optional"`
KeyType string `hcl:"key_type,optional"`
KeyBits int `hcl:"key_bits,optional"`
KeyName string `hcl:"key_name,optional"`
KeyRef string `hcl:"key_ref,optional"`
SignatureBits int `hcl:"signature_bits,optional"`
ExcludeCNFromSANS bool `hcl:"exclude_cn_from_sans,optional"`
OU string `hcl:"ou,optional"`
Organization string `hcl:"organization,optional"`
Country string `hcl:"countrty,optional"`
Locality string `hcl:"locality,optional"`
Province string `hcl:"province,optional"`
StreetAddress string `hcl:"street_address,optional"`
PostalCode string `hcl:"postal_code,optional"`
SerialNumber string `hcl:"serial_number,optional"`
AddBasicConstraints bool `hcl:"add_basic_constraints,optional"`
ManagedKeyName string `hcl:"managed_key_name,optional"`
ManagedKeyID string `hcl:"managed_key_id,optional"`
}
// PKISignIntCAConfig is the configuration
// for the signing operation of the intermediate
// CA CSR.
//
// /pki/root/sign-intermediate
type pkiSignIntCAConfig struct {
CSR string `hcl:"csr,optional"`
CommonName string `hcl:"common_name,optional"`
AltNames string `hcl:"alt_names,optional"`
IPSANS string `hcl:"ip_sans,optional"`
URISANS string `hcl:"uri_sans,optional"`
OtherSANS string `hcl:"other_sans,optional"`
TTL string `hcl:"ttl,optional"`
Format string `hcl:"format,optional"`
MaxPathLength int `hcl:"max_path_length,optional"`
UseCSRValues bool `hcl:"use_csr_values,optional"`
PermittedDNSDomains string `hcl:"permitted_dns_domains,optional"`
OU string `hcl:"ou,optional"`
Organization string `hcl:"organization,optional"`
Country string `hcl:"countrty,optional"`
Locality string `hcl:"locality,optional"`
Province string `hcl:"province,optional"`
StreetAddress string `hcl:"street_address,optional"`
PostalCode string `hcl:"postal_code,optional"`
SerialNumber string `hcl:"serial_number,optional"`
NotBeforeDuration string `hcl:"not_before_duration,optional"`
NotAfter string `hcl:"not_after,optional"`
SignatureBits int `hcl:"signature_bits,optional"`
SKID string `hcl:"skid,optional"`
UsePSS bool `hcl:"use_pss,optional"`
}
// PKI Role config defining how the issued cert
// should be configured
//
// /pki/roles/:name
type pkiSignRoleConfig struct {
Name string `hcl:"name,optional"`
TTL string `hcl:"ttl,optional"`
MaxTTL string `hcl:"max_ttl,optional"`
AllowLocalhost *bool `hcl:"allow_localhost,optional"`
AllowedDomains []string `hcl:"allowed_domains,optional"`
AllowedDomainsTemplate bool `hcl:"allowed_domain_template,optional"`
AllowBareDomains bool `hcl:"allow_bare_domains,optional"`
AllowSubdomains bool `hcl:"allow_subdomains,optional"`
AllowGlobDomains bool `hcl:"allow_glob_domains,optional"`
AllowWildcardCertificates *bool `hcl:"allow_wildcard_certificates,optional"`
AllowAnyName bool `hcl:"allow_any_name,optional"`
EnforceHostnames *bool `hcl:"enforce_hostnames,optional"`
AllowIPSANS *bool `hcl:"allow_ip_sans,optional"`
AllowedURISANS string `hcl:"allowed_uri_sans,optional"`
AllowedURISANSTemplate bool `hcl:"allowed_uri_sans_template,optional"`
AllowedOtherSANS string `hcl:"allowed_other_sans,optional"`
AllowedSerialNumbers string `hcl:"allowed_serial_numbers,optional"`
ServerFlag *bool `hcl:"server_flag,optional"`
ClientFlag *bool `hcl:"client_flag,optional"`
CodeSigningFlag bool `hcl:"code_signing_flag,optional"`
EmailProtectionFlag bool `hcl:"email_protection_flag,optional"`
KeyType string `hcl:"key_type,optional"`
KeyBits int `hcl:"key_bits,optional"`
SignatureBits int `hcl:"signature_bits,optional"`
UsePSS bool `hcl:"use_pss,optional"`
KeyUsage []string `hcl:"key_usage,optional"`
ExtKeyUsage []string `hcl:"ext_key_usage,optional"`
ExtKeyUsageOIDS string `hcl:"ext_key_usage_oids,optional"`
UseCSRCommonName *bool `hcl:"use_csr_common_name,optional"`
UseCSRSANS *bool `hcl:"use_csr_sans,optional"`
OU string `hcl:"ou,optional"`
Organization string `hcl:"organization,optional"`
Country string `hcl:"countrty,optional"`
Locality string `hcl:"locality,optional"`
Province string `hcl:"province,optional"`
StreetAddress string `hcl:"street_address,optional"`
PostalCode string `hcl:"postal_code,optional"`
GenerateLease bool `hcl:"generate_lease,optional"`
NoStore bool `hcl:"no_store,optional"`
RequireCN *bool `hcl:"require_cn,optional"`
PolicyIdentifiers []string `hcl:"policy_identifiers,optional"`
BasicConstrainsValidForNonCA bool `hcl:"basic_constraints_valid_for_non_ca,optional"`
NotBeforeDuration string `hcl:"not_before_duration,optional"`
NotAfter string `hcl:"not_after,optional"`
CNValidations []string `hcl:"cn_validations,optional"`
AllowedUserIDs string `hcl:"allowed_user_ids,optional"`
}
func (p *PKISignTest) ParseConfig(body hcl.Body) error {
testConfig := &struct {
Config *pkiSecretIssueTestConfig `hcl:"config,block"`
}{
Config: &pkiSecretIssueTestConfig{
SetupDelay: "1s",
RootCAConfig: &pkiSignRootConfig{
Type: "internal",
CommonName: "example.com",
},
IntermediateCSRConfig: &pkiSignIntCSRConfig{
Type: "internal",
CommonName: "example.com Intermediate Authority",
},
IntermediateCAConfig: &pkiSignIntCAConfig{
Format: "pem_bundle",
},
RoleConfig: &pkiSignRoleConfig{
Name: "benchmark-sign",
AllowSubdomains: true,
AllowAnyName: true,
TTL: "5m",
},
SignConfig: &pkiSignCSRConfig{},
},
}
diags := gohcl.DecodeBody(body, nil, testConfig)
if diags.HasErrors() {
return fmt.Errorf("error decoding to struct: %v", diags)
}
p.config = testConfig.Config
return nil
}
func (p *PKISignTest) Target(client *api.Client) vegeta.Target {
return vegeta.Target{
Method: PKISignTestMethod,
URL: client.Address() + p.pathPrefix,
Body: p.body,
Header: p.header,
}
}
func (p *PKISignTest) GetTargetInfo() TargetInfo {
return TargetInfo{
method: PKISignTestMethod,
pathPrefix: p.pathPrefix,
}
}
func (p *PKISignTest) Cleanup(client *api.Client) error {
// Unmount Root
p.logger.Trace(cleanupLogMessage(p.rootpath))
_, err := client.Logical().Delete(filepath.Join("/sys/mounts/", p.rootpath))
if err != nil {
return fmt.Errorf("error cleaning up mount: %v", err)
}
// Unmount Intermediate
p.logger.Trace(cleanupLogMessage(p.intpath))
_, err = client.Logical().Delete(filepath.Join("/sys/mounts/", p.intpath))
if err != nil {
return fmt.Errorf("error cleaning up mount: %v", err)
}
return nil
}
func (p *PKISignTest) Setup(client *api.Client, mountName string, topLevelConfig *TopLevelTargetConfig) (BenchmarkBuilder, error) {
var err error
secretPath := mountName
p.logger = targetLogger.Named(PKISignTestType)
if topLevelConfig.RandomMounts {
secretPath, err = uuid.GenerateUUID()
if err != nil {
log.Fatalf("can't create UUID")
}
}
p.logger = p.logger.Named(secretPath)
// Create Root CA
err = p.createRootCA(client, secretPath)
if err != nil {
return nil, fmt.Errorf("error creating root CA: %v", err)
}
// Create and sign Intermediate CA
path, err := p.createIntermediateCA(client, secretPath)
if err != nil {
return nil, fmt.Errorf("error creating intermediate ca: %v", err)
}
// CSR parsing / creation
if p.config.SignConfig.CSR == nil {
p.logger.Warn("generating csr as one was not provided")
tCSR, err := p.generateTestCSR()
if err != nil {
return nil, fmt.Errorf("error generating test csr: %v", err)
}
p.config.SignConfig.CSR = &tCSR
} else {
// Check to see if its a path or a string and handle it
if ok, err := IsFile(*p.config.SignConfig.CSR); ok {
p.logger.Trace("loading csr from file", "path", *p.config.SignConfig.CSR)
csrBytes, err := os.ReadFile(*p.config.SignConfig.CSR)
if err != nil {
return nil, fmt.Errorf("error parsing CSR from file: %v", err)
}
csrString := string(csrBytes)
p.config.SignConfig.CSR = &csrString
} else {
// Fast path out if directory
if err == ErrIsDirectory {
return nil, fmt.Errorf("error parsing CSR from file: %v", err)
}
// Check if CSR data is valid
p.logger.Trace("validating csr string")
b, _ := pem.Decode([]byte(*p.config.SignConfig.CSR))
if b == nil {
_, err = x509.ParseCertificateRequest([]byte(*p.config.SignConfig.CSR))
if err != nil {
return nil, fmt.Errorf("error parsing CSR from string: %v", err)
}
} else {
_, err = x509.ParseCertificateRequest(b.Bytes)
if err != nil {
return nil, fmt.Errorf("error parsing CSR from string: %v", err)
}
}
// Valid CSR
}
}
// Decode Signing Config
p.logger.Trace(parsingConfigLogMessage("signing"))
signingData, err := structToMap(p.config.SignConfig)
if err != nil {
return nil, fmt.Errorf("error parsing signing config from struct: %v", err)
}
signingDataString, err := json.Marshal(signingData)
if err != nil {
return nil, fmt.Errorf("error marshaling signing config data: %v", err)
}
return &PKISignTest{
pathPrefix: "/v1/" + path,
cn: p.config.SignConfig.CommonName,
header: generateHeader(client),
body: []byte(signingDataString),
rootpath: p.rootpath,
intpath: p.intpath,
logger: p.logger,
}, nil
}
func (p *PKISignTest) createRootCA(cli *api.Client, pfx string) error {
rootPath := pfx + "-root"
// Create PKI Root mount
p.logger.Trace(mountLogMessage("secrets", "pki", rootPath))
err := cli.Sys().Mount(rootPath, &api.MountInput{
Type: "pki",
Config: api.MountConfigInput{
MaxLeaseTTL: "87600h",
},
})
if err != nil {
return fmt.Errorf("error mounting pki secrets engine: %v", err)
}
p.rootpath = rootPath
rootSetupLogger := p.logger.Named(rootPath)
// Avoid slow mount setup:
// URL: PUT $VAULT_ADDR/v1/9679cb02-65a4-f625-2f27-68d51e46af46-root/root/generate/internal
// Code: 404. Errors: * no handler for route "9679cb02-65a4-f625-2f27-68d51e46af46-root/root/generate/internal". route entry not found.
delay, err := time.ParseDuration(p.config.SetupDelay)
if err != nil {
return fmt.Errorf("error parsing duration: %v", err)
}
time.Sleep(delay)
// Decode Root Config struct into map to pass with request
rootSetupLogger.Trace(parsingConfigLogMessage("root"))
rootData, err := structToMap(p.config.RootCAConfig)
if err != nil {
return fmt.Errorf("error parsing root config from struct: %v", err)
}
// Setup Root CA
rootSetupLogger.Trace("generating root ca")
_, err = cli.Logical().Write(filepath.Join(rootPath, "root", "generate", p.config.RootCAConfig.Type), rootData)
if err != nil {
return fmt.Errorf("error generating root CA: %v", err)
}
rootSetupLogger.Trace("configuring urls")
_, err = cli.Logical().Write(filepath.Join(rootPath, "config", "urls"), map[string]interface{}{
"issuing_certificates": fmt.Sprintf("%s/v1/%s/ca", cli.Address(), rootPath),
"crl_distribution_points": []string{fmt.Sprintf("%s/v1/%s/crl", cli.Address(), rootPath)},
})
if err != nil {
return fmt.Errorf("error configuring urls: %v", err)
}
return nil
}
func (p *PKISignTest) createIntermediateCA(cli *api.Client, pfx string) (string, error) {
rootPath := fmt.Sprintf("%v-root", pfx)
intPath := fmt.Sprintf("%v-int", pfx)
// Create PKI Int Mount
p.logger.Trace(mountLogMessage("secrets", "pki", intPath))
err := cli.Sys().Mount(intPath, &api.MountInput{
Type: "pki",
Config: api.MountConfigInput{
MaxLeaseTTL: "87600h",
},
})
if err != nil {
return "", fmt.Errorf("error mounting pki secrets engine: %v", err)
}
p.intpath = intPath
intSetupLogger := p.logger.Named(intPath)
// Avoid slow mount setup:
// URL: PUT $VAULT_ADDR/v1/9679cb02-65a4-f625-2f27-68d51e46af46-root/root/generate/internal
// Code: 404. Errors: * no handler for route "9679cb02-65a4-f625-2f27-68d51e46af46-root/root/generate/internal". route entry not found.
delay, err := time.ParseDuration(p.config.SetupDelay)
if err != nil {
return "", fmt.Errorf("error parsing duration: %v", err)
}
time.Sleep(delay)
// Decode Intermediate CSR config to map to pass with request
intSetupLogger.Trace(parsingConfigLogMessage("intermediate ca csr"))
intCSRData, err := structToMap(p.config.IntermediateCSRConfig)
if err != nil {
return "", fmt.Errorf("error parsing intermediate csr config from struct: %v", err)
}
// Create Intermediate CSR
intSetupLogger.Trace("generating intermediate cert csr")
resp, err := cli.Logical().Write(filepath.Join(intPath, "intermediate", "generate", p.config.IntermediateCSRConfig.Type), intCSRData)
if err != nil {
return "", fmt.Errorf("error generating intermediate cert csr: %v", err)
}
p.config.IntermediateCAConfig.CSR = resp.Data["csr"].(string)
// Decode Intermediate Signing config to map to pass with request
intSetupLogger.Trace(parsingConfigLogMessage("intermediate cert signing"))
intSignData, err := structToMap(p.config.IntermediateCAConfig)
if err != nil {
return "", fmt.Errorf("error parsing intermediate signing config from struct: %v", err)
}
intSetupLogger.Trace("signing intermediate cert with root ca")
resp, err = cli.Logical().Write(filepath.Join(rootPath, "root", "sign-intermediate"), intSignData)
if err != nil {
return "", fmt.Errorf("error signing intermediate cert: %v", err)
}
// Set Intermediate signed certificate
intSetupLogger.Trace("setting intermediate signed cert")
_, err = cli.Logical().Write(filepath.Join(intPath, "intermediate", "set-signed"), map[string]interface{}{
"certificate": strings.Join([]string{resp.Data["certificate"].(string), resp.Data["issuing_ca"].(string)}, "\n"),
})
if err != nil {
return "", fmt.Errorf("error setting intermediate signed cert: %v", err)
}
// Decode Role config to map to pass with request
intSetupLogger.Trace(parsingConfigLogMessage("role"))
roleData, err := structToMap(p.config.RoleConfig)
if err != nil {
return "", fmt.Errorf("error parsing role config from struct: %v", err)
}
// Create Role
intSetupLogger.Trace(writingLogMessage("pki role"), "name", p.config.RoleConfig.Name)
_, err = cli.Logical().Write(filepath.Join(intPath, "roles", p.config.RoleConfig.Name), roleData)
if err != nil {
return "", fmt.Errorf("error writing pki role: %v", err)
}
return filepath.Join(intPath, "sign", p.config.RoleConfig.Name), nil
}
func (p *PKISignTest) generateTestCSR() (string, error) {
cBundle := &certutil.CreationBundle{
Params: &certutil.CreationParameters{
Subject: pkix.Name{
CommonName: "test.vault.benchmark",
Country: []string{"US"},
Organization: []string{"Hashicorp"},
Locality: []string{"San Francisco"},
OrganizationalUnit: []string{"VaultBenchmarking"},
},
KeyType: "rsa",
KeyBits: 2048,
NotAfter: time.Now().Add(1 * time.Hour),
},
}
csr, err := certutil.CreateCSR(cBundle, true)
if err != nil {
return "", err
}
bundle, err := csr.ToCSRBundle()
if err != nil {
return "", err
}
return bundle.CSR, nil
}
func (p *PKISignTest) Flags(fs *flag.FlagSet) {}