app.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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/smallstep/certificates/acme"
  15. "github.com/smallstep/certificates/authority/config"
  16. "github.com/smallstep/certificates/authority/provisioner"
  17. "github.com/smallstep/certificates/ca"
  18. "github.com/smallstep/certificates/db"
  19. "github.com/smallstep/certificates/pki"
  20. "github.com/urfave/cli"
  21. "go.step.sm/cli-utils/errs"
  22. "go.step.sm/cli-utils/step"
  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.StringFlag{
  84. Name: "pidfile",
  85. Usage: "the path to the <file> to write the process ID.",
  86. },
  87. cli.BoolFlag{
  88. Name: "insecure",
  89. Usage: "enable insecure flags.",
  90. },
  91. },
  92. }
  93. var pidfile string
  94. // AppAction is the action used when the top command runs.
  95. func appAction(ctx *cli.Context) error {
  96. passFile := ctx.String("password-file")
  97. sshHostPassFile := ctx.String("ssh-host-password-file")
  98. sshUserPassFile := ctx.String("ssh-user-password-file")
  99. issuerPassFile := ctx.String("issuer-password-file")
  100. resolver := ctx.String("resolver")
  101. token := ctx.String("token")
  102. quiet := ctx.Bool("quiet")
  103. if ctx.NArg() > 1 {
  104. return errs.TooManyArguments(ctx)
  105. }
  106. // Allow custom ACME ports with insecure
  107. if acmePort := ctx.Int("acme-http-port"); acmePort != 0 {
  108. if ctx.Bool("insecure") {
  109. acme.InsecurePortHTTP01 = acmePort
  110. } else {
  111. return fmt.Errorf("flag '--acme-http-port' requires the '--insecure' flag")
  112. }
  113. }
  114. if acmePort := ctx.Int("acme-tls-port"); acmePort != 0 {
  115. if ctx.Bool("insecure") {
  116. acme.InsecurePortTLSALPN01 = acmePort
  117. } else {
  118. return fmt.Errorf("flag '--acme-tls-port' requires the '--insecure' flag")
  119. }
  120. }
  121. // Allow custom contexts.
  122. if caCtx := ctx.String("context"); caCtx != "" {
  123. if _, ok := step.Contexts().Get(caCtx); ok {
  124. if err := step.Contexts().SetCurrent(caCtx); err != nil {
  125. return err
  126. }
  127. } else if token == "" {
  128. return fmt.Errorf("context %q not found", caCtx)
  129. } else if err := createContext(caCtx); err != nil {
  130. return err
  131. }
  132. }
  133. var configFile string
  134. if ctx.NArg() > 0 {
  135. configFile = ctx.Args().Get(0)
  136. } else {
  137. configFile = step.CaConfigFile()
  138. }
  139. cfg, err := config.LoadConfiguration(configFile)
  140. if err != nil && token == "" {
  141. var pathErr *os.PathError
  142. if errors.As(err, &pathErr) {
  143. fmt.Println("step-ca can't find or open the configuration file for your CA.")
  144. fmt.Println("You may need to create a CA first by running `step ca init`.")
  145. fmt.Println("Documentation: https://u.step.sm/docs/ca")
  146. os.Exit(1)
  147. }
  148. fatal(err)
  149. }
  150. // Initialize a basic configuration to be used with an automatically
  151. // configured linked RA. Default configuration includes:
  152. // * badgerv2 on $(step path)/db
  153. // * JSON logger
  154. // * Default TLS options
  155. if cfg == nil {
  156. cfg = &config.Config{
  157. SkipValidation: true,
  158. Logger: []byte(`{"format":"json"}`),
  159. DB: &db.Config{
  160. Type: "badgerv2",
  161. DataSource: filepath.Join(step.Path(), "db"),
  162. },
  163. AuthorityConfig: &config.AuthConfig{
  164. DeploymentType: pki.LinkedDeployment.String(),
  165. Provisioners: provisioner.List{},
  166. Template: &config.ASN1DN{},
  167. Backdate: &provisioner.Duration{
  168. Duration: config.DefaultBackdate,
  169. },
  170. },
  171. TLS: &config.DefaultTLSOptions,
  172. }
  173. }
  174. if cfg.AuthorityConfig != nil {
  175. if token == "" && strings.EqualFold(cfg.AuthorityConfig.DeploymentType, pki.LinkedDeployment.String()) {
  176. return errors.New(`'step-ca' requires the '--token' flag for linked deploy type.
  177. To get a linked authority token:
  178. 1. Log in or create a Certificate Manager account at ` + "\033[1mhttps://u.step.sm/linked\033[0m" + `
  179. 2. Add a new authority and select "Link a step-ca instance"
  180. 3. Follow instructions in browser to start 'step-ca' using the '--token' flag
  181. `)
  182. }
  183. }
  184. var password []byte
  185. if passFile != "" {
  186. if password, err = os.ReadFile(passFile); err != nil {
  187. fatal(errors.Wrapf(err, "error reading %s", passFile))
  188. }
  189. password = bytes.TrimRightFunc(password, unicode.IsSpace)
  190. }
  191. var sshHostPassword []byte
  192. if sshHostPassFile != "" {
  193. if sshHostPassword, err = os.ReadFile(sshHostPassFile); err != nil {
  194. fatal(errors.Wrapf(err, "error reading %s", sshHostPassFile))
  195. }
  196. sshHostPassword = bytes.TrimRightFunc(sshHostPassword, unicode.IsSpace)
  197. }
  198. var sshUserPassword []byte
  199. if sshUserPassFile != "" {
  200. if sshUserPassword, err = os.ReadFile(sshUserPassFile); err != nil {
  201. fatal(errors.Wrapf(err, "error reading %s", sshUserPassFile))
  202. }
  203. sshUserPassword = bytes.TrimRightFunc(sshUserPassword, unicode.IsSpace)
  204. }
  205. var issuerPassword []byte
  206. if issuerPassFile != "" {
  207. if issuerPassword, err = os.ReadFile(issuerPassFile); err != nil {
  208. fatal(errors.Wrapf(err, "error reading %s", issuerPassFile))
  209. }
  210. issuerPassword = bytes.TrimRightFunc(issuerPassword, unicode.IsSpace)
  211. }
  212. if filename := ctx.String("pidfile"); filename != "" {
  213. pid := []byte(strconv.Itoa(os.Getpid()) + "\n")
  214. //nolint:gosec // 0644 (-rw-r--r--) are common permissions for a pid file
  215. if err := os.WriteFile(filename, pid, 0644); err != nil {
  216. fatal(errors.Wrap(err, "error writing pidfile"))
  217. }
  218. pidfile = filename
  219. }
  220. // replace resolver if requested
  221. if resolver != "" {
  222. net.DefaultResolver.PreferGo = true
  223. net.DefaultResolver.Dial = func(ctx context.Context, network, address string) (net.Conn, error) {
  224. return net.Dial(network, resolver)
  225. }
  226. }
  227. srv, err := ca.New(cfg,
  228. ca.WithConfigFile(configFile),
  229. ca.WithPassword(password),
  230. ca.WithSSHHostPassword(sshHostPassword),
  231. ca.WithSSHUserPassword(sshUserPassword),
  232. ca.WithIssuerPassword(issuerPassword),
  233. ca.WithLinkedCAToken(token),
  234. ca.WithQuiet(quiet),
  235. )
  236. if err != nil {
  237. fatal(err)
  238. }
  239. go ca.StopReloaderHandler(srv)
  240. if err = srv.Run(); err != nil && !errors.Is(err, http.ErrServerClosed) {
  241. fatal(err)
  242. }
  243. if pidfile != "" {
  244. os.Remove(pidfile)
  245. }
  246. return nil
  247. }
  248. // createContext creates a new context using the given name for the context,
  249. // authority and profile.
  250. func createContext(name string) error {
  251. if err := step.Contexts().Add(&step.Context{
  252. Name: name, Authority: name, Profile: name,
  253. }); err != nil {
  254. return fmt.Errorf("error adding context: %w", err)
  255. }
  256. if err := step.Contexts().SaveCurrent(name); err != nil {
  257. return fmt.Errorf("error saving context: %w", err)
  258. }
  259. if err := step.Contexts().SetCurrent(name); err != nil {
  260. return fmt.Errorf("error setting context: %w", err)
  261. }
  262. if err := os.MkdirAll(step.Path(), 0700); err != nil {
  263. return fmt.Errorf("error creating directory: %w", err)
  264. }
  265. return nil
  266. }
  267. // fatal writes the passed error on the standard error and exits with the exit
  268. // code 1. If the environment variable STEPDEBUG is set to 1 it shows the
  269. // stack trace of the error.
  270. func fatal(err error) {
  271. if os.Getenv("STEPDEBUG") == "1" {
  272. fmt.Fprintf(os.Stderr, "%+v\n", err)
  273. } else {
  274. fmt.Fprintln(os.Stderr, err)
  275. }
  276. if pidfile != "" {
  277. os.Remove(pidfile)
  278. }
  279. os.Exit(2)
  280. }