| 1 | package certificate |
| 2 | |
| 3 | import ( |
| 4 | "encoding/pem" |
| 5 | "io/ioutil" |
| 6 | |
| 7 | "github.com/pkg/errors" |
| 8 | "github.com/smallstep/cli/command" |
| 9 | "github.com/smallstep/cli/errs" |
| 10 | "github.com/smallstep/cli/flags" |
| 11 | "github.com/smallstep/cli/ui" |
| 12 | "github.com/smallstep/cli/utils" |
| 13 | "github.com/urfave/cli" |
| 14 | ) |
| 15 | |
| 16 | func bundleCommand() cli.Command { |
| 17 | return cli.Command{ |
| 18 | Name: "bundle", |
| 19 | Action: command.ActionFunc(bundleAction), |
| 20 | Usage: `bundle a certificate with intermediate certificate(s) needed for certificate path validation`, |
| 21 | UsageText: `**step certificate bundle** <crt_file> <ca> <bundle_file>`, |
| 22 | Description: `**step certificate bundle** bundles a certificate |
| 23 | with any intermediates necessary to validate the certificate. |
| 24 | |
| 25 | ## POSITIONAL ARGUMENTS |
| 26 | |
| 27 | <crt_file> |
| 28 | : The path to a leaf certificate to bundle with issuing certificate(s). |
| 29 | |
| 30 | <ca> |
| 31 | : The path to the Certificate Authority issusing certificate. |
| 32 | |
| 33 | <bundle_file> |
| 34 | : The path to write the bundle. |
| 35 | |
| 36 | ## EXIT CODES |
| 37 | |
| 38 | This command returns 0 on success and \>0 if any error occurs. |
| 39 | |
| 40 | ## EXAMPLES |
| 41 | |
| 42 | Bundle a certificate with the intermediate certificate authority (issuer): |
| 43 | |
| 44 | ''' |
| 45 | $ step certificate bundle foo.crt intermediate-ca.crt foo-bundle.crt |
| 46 | ''' |
| 47 | `, |
| 48 | Flags: []cli.Flag{flags.Force}, |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | func bundleAction(ctx *cli.Context) error { |
| 53 | if err := errs.NumberOfArguments(ctx, 3); err != nil { |
| 54 | return err |
| 55 | } |
| 56 | |
| 57 | crtFile := ctx.Args().Get(0) |
| 58 | crtBytes, err := ioutil.ReadFile(crtFile) |
| 59 | if err != nil { |
| 60 | return errs.FileError(err, crtFile) |
| 61 | } |
| 62 | crtBlock, _ := pem.Decode(crtBytes) |
| 63 | if crtBlock == nil { |
| 64 | return errors.Errorf("could not parse certificate file '%s'", crtFile) |
| 65 | } |
| 66 | |
| 67 | caFile := ctx.Args().Get(1) |
| 68 | caBytes, err := ioutil.ReadFile(caFile) |
| 69 | if err != nil { |
| 70 | return errs.FileError(err, caFile) |
| 71 | } |
| 72 | caBlock, _ := pem.Decode(caBytes) |
| 73 | if caBlock == nil { |
| 74 | return errors.Errorf("could not parse certificate file '%s'", caFile) |
| 75 | } |
| 76 | |
| 77 | chainFile := ctx.Args().Get(2) |
| 78 | if err := utils.WriteFile(chainFile, |
| 79 | append(pem.EncodeToMemory(crtBlock), pem.EncodeToMemory(caBlock)...), 0600); err != nil { |
| 80 | return err |
| 81 | } |
| 82 | |
| 83 | ui.Printf("Your certificate has been saved in %s.\n", chainFile) |
| 84 | return nil |
| 85 | } |