/
utils.go
657 lines (560 loc) · 15.5 KB
/
utils.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
/*
* Copyright 2018-2021 Venafi, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"crypto/sha1"
"crypto/x509"
"encoding/hex"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
"log"
"math/rand"
"os"
"regexp"
"strconv"
"strings"
"time"
"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/util"
"github.com/spf13/viper"
"github.com/urfave/cli/v2"
)
const (
vCertURL = "VCERT_URL"
vCertZone = "VCERT_ZONE"
/* #nosec */
vCertToken = "VCERT_TOKEN"
/* #nosec */
vCertApiKey = "VCERT_APIKEY"
vCertTrustBundle = "VCERT_TRUST_BUNDLE"
JKSFormat = "jks"
Pkcs12 = "pkcs12"
Sha256 = "SHA256"
SshCertPubKeyServ = "service"
SshCertPubKeyFilePreff = "file:"
SshCertPubKeyLocal = "local"
sshCertFileExt = "-cert.pub"
sshPubKeyFileExt = ".pub"
)
func parseCustomField(s string) (key, value string, err error) {
sl := strings.Split(s, "=")
if len(sl) < 2 {
err = fmt.Errorf("custom field should have format key=value")
return
}
key = strings.TrimSpace(sl[0])
value = strings.TrimSpace(strings.Join(sl[1:], "="))
return
}
// fillCertificateRequest populates the certificate request payload with values from command flags
func fillCertificateRequest(req *certificate.Request, cf *commandFlags) *certificate.Request {
if cf.caDN != "" {
req.CADN = cf.caDN
}
if cf.friendlyName != "" {
req.FriendlyName = cf.friendlyName
}
if cf.commonName != "" {
req.Subject.CommonName = cf.commonName
}
if cf.country != "" {
req.Subject.Country = []string{cf.country}
}
if cf.state != "" {
req.Subject.Province = []string{cf.state}
}
if cf.locality != "" {
req.Subject.Locality = []string{cf.locality}
}
if cf.org != "" {
req.Subject.Organization = []string{cf.org}
}
if len(cf.orgUnits) > 0 {
req.Subject.OrganizationalUnit = cf.orgUnits
}
if len(cf.dnsSans) > 0 {
req.DNSNames = cf.dnsSans
}
if len(cf.ipSans) > 0 {
req.IPAddresses = cf.ipSans
}
if len(cf.emailSans) > 0 {
req.EmailAddresses = cf.emailSans
}
if len(cf.uriSans) > 0 {
req.URIs = cf.uriSans
}
if len(cf.upnSans) > 0 {
req.UPNs = cf.upnSans
}
req.OmitSANs = cf.omitSans
for _, f := range cf.customFields {
k, v, err := parseCustomField(f)
if err != nil {
logger.Panic(err)
}
req.CustomFields = append(req.CustomFields, certificate.CustomField{Name: k, Value: v})
}
if len(cf.instance) > 0 {
req.Location = &certificate.Location{}
instance := strings.Split(cf.instance, ":")
req.Location.Instance = instance[0]
if len(instance) > 1 {
req.Location.Workload = instance[1]
}
req.Location.TLSAddress = cf.tlsAddress
req.Location.Replace = cf.replaceInstance
}
origin := OriginName
if len(cf.appInfo) > 0 {
origin = cf.appInfo
}
req.CustomFields = append(req.CustomFields, certificate.CustomField{Name: "Origin", Value: origin, Type: certificate.CustomFieldOrigin})
switch true {
case 0 == strings.Index(cf.csrOption, "file:"):
var err error
csrFileName := cf.csrOption[5:]
csr, err := readCSRfromFile(csrFileName)
if err != nil {
logger.Panicf("Failed to read CSR from file %s: %s", csrFileName, err)
}
err = req.SetCSR(csr)
if err != nil {
logger.Panicf("Failed to set CSR %s", err)
}
req.CsrOrigin = certificate.UserProvidedCSR
case "service" == cf.csrOption:
if cf.keyType != nil {
req.KeyType = *cf.keyType
}
if cf.keySize > 0 {
req.KeyLength = cf.keySize
} else if req.KeyLength == 0 {
req.KeyLength = 2048
}
if cf.keyCurve != certificate.EllipticCurveNotSet {
req.KeyCurve = cf.keyCurve
}
req.CsrOrigin = certificate.ServiceGeneratedCSR
default: // "local" == cf.csrOption:
if cf.keyType != nil {
req.KeyType = *cf.keyType
}
if cf.keySize > 0 {
req.KeyLength = cf.keySize
} else if req.KeyLength == 0 {
req.KeyLength = 2048
}
if cf.keyCurve != certificate.EllipticCurveNotSet {
req.KeyCurve = cf.keyCurve
}
req.CsrOrigin = certificate.LocalGeneratedCSR
}
if cf.validDays != "" {
validDays := cf.validDays
data := strings.Split(validDays, "#")
days, _ := strconv.ParseInt(data[0], 10, 64)
hours := days * 24
req.ValidityHours = int(hours)
issuerHint := ""
if len(data) > 1 { //means that issuer hint is set
option := strings.ToLower(data[1])
switch option {
case "m":
issuerHint = util.IssuerHintMicrosoft
case "d":
issuerHint = util.IssuerHintDigicert
case "e":
issuerHint = util.IssuerHintEntrust
}
}
req.IssuerHint = issuerHint
}
return req
}
func generateRenewalRequest(cf *commandFlags, certReq *certificate.Request) *certificate.RenewalRequest {
req := &certificate.RenewalRequest{}
req.Thumbprint = cf.thumbprint
req.CertificateDN = cf.distinguishedName
req.CertificateRequest = certReq
return req
}
func readThumbprintFromFile(fname string) (string, error) {
var err error
bytes, err := ioutil.ReadFile(fname)
if err != nil {
return "", err
}
// check if there's a thumbprint in the file
s := strings.TrimSpace(string(bytes))
s = strings.Replace(s, ":", "", -1)
s = strings.ToUpper(s)
matched, _ := regexp.MatchString("^[A-F0-9]{40}$", s)
if matched {
return s, nil
}
// check if there's a PEM certificate in the file
var block *pem.Block
var rest []byte
for {
block, rest = pem.Decode(bytes)
if block != nil && block.Type == "CERTIFICATE" {
break
}
if block == nil || len(rest) == 0 {
break
}
bytes = rest
}
if block != nil {
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return "", fmt.Errorf("failed to read certificate from file: %s: %s", fname, err)
}
fp := sha1.Sum(cert.Raw)
return strings.ToUpper(hex.EncodeToString(fp[:])), nil
}
return "", fmt.Errorf("failed to parse file %s", fname)
}
func readCSRfromFile(fileName string) ([]byte, error) {
bytes, err := ioutil.ReadFile(fileName)
if err != nil {
return nil, err
}
for {
block, rest := pem.Decode(bytes)
if block != nil && strings.HasSuffix(block.Type, "CERTIFICATE REQUEST") {
return pem.EncodeToMemory(block), nil
}
if block == nil || len(rest) == 0 {
return nil, fmt.Errorf("failed to find CSR in file: %s", fileName)
}
bytes = rest
}
}
func retrieveCertificate(connector endpoint.Connector, req *certificate.Request, timeout time.Duration) (certificates *certificate.PEMCollection, err error) {
startTime := time.Now()
for {
certificates, err = connector.RetrieveCertificate(req)
if err != nil {
_, ok := err.(endpoint.ErrCertificatePending)
if ok && timeout > 0 {
if time.Now().After(startTime.Add(timeout)) {
return nil, endpoint.ErrRetrieveCertificateTimeout{CertificateID: req.PickupID}
}
if timeout > 0 {
logger.Printf("Issuance of certificate is pending...")
time.Sleep(time.Duration(5) * time.Second)
}
} else {
return nil, err
}
} else if certificates == nil {
return nil, fmt.Errorf("fail: certificate is not returned by remote, while error is nil")
} else {
return certificates, nil
}
}
}
// TODO: This one utilizes req.Timeout feature that is added to connector.RetrieveCertificate(), but
// it cannot do logging in CLI context right now -- logger.Printf("Issuance of certificate is pending ...")
func retrieveCertificateNew(connector endpoint.Connector, req *certificate.Request, timeout time.Duration) (certificates *certificate.PEMCollection, err error) {
req.Timeout = timeout
certificates, err = connector.RetrieveCertificate(req)
if err != nil {
return nil, err
}
if certificates == nil {
return nil, fmt.Errorf("fail: certificate is not returned by remote, while error is nil")
}
return certificates, nil
}
func getFileWriter(fileName string) io.Writer {
var writer io.Writer
if fileName != "" {
f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
writer = f
if err != nil {
logger.Panicf("%s", err)
}
} else {
writer = os.Stdout
}
return writer
}
func doValuesMatch(value1 []byte, value2 []byte) bool {
if len(value1) != len(value2) {
return false
}
for idx := range value1 {
if value1[idx] != value2[idx] {
return false
}
}
return true
}
func isValidRFC822Name(name string) bool {
reg := regexp.MustCompile(rfc822NameRegex)
return reg.FindStringIndex(name) != nil
}
func getPropertyFromEnvironment(s string) string {
viper.AutomaticEnv()
urlS := viper.Get(s)
if urlS == nil {
return ""
} else {
return fmt.Sprintf("%v", urlS)
}
}
func writeToFile(content []byte, fileName string, perm os.FileMode) error {
err := ioutil.WriteFile(fileName, content, perm)
if err != nil {
return err
}
return nil
}
func writeSshFiles(privateKeyFileName string, privKey, pubKey, cert []byte) error {
fileName, err := normalizeSshCertFileName(privateKeyFileName)
if err != nil {
return err
}
if !isPubKeyInFile() && len(privKey) > 0 {
err = writeToFile(privKey, fileName, 0600)
if err != nil {
return err
}
log.Println("Private key has been written to: " + fileName)
}
//only write public key into a file if is not provided.
if !isPubKeyInFile() {
pubFileName := fileName + sshPubKeyFileExt
err = writeToFile(pubKey, pubFileName, 0644)
if err != nil {
return err
}
log.Println("Public key has been written to: " + pubFileName)
}
certFileName := fileName + sshCertFileExt
err = writeToFile(cert, certFileName, 0644)
if err != nil {
return err
}
log.Println("Certificate has been written to: " + certFileName)
return nil
}
func printExtensions(e map[string]interface{}) {
logf("\tExtensions: ")
if len(e) > 0 {
for k, v := range e {
if v != "" {
kv := fmt.Sprintf("%s:%v", k, v)
logf("\t\t%s", kv)
} else {
logf("\t\t%s", k)
}
}
} else {
logf("\t\tNone")
}
}
func printPrincipals(p []string) {
logf("\tPrincipals: ")
if len(p) > 0 {
for _, v := range p {
logf("\t\t%s", v)
}
} else {
logf("\t\tNone")
}
}
func printCriticalOptions(fc string, sa []string) {
logf("\tCritical Options: ")
if fc == "" && len(sa) == 0 {
logf("\t\tNone")
} else {
if fc != "" {
logf("\t\tForce command: %s", fc)
}
if len(sa) > 0 {
sourceAddsStr := ""
size := len(sa)
for i, val := range sa {
sourceAddsStr = sourceAddsStr + val
if i < size-1 {
sourceAddsStr = sourceAddsStr + ","
}
}
logf("\t\tSource addresses: %s", sourceAddsStr)
}
}
}
func printSshMetadata(data *certificate.SshCertificateObject) {
logf("SSH certificate:")
logf("\tCertificate Type: %s", data.CertificateDetails.CertificateType)
pubKey := fmt.Sprintf("%s:%s", Sha256, data.CertificateDetails.PublicKeyFingerprintSHA256)
logf("\tPublic key: %s", pubKey)
signingCa := fmt.Sprintf("%s:%s", Sha256, data.CertificateDetails.CAFingerprintSHA256)
logf("\tSigning CA: %s", signingCa)
logf("\tCertificate Identifier: %s", data.CertificateDetails.KeyID)
logf("\tSerial: %s", data.CertificateDetails.SerialNumber)
logf("\tValid From: %s", util.ConvertSecondsToTime(data.CertificateDetails.ValidFrom).String())
logf("\tValid To: %s", util.ConvertSecondsToTime(data.CertificateDetails.ValidTo).String())
printPrincipals(data.CertificateDetails.Principals)
printCriticalOptions(data.CertificateDetails.ForceCommand, data.CertificateDetails.SourceAddresses)
printExtensions(data.CertificateDetails.Extensions)
}
func isPubKeyInFile() bool {
value := flags.sshCertPubKey
if value != "" {
if strings.HasPrefix(value, SshCertPubKeyFilePreff) {
return true
}
}
return false
}
func isServiceGenerated() bool {
value := flags.sshCertPubKey
return value == SshCertPubKeyServ
}
func getSshPubKeyFromFile() (content string, err error) {
value := flags.sshCertPubKey
if value != "" {
data := strings.Split(value, ":")
if len(data) == 2 {
fileName := data[1]
var fileContent []byte
fileContent, err = ioutil.ReadFile(fileName)
if err != nil {
return
}
content = string(fileContent)
} else {
err = fmt.Errorf("wrong specification on sshCertPubKey flag value, please provide a file name in the format: file:file-name")
return
}
}
return
}
func getExistingSshFiles(id string) ([]string, error) {
fileName, err := normalizeSshCertFileName(id)
if err != nil {
return nil, err
}
existingFiles := make([]string, 0)
certFile, err := ioutil.ReadFile(fileName + sshCertFileExt)
if err == nil && certFile != nil { //means file exists.
existingFiles = append(existingFiles, fileName+sshCertFileExt)
}
pubKeyFile, err := ioutil.ReadFile(fileName + sshPubKeyFileExt)
if err == nil && pubKeyFile != nil { //means file exists.
existingFiles = append(existingFiles, fileName+sshPubKeyFileExt)
}
privKeyFile, err := ioutil.ReadFile(fileName)
if err == nil && privKeyFile != nil { //means file exists.
existingFiles = append(existingFiles, fileName)
}
return existingFiles, nil
}
func normalizeSshCertFileName(s string) (string, error) {
regex, err := regexp.Compile("[^A-Za-z0-9]+")
if err != nil {
return "", err
}
fileName := regex.ReplaceAllString(s, "_")
return fileName, err
}
func AddLineEnding(s string) string {
if !flags.sshCertWindows {
s = strings.ReplaceAll(s, "\r\n", "\n")
}
return s
}
func IsCSRServiceVaaSGenerated(commandName string) bool {
cloudSerViceGenerated := false
if commandName == commandPickupName {
context := &cli.Context{
Command: &cli.Command{
Name: commandPickupName,
},
}
cfg, err := buildConfig(context, &flags)
if err == nil {
connector, err := vcert.NewClient(&cfg)
if err == nil && endpoint.ConnectorTypeCloud == connector.GetType() {
var req = &certificate.Request{
PickupID: flags.pickupID,
}
cloudSerViceGenerated, _ = connector.IsCSRServiceGenerated(req)
}
}
}
return cloudSerViceGenerated
}
func isTppConnector(commandName string) bool {
if commandName == commandPickupName {
context := &cli.Context{
Command: &cli.Command{
Name: commandPickupName,
},
}
cfg, err := buildConfig(context, &flags)
if err == nil {
connector, err := vcert.NewClient(&cfg)
if err == nil && endpoint.ConnectorTypeTPP == connector.GetType() {
return true
}
}
}
return false
}
func randRunes(n int) string {
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyz")
b := make([]rune, n)
for i := range b {
/* #nosec */
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}
func getUserParameterProvidedForGetCred() (string, error) {
tppTokenS := flags.tppToken
if tppTokenS == "" {
tppTokenS = getPropertyFromEnvironment(vCertToken)
}
identityParameters := map[string]bool{
flagTPPUser.Name: flags.tppUser != "",
flagTPPToken.Name: tppTokenS != "",
flagClientP12.Name: flags.clientP12 != "",
flagEmail.Name: flags.email != "",
}
var uniqueIdentity string
for identityName, identityValue := range identityParameters {
if identityValue {
if uniqueIdentity != "" {
return "", fmt.Errorf("only one of either --username, --p12-file, -t or --email can be specified")
}
uniqueIdentity = identityName
}
}
if uniqueIdentity == "" {
return "", fmt.Errorf("either --username, --p12-file, -t or --email must be specified")
}
return uniqueIdentity, nil
}