app.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. package commands
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "net"
  7. "net/http"
  8. "os"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "unicode"
  14. "github.com/pkg/errors"
  15. "github.com/smallstep/certificates/acme"
  16. "github.com/smallstep/certificates/authority/config"
  17. "github.com/smallstep/certificates/authority/provisioner"
  18. "github.com/smallstep/certificates/ca"
  19. "github.com/smallstep/certificates/db"
  20. "github.com/smallstep/certificates/pki"
  21. "github.com/urfave/cli"
  22. "go.step.sm/cli-utils/errs"
  23. "go.step.sm/cli-utils/step"
  24. )
  25. // AppCommand is the action used as the top action.
  26. var AppCommand = cli.Command{
  27. Name: "start",
  28. Action: appAction,
  29. UsageText: `**step-ca** <config> [**--password-file**=<file>]
  30. [**--ssh-host-password-file**=<file>] [**--ssh-user-password-file**=<file>]
  31. [**--issuer-password-file**=<file>] [**--pidfile**=<file>] [**--resolver**=<addr>]`,
  32. Flags: []cli.Flag{
  33. cli.StringFlag{
  34. Name: "password-file",
  35. Usage: `path to the <file> containing the password to decrypt the
  36. intermediate private key.`,
  37. },
  38. cli.StringFlag{
  39. Name: "ssh-host-password-file",
  40. Usage: `path to the <file> containing the password to decrypt the
  41. private key used to sign SSH host certificates. If the flag is not passed it
  42. will default to --password-file.`,
  43. },
  44. cli.StringFlag{
  45. Name: "ssh-user-password-file",
  46. Usage: `path to the <file> containing the password to decrypt the
  47. private key used to sign SSH user certificates. If the flag is not passed it
  48. will default to --password-file.`,
  49. },
  50. cli.StringFlag{
  51. Name: "issuer-password-file",
  52. Usage: `path to the <file> containing the password to decrypt the
  53. certificate issuer private key used in the RA mode.`,
  54. },
  55. cli.StringFlag{
  56. Name: "resolver",
  57. Usage: "address of a DNS resolver to be used instead of the default.",
  58. },
  59. cli.StringFlag{
  60. Name: "token",
  61. Usage: "token used to enable the linked ca.",
  62. EnvVar: "STEP_CA_TOKEN",
  63. },
  64. cli.BoolFlag{
  65. Name: "quiet",
  66. Usage: "disable startup information",
  67. EnvVar: "STEP_CA_QUIET",
  68. },
  69. cli.StringFlag{
  70. Name: "context",
  71. Usage: "the <name> of the authority's context.",
  72. EnvVar: "STEP_CA_CONTEXT",
  73. },
  74. cli.DurationFlag{
  75. Name: "http-timeout",
  76. Usage: "the (shared) duration for HTTP timeouts (experimental).",
  77. EnvVar: "STEP_CA_HTTP_TIMEOUT",
  78. Value: 15 * time.Second,
  79. Hidden: true,
  80. },
  81. cli.IntFlag{
  82. Name: "acme-http-port",
  83. Usage: `the <port> used on http-01 challenges. It can be changed for testing purposes.
  84. Requires **--insecure** flag.`,
  85. },
  86. cli.IntFlag{
  87. Name: "acme-tls-port",
  88. Usage: `the <port> used on tls-alpn-01 challenges. It can be changed for testing purposes.
  89. Requires **--insecure** flag.`,
  90. },
  91. cli.StringFlag{
  92. Name: "pidfile",
  93. Usage: "the path to the <file> to write the process ID.",
  94. },
  95. cli.BoolFlag{
  96. Name: "insecure",
  97. Usage: "enable insecure flags.",
  98. },
  99. },
  100. }
  101. var pidfile string
  102. // AppAction is the action used when the top command runs.
  103. func appAction(ctx *cli.Context) error {
  104. passFile := ctx.String("password-file")
  105. sshHostPassFile := ctx.String("ssh-host-password-file")
  106. sshUserPassFile := ctx.String("ssh-user-password-file")
  107. issuerPassFile := ctx.String("issuer-password-file")
  108. resolver := ctx.String("resolver")
  109. token := ctx.String("token")
  110. quiet := ctx.Bool("quiet")
  111. httpTimeout := ctx.Duration("http-timeout")
  112. if ctx.NArg() > 1 {
  113. return errs.TooManyArguments(ctx)
  114. }
  115. // Allow custom ACME ports with insecure
  116. if acmePort := ctx.Int("acme-http-port"); acmePort != 0 {
  117. if ctx.Bool("insecure") {
  118. acme.InsecurePortHTTP01 = acmePort
  119. } else {
  120. return fmt.Errorf("flag '--acme-http-port' requires the '--insecure' flag")
  121. }
  122. }
  123. if acmePort := ctx.Int("acme-tls-port"); acmePort != 0 {
  124. if ctx.Bool("insecure") {
  125. acme.InsecurePortTLSALPN01 = acmePort
  126. } else {
  127. return fmt.Errorf("flag '--acme-tls-port' requires the '--insecure' flag")
  128. }
  129. }
  130. // Allow custom contexts.
  131. if caCtx := ctx.String("context"); caCtx != "" {
  132. if _, ok := step.Contexts().Get(caCtx); ok {
  133. if err := step.Contexts().SetCurrent(caCtx); err != nil {
  134. return err
  135. }
  136. } else if token == "" {
  137. return fmt.Errorf("context %q not found", caCtx)
  138. } else if err := createContext(caCtx); err != nil {
  139. return err
  140. }
  141. }
  142. var configFile string
  143. if ctx.NArg() > 0 {
  144. configFile = ctx.Args().Get(0)
  145. } else {
  146. configFile = step.CaConfigFile()
  147. }
  148. cfg, err := config.LoadConfiguration(configFile)
  149. if err != nil && token == "" {
  150. var pathErr *os.PathError
  151. if errors.As(err, &pathErr) {
  152. fmt.Println("step-ca can't find or open the configuration file for your CA.")
  153. fmt.Println("You may need to create a CA first by running `step ca init`.")
  154. fmt.Println("Documentation: https://u.step.sm/docs/ca")
  155. os.Exit(1)
  156. }
  157. fatal(err)
  158. }
  159. // Initialize a basic configuration to be used with an automatically
  160. // configured linked RA. Default configuration includes:
  161. // * badgerv2 on $(step path)/db
  162. // * JSON logger
  163. // * Default TLS options
  164. if cfg == nil {
  165. cfg = &config.Config{
  166. SkipValidation: true,
  167. Logger: []byte(`{"format":"json"}`),
  168. DB: &db.Config{
  169. Type: "badgerv2",
  170. DataSource: filepath.Join(step.Path(), "db"),
  171. },
  172. AuthorityConfig: &config.AuthConfig{
  173. DeploymentType: pki.LinkedDeployment.String(),
  174. Provisioners: provisioner.List{},
  175. Template: &config.ASN1DN{},
  176. Backdate: &provisioner.Duration{
  177. Duration: config.DefaultBackdate,
  178. },
  179. },
  180. TLS: &config.DefaultTLSOptions,
  181. }
  182. }
  183. if cfg.AuthorityConfig != nil {
  184. if token == "" && strings.EqualFold(cfg.AuthorityConfig.DeploymentType, pki.LinkedDeployment.String()) {
  185. return errors.New(`'step-ca' requires the '--token' flag for linked deploy type.
  186. To get a linked authority token:
  187. 1. Log in or create a Certificate Manager account at ` + "\033[1mhttps://u.step.sm/linked\033[0m" + `
  188. 2. Add a new authority and select "Link a step-ca instance"
  189. 3. Follow instructions in browser to start 'step-ca' using the '--token' flag
  190. `)
  191. }
  192. }
  193. var password []byte
  194. if passFile != "" {
  195. if password, err = os.ReadFile(passFile); err != nil {
  196. fatal(errors.Wrapf(err, "error reading %s", passFile))
  197. }
  198. password = bytes.TrimRightFunc(password, unicode.IsSpace)
  199. }
  200. var sshHostPassword []byte
  201. if sshHostPassFile != "" {
  202. if sshHostPassword, err = os.ReadFile(sshHostPassFile); err != nil {
  203. fatal(errors.Wrapf(err, "error reading %s", sshHostPassFile))
  204. }
  205. sshHostPassword = bytes.TrimRightFunc(sshHostPassword, unicode.IsSpace)
  206. }
  207. var sshUserPassword []byte
  208. if sshUserPassFile != "" {
  209. if sshUserPassword, err = os.ReadFile(sshUserPassFile); err != nil {
  210. fatal(errors.Wrapf(err, "error reading %s", sshUserPassFile))
  211. }
  212. sshUserPassword = bytes.TrimRightFunc(sshUserPassword, unicode.IsSpace)
  213. }
  214. var issuerPassword []byte
  215. if issuerPassFile != "" {
  216. if issuerPassword, err = os.ReadFile(issuerPassFile); err != nil {
  217. fatal(errors.Wrapf(err, "error reading %s", issuerPassFile))
  218. }
  219. issuerPassword = bytes.TrimRightFunc(issuerPassword, unicode.IsSpace)
  220. }
  221. if filename := ctx.String("pidfile"); filename != "" {
  222. pid := []byte(strconv.Itoa(os.Getpid()) + "\n")
  223. //nolint:gosec // 0644 (-rw-r--r--) are common permissions for a pid file
  224. if err := os.WriteFile(filename, pid, 0644); err != nil {
  225. fatal(errors.Wrap(err, "error writing pidfile"))
  226. }
  227. pidfile = filename
  228. }
  229. // replace resolver if requested
  230. if resolver != "" {
  231. net.DefaultResolver.PreferGo = true
  232. net.DefaultResolver.Dial = func(ctx context.Context, network, address string) (net.Conn, error) {
  233. return net.Dial(network, resolver)
  234. }
  235. }
  236. srv, err := ca.New(cfg,
  237. ca.WithConfigFile(configFile),
  238. ca.WithPassword(password),
  239. ca.WithSSHHostPassword(sshHostPassword),
  240. ca.WithSSHUserPassword(sshUserPassword),
  241. ca.WithIssuerPassword(issuerPassword),
  242. ca.WithLinkedCAToken(token),
  243. ca.WithQuiet(quiet),
  244. ca.WithHTTPTimeout(httpTimeout))
  245. if err != nil {
  246. fatal(err)
  247. }
  248. go ca.StopReloaderHandler(srv)
  249. if err = srv.Run(); err != nil && !errors.Is(err, http.ErrServerClosed) {
  250. fatal(err)
  251. }
  252. if pidfile != "" {
  253. os.Remove(pidfile)
  254. }
  255. return nil
  256. }
  257. // createContext creates a new context using the given name for the context,
  258. // authority and profile.
  259. func createContext(name string) error {
  260. if err := step.Contexts().Add(&step.Context{
  261. Name: name, Authority: name, Profile: name,
  262. }); err != nil {
  263. return fmt.Errorf("error adding context: %w", err)
  264. }
  265. if err := step.Contexts().SaveCurrent(name); err != nil {
  266. return fmt.Errorf("error saving context: %w", err)
  267. }
  268. if err := step.Contexts().SetCurrent(name); err != nil {
  269. return fmt.Errorf("error setting context: %w", err)
  270. }
  271. if err := os.MkdirAll(step.Path(), 0700); err != nil {
  272. return fmt.Errorf("error creating directory: %w", err)
  273. }
  274. return nil
  275. }
  276. // fatal writes the passed error on the standard error and exits with the exit
  277. // code 1. If the environment variable STEPDEBUG is set to 1 it shows the
  278. // stack trace of the error.
  279. func fatal(err error) {
  280. if os.Getenv("STEPDEBUG") == "1" {
  281. fmt.Fprintf(os.Stderr, "%+v\n", err)
  282. } else {
  283. fmt.Fprintln(os.Stderr, err)
  284. }
  285. if pidfile != "" {
  286. os.Remove(pidfile)
  287. }
  288. os.Exit(2)
  289. }