4
0

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