-
Notifications
You must be signed in to change notification settings - Fork 61
/
validators.go
685 lines (576 loc) · 19.4 KB
/
validators.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
/*
* Copyright 2020-2023 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 (
"bufio"
"fmt"
"os"
"regexp"
"strings"
"github.com/Venafi/vcert/v5/pkg/certificate"
"github.com/Venafi/vcert/v5/pkg/util"
"github.com/Venafi/vcert/v5/pkg/venafi"
)
// RevocationReasonOptions is an array of strings containing reasons for certificate revocation
var RevocationReasonOptions = []string{
"none",
"key-compromise",
"ca-compromise",
"affiliation-changed",
"superseded",
"cessation-of-operation",
}
// JKSMinPasswordLen taken from keystore.minPasswordLen constant
const JKSMinPasswordLen = 6
func validateCommonFlags(commandName string) error {
if flags.format != "" && flags.format != "pem" && flags.format != "json" && flags.format != P12Format && flags.format != LegacyP12Format && flags.format != JKSFormat && flags.format != util.LegacyPem {
return fmt.Errorf("Unexpected output format: %s", flags.format)
}
if flags.file != "" && (flags.certFile != "" || flags.chainFile != "" || flags.keyFile != "") {
return fmt.Errorf("The '-file' option cannot be used used with any other -*-file flags. Either all data goes into one file or individual files must be specified using the appropriate flags")
}
var csrOptionRegex *regexp.Regexp
if flags.platform == venafi.Firefly {
csrOptionRegex = regexp.MustCompile(`(^file:).*$|^service$|^$`)
if !csrOptionRegex.MatchString(flags.csrOption) {
return fmt.Errorf("unexpected --csr option provided: %s; specify one of the following options: %s, or %s", flags.csrOption, "'file:<filename>'", "'service'")
}
} else {
csrOptionRegex = regexp.MustCompile(`(^file:).*$|^local$|^service$|^$`)
if !csrOptionRegex.MatchString(flags.csrOption) {
return fmt.Errorf("unexpected --csr option provided: %s; specify one of the following options: %s, %s, or %s", flags.csrOption, "'file:<filename>'", "'local'", "'service'")
}
}
csrOptFlagResults := csrOptionRegex.FindStringSubmatch(flags.csrOption)
if csrOptFlagResults[1] != "" && (flags.keyTypeString != "" || flags.keyCurveString != "" || flags.keySize > 0) {
return fmt.Errorf("the '--keytype','--keycurve' and '--key-size' options cannot be used when '--csr file:' option is provided")
}
switch flags.keyTypeString {
case "rsa":
kt := certificate.KeyTypeRSA
flags.keyType = &kt
case "ecdsa":
kt := certificate.KeyTypeECDSA
flags.keyType = &kt
case "":
default:
return fmt.Errorf("unknown key type: %s", flags.keyTypeString)
}
switch strings.ToLower(flags.keyCurveString) {
case "p256":
flags.keyCurve = certificate.EllipticCurveP256
case "p384":
flags.keyCurve = certificate.EllipticCurveP384
case "p521":
flags.keyCurve = certificate.EllipticCurveP521
case "":
default:
return fmt.Errorf("unknown EC key curve: %s", flags.keyTypeString)
}
return nil
}
func validateConnectionFlags(commandName string) error {
if flags.config != "" {
if flags.apiKey != "" ||
flags.userName != "" ||
flags.password != "" ||
flags.token != "" ||
flags.url != "" ||
flags.vaasTenantID != "" ||
flags.externalJWT != "" ||
flags.testMode {
return fmt.Errorf("connection details cannot be specified with flags when --config is used")
}
return nil
}
if flags.profile != "" {
return fmt.Errorf("--profile option cannot be used without --config option")
}
// Nothing to do in test mode
if flags.testMode {
if commandName == commandGetCredName {
// unless it is get credentials which cannot be emulated
return fmt.Errorf("there is no test mode for %s command", commandName)
}
return nil
}
switch flags.platform {
case venafi.TPP:
return validateConnectionFlagsTPP(commandName)
case venafi.TLSPCloud:
return validateConnectionFlagsCloud(commandName)
case venafi.Firefly:
return validateConnectionFlagsFirefly(commandName)
}
tppToken := flags.token
if tppToken == "" {
tppToken = getPropertyFromEnvironment(vCertToken)
}
//Guessing the platform by checking flags
// - Firefly not present here as it is required to pass the platform flag
// - Token empty is considered to mean Cloud connector to keep previous behavior where token was exclusive to TPP
// - To use token with VaaS, the platform flag is required.
// - If the platform flag is set we would not be guessing here
if flags.userName == "" && tppToken == "" && flags.clientP12 == "" {
// should be SaaS endpoint
return validateConnectionFlagsCloud(commandName)
} else {
// should be TPP service
return validateConnectionFlagsTPP(commandName)
}
}
func validatePKCS12Flags(commandName string) error {
if flags.format == P12Format || flags.format == LegacyP12Format {
if commandName == commandEnrollName {
if flags.file == "" && flags.csrOption != "service" {
return fmt.Errorf("PKCS#12 format requires certificate, private key, and chain to be written to a single file; specify using --file")
}
} else {
if flags.file == "" { // todo: for enroll it also checks flags.csrOption != "service"
return fmt.Errorf("PKCS#12 format requires certificate, private key, and chain to be written to a single file; specify using --file")
}
}
if flags.certFile != "" || flags.chainFile != "" || flags.keyFile != "" {
return fmt.Errorf(`The --file parameter may not be combined with the --cert-file, --key-file, or --chain-file parameters when --format is %q`, flags.format)
}
if strings.HasPrefix(flags.csrOption, "file:") {
return fmt.Errorf(`The --csr "file" option may not be used with the enroll or renew actions when --format is %q`, flags.format)
}
if (flags.csrOption == "" || flags.csrOption == "local") && flags.noPickup {
return fmt.Errorf(`The --csr "local" option may not be used with the enroll or renew actions when --format is %q and --no-pickup is specified`, flags.format)
}
}
return nil
}
func validateJKSFlags(commandName string) error {
if flags.format == JKSFormat {
if commandName == commandEnrollName {
if flags.file == "" && flags.csrOption != "service" {
return fmt.Errorf("JKS format requires certificate, private key, and chain to be written to a single file; specify using --file")
}
} else {
if flags.file == "" { // todo: for enroll it also checks flags.csrOption != "service"
return fmt.Errorf("JKS format requires certificate, private key, and chain to be written to a single file; specify using --file")
}
}
if flags.certFile != "" || flags.chainFile != "" || flags.keyFile != "" {
return fmt.Errorf(`The --file parameter may not be combined with the --cert-file, --key-file, or --chain-file parameters when --format is "jks"`)
}
if strings.HasPrefix(flags.csrOption, "file:") {
return fmt.Errorf(`The --csr "file" option may not be used with the enroll or renew actions when --format is "jks"`)
}
if (flags.csrOption == "" || flags.csrOption == "local") && flags.noPickup {
return fmt.Errorf(`The --csr "local" option may not be used with the enroll or renew actions when --format is "jks" and --no-pickup is specified`)
}
if flags.keyPassword == "" {
return fmt.Errorf("JKS format requires passwords that are at least %d characters long", JKSMinPasswordLen)
} else {
if (flags.jksPassword != "" && len(flags.jksPassword) < JKSMinPasswordLen) || (flags.keyPassword != "" && len(flags.keyPassword) < JKSMinPasswordLen) {
return fmt.Errorf("JKS format requires passwords that are at least %d characters long", JKSMinPasswordLen)
}
}
if flags.jksAlias == "" {
return fmt.Errorf("The --jks-alias parameter is required with --format jks")
}
} else {
if flags.jksPassword != "" {
return fmt.Errorf("The --jks-password parameter may only be used with --format jks")
}
if flags.jksAlias != "" {
return fmt.Errorf("The --jks-alias parameter may only be used with --format jks")
}
}
return nil
}
func validateEnrollFlags(commandName string) error {
err := validateConnectionFlags(commandName)
if err != nil {
return err
}
err = validateCommonFlags(commandName)
if err != nil {
return err
}
err = readData(commandName)
if err != nil {
return err
}
if strings.Index(flags.csrOption, "file:") == 0 {
if flags.commonName != "" {
return fmt.Errorf("the '--cn' option cannot be used in --csr file: provided mode")
}
} else {
if flags.commonName == "" {
return fmt.Errorf("a Common Name is required for enrollment")
}
}
if flags.chainOption == "ignore" && flags.chainFile != "" {
return fmt.Errorf("the `--chain ignore` option cannot be used with --chain-file option")
}
if !flags.testMode && flags.config == "" {
zone := flags.zone
if zone == "" {
zone = getPropertyFromEnvironment(vCertZone)
}
if zone == "" {
return fmt.Errorf("a zone is required for requesting a certificate. You can set the zone using the -z flag")
}
if flags.validDays != "" {
valid := validateValidDaysFlag(commandName)
if !valid {
return fmt.Errorf("--valid-days is set but, it have an invalid format/data")
}
}
}
if flags.csrOption == "file" && flags.keyFile != "" { // Do not specify -key-file with -csr file as VCert cannot access the private key
return fmt.Errorf("--key-file cannot be used with -csr file as VCert cannot access the private key")
}
err = validatePKCS12Flags(commandName)
if err != nil {
return err
}
err = validateJKSFlags(commandName)
if err != nil {
return err
}
if flags.tlsAddress != "" && flags.instance == "" {
return fmt.Errorf("--tls-address cannot be used without --instance")
}
apiKey := flags.apiKey
if apiKey == "" {
apiKey = getPropertyFromEnvironment(vCertApiKey)
}
addrInstPresent := flags.tlsAddress != "" || flags.instance != ""
isCloud := apiKey != "" || flags.platform == venafi.TLSPCloud
if addrInstPresent && isCloud {
return fmt.Errorf("--instance and --tls-address are not applicable to Venafi as a Service platform")
}
return nil
}
func validateValidDaysFlag(cn string) bool {
if cn != "enroll" {
return false
}
if flags.validDays != "" {
validDays := flags.validDays
var regex = regexp.MustCompile("[1-9]+[0-9]*(#[DdEeMm])?")
return regex.MatchString(validDays)
}
return true
}
func validateCredMgmtFlags1(commandName string) error {
err := validateConnectionFlags(commandName)
if err != nil {
return err
}
err = validateCommonFlags(commandName)
if err != nil {
return err
}
err = readData(commandName)
if err != nil {
return err
}
return nil
}
func validateGenerateFlags1(commandName string) error {
err := validateCommonFlags(commandName)
if err != nil {
return err
}
err = readData(commandName)
if err != nil {
return err
}
// X.509 certificates must have either a Subject DN...
if flags.commonName != "" || len(flags.orgUnits) > 0 || flags.org != "" ||
flags.locality != "" || flags.state != "" || flags.country != "" {
return nil
}
// ...or at least one Subject Alternative Name
if len(flags.dnsSans) > 0 || len(flags.ipSans) > 0 || len(flags.emailSans) > 0 ||
len(flags.uriSans) > 0 || len(flags.upnSans) > 0 {
return nil
}
// the enrolling CA may have more strict requirements when the CSR is submitted
return fmt.Errorf("At least one Subject DN component or Subject Alternative Name value is required")
}
func validateRenewFlags1(commandName string) error {
err := validateConnectionFlags(commandName)
if err != nil {
return err
}
err = validateCommonFlags(commandName)
if err != nil {
return err
}
err = readData(commandName)
if err != nil {
return err
}
if flags.distinguishedName == "" && flags.thumbprint == "" {
return fmt.Errorf("-id or -thumbprint required to identify the certificate to renew")
}
if flags.distinguishedName != "" && flags.thumbprint != "" {
return fmt.Errorf("-id and -thumbprint cannot be used at the same time")
}
if flags.chainOption == "ignore" && flags.chainFile != "" {
return fmt.Errorf("The `-chain ignore` option cannot be used with -chain-file option")
}
if flags.csrOption == "service" {
if !(flags.noPickup) && flags.noPrompt && len(flags.keyPassword) == 0 && (flags.userName != "" || flags.token != "") {
return fmt.Errorf("-key-password cannot be empty in -csr service mode for TPP unless -no-pickup specified")
}
if flags.commonName != "" ||
flags.country != "" ||
flags.org != "" ||
flags.state != "" ||
flags.keySize != 0 ||
len(flags.orgUnits) > 0 ||
len(flags.dnsSans) > 0 ||
len(flags.emailSans) > 0 ||
len(flags.ipSans) > 0 {
return fmt.Errorf("Renewal with -csr=service does not allow options: " +
"-cn, -c, -o, -ou, -l, -st, -san-*, -key-type, -key-size")
}
}
if strings.HasPrefix(flags.csrOption, "file:") {
if flags.commonName != "" ||
flags.country != "" ||
flags.org != "" ||
flags.state != "" ||
flags.keySize != 0 ||
len(flags.orgUnits) > 0 ||
len(flags.dnsSans) > 0 ||
len(flags.emailSans) > 0 ||
len(flags.ipSans) > 0 {
return fmt.Errorf("Renewal with -csr file:CSR.pem does not allow options: " +
"-cn, -c, -o, -ou, -l, -st, -san-*, -key-type, -key-size")
}
}
if flags.csrOption == "" || flags.csrOption == "local" {
if flags.commonName != "" ||
flags.country != "" ||
flags.org != "" ||
flags.state != "" ||
flags.locality != "" ||
len(flags.orgUnits) > 0 {
return fmt.Errorf("Renewal does not allow options: -cn, -c, -o, -ou, -l, -st")
}
}
err = validatePKCS12Flags(commandName)
if err != nil {
return err
}
err = validateJKSFlags(commandName)
if err != nil {
return err
}
return nil
}
func validatePickupFlags1(commandName string) error {
err := validateConnectionFlags(commandName)
if err != nil {
return err
}
err = validateCommonFlags(commandName)
if err != nil {
return err
}
cloudSerViceGenerated := IsCSRServiceVaaSGenerated(commandName)
if cloudSerViceGenerated && flags.noPrompt && (flags.keyPassword == "") {
return fmt.Errorf("key-password is required")
}
err = readData(commandName)
if err != nil {
return err
}
if flags.pickupID == "" && flags.pickupIDFile == "" {
return fmt.Errorf("A Pickup ID is required to pickup a certificate provided by -pickup-id OR -pickup-id-file options")
}
if flags.pickupID != "" && flags.pickupIDFile != "" {
return fmt.Errorf("Both -pickup-id and -pickup-id-file options cannot be specified at the same time")
}
err = validatePKCS12Flags(commandName)
if err != nil {
return err
}
err = validateJKSFlags(commandName)
if err != nil {
return err
}
return nil
}
func validateRevokeFlags1(commandName string) error {
err := validateConnectionFlags(commandName)
if err != nil {
return err
}
err = validateCommonFlags(commandName)
if err != nil {
return err
}
err = readData(commandName)
if err != nil {
return err
}
if flags.distinguishedName == "" && flags.thumbprint == "" {
return fmt.Errorf("Certificate DN or Thumbprint is required to revoke the certificate")
}
if flags.distinguishedName != "" && flags.thumbprint != "" {
return fmt.Errorf("Either -id or -thumbprint can be used")
}
if flags.revocationReason != "" {
isValidReason := func(reason string) bool {
for _, v := range RevocationReasonOptions {
if v == reason {
return true
}
}
return false
}(flags.revocationReason)
if !isValidReason {
return fmt.Errorf("%s is not valid revocation reason. it should be one of %v", flags.revocationReason, RevocationReasonOptions)
}
}
return nil
}
func validateRetireFlags(commandName string) error {
err := validateConnectionFlags(commandName)
if err != nil {
return err
}
err = validateCommonFlags(commandName)
if err != nil {
return err
}
err = readData(commandName)
if err != nil {
return err
}
if flags.distinguishedName == "" && flags.thumbprint == "" {
return fmt.Errorf("Certificate DN or Thumbprint is required to revoke the certificate")
}
if flags.distinguishedName != "" && flags.thumbprint != "" {
return fmt.Errorf("Either -id or -thumbprint can be used")
}
return nil
}
func validateGetPolicyFlags(commandName string) error {
isPolicyConfigStarter := flags.policyConfigStarter
if isPolicyConfigStarter {
if flags.userName != "" || flags.password != "" || flags.token != "" || flags.apiKey != "" {
return fmt.Errorf("starter flag and credentials are set, please remove credentials to be able to use starter flag")
}
} else {
if flags.userName != "" && flags.password != "" && flags.token != "" && flags.apiKey != "" {
return fmt.Errorf("credentials are required")
}
if flags.policyName == "" {
return fmt.Errorf("zone is required")
}
}
return nil
}
func validateSetPolicyFlags(commandName string) error {
isVerifyPolicy := flags.verifyPolicyConfig
if isVerifyPolicy {
if flags.userName != "" || flags.password != "" || flags.token != "" || flags.apiKey != "" {
return fmt.Errorf("starter flag and credentials are set, please remove credentials to be able to use starter flag")
}
} else {
if flags.userName != "" && flags.password != "" && flags.token != "" && flags.apiKey != "" {
return fmt.Errorf("credentials are required")
}
if flags.policyName == "" {
return fmt.Errorf("zone is required")
}
if flags.policySpecLocation == "" {
return fmt.Errorf("a policy specification file is required")
}
}
return nil
}
func validateSshEnrollFlags(commandName string) error {
err := validateConnectionFlags(commandName)
if err != nil {
return err
}
if flags.sshCertTemplate == "" {
return fmt.Errorf("certificate issuing template value is required (--template)")
}
if flags.sshCertPubKey == "" {
return fmt.Errorf("public-key value is required")
} else {
pubKeyType := flags.sshCertPubKey
if pubKeyType != SshCertPubKeyServ && pubKeyType != SshCertPubKeyLocal && !strings.HasPrefix(pubKeyType, SshCertPubKeyFilePreff) {
return fmt.Errorf("public-key value: %s is not expected, please provide: service, local or file:path value", pubKeyType)
}
}
err = readData(commandName)
if err != nil {
return err
}
return nil
}
func validateGetSshConfigFlags(commandName string) error {
err := validateConnectionFlags(commandName)
if err != nil {
return err
}
if flags.sshCertTemplate == "" && flags.sshCertGuid == "" {
return fmt.Errorf("SSH certificate issuance template name (--template) or template guid (--guid) value is required")
}
return nil
}
func validateSshRetrieveFlags(commandName string) error {
err := validateConnectionFlags(commandName)
if err != nil {
return err
}
if flags.sshCertPickupId == "" && flags.sshCertGuid == "" {
return fmt.Errorf("please provide a pick up id or guid value")
}
err = readData(commandName)
if err != nil {
return err
}
return nil
}
func validateExistingFile(f string) error {
fileNames, err := getExistingSshFiles(f)
if err != nil {
return err
}
if len(fileNames) > 0 {
START:
fmt.Print("The following files already exists: ", fileNames, " would you like to override them? y/n: ")
reader := bufio.NewReader(os.Stdin)
text, err := reader.ReadString('\n')
if err != nil {
return err
}
text = strings.ToLower(text)
if !strings.HasPrefix(text, "y") {
if strings.HasPrefix(text, "n") {
return fmt.Errorf("user aborted operation")
} else {
goto START
}
}
}
return nil
}