onboard.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. package commands
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io"
  6. "net/http"
  7. "net/url"
  8. "os"
  9. "github.com/pkg/errors"
  10. "github.com/smallstep/certificates/authority"
  11. "github.com/smallstep/certificates/ca"
  12. "github.com/smallstep/certificates/cas/apiv1"
  13. "github.com/smallstep/certificates/pki"
  14. "github.com/urfave/cli"
  15. "go.step.sm/cli-utils/command"
  16. "go.step.sm/cli-utils/errs"
  17. "go.step.sm/cli-utils/fileutil"
  18. "go.step.sm/cli-utils/ui"
  19. "go.step.sm/crypto/randutil"
  20. )
  21. // defaultOnboardingURL is the production onboarding url, to use a development
  22. // url use:
  23. // export STEP_CA_ONBOARDING_URL=http://localhost:3002/onboarding/
  24. const defaultOnboardingURL = "https://api.smallstep.com/onboarding/"
  25. type onboardingConfiguration struct {
  26. Name string `json:"name"`
  27. DNS string `json:"dns"`
  28. Address string `json:"address"`
  29. password []byte
  30. }
  31. type onboardingPayload struct {
  32. Fingerprint string `json:"fingerprint"`
  33. }
  34. type onboardingError struct {
  35. StatusCode int `json:"statusCode"`
  36. Message string `json:"message"`
  37. }
  38. func (e onboardingError) Error() string {
  39. return e.Message
  40. }
  41. func init() {
  42. command.Register(cli.Command{
  43. Name: "onboard",
  44. Usage: "configure and run step-ca from the onboarding guide",
  45. UsageText: "**step-ca onboard** <token>",
  46. Action: onboardAction,
  47. Description: `**step-ca onboard** configures step certificates using the onboarding guide.
  48. Open https://smallstep.com/onboarding in your browser and start the CA with the
  49. given token:
  50. '''
  51. $ step-ca onboard <token>
  52. '''
  53. ## POSITIONAL ARGUMENTS
  54. <token>
  55. : The token string provided by the onboarding guide.`,
  56. })
  57. }
  58. func onboardAction(ctx *cli.Context) error {
  59. if ctx.NArg() == 0 {
  60. return cli.ShowCommandHelp(ctx, "onboard")
  61. }
  62. if err := errs.NumberOfArguments(ctx, 1); err != nil {
  63. return err
  64. }
  65. // Get onboarding url
  66. onboarding := defaultOnboardingURL
  67. if v := os.Getenv("STEP_CA_ONBOARDING_URL"); v != "" {
  68. onboarding = v
  69. }
  70. u, err := url.Parse(onboarding)
  71. if err != nil {
  72. return errors.Wrapf(err, "error parsing %s", onboarding)
  73. }
  74. ui.Println("Connecting to onboarding guide...")
  75. token := ctx.Args().Get(0)
  76. onboardingURL := u.ResolveReference(&url.URL{Path: token}).String()
  77. res, err := http.Get(onboardingURL)
  78. if err != nil {
  79. return errors.Wrap(err, "error connecting onboarding guide")
  80. }
  81. if res.StatusCode >= 400 {
  82. var msg onboardingError
  83. if err := readJSON(res.Body, &msg); err != nil {
  84. return errors.Wrap(err, "error unmarshaling response")
  85. }
  86. return errors.Wrap(msg, "error receiving onboarding guide")
  87. }
  88. var config onboardingConfiguration
  89. if err := readJSON(res.Body, &config); err != nil {
  90. return errors.Wrap(err, "error unmarshaling response")
  91. }
  92. password, err := randutil.ASCII(32)
  93. if err != nil {
  94. return err
  95. }
  96. config.password = []byte(password)
  97. ui.Println("Initializing step-ca with the following configuration:")
  98. ui.PrintSelected("Name", config.Name)
  99. ui.PrintSelected("DNS", config.DNS)
  100. ui.PrintSelected("Address", config.Address)
  101. ui.PrintSelected("Password", password)
  102. ui.Println()
  103. caConfig, fp, err := onboardPKI(config)
  104. if err != nil {
  105. return err
  106. }
  107. payload, err := json.Marshal(onboardingPayload{Fingerprint: fp})
  108. if err != nil {
  109. return errors.Wrap(err, "error marshaling payload")
  110. }
  111. resp, err := http.Post(onboardingURL, "application/json", bytes.NewBuffer(payload))
  112. if err != nil {
  113. return errors.Wrap(err, "error connecting onboarding guide")
  114. }
  115. if resp.StatusCode >= 400 {
  116. var msg onboardingError
  117. if err := readJSON(resp.Body, &msg); err != nil {
  118. ui.Printf("%s {{ \"error unmarshalling response: %v\" | yellow }}\n", ui.IconWarn, err)
  119. } else {
  120. ui.Printf("%s {{ \"error posting fingerprint: %s\" | yellow }}\n", ui.IconWarn, msg.Message)
  121. }
  122. } else {
  123. resp.Body.Close()
  124. }
  125. ui.Println("Initialized!")
  126. ui.Println("Step CA is starting. Please return to the onboarding guide in your browser to continue.")
  127. srv, err := ca.New(caConfig, ca.WithPassword(config.password))
  128. if err != nil {
  129. fatal(err)
  130. }
  131. go ca.StopReloaderHandler(srv)
  132. if err = srv.Run(); err != nil && err != http.ErrServerClosed {
  133. fatal(err)
  134. }
  135. return nil
  136. }
  137. func onboardPKI(config onboardingConfiguration) (*authority.Config, string, error) {
  138. p, err := pki.New(apiv1.Options{
  139. Type: apiv1.SoftCAS,
  140. IsCreator: true,
  141. })
  142. if err != nil {
  143. return nil, "", err
  144. }
  145. p.SetAddress(config.Address)
  146. p.SetDNSNames([]string{config.DNS})
  147. ui.Println("Generating root certificate...")
  148. root, err := p.GenerateRootCertificate(config.Name, config.Name, config.Name, config.password)
  149. if err != nil {
  150. return nil, "", err
  151. }
  152. ui.Println("Generating intermediate certificate...")
  153. err = p.GenerateIntermediateCertificate(config.Name, config.Name, config.Name, root, config.password)
  154. if err != nil {
  155. return nil, "", err
  156. }
  157. // Generate provisioner
  158. p.SetProvisioner("admin")
  159. ui.Println("Generating admin provisioner...")
  160. if err = p.GenerateKeyPairs(config.password); err != nil {
  161. return nil, "", err
  162. }
  163. // Generate and write configuration
  164. caConfig, err := p.GenerateConfig()
  165. if err != nil {
  166. return nil, "", err
  167. }
  168. b, err := json.MarshalIndent(caConfig, "", " ")
  169. if err != nil {
  170. return nil, "", errors.Wrapf(err, "error marshaling %s", p.GetCAConfigPath())
  171. }
  172. if err = fileutil.WriteFile(p.GetCAConfigPath(), b, 0666); err != nil {
  173. return nil, "", errs.FileError(err, p.GetCAConfigPath())
  174. }
  175. return caConfig, p.GetRootFingerprint(), nil
  176. }
  177. func readJSON(r io.ReadCloser, v interface{}) error {
  178. defer r.Close()
  179. return json.NewDecoder(r).Decode(v)
  180. }