onboard.go 5.4 KB

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