main.go 5.5 KB

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