app.go 9.4 KB

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