app.go 9.3 KB

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