main.go 7.4 KB

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