app.go 7.9 KB

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