main.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. package main
  2. import (
  3. "bytes"
  4. "flag"
  5. "fmt"
  6. "io/ioutil"
  7. "log"
  8. "net/http"
  9. "os"
  10. "reflect"
  11. "regexp"
  12. "runtime"
  13. "time"
  14. "unicode"
  15. "github.com/pkg/errors"
  16. "github.com/smallstep/certificates/authority"
  17. "github.com/smallstep/certificates/ca"
  18. "github.com/smallstep/cli/errs"
  19. "github.com/smallstep/cli/usage"
  20. "github.com/urfave/cli"
  21. )
  22. // commit and buildTime are filled in during build by the Makefile
  23. var (
  24. BuildTime = "N/A"
  25. Version = "N/A"
  26. )
  27. // Version returns the current version of the binary.
  28. func version() string {
  29. out := Version
  30. if out == "N/A" {
  31. out = "0000000-dev"
  32. }
  33. return fmt.Sprintf("Smallstep CA/%s (%s/%s)",
  34. out, runtime.GOOS, runtime.GOARCH)
  35. }
  36. // ReleaseDate returns the time of when the binary was built.
  37. func releaseDate() string {
  38. out := BuildTime
  39. if out == "N/A" {
  40. out = time.Now().UTC().Format("2006-01-02 15:04 MST")
  41. }
  42. return out
  43. }
  44. // Print version and release date.
  45. func printFullVersion() {
  46. fmt.Printf("%s\n", version())
  47. fmt.Printf("Release Date: %s\n", releaseDate())
  48. }
  49. func main() {
  50. // Override global framework components
  51. cli.VersionPrinter = func(c *cli.Context) {
  52. printFullVersion()
  53. }
  54. cli.AppHelpTemplate = usage.AppHelpTemplate
  55. cli.SubcommandHelpTemplate = usage.SubcommandHelpTemplate
  56. cli.CommandHelpTemplate = usage.CommandHelpTemplate
  57. cli.HelpPrinter = usage.HelpPrinter
  58. cli.FlagNamePrefixer = usage.FlagNamePrefixer
  59. cli.FlagStringer = stringifyFlag
  60. // Configure cli app
  61. app := cli.NewApp()
  62. app.Name = "step-ca"
  63. app.HelpName = "step-ca"
  64. app.Version = version()
  65. app.Usage = "an online certificate authority for secure automated certificate management"
  66. app.UsageText = `**step-ca** <config> [**--password-file**=<file>] [**--version**]`
  67. app.Description = `**step-ca** runs the Step Online Certificate Authority
  68. (Step CA) using the given configuration.
  69. See the README.md for more detailed configuration documentation.
  70. ## POSITIONAL ARGUMENTS
  71. <config>
  72. : File that configures the operation of the Step CA; this file is generated
  73. when you initialize the Step CA using 'step ca init'
  74. ## EXIT CODES
  75. This command will run indefinitely on success and return \>0 if any error occurs.
  76. ## EXAMPLES
  77. These examples assume that you have already initialized your PKI by running
  78. 'step ca init'. If you have not completed this step please see the 'Getting Started'
  79. section of the README.
  80. Run the Step CA and prompt for password:
  81. '''
  82. $ step-ca $STEPPATH/config/ca.json
  83. '''
  84. Run the Step CA and read the password from a file - this is useful for
  85. automating deployment:
  86. '''
  87. $ step-ca $STEPPATH/config/ca.json --password-file ./password.txt
  88. '''`
  89. app.Flags = append(app.Flags, []cli.Flag{
  90. cli.StringFlag{
  91. Name: "password-file",
  92. Usage: `path to the <file> containing the password to decrypt the
  93. intermediate private key.`,
  94. },
  95. }...)
  96. app.Copyright = "(c) 2019 Smallstep Labs, Inc."
  97. // All non-successful output should be written to stderr
  98. app.Writer = os.Stdout
  99. app.ErrWriter = os.Stderr
  100. app.Commands = []cli.Command{
  101. {
  102. Name: "version",
  103. Usage: "Displays the current version of the cli",
  104. // Command prints out the current version of the tool
  105. Action: func(c *cli.Context) error {
  106. printFullVersion()
  107. return nil
  108. },
  109. },
  110. {
  111. Name: "help",
  112. Aliases: []string{"h"},
  113. Usage: "displays help for the specified command or command group",
  114. ArgsUsage: "",
  115. Action: usage.HelpCommandAction,
  116. },
  117. }
  118. // Start the golang debug logger if environment variable is set.
  119. // See https://golang.org/pkg/net/http/pprof/
  120. debugProfAddr := os.Getenv("STEP_PROF_ADDR")
  121. if debugProfAddr != "" {
  122. go func() {
  123. log.Println(http.ListenAndServe(debugProfAddr, nil))
  124. }()
  125. }
  126. app.Action = func(ctx *cli.Context) error {
  127. // Hack to be able to run a the top action as a subcommand
  128. cmd := cli.Command{Name: "start", Action: startAction, Flags: app.Flags}
  129. set := flag.NewFlagSet(app.Name, flag.ContinueOnError)
  130. set.Parse(os.Args)
  131. ctx = cli.NewContext(app, set, nil)
  132. return cmd.Run(ctx)
  133. }
  134. if err := app.Run(os.Args); err != nil {
  135. if os.Getenv("STEPDEBUG") == "1" {
  136. fmt.Fprintf(os.Stderr, "%+v\n", err)
  137. } else {
  138. fmt.Fprintln(os.Stderr, err)
  139. }
  140. os.Exit(1)
  141. }
  142. }
  143. func startAction(ctx *cli.Context) error {
  144. passFile := ctx.String("password-file")
  145. // If zero cmd line args show help, if >1 cmd line args show error.
  146. if ctx.NArg() == 0 {
  147. return cli.ShowAppHelp(ctx)
  148. }
  149. if err := errs.NumberOfArguments(ctx, 1); err != nil {
  150. return err
  151. }
  152. configFile := ctx.Args().Get(0)
  153. config, err := authority.LoadConfiguration(configFile)
  154. if err != nil {
  155. fatal(err)
  156. }
  157. var password []byte
  158. if passFile != "" {
  159. if password, err = ioutil.ReadFile(passFile); err != nil {
  160. fatal(errors.Wrapf(err, "error reading %s", passFile))
  161. }
  162. password = bytes.TrimRightFunc(password, unicode.IsSpace)
  163. }
  164. srv, err := ca.New(config, ca.WithConfigFile(configFile), ca.WithPassword(password))
  165. if err != nil {
  166. fatal(err)
  167. }
  168. go ca.StopReloaderHandler(srv)
  169. if err = srv.Run(); err != nil && err != http.ErrServerClosed {
  170. fatal(err)
  171. }
  172. return nil
  173. }
  174. // fatal writes the passed error on the standard error and exits with the exit
  175. // code 1. If the environment variable STEPDEBUG is set to 1 it shows the
  176. // stack trace of the error.
  177. func fatal(err error) {
  178. if os.Getenv("STEPDEBUG") == "1" {
  179. fmt.Fprintf(os.Stderr, "%+v\n", err)
  180. } else {
  181. fmt.Fprintln(os.Stderr, err)
  182. }
  183. os.Exit(2)
  184. }
  185. func flagValue(f cli.Flag) reflect.Value {
  186. fv := reflect.ValueOf(f)
  187. for fv.Kind() == reflect.Ptr {
  188. fv = reflect.Indirect(fv)
  189. }
  190. return fv
  191. }
  192. var placeholderString = regexp.MustCompile(`<.*?>`)
  193. func stringifyFlag(f cli.Flag) string {
  194. fv := flagValue(f)
  195. usage := fv.FieldByName("Usage").String()
  196. placeholder := placeholderString.FindString(usage)
  197. if placeholder == "" {
  198. placeholder = "<value>"
  199. }
  200. return cli.FlagNamePrefixer(fv.FieldByName("Name").String(), placeholder) + "\t" + usage
  201. }