-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
621 lines (555 loc) · 14.2 KB
/
main.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
package main
import (
"encoding/json"
"fmt"
"math/rand"
"os"
"path/filepath"
"time"
"github.com/joho/godotenv"
"github.com/trisacrypto/directory/pkg"
"github.com/trisacrypto/directory/pkg/sectigo"
"github.com/trisacrypto/directory/pkg/sectigo/server"
"github.com/urfave/cli/v2"
)
var (
api *sectigo.Sectigo
encoder *json.Encoder
)
func main() {
// Load the dotenv file if it exists
godotenv.Load()
app := cli.NewApp()
app.Name = "sectigo"
app.Version = pkg.Version()
app.Usage = "CLI helper for Sectigo API access and debugging"
app.Before = initAPI
app.Flags = []cli.Flag{
&cli.StringFlag{
Name: "username",
Aliases: []string{"u"},
Usage: "API access login username",
EnvVars: []string{sectigo.UsernameEnv},
},
&cli.StringFlag{
Name: "password",
Aliases: []string{"p"},
Usage: "API access login password",
EnvVars: []string{sectigo.PasswordEnv},
},
&cli.StringFlag{
Name: "profile",
Aliases: []string{"P"},
Usage: "Specify the profile to use for certificate requests",
EnvVars: []string{sectigo.ProfileEnv},
},
&cli.StringFlag{
Name: "environment",
Aliases: []string{"E", "env"},
Usage: "Specify the environment that the Sectigo/cathy server is running in",
EnvVars: []string{sectigo.EnvironmentEnv},
},
&cli.StringFlag{
Name: "endpoint",
Aliases: []string{"e", "url"},
Usage: "Specify endpoint to connect to Sectigo on",
EnvVars: []string{sectigo.EndpointEnv},
},
}
app.Commands = []*cli.Command{
{
Name: "auth",
Usage: "check authentication status with server",
Action: auth,
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "debug",
Aliases: []string{"d"},
Usage: "do not refresh or authenticate, print state and exit",
},
&cli.BoolFlag{
Name: "cache",
Aliases: []string{"C"},
Usage: "print cache location and exit",
},
},
},
{
Name: "create",
Usage: "create single certificate batch",
Action: createSingle,
Flags: []cli.Flag{
&cli.IntFlag{
Name: "authority",
Aliases: []string{"a"},
Usage: "id of the authority or profile to issue the cert",
},
&cli.StringFlag{
Name: "domain",
Aliases: []string{"d"},
Usage: "common name of the subject to issue the cert for",
},
&cli.StringFlag{
Name: "password",
Aliases: []string{"p"},
Usage: "password for script (automatically generated by default)",
},
&cli.StringFlag{
Name: "country",
Aliases: []string{"c"},
Usage: "two-letter ISO 3166-1 country code",
},
&cli.StringFlag{
Name: "state",
Aliases: []string{"s"},
Usage: "state or province name",
},
&cli.StringFlag{
Name: "locality",
Aliases: []string{"l"},
Usage: "city or locality name",
},
&cli.StringFlag{
Name: "batch-name",
Aliases: []string{"b"},
Usage: "description of the batch for review purposes",
},
},
},
{
Name: "upload",
Usage: "upload a certificate signing request",
ArgsUsage: "request.csr",
Action: uploadCSR,
Flags: []cli.Flag{
&cli.IntFlag{
Name: "profile",
Aliases: []string{"p"},
Usage: "profile/authority id of the cert issuer",
},
},
},
{
Name: "batches",
Usage: "view batch jobs for certificate creation",
Action: batches,
Flags: []cli.Flag{
&cli.IntFlag{
Name: "id",
Aliases: []string{"i"},
Usage: "if specified get detail for batch with id",
},
&cli.BoolFlag{
Name: "info",
Aliases: []string{"I"},
Usage: "get batch processing info",
},
&cli.BoolFlag{
Name: "status",
Aliases: []string{"s"},
Usage: "get batch processing status (text description)",
},
},
},
{
Name: "download",
Usage: "download batch as a ZIP file",
Action: download,
Flags: []cli.Flag{
&cli.IntFlag{
Name: "id",
Aliases: []string{"i"},
Usage: "the batch ID to download",
},
&cli.StringFlag{
Name: "outdir",
Aliases: []string{"o"},
Usage: "the directory to download the zip file to",
},
},
},
{
Name: "licenses",
Usage: "view the ordered/issued certificates",
Action: licenses,
Flags: []cli.Flag{},
},
{
Name: "authorities",
Usage: "view the current users authorities by ecosystem",
Action: authorities,
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "balances",
Aliases: []string{"b"},
Usage: "also fetch balance for each authority",
},
},
},
{
Name: "profiles",
Usage: "view profiles available to the user",
Action: profiles,
Flags: []cli.Flag{
&cli.IntFlag{
Name: "id",
Aliases: []string{"i"},
Usage: "if specified get detail for profile with id",
},
&cli.BoolFlag{
Name: "params",
Aliases: []string{"p"},
Usage: "if specified, get params for profile with id",
},
},
},
{
Name: "organization",
Usage: "view organization of the current user",
Action: organization,
Flags: []cli.Flag{},
},
{
Name: "find",
Usage: "search for certs by common name and serial number",
Action: findCert,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "common-name",
Aliases: []string{"n"},
Usage: "search by common name",
},
&cli.StringFlag{
Name: "serial-number",
Usage: "search by serial number",
Aliases: []string{"s"},
},
},
},
{
Name: "revoke",
Usage: "revoke a certificate by serial number",
Action: revokeCert,
Flags: []cli.Flag{
&cli.IntFlag{
Name: "profile",
Usage: "profile/authority id of the cert issuer",
Aliases: []string{"p"},
},
&cli.StringFlag{
Name: "reason",
Aliases: []string{"r"},
Usage: "RFC 5280 reason text",
},
&cli.StringFlag{
Name: "serial-number",
Aliases: []string{"s"},
Usage: "serial number of the cert to revoke",
},
},
},
{
Name: "serve",
Usage: "run the sectigo integration api server for testing",
Action: serve,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "addr",
Aliases: []string{"a"},
Usage: "specify the bind addr for the api server",
EnvVars: []string{"SIAS_BIND_ADDR"},
},
},
},
{
Name: "validate",
Usage: "validate the current server configuration",
Action: validate,
},
}
app.Run(os.Args)
}
func initAPI(c *cli.Context) (err error) {
conf := sectigo.Config{
Username: c.String("username"),
Password: c.String("password"),
Profile: c.String("profile"),
Endpoint: c.String("endpoint"),
Environment: c.String("environment"),
}
if api, err = sectigo.New(conf); err != nil {
return cli.Exit(err, 1)
}
encoder = json.NewEncoder(os.Stdout)
encoder.SetIndent("", " ")
return nil
}
func auth(c *cli.Context) (err error) {
creds := api.Creds()
if c.Bool("cache") {
if cacheFile := creds.CacheFile(); cacheFile != "" {
fmt.Println(cacheFile)
} else {
fmt.Println("no credentials cache file exists")
}
return nil
}
if c.Bool("debug") {
if creds.Valid() {
fmt.Printf("credentials are valid until %s\n", creds.ExpiresAt)
return nil
}
if creds.Current() {
fmt.Printf("credentials are current until %s\n", creds.RefreshBy)
return nil
}
fmt.Println("credentials are expired or invalid")
return nil
}
if !creds.Valid() {
if creds.Refreshable() {
if err = api.Refresh(); err != nil {
return cli.Exit(err, 1)
}
} else {
if err = api.Authenticate(); err != nil {
return cli.Exit(err, 1)
}
}
}
fmt.Println("user authenticated and credentials cached")
return nil
}
func createSingle(c *cli.Context) (err error) {
domain := c.String("domain")
if domain == "" {
return cli.Exit("must specify domain name of cert subject", 1)
}
authority := c.Int("authority")
if authority == 0 {
return cli.Exit("must specify authority ID", 1)
}
params := make(map[string]string)
params["commonName"] = domain
params["dNSName"] = domain
params["pkcs12Password"] = c.String("password")
if params["pkcs12Password"] == "" {
params["pkcs12Password"] = randomPassword(10)
fmt.Printf("pkcs12 password: %s\n", params["pkcs12Password"])
}
if api.Profile() == sectigo.ProfileCipherTraceEndEntityCertificate || api.Profile() == sectigo.ProfileIDCipherTraceEndEntityCertificate {
params["localityName"] = c.String("locality")
params["stateOrProvinceName"] = c.String("state")
params["countryName"] = c.String("country")
}
batchName := c.String("batch-name")
if batchName == "" {
batchName = fmt.Sprintf("new certs for %s", domain)
}
var rep *sectigo.BatchResponse
if rep, err = api.CreateSingleCertBatch(authority, batchName, params); err != nil {
return cli.Exit(err, 1)
}
printJSON(rep)
return nil
}
func uploadCSR(c *cli.Context) (err error) {
if c.NArg() != 1 {
return cli.Exit("specify the path to one CSR for upload", 1)
}
path := c.Args().First()
filename := filepath.Base(path)
// Create the request parameters
profileId := c.Int("profile")
params := make(map[string]string)
if profileId == 0 {
return cli.Exit("specify the profile ID to sign the cert under", 1)
}
// Load the CSR data from the file
var csrData []byte
if csrData, err = os.ReadFile(path); err != nil {
return cli.Exit(fmt.Errorf("could not read %s: %s", path, err), 1)
}
var rep *sectigo.BatchResponse
if rep, err = api.UploadCSRBatch(profileId, filename, csrData, params); err != nil {
return cli.Exit(err, 1)
}
printJSON(rep)
return nil
}
func batches(c *cli.Context) (err error) {
id := c.Int("id")
if id != 0 {
// Perform batch detail lookup
if c.Bool("info") {
var rep *sectigo.ProcessingInfoResponse
if rep, err = api.ProcessingInfo(id); err != nil {
return cli.Exit(err, 1)
}
printJSON(rep)
return nil
}
// Perform text status lookup
if c.Bool("status") {
var status string
if status, err = api.BatchStatus(id); err != nil {
return cli.Exit(err, 1)
}
fmt.Println(status)
return nil
}
var rep *sectigo.BatchResponse
if rep, err = api.BatchDetail(id); err != nil {
return cli.Exit(err, 1)
}
printJSON(rep)
return nil
}
return cli.Exit("specify batch id to get information", 1)
}
func download(c *cli.Context) (err error) {
outdir := c.String("outdir")
batch := c.Int("id")
if batch == 0 {
return cli.Exit("must specify batch id for download", 1)
}
var path string
if path, err = api.Download(batch, outdir); err != nil {
return cli.Exit(err, 1)
}
fmt.Printf("downloaded batch %d to %s\n", batch, path)
fmt.Println("after unzipping, unencrypt with your password using `openssl pkcs12 -in INFILE.p12 -out OUTFILE.crt -nodes`")
return nil
}
func licenses(c *cli.Context) (err error) {
var rep *sectigo.LicensesUsedResponse
if rep, err = api.LicensesUsed(); err != nil {
return cli.Exit(err, 1)
}
printJSON(rep)
return nil
}
func authorities(c *cli.Context) (err error) {
var rep []*sectigo.AuthorityResponse
if rep, err = api.UserAuthorities(); err != nil {
return cli.Exit(err, 1)
}
// Print the authority details
printJSON(rep)
if c.Bool("balances") {
// Fetch the balances for each authority and print them
balances := make(map[int]int)
for _, authority := range rep {
if balances[authority.ID], err = api.AuthorityAvailableBalance(authority.ID); err != nil {
return cli.Exit(err, 1)
}
}
printJSON(balances)
}
return nil
}
func profiles(c *cli.Context) (err error) {
pid := c.Int("id")
if pid != 0 {
// Perform a detail request instead of a list request
// Get params detail for the profile
if c.Bool("params") {
var rep []*sectigo.ProfileParamsResponse
if rep, err = api.ProfileParams(pid); err != nil {
return cli.Exit(err, 1)
}
printJSON(rep)
return nil
}
// Get profile extended information
var rep *sectigo.ProfileDetailResponse
if rep, err = api.ProfileDetail(pid); err != nil {
return cli.Exit(err, 1)
}
printJSON(rep)
return nil
}
if c.Bool("params") {
return cli.Exit("must specify id to get profile params", 1)
}
var rep []*sectigo.ProfileResponse
if rep, err = api.Profiles(); err != nil {
return cli.Exit(err, 1)
}
printJSON(rep)
return nil
}
func organization(c *cli.Context) (err error) {
var rep *sectigo.OrganizationResponse
if rep, err = api.Organization(); err != nil {
return cli.Exit(err, 1)
}
printJSON(rep)
return nil
}
func findCert(c *cli.Context) (err error) {
var rep *sectigo.FindCertificateResponse
if rep, err = api.FindCertificate(c.String("common-name"), c.String("serial-number")); err != nil {
return cli.Exit(err, 1)
}
printJSON(rep)
return nil
}
func revokeCert(c *cli.Context) (err error) {
pid := c.Int("profile")
if pid == 0 {
return cli.Exit("must specify profile id", 1)
}
var reasonCode sectigo.CRLReason
if reasonCode, err = sectigo.RevokeReasonCode(c.String("reason")); err != nil {
return cli.Exit(err, 1)
}
sn := c.String("serial-number")
if sn == "" {
return cli.Exit("must specify serial number of certificate", 1)
}
if err = api.RevokeCertificate(pid, int(reasonCode), sn); err != nil {
return cli.Exit(err, 1)
}
return nil
}
func serve(c *cli.Context) (err error) {
var conf server.Config
if conf, err = server.NewConfig(); err != nil {
return cli.Exit(err, 1)
}
if addr := c.String("addr"); addr != "" {
conf.BindAddr = addr
}
var srv *server.Server
if srv, err = server.New(conf); err != nil {
return cli.Exit(err, 1)
}
if err = srv.Serve(); err != nil {
return cli.Exit(err, 1)
}
return nil
}
// validate checks the current trtl configuration and prints the status.
func validate(c *cli.Context) (err error) {
var conf server.Config
if conf, err = server.NewConfig(); err != nil {
return cli.Exit(err, 1)
}
return printJSON(conf)
}
func printJSON(data interface{}) (err error) {
if err = encoder.Encode(data); err != nil {
return err
}
return nil
}
const pwcharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&*-<>~"
func randomPassword(length int) string {
seededRand := rand.New(rand.NewSource(time.Now().UnixNano()))
buf := make([]byte, length)
for i := range buf {
buf[i] = pwcharset[seededRand.Intn(len(pwcharset))]
}
return string(buf)
}