cloudflare/cfssl_trust

Public

mirrored fromhttps://github.com/cloudflare/cfssl_trustAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
trust-store-2026.1.2

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

cli/bundle.go

97lines · modecode

1package cli
2
3import (
4 "bytes"
5 "database/sql"
6 "encoding/pem"
7 "fmt"
8 "io/ioutil"
9 "os"
10
11 "github.com/cloudflare/cfssl_trust/model/certdb"
12 "github.com/spf13/cobra"
13 "github.com/spf13/viper"
14)
15
16var bundleCmd = &cobra.Command{
17 Use: "bundle",
18 Short: "Emit a certificate bundle.",
19 Long: `Emit either a root or intermediate bundle for a given release. If given a
20filename, the bundle will be written to that file.`,
21 Run: buildBundle,
22}
23
24func init() {
25 rootCmd.AddCommand(bundleCmd)
26}
27
28func encodeBundle(certs []*certdb.Certificate) string {
29 var buf = &bytes.Buffer{}
30 for _, cert := range certs {
31 p := &pem.Block{
32 Type: "CERTIFICATE",
33 Bytes: cert.Raw,
34 }
35
36 err := pem.Encode(buf, p)
37 if err != nil {
38 // A bytes.Buffer write should never fail.
39 panic("cfssl-trust: write to *bytes.Buffer should never fail")
40 }
41 }
42
43 return buf.String()
44}
45
46func buildBundle(cmd *cobra.Command, args []string) {
47 dbPath := viper.GetString("database.path")
48 db, err := sql.Open("sqlite3", dbPath)
49 if err != nil {
50 fmt.Fprintf(os.Stderr, "[!] %s\n", err)
51 os.Exit(1)
52 }
53
54 tx, err := db.Begin()
55 if err != nil {
56 if err != nil {
57 fmt.Fprintf(os.Stderr, "[!] %s\n", err)
58 os.Exit(1)
59 }
60 }
61 defer func() {
62 if err == nil {
63 err = tx.Commit()
64 if err != nil {
65 fmt.Fprintf(os.Stderr, "[!] failed to commit transaction: %s\n", err)
66 os.Exit(1)
67 }
68 } else {
69 tx.Rollback()
70 }
71 }()
72
73 certs, err := certdb.CollectRelease(bundle, bundleRelease, tx)
74 if err != nil {
75 fmt.Fprintf(os.Stderr, "[!] %s\n", err)
76 os.Exit(1)
77 }
78
79 fmt.Printf("Selected %d certificates for this release.\n", len(certs))
80
81 pemBundle := encodeBundle(certs)
82 switch len(args) {
83 case 0:
84 fmt.Println(pemBundle)
85 case 1:
86 err = ioutil.WriteFile(args[0], []byte(pemBundle), 0644)
87 if err != nil {
88 fmt.Fprintf(os.Stderr, "[!] %s\n", err)
89 os.Exit(1)
90 }
91 default:
92 fmt.Fprintf(os.Stderr, `[!] %d arguments were passed to 'bundle, but the command only accepts a
93 single, optional file name. Refusing to proceed.`, len(args))
94 os.Exit(1)
95 }
96
97}