-
Notifications
You must be signed in to change notification settings - Fork 317
Add step certificate unbundle subcommand
#1685
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
+276
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
141 changes: 141 additions & 0 deletions
command/certificate/unbundle.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,141 @@ | ||
| package certificate | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "crypto/x509" | ||
| "encoding/pem" | ||
| "os" | ||
|
|
||
| "github.com/pkg/errors" | ||
| "github.com/urfave/cli" | ||
| "go.step.sm/crypto/pemutil" | ||
|
|
||
| "github.com/smallstep/cli-utils/command" | ||
| "github.com/smallstep/cli-utils/errs" | ||
| "github.com/smallstep/cli-utils/fileutil" | ||
| "github.com/smallstep/cli-utils/ui" | ||
|
|
||
| "github.com/smallstep/cli/flags" | ||
| "github.com/smallstep/cli/utils" | ||
| ) | ||
|
|
||
| func unbundleCommand() cli.Command { | ||
| return cli.Command{ | ||
| Name: "unbundle", | ||
| Action: command.ActionFunc(unbundleAction), | ||
| Usage: `split a bundle of certificates into its leaf and intermediates`, | ||
| UsageText: `**step certificate unbundle** <crt-file> [**--leaf**] [**--intermediate**] [**--out**=<file>]`, | ||
| Description: `**step certificate unbundle** splits a certificate bundle into the leaf | ||
| certificate and its intermediates. It's the inverse of **step certificate bundle**. | ||
|
|
||
| The first certificate in the bundle is treated as the leaf; everything after it is | ||
| treated as the intermediate chain. Pass --leaf or --intermediate to pick which part | ||
| to output. Without --out the result is printed to STDOUT, otherwise it's written to | ||
| the given file. | ||
|
|
||
| ## POSITIONAL ARGUMENTS | ||
|
|
||
| <crt-file> | ||
| : Path to a certificate bundle. A hyphen ("-") indicates STDIN. | ||
|
|
||
| ## EXIT CODES | ||
|
|
||
| This command returns 0 on success and \>0 if any error occurs. | ||
|
|
||
| ## EXAMPLES | ||
|
|
||
| Print the leaf certificate from a bundle: | ||
| ''' | ||
| $ step certificate unbundle --leaf bundle.crt | ||
| ''' | ||
|
|
||
| Print the intermediate chain from a bundle: | ||
| ''' | ||
| $ step certificate unbundle --intermediate bundle.crt | ||
| ''' | ||
|
|
||
| Write the leaf certificate to a file: | ||
| ''' | ||
| $ step certificate unbundle --leaf --out leaf.crt bundle.crt | ||
| ''' | ||
|
|
||
| Write the intermediate chain to a file: | ||
| ''' | ||
| $ step certificate unbundle --intermediate --out intermediate.crt bundle.crt | ||
| ''' | ||
| `, | ||
| Flags: []cli.Flag{ | ||
| cli.BoolFlag{ | ||
| Name: "leaf", | ||
| Usage: `Output the leaf (first) certificate in the bundle.`, | ||
| }, | ||
| cli.BoolFlag{ | ||
| Name: "intermediate", | ||
| Usage: `Output the intermediate certificate chain (everything after the leaf).`, | ||
| }, | ||
| cli.StringFlag{ | ||
| Name: "out", | ||
| Usage: `Path to write the selected certificate(s). Defaults to STDOUT.`, | ||
| }, | ||
| flags.Force, | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| func unbundleAction(ctx *cli.Context) error { | ||
| if err := errs.NumberOfArguments(ctx, 1); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| leaf := ctx.Bool("leaf") | ||
| intermediate := ctx.Bool("intermediate") | ||
| switch { | ||
| case leaf && intermediate: | ||
| return errs.IncompatibleFlagWithFlag(ctx, "leaf", "intermediate") | ||
| case !leaf && !intermediate: | ||
| return errs.RequiredOrFlag(ctx, "leaf", "intermediate") | ||
| } | ||
|
|
||
| crtFile := ctx.Args().First() | ||
| b, err := utils.ReadFile(crtFile) | ||
| if err != nil { | ||
| return errs.FileError(err, crtFile) | ||
| } | ||
|
|
||
| certs, err := pemutil.ParseCertificateBundle(b) | ||
| if err != nil { | ||
| return errors.Wrapf(err, "error parsing %s", crtFile) | ||
| } | ||
|
|
||
| var selected []*x509.Certificate | ||
| if leaf { | ||
| selected = certs[:1] | ||
| } else { | ||
| selected = certs[1:] | ||
| if len(selected) == 0 { | ||
| return errors.Errorf("%s does not contain any intermediate certificates", crtFile) | ||
| } | ||
| } | ||
|
|
||
| var buf bytes.Buffer | ||
| for _, crt := range selected { | ||
| if err := pem.Encode(&buf, &pem.Block{ | ||
| Type: "CERTIFICATE", | ||
| Bytes: crt.Raw, | ||
| }); err != nil { | ||
| return errors.Wrap(err, "error encoding certificate") | ||
| } | ||
| } | ||
|
|
||
| out := ctx.String("out") | ||
| if out == "" { | ||
| os.Stdout.Write(buf.Bytes()) | ||
| return nil | ||
| } | ||
|
|
||
| if err := fileutil.WriteFile(out, buf.Bytes(), 0o600); err != nil { | ||
| return err | ||
| } | ||
| ui.Printf("Your certificate has been saved in %s.\n", out) | ||
| return nil | ||
| } |
129 changes: 129 additions & 0 deletions
command/certificate/unbundle_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| package certificate | ||
|
|
||
| import ( | ||
| "crypto/ecdsa" | ||
| "crypto/elliptic" | ||
| "crypto/rand" | ||
| "crypto/x509" | ||
| "crypto/x509/pkix" | ||
| "encoding/pem" | ||
| "flag" | ||
| "math/big" | ||
| "os" | ||
| "path/filepath" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/smallstep/assert" | ||
| "github.com/urfave/cli" | ||
| "go.step.sm/crypto/pemutil" | ||
| ) | ||
|
|
||
| func testCertPEM(t *testing.T, cn string) []byte { | ||
| t.Helper() | ||
| priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) | ||
| assert.FatalError(t, err) | ||
| tmpl := &x509.Certificate{ | ||
| SerialNumber: big.NewInt(time.Now().UnixNano()), | ||
| Subject: pkix.Name{CommonName: cn}, | ||
| NotBefore: time.Now(), | ||
| NotAfter: time.Now().Add(time.Hour), | ||
| } | ||
| der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &priv.PublicKey, priv) | ||
| assert.FatalError(t, err) | ||
| return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) | ||
| } | ||
|
|
||
| func runUnbundle(t *testing.T, crtFile, out string, leaf, intermediate bool) error { | ||
| t.Helper() | ||
| set := flag.NewFlagSet("unbundle", 0) | ||
| set.Bool("leaf", false, "") | ||
| set.Bool("intermediate", false, "") | ||
| set.String("out", "", "") | ||
| set.Bool("force", false, "") | ||
|
|
||
| args := []string{} | ||
| if leaf { | ||
| args = append(args, "--leaf") | ||
| } | ||
| if intermediate { | ||
| args = append(args, "--intermediate") | ||
| } | ||
| if out != "" { | ||
| args = append(args, "--out", out) | ||
| } | ||
| args = append(args, crtFile) | ||
| assert.FatalError(t, set.Parse(args)) | ||
|
|
||
| return unbundleAction(cli.NewContext(&cli.App{}, set, nil)) | ||
| } | ||
|
|
||
| func TestUnbundle(t *testing.T) { | ||
| dir := t.TempDir() | ||
|
|
||
| leafPEM := testCertPEM(t, "leaf.example.com") | ||
| interPEM := testCertPEM(t, "intermediate.example.com") | ||
|
|
||
| bundle := append(append([]byte{}, leafPEM...), interPEM...) | ||
| bundleFile := filepath.Join(dir, "bundle.crt") | ||
| assert.FatalError(t, os.WriteFile(bundleFile, bundle, 0o600)) | ||
|
|
||
| singleFile := filepath.Join(dir, "single.crt") | ||
| assert.FatalError(t, os.WriteFile(singleFile, leafPEM, 0o600)) | ||
|
|
||
| badFile := filepath.Join(dir, "bad.crt") | ||
| assert.FatalError(t, os.WriteFile(badFile, []byte("not a certificate"), 0o600)) | ||
|
|
||
| t.Run("leaf from bundle", func(t *testing.T) { | ||
| out := filepath.Join(dir, "leaf-out.crt") | ||
| assert.FatalError(t, runUnbundle(t, bundleFile, out, true, false)) | ||
| certs := readBundle(t, out) | ||
| assert.Equals(t, 1, len(certs)) | ||
| assert.Equals(t, "leaf.example.com", certs[0].Subject.CommonName) | ||
| }) | ||
|
|
||
| t.Run("intermediate from bundle", func(t *testing.T) { | ||
| out := filepath.Join(dir, "inter-out.crt") | ||
| assert.FatalError(t, runUnbundle(t, bundleFile, out, false, true)) | ||
| certs := readBundle(t, out) | ||
| assert.Equals(t, 1, len(certs)) | ||
| assert.Equals(t, "intermediate.example.com", certs[0].Subject.CommonName) | ||
| }) | ||
|
|
||
| t.Run("leaf from single cert", func(t *testing.T) { | ||
| out := filepath.Join(dir, "single-out.crt") | ||
| assert.FatalError(t, runUnbundle(t, singleFile, out, true, false)) | ||
| certs := readBundle(t, out) | ||
| assert.Equals(t, 1, len(certs)) | ||
| assert.Equals(t, "leaf.example.com", certs[0].Subject.CommonName) | ||
| }) | ||
|
|
||
| t.Run("intermediate from single cert errors", func(t *testing.T) { | ||
| err := runUnbundle(t, singleFile, filepath.Join(dir, "nope.crt"), false, true) | ||
| assert.Error(t, err) | ||
| }) | ||
|
|
||
| t.Run("bad input errors", func(t *testing.T) { | ||
| err := runUnbundle(t, badFile, filepath.Join(dir, "nope2.crt"), true, false) | ||
| assert.Error(t, err) | ||
| }) | ||
|
|
||
| t.Run("no selector errors", func(t *testing.T) { | ||
| err := runUnbundle(t, bundleFile, "", false, false) | ||
| assert.Error(t, err) | ||
| }) | ||
|
|
||
| t.Run("both selectors error", func(t *testing.T) { | ||
| err := runUnbundle(t, bundleFile, "", true, true) | ||
| assert.Error(t, err) | ||
| }) | ||
| } | ||
|
|
||
| func readBundle(t *testing.T, file string) []*x509.Certificate { | ||
| t.Helper() | ||
| b, err := os.ReadFile(file) | ||
| assert.FatalError(t, err) | ||
| certs, err := pemutil.ParseCertificateBundle(b) | ||
| assert.FatalError(t, err) | ||
| return certs | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.