-
Notifications
You must be signed in to change notification settings - Fork 64
/
commands.go
764 lines (677 loc) · 21.8 KB
/
commands.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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
package main
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"github.com/Venafi/vcert/v4"
"github.com/Venafi/vcert/v4/pkg/certificate"
"github.com/Venafi/vcert/v4/pkg/endpoint"
"github.com/Venafi/vcert/v4/pkg/venafi/tpp"
"github.com/urfave/cli/v2"
"golang.org/x/crypto/pkcs12"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"strings"
"time"
)
var (
tlsConfig tls.Config
connectionType endpoint.ConnectorType
commandEnroll = &cli.Command{
Before: runBeforeCommand,
Flags: enrollFlags,
Action: doCommandEnroll1,
Name: commandEnrollName,
Usage: "To enroll a certificate",
UsageText: ` vcert enroll <Required Venafi Cloud Config> OR <Required Trust Protection Platform Config> <Options>
vcert enroll -k <Venafi Cloud API key> -z <zone> --cn <common name>
vcert enroll -k <Venafi Cloud API key> -z <zone> --cn <common name> --key-type rsa --key-size 4096 --san-dns <alt name> --san-dns <alt name2>
vcert enroll -u https://tpp.example.com -t <TPP access token> -z <zone> --cn <common name>
vcert enroll -u https://tpp.example.com -t <TPP access token> -z <zone> --cn <common name> --key-size 4096 --san-dns <alt name> --san-dns <alt name2>
vcert enroll -u https://tpp.example.com -t <TPP access token> -z <zone> --cn <common name> --key-type ecdsa --key-curve p384 --san-dns <alt name> -san-dns <alt name2>
vcert enroll -u https://tpp.example.com -t <TPP access token> -z <zone> --p12-file <PKCS#12 client cert> --p12-password <PKCS#12 password> --cn <common name>`,
}
commandGetcred = &cli.Command{
Before: runBeforeCommand,
Name: commandGetcredName,
Flags: getcredFlags,
Action: doCommandGetcred1,
Usage: "To obtain a new credential (token) for authentication",
UsageText: ` vcert getcred -u https://tpp.example.com --username <TPP user> --password <TPP user password>
vcert getcred -u https://tpp.example.com --p12-file <PKCS#12 client cert> --p12-password <PKCS#12 password> --trust-bundle /path-to/bundle.pem
vcert getcred -u https://tpp.example.com -t <TPP refresh token>
vcert getcred -u https://tpp.example.com -t <TPP refresh token> --scope <scopes and restrictions>`,
}
commandGenCSR = &cli.Command{
Before: runBeforeCommand,
Name: commandGenCSRName,
Flags: genCsrFlags,
Action: doCommandGenCSR1,
Usage: "To generate a certificate signing request (CSR)",
UsageText: ` vcert gencsr --cn <common name> -o <organization> --ou <organizational unit> -l <locality> --st <state> -c <country> --key-file <key output file> --csr-file <csr output file>
vcert gencsr --cn <common name> -o <organization> --ou <organizational unit> --ou <organizational unit2> -l <locality> --st <state> -c <country> --key-file <key output file> --csr-file <csr output file>`,
}
commandPickup = &cli.Command{
Before: runBeforeCommand,
Name: commandPickupName,
Flags: pickupFlags,
Action: doCommandPickup1,
Usage: "To download a certificate",
UsageText: ` vcert pickup <Required Venafi Cloud Config> OR <Required Trust Protection Platform Config> <Options>
vcert pickup -k <Venafi Cloud API key> [--pickup-id <ID value> | --pickup-id-file <file containing ID value>]
vcert pickup -u https://tpp.example.com -t <TPP access token> --pickup-id <ID value>`,
}
commandRevoke = &cli.Command{
Before: runBeforeCommand,
Name: commandRevokeName,
Flags: revokeFlags,
Action: doCommandRevoke1,
Usage: "To revoke a certificate",
UsageText: ` vcert revoke <Required Trust Protection Platform Config> <Options>
vcert revoke -u https://tpp.example.com -t <TPP access token> --thumbprint <cert SHA1 thumbprint>
vcert revoke -u https://tpp.example.com -t <TPP access token> --id <ID value>`,
}
commandRenew = &cli.Command{
Before: runBeforeCommand,
Name: commandRenewName,
Flags: renewFlags,
Action: doCommandRenew1,
Usage: "To renew a certificate",
UsageText: ` vcert renew <Required Venafi Cloud Config> OR <Required Trust Protection Platform Config> <Options>
vcert renew -u https://tpp.example.com -t <TPP access token> --id <ID value>
vcert renew -k <Venafi Cloud API key> --thumbprint <cert SHA1 fingerprint>`,
}
)
func runBeforeCommand(c *cli.Context) error {
//TODO: move all flag validations here
flags.orgUnits = c.StringSlice("ou")
flags.dnsSans = c.StringSlice("san-dns")
flags.emailSans = c.StringSlice("san-email")
flags.upnSans = c.StringSlice("san-upn")
flags.customFields = c.StringSlice("field")
noDuplicatedFlags := []string{"instance", "tls-address", "app-info"}
for _, f := range noDuplicatedFlags {
if len(c.StringSlice(f)) > 1 {
return fmt.Errorf("flag %s can not be duplicated", f)
} else if len(c.StringSlice(f)) == 1 {
switch f {
case "instance":
flags.instance = c.StringSlice(f)[0]
case "tls-address":
flags.tlsAddress = c.StringSlice(f)[0]
case "app-info":
flags.appInfo = c.StringSlice(f)[0]
}
}
}
for _, stringIP := range c.StringSlice("san-ip") {
ip := net.ParseIP(stringIP)
flags.ipSans = append(flags.ipSans, ip)
}
for _, stringURI := range c.StringSlice("san-uri") {
uri, _ := url.Parse(stringURI)
flags.uriSans = append(flags.uriSans, uri)
}
return nil
}
func setTLSConfig() error {
//Set RenegotiateFreelyAsClient in case of we're communicating with MTLS TPP server with only user\password
if flags.apiKey == "" {
tlsConfig.Renegotiation = tls.RenegotiateFreelyAsClient
}
if flags.insecure {
tlsConfig.InsecureSkipVerify = true
}
if flags.clientP12 != "" {
// Load client PKCS#12 archive
p12, err := ioutil.ReadFile(flags.clientP12)
if err != nil {
return fmt.Errorf("Error reading PKCS#12 archive file: %s", err)
}
blocks, err := pkcs12.ToPEM(p12, flags.clientP12PW)
if err != nil {
return fmt.Errorf("Error converting PKCS#12 archive file to PEM blocks: %s", err)
}
var pemData []byte
for _, b := range blocks {
pemData = append(pemData, pem.EncodeToMemory(b)...)
}
// Construct TLS certificate from PEM data
cert, err := tls.X509KeyPair(pemData, pemData)
if err != nil {
return fmt.Errorf("Error reading PEM data to build X.509 certificate: %s", err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(pemData)
// Setup HTTPS client
tlsConfig.Certificates = []tls.Certificate{cert}
tlsConfig.RootCAs = caCertPool
// nolint:staticcheck
tlsConfig.BuildNameToCertificate()
}
//Setting TLS configuration
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tlsConfig
return nil
}
func doCommandEnroll1(c *cli.Context) error {
err := validateEnrollFlags(c.Command.Name)
if err != nil {
return err
}
err = setTLSConfig()
if err != nil {
return err
}
validateOverWritingEnviromentVariables()
cfg, err := buildConfig(c, &flags)
if err != nil {
return fmt.Errorf("Failed to build vcert config: %s", err)
}
connector, err := vcert.NewClient(&cfg)
if err != nil {
logf("Unable to connect to %s: %s", cfg.ConnectorType, err)
} else {
logf("Successfully connected to %s", cfg.ConnectorType)
}
var req = &certificate.Request{}
var pcc = &certificate.PEMCollection{}
zoneConfig, err := connector.ReadZoneConfiguration()
if err != nil {
return err
}
logf("Successfully read zone configuration for %s", flags.zone)
req = fillCertificateRequest(req, &flags)
err = connector.GenerateRequest(zoneConfig, req)
if err != nil {
return err
}
var requestedFor string
if req.Subject.CommonName != "" {
requestedFor = req.Subject.CommonName
} else {
requestedFor = flags.csrOption
}
logf("Successfully created request for %s", requestedFor)
flags.pickupID, err = connector.RequestCertificate(req)
if err != nil {
return err
}
logf("Successfully posted request for %s, will pick up by %s", requestedFor, flags.pickupID)
if flags.noPickup {
pcc, err = certificate.NewPEMCollection(nil, req.PrivateKey, []byte(flags.keyPassword))
if err != nil {
return err
}
} else {
req.PickupID = flags.pickupID
req.ChainOption = certificate.ChainOptionFromString(flags.chainOption)
req.KeyPassword = flags.keyPassword
pcc, err = retrieveCertificate(connector, req, time.Duration(flags.timeout)*time.Second)
if err != nil {
return err
}
logf("Successfully retrieved request for %s", flags.pickupID)
if req.CsrOrigin == certificate.LocalGeneratedCSR {
// otherwise private key can be taken from *req
err := pcc.AddPrivateKey(req.PrivateKey, []byte(flags.keyPassword))
if err != nil {
log.Fatal(err)
}
}
}
result := &Result{
Pcc: pcc,
PickupId: flags.pickupID,
Config: &Config{
Command: c.Command.Name,
Format: flags.format,
JKSAlias: flags.jksAlias,
JKSPassword: flags.jksPassword,
ChainOption: certificate.ChainOptionFromString(flags.chainOption),
AllFile: flags.file,
KeyFile: flags.keyFile,
CertFile: flags.certFile,
ChainFile: flags.chainFile,
PickupIdFile: flags.pickupIDFile,
KeyPassword: flags.keyPassword,
},
}
err = result.Flush()
if err != nil {
return fmt.Errorf("Failed to output the results: %s", err)
}
return nil
}
func doCommandGetcred1(c *cli.Context) error {
err := validateGetcredFlags1(c.Command.Name)
if err != nil {
return err
}
validateOverWritingEnviromentVariables()
err = setTLSConfig()
if err != nil {
return err
}
cfg, err := buildConfig(c, &flags)
if err != nil {
return fmt.Errorf("Failed to build vcert config: %s", err)
}
//TODO: quick workaround to supress logs when output is in JSON.
if flags.credFormat != "json" {
logf("Getting credentials")
}
var clientP12 bool
if flags.clientP12 != "" {
clientP12 = true
}
var connectionTrustBundle *x509.CertPool
if cfg.ConnectionTrust != "" {
logf("You specified a trust bundle.")
connectionTrustBundle = x509.NewCertPool()
if !connectionTrustBundle.AppendCertsFromPEM([]byte(cfg.ConnectionTrust)) {
return fmt.Errorf("Failed to parse PEM trust bundle")
}
}
tppConnector, err := tpp.NewConnector(cfg.BaseUrl, "", cfg.LogVerbose, connectionTrustBundle)
if err != nil {
return fmt.Errorf("could not create TPP connector: %s", err)
}
if cfg.Credentials.RefreshToken != "" {
resp, err := tppConnector.RefreshAccessToken(&endpoint.Authentication{
RefreshToken: cfg.Credentials.RefreshToken,
ClientId: flags.clientId,
Scope: flags.scope,
})
if err != nil {
return err
}
if flags.credFormat == "json" {
jsonData, err := json.MarshalIndent(resp, "", " ")
if err != nil {
return err
}
fmt.Println(string(jsonData))
} else {
tm := time.Unix(int64(resp.Expires), 0).UTC().Format(time.RFC3339)
fmt.Println("access_token: ", resp.Access_token)
fmt.Println("access_token_expires: ", tm)
fmt.Println("refresh_token: ", resp.Refresh_token)
}
} else if cfg.Credentials.User != "" && cfg.Credentials.Password != "" {
resp, err := tppConnector.GetRefreshToken(&endpoint.Authentication{
User: cfg.Credentials.User,
Password: cfg.Credentials.Password,
Scope: flags.scope,
ClientId: flags.clientId})
if err != nil {
return err
}
if flags.credFormat == "json" {
jsonData, err := json.MarshalIndent(resp, "", " ")
if err != nil {
return err
}
fmt.Println(string(jsonData))
} else {
tm := time.Unix(int64(resp.Expires), 0).UTC().Format(time.RFC3339)
fmt.Println("access_token: ", resp.Access_token)
fmt.Println("access_token_expires: ", tm)
if resp.Refresh_token != "" {
fmt.Println("refresh_token: ", resp.Refresh_token)
}
}
} else if clientP12 {
resp, err := tppConnector.GetRefreshToken(&endpoint.Authentication{
ClientPKCS12: clientP12,
Scope: flags.scope,
ClientId: flags.clientId})
if err != nil {
return err
}
if flags.credFormat == "json" {
jsonData, err := json.MarshalIndent(resp, "", " ")
if err != nil {
return err
}
fmt.Println(string(jsonData))
} else {
tm := time.Unix(int64(resp.Expires), 0).UTC().Format(time.RFC3339)
fmt.Println("access_token: ", resp.Access_token)
fmt.Println("access_token_expires: ", tm)
fmt.Println("refresh_token: ", resp.Refresh_token)
}
} else {
return fmt.Errorf("Failed to determine credentials set")
}
return nil
}
func doCommandGenCSR1(c *cli.Context) error {
err := validateGenerateFlags1(c.Command.Name)
if err != nil {
return err
}
key, csr, err := generateCsrForCommandGenCsr(&flags, []byte(flags.keyPassword))
if err != nil {
return err
}
err = writeOutKeyAndCsr(c.Command.Name, &flags, key, csr)
if err != nil {
return err
}
return nil
}
func doCommandPickup1(c *cli.Context) error {
err := validatePickupFlags1(c.Command.Name)
if err != nil {
return err
}
err = setTLSConfig()
if err != nil {
return err
}
validateOverWritingEnviromentVariables()
cfg, err := buildConfig(c, &flags)
if err != nil {
return fmt.Errorf("Failed to build vcert config: %s", err)
}
connector, err := vcert.NewClient(&cfg) // Everything else requires an endpoint connection
if err != nil {
logf("Unable to connect to %s: %s", cfg.ConnectorType, err)
} else {
logf("Successfully connected to %s", cfg.ConnectorType)
}
if flags.pickupIDFile != "" {
bytes, err := ioutil.ReadFile(flags.pickupIDFile)
if err != nil {
return fmt.Errorf("Failed to read Pickup ID value: %s", err)
}
flags.pickupID = strings.TrimSpace(string(bytes))
}
var req = &certificate.Request{
PickupID: flags.pickupID,
ChainOption: certificate.ChainOptionFromString(flags.chainOption),
}
if flags.keyPassword != "" {
// key password is provided, which means will be requesting private key
req.KeyPassword = flags.keyPassword
req.FetchPrivateKey = true
}
var pcc *certificate.PEMCollection
pcc, err = retrieveCertificate(connector, req, time.Duration(flags.timeout)*time.Second)
if err != nil {
return fmt.Errorf("Failed to retrieve certificate: %s", err)
}
logf("Successfully retrieved request for %s", flags.pickupID)
result := &Result{
Pcc: pcc,
PickupId: flags.pickupID,
Config: &Config{
Command: c.Command.Name,
Format: flags.format,
JKSAlias: flags.jksAlias,
JKSPassword: flags.jksPassword,
ChainOption: certificate.ChainOptionFromString(flags.chainOption),
AllFile: flags.file,
KeyFile: flags.keyFile,
CertFile: flags.certFile,
ChainFile: flags.chainFile,
PickupIdFile: flags.pickupIDFile,
KeyPassword: flags.keyPassword,
},
}
err = result.Flush()
if err != nil {
return fmt.Errorf("Failed to output the results: %s", err)
}
return nil
}
func doCommandRevoke1(c *cli.Context) error {
err := validateRevokeFlags1(c.Command.Name)
if err != nil {
return err
}
err = setTLSConfig()
if err != nil {
return err
}
validateOverWritingEnviromentVariables()
cfg, err := buildConfig(c, &flags)
if err != nil {
return fmt.Errorf("Failed to build vcert config: %s", err)
}
connector, err := vcert.NewClient(&cfg) // Everything else requires an endpoint connection
if err != nil {
logf("Unable to connect to %s: %s", cfg.ConnectorType, err)
} else {
logf("Successfully connected to %s", cfg.ConnectorType)
}
var revReq = &certificate.RevocationRequest{}
switch true {
case flags.distinguishedName != "":
revReq.CertificateDN = flags.distinguishedName
revReq.Disable = !flags.noRetire
case flags.thumbprint != "":
revReq.Thumbprint = flags.thumbprint
revReq.Disable = false
default:
return fmt.Errorf("Certificate DN or Thumbprint is required")
}
requestedFor := func() string {
if flags.distinguishedName != "" {
return flags.distinguishedName
}
if flags.thumbprint != "" {
return flags.thumbprint
}
return ""
}()
revReq.Reason = flags.revocationReason
revReq.Comments = "revocation request from command line utility"
err = connector.RevokeCertificate(revReq)
if err != nil {
return fmt.Errorf("Failed to revoke certificate: %s", err)
}
logf("Successfully created revocation request for %s", requestedFor)
return nil
}
func doCommandRenew1(c *cli.Context) error {
err := validateRenewFlags1(c.Command.Name)
if err != nil {
return err
}
err = setTLSConfig()
if err != nil {
return err
}
validateOverWritingEnviromentVariables()
cfg, err := buildConfig(c, &flags)
if err != nil {
return fmt.Errorf("Failed to build vcert config: %s", err)
}
connector, err := vcert.NewClient(&cfg) // Everything else requires an endpoint connection
if err != nil {
logf("Unable to connect to %s: %s", cfg.ConnectorType, err)
} else {
logf("Successfully connected to %s", cfg.ConnectorType)
}
var req = &certificate.Request{}
var pcc = &certificate.PEMCollection{}
searchReq := &certificate.Request{
PickupID: flags.distinguishedName,
Thumbprint: flags.thumbprint,
}
// here we fetch old cert anyway
oldPcc, err := connector.RetrieveCertificate(searchReq)
if err != nil {
return fmt.Errorf("Failed to fetch old certificate by id %s: %s", flags.distinguishedName, err)
}
oldCertBlock, _ := pem.Decode([]byte(oldPcc.Certificate))
if oldCertBlock == nil || oldCertBlock.Type != "CERTIFICATE" {
return fmt.Errorf("Failed to fetch old certificate by id %s: PEM parse error", flags.distinguishedName)
}
oldCert, err := x509.ParseCertificate([]byte(oldCertBlock.Bytes))
if err != nil {
return fmt.Errorf("Failed to fetch old certificate by id %s: %s", flags.distinguishedName, err)
}
// now we have old one
logf("Fetched the latest certificate. Serial: %x, NotAfter: %s", oldCert.SerialNumber, oldCert.NotAfter)
switch true {
case strings.HasPrefix(flags.csrOption, "file:"):
// will be just sending CSR to backend
req = fillCertificateRequest(req, &flags)
case "local" == flags.csrOption || "" == flags.csrOption:
// restore certificate request from old certificate
req = certificate.NewRequest(oldCert)
// override values with those from command line flags
req = fillCertificateRequest(req, &flags)
case "service" == flags.csrOption:
// logger.Panic("service side renewal is not implemented")
req = fillCertificateRequest(req, &flags)
default:
return fmt.Errorf("unexpected -csr option: %s", flags.csrOption)
}
// here we ignore zone for Renew action, however, API still needs it
zoneConfig := &endpoint.ZoneConfiguration{}
err = connector.GenerateRequest(zoneConfig, req)
if err != nil {
return err
}
requestedFor := func() string {
if flags.distinguishedName != "" {
return flags.distinguishedName
}
if flags.thumbprint != "" {
return flags.thumbprint
}
return ""
}()
logf("Successfully created request for %s", requestedFor)
renewReq := generateRenewalRequest(&flags, req)
flags.pickupID, err = connector.RenewCertificate(renewReq)
if err != nil {
return err
}
logf("Successfully posted renewal request for %s, will pick up by %s", requestedFor, flags.pickupID)
if flags.noPickup {
pcc, err = certificate.NewPEMCollection(nil, req.PrivateKey, []byte(flags.keyPassword))
if err != nil {
return err
}
} else {
req.PickupID = flags.pickupID
req.ChainOption = certificate.ChainOptionFromString(flags.chainOption)
req.KeyPassword = flags.keyPassword
pcc, err = retrieveCertificate(connector, req, time.Duration(flags.timeout)*time.Second)
if err != nil {
return err
}
logf("Successfully retrieved request for %s", flags.pickupID)
if req.CsrOrigin == certificate.LocalGeneratedCSR {
// otherwise private key can be taken from *req
err = pcc.AddPrivateKey(req.PrivateKey, []byte(flags.keyPassword))
if err != nil {
logger.Fatal(err)
}
}
}
// check if previous and renewed certificates are of the same private key
newCertBlock, _ := pem.Decode([]byte(pcc.Certificate))
if newCertBlock != nil && newCertBlock.Type == "CERTIFICATE" {
newCert, err := x509.ParseCertificate([]byte(newCertBlock.Bytes))
if err == nil {
old, _ := json.Marshal(oldCert.PublicKey)
new, _ := json.Marshal(newCert.PublicKey)
if len(old) > 0 && string(old) == string(new) {
logf("WARNING: private key reused")
}
}
}
result := &Result{
Pcc: pcc,
PickupId: flags.pickupID,
Config: &Config{
Command: c.Command.Name,
Format: flags.format,
JKSAlias: flags.jksAlias,
JKSPassword: flags.jksPassword,
ChainOption: certificate.ChainOptionFromString(flags.chainOption),
AllFile: flags.file,
KeyFile: flags.keyFile,
CertFile: flags.certFile,
ChainFile: flags.chainFile,
PickupIdFile: flags.pickupIDFile,
KeyPassword: flags.keyPassword,
},
}
err = result.Flush()
if err != nil {
return fmt.Errorf("Failed to output the results: %s", err)
}
return nil
}
func generateCsrForCommandGenCsr(cf *commandFlags, privateKeyPass []byte) (privateKey []byte, csr []byte, err error) {
certReq := &certificate.Request{}
if cf.keyType != nil {
certReq.KeyType = *cf.keyType
}
certReq.KeyLength = cf.keySize
if cf.keyCurve != certificate.EllipticCurveNotSet {
certReq.KeyCurve = cf.keyCurve
}
err = certReq.GeneratePrivateKey()
if err != nil {
return
}
var pBlock *pem.Block
if len(privateKeyPass) == 0 {
pBlock, err = certificate.GetPrivateKeyPEMBock(certReq.PrivateKey)
if err != nil {
return
}
privateKey = pem.EncodeToMemory(pBlock)
} else {
pBlock, err = certificate.GetEncryptedPrivateKeyPEMBock(certReq.PrivateKey, privateKeyPass)
if err != nil {
return
}
privateKey = pem.EncodeToMemory(pBlock)
}
certReq = fillCertificateRequest(certReq, cf)
err = certReq.GenerateCSR()
if err != nil {
return
}
err = certReq.GeneratePrivateKey()
if err != nil {
return
}
csr = certReq.GetCSR()
return
}
func writeOutKeyAndCsr(commandName string, cf *commandFlags, key []byte, csr []byte) (err error) {
pcc := &certificate.PEMCollection{}
pcc.CSR = string(csr[:])
pcc.PrivateKey = string(key[:])
result := &Result{
Pcc: pcc,
PickupId: "",
Config: &Config{
Command: commandName,
Format: cf.csrFormat,
ChainOption: certificate.ChainOptionFromString(cf.chainOption),
AllFile: cf.file,
KeyFile: cf.keyFile,
CSRFile: cf.csrFile,
ChainFile: "",
PickupIdFile: "",
KeyPassword: cf.keyPassword,
},
}
err = result.Flush()
return
}