main.go 7.0 KB

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