main.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "html"
  6. "log"
  7. "math/rand"
  8. "net/http"
  9. "os"
  10. "reflect"
  11. "regexp"
  12. "strconv"
  13. "time"
  14. // Server profiler
  15. //nolint:gosec // profile server, if enabled runs on a different port
  16. _ "net/http/pprof"
  17. "github.com/smallstep/certificates/authority"
  18. "github.com/smallstep/certificates/commands"
  19. "github.com/urfave/cli"
  20. "go.step.sm/cli-utils/command"
  21. "go.step.sm/cli-utils/command/version"
  22. "go.step.sm/cli-utils/step"
  23. "go.step.sm/cli-utils/ui"
  24. "go.step.sm/cli-utils/usage"
  25. "go.step.sm/crypto/pemutil"
  26. // Enabled kms interfaces.
  27. _ "go.step.sm/crypto/kms/awskms"
  28. _ "go.step.sm/crypto/kms/azurekms"
  29. _ "go.step.sm/crypto/kms/cloudkms"
  30. _ "go.step.sm/crypto/kms/pkcs11"
  31. _ "go.step.sm/crypto/kms/softkms"
  32. _ "go.step.sm/crypto/kms/sshagentkms"
  33. _ "go.step.sm/crypto/kms/yubikey"
  34. // Enabled cas interfaces.
  35. _ "github.com/smallstep/certificates/cas/cloudcas"
  36. _ "github.com/smallstep/certificates/cas/softcas"
  37. _ "github.com/smallstep/certificates/cas/stepcas"
  38. _ "github.com/smallstep/certificates/cas/vaultcas"
  39. )
  40. // commit and buildTime are filled in during build by the Makefile
  41. var (
  42. BuildTime = "N/A"
  43. Version = "N/A"
  44. )
  45. func init() {
  46. step.Set("Smallstep CA", Version, BuildTime)
  47. authority.GlobalVersion.Version = Version
  48. rand.Seed(time.Now().UnixNano())
  49. // Add support for asking passwords
  50. pemutil.PromptPassword = func(msg string) ([]byte, error) {
  51. return ui.PromptPassword(msg)
  52. }
  53. }
  54. func exit(code int) {
  55. ui.Reset()
  56. os.Exit(code)
  57. }
  58. // appHelpTemplate contains the modified template for the main app
  59. var appHelpTemplate = `## NAME
  60. **{{.HelpName}}** -- {{.Usage}}
  61. ## USAGE
  62. {{if .UsageText}}{{.UsageText}}{{else}}**{{.HelpName}}**{{if .Commands}} <command>{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}_[arguments]_{{end}}{{end}}{{if .Description}}
  63. ## DESCRIPTION
  64. {{.Description}}{{end}}{{if .VisibleCommands}}
  65. ## COMMANDS
  66. {{range .VisibleCategories}}{{if .Name}}{{.Name}}:{{end}}
  67. |||
  68. |---|---|{{range .VisibleCommands}}
  69. | **{{join .Names ", "}}** | {{.Usage}} |{{end}}
  70. {{end}}{{if .VisibleFlags}}{{end}}
  71. ## OPTIONS
  72. {{range $index, $option := .VisibleFlags}}{{if $index}}
  73. {{end}}{{$option}}
  74. {{end}}{{end}}{{if .Copyright}}{{if len .Authors}}
  75. ## AUTHOR{{with $length := len .Authors}}{{if ne 1 $length}}S{{end}}{{end}}:
  76. {{range $index, $author := .Authors}}{{if $index}}
  77. {{end}}{{$author}}{{end}}{{end}}{{if .Version}}{{if not .HideVersion}}
  78. ## ONLINE
  79. This documentation is available online at https://smallstep.com/docs/certificates
  80. ## VERSION
  81. {{.Version}}{{end}}{{end}}
  82. ## COPYRIGHT
  83. {{.Copyright}}
  84. ## FEEDBACK ` +
  85. html.UnescapeString("&#"+strconv.Itoa(128525)+";") + " " +
  86. html.UnescapeString("&#"+strconv.Itoa(127867)+";") +
  87. `
  88. The **step-ca** utility is not instrumented for usage statistics. It does not phone home.
  89. But your feedback is extremely valuable. Any information you can provide regarding how you’re using **step-ca** helps.
  90. Please send us a sentence or two, good or bad: **feedback@smallstep.com** or https://github.com/smallstep/certificates/discussions.
  91. {{end}}
  92. `
  93. func main() {
  94. // initialize step environment.
  95. if err := step.Init(); err != nil {
  96. fmt.Fprintln(os.Stderr, err.Error())
  97. os.Exit(1)
  98. }
  99. // Initialize windows terminal
  100. ui.Init()
  101. // Override global framework components
  102. cli.VersionPrinter = func(c *cli.Context) {
  103. version.Command(c)
  104. }
  105. cli.AppHelpTemplate = appHelpTemplate
  106. cli.SubcommandHelpTemplate = usage.SubcommandHelpTemplate
  107. cli.CommandHelpTemplate = usage.CommandHelpTemplate
  108. cli.HelpPrinter = usage.HelpPrinter
  109. cli.FlagNamePrefixer = usage.FlagNamePrefixer
  110. cli.FlagStringer = stringifyFlag
  111. // Configure cli app
  112. app := cli.NewApp()
  113. app.Name = "step-ca"
  114. app.HelpName = "step-ca"
  115. app.Version = step.Version()
  116. app.Usage = "an online certificate authority for secure automated certificate management"
  117. app.UsageText = `**step-ca** [config] [**--context**=<name>] [**--password-file**=<file>]
  118. [**--ssh-host-password-file**=<file>] [**--ssh-user-password-file**=<file>]
  119. [**--issuer-password-file**=<file>] [**--resolver**=<addr>] [**--help**] [**--version**]`
  120. app.Description = `**step-ca** runs the Step Online Certificate Authority
  121. (Step CA) using the given configuration.
  122. See the README.md for more detailed configuration documentation.
  123. ## POSITIONAL ARGUMENTS
  124. <config>
  125. : File that configures the operation of the Step CA; this file is generated
  126. when you initialize the Step CA using 'step ca init'
  127. ## EXIT CODES
  128. This command will run indefinitely on success and return \>0 if any error occurs.
  129. ## EXAMPLES
  130. These examples assume that you have already initialized your PKI by running
  131. 'step ca init'. If you have not completed this step please see the 'Getting Started'
  132. section of the README.
  133. Run the Step CA and prompt for password:
  134. '''
  135. $ step-ca $STEPPATH/config/ca.json
  136. '''
  137. Run the Step CA and read the password from a file - this is useful for
  138. automating deployment:
  139. '''
  140. $ step-ca $STEPPATH/config/ca.json --password-file ./password.txt
  141. '''
  142. Run the Step CA for the context selected with step and a custom password file:
  143. '''
  144. $ step context select ssh
  145. $ step-ca --password-file ./password.txt
  146. '''
  147. Run the Step CA for the context named _mybiz_ and prompt for password:
  148. '''
  149. $ step-ca --context=mybiz
  150. '''
  151. Run the Step CA for the context named _mybiz_ and an alternate ca.json file:
  152. '''
  153. $ step-ca --context=mybiz other-ca.json
  154. '''
  155. Run the Step CA for the context named _mybiz_ and read the password from a file - this is useful for
  156. automating deployment:
  157. '''
  158. $ step-ca --context=mybiz --password-file ./password.txt
  159. '''
  160. `
  161. app.Flags = append(app.Flags, commands.AppCommand.Flags...)
  162. app.Flags = append(app.Flags, cli.HelpFlag)
  163. app.Copyright = fmt.Sprintf("(c) 2018-%d Smallstep Labs, Inc.", time.Now().Year())
  164. // All non-successful output should be written to stderr
  165. app.Writer = os.Stdout
  166. app.ErrWriter = os.Stderr
  167. app.Commands = command.Retrieve()
  168. // Start the golang debug logger if environment variable is set.
  169. // See https://golang.org/pkg/net/http/pprof/
  170. debugProfAddr := os.Getenv("STEP_PROF_ADDR")
  171. if debugProfAddr != "" {
  172. go func() {
  173. srv := http.Server{
  174. Addr: debugProfAddr,
  175. ReadHeaderTimeout: 15 * time.Second,
  176. }
  177. log.Println(srv.ListenAndServe())
  178. }()
  179. }
  180. app.Action = func(_ *cli.Context) error {
  181. // Hack to be able to run a the top action as a subcommand
  182. set := flag.NewFlagSet(app.Name, flag.ContinueOnError)
  183. set.Parse(os.Args)
  184. ctx := cli.NewContext(app, set, nil)
  185. return commands.AppCommand.Run(ctx)
  186. }
  187. if err := app.Run(os.Args); err != nil {
  188. if os.Getenv("STEPDEBUG") == "1" {
  189. fmt.Fprintf(os.Stderr, "%+v\n", err)
  190. } else {
  191. fmt.Fprintln(os.Stderr, err)
  192. }
  193. exit(1)
  194. }
  195. exit(0)
  196. }
  197. func flagValue(f cli.Flag) reflect.Value {
  198. fv := reflect.ValueOf(f)
  199. for fv.Kind() == reflect.Ptr {
  200. fv = reflect.Indirect(fv)
  201. }
  202. return fv
  203. }
  204. var placeholderString = regexp.MustCompile(`<.*?>`)
  205. func stringifyFlag(f cli.Flag) string {
  206. fv := flagValue(f)
  207. usg := fv.FieldByName("Usage").String()
  208. placeholder := placeholderString.FindString(usg)
  209. if placeholder == "" {
  210. switch f.(type) {
  211. case cli.BoolFlag, cli.BoolTFlag:
  212. default:
  213. placeholder = "<value>"
  214. }
  215. }
  216. return cli.FlagNamePrefixer(fv.FieldByName("Name").String(), placeholder) + "\t" + usg
  217. }