capi.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "io/ioutil"
  6. "net/url"
  7. "github.com/crowdsecurity/crowdsec/pkg/apiclient"
  8. "github.com/crowdsecurity/crowdsec/pkg/csconfig"
  9. "github.com/crowdsecurity/crowdsec/pkg/cwhub"
  10. "github.com/crowdsecurity/crowdsec/pkg/cwversion"
  11. "github.com/crowdsecurity/crowdsec/pkg/models"
  12. "github.com/go-openapi/strfmt"
  13. "github.com/pkg/errors"
  14. log "github.com/sirupsen/logrus"
  15. "github.com/spf13/cobra"
  16. "gopkg.in/yaml.v2"
  17. )
  18. var CAPIURLPrefix string = "v2"
  19. var CAPIBaseURL string = "https://api.crowdsec.net/"
  20. var capiUserPrefix string
  21. func NewCapiCmd() *cobra.Command {
  22. var cmdCapi = &cobra.Command{
  23. Use: "capi [action]",
  24. Short: "Manage interaction with Central API (CAPI)",
  25. Args: cobra.MinimumNArgs(1),
  26. DisableAutoGenTag: true,
  27. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  28. if err := csConfig.LoadAPIServer(); err != nil || csConfig.DisableAPI {
  29. return errors.Wrap(err, "Local API is disabled, please run this command on the local API machine")
  30. }
  31. if csConfig.API.Server.OnlineClient == nil {
  32. log.Fatalf("no configuration for Central API in '%s'", *csConfig.FilePath)
  33. }
  34. return nil
  35. },
  36. }
  37. var cmdCapiRegister = &cobra.Command{
  38. Use: "register",
  39. Short: "Register to Central API (CAPI)",
  40. Args: cobra.MinimumNArgs(0),
  41. DisableAutoGenTag: true,
  42. Run: func(cmd *cobra.Command, args []string) {
  43. var err error
  44. capiUser, err := generateID(capiUserPrefix)
  45. if err != nil {
  46. log.Fatalf("unable to generate machine id: %s", err)
  47. }
  48. password := strfmt.Password(generatePassword(passwordLength))
  49. apiurl, err := url.Parse(CAPIBaseURL)
  50. if err != nil {
  51. log.Fatalf("unable to parse api url %s : %s", CAPIBaseURL, err)
  52. }
  53. _, err = apiclient.RegisterClient(&apiclient.Config{
  54. MachineID: capiUser,
  55. Password: password,
  56. UserAgent: fmt.Sprintf("crowdsec/%s", cwversion.VersionStr()),
  57. URL: apiurl,
  58. VersionPrefix: CAPIURLPrefix,
  59. }, nil)
  60. if err != nil {
  61. log.Fatalf("api client register ('%s'): %s", CAPIBaseURL, err)
  62. }
  63. log.Printf("Successfully registered to Central API (CAPI)")
  64. var dumpFile string
  65. if outputFile != "" {
  66. dumpFile = outputFile
  67. } else if csConfig.API.Server.OnlineClient.CredentialsFilePath != "" {
  68. dumpFile = csConfig.API.Server.OnlineClient.CredentialsFilePath
  69. } else {
  70. dumpFile = ""
  71. }
  72. apiCfg := csconfig.ApiCredentialsCfg{
  73. Login: capiUser,
  74. Password: password.String(),
  75. URL: CAPIBaseURL,
  76. }
  77. apiConfigDump, err := yaml.Marshal(apiCfg)
  78. if err != nil {
  79. log.Fatalf("unable to marshal api credentials: %s", err)
  80. }
  81. if dumpFile != "" {
  82. err = ioutil.WriteFile(dumpFile, apiConfigDump, 0600)
  83. if err != nil {
  84. log.Fatalf("write api credentials in '%s' failed: %s", dumpFile, err)
  85. }
  86. log.Printf("Central API credentials dumped to '%s'", dumpFile)
  87. } else {
  88. fmt.Printf("%s\n", string(apiConfigDump))
  89. }
  90. log.Warningf(ReloadMessage())
  91. },
  92. }
  93. cmdCapiRegister.Flags().StringVarP(&outputFile, "file", "f", "", "output file destination")
  94. cmdCapiRegister.Flags().StringVar(&capiUserPrefix, "schmilblick", "", "set a schmilblick (use in tests only)")
  95. if err := cmdCapiRegister.Flags().MarkHidden("schmilblick"); err != nil {
  96. log.Fatalf("failed to hide flag: %s", err)
  97. }
  98. cmdCapi.AddCommand(cmdCapiRegister)
  99. var cmdCapiStatus = &cobra.Command{
  100. Use: "status",
  101. Short: "Check status with the Central API (CAPI)",
  102. Args: cobra.MinimumNArgs(0),
  103. DisableAutoGenTag: true,
  104. Run: func(cmd *cobra.Command, args []string) {
  105. var err error
  106. if csConfig.API.Server == nil {
  107. log.Fatalln("There is no configuration on 'api.server:'")
  108. }
  109. if csConfig.API.Server.OnlineClient == nil {
  110. log.Fatalf("Please provide credentials for the Central API (CAPI) in '%s'", csConfig.API.Server.OnlineClient.CredentialsFilePath)
  111. }
  112. if csConfig.API.Server.OnlineClient.Credentials == nil {
  113. log.Fatalf("no credentials for Central API (CAPI) in '%s'", csConfig.API.Server.OnlineClient.CredentialsFilePath)
  114. }
  115. password := strfmt.Password(csConfig.API.Server.OnlineClient.Credentials.Password)
  116. apiurl, err := url.Parse(csConfig.API.Server.OnlineClient.Credentials.URL)
  117. if err != nil {
  118. log.Fatalf("parsing api url ('%s'): %s", csConfig.API.Server.OnlineClient.Credentials.URL, err)
  119. }
  120. if err := csConfig.LoadHub(); err != nil {
  121. log.Fatal(err)
  122. }
  123. if err := cwhub.GetHubIdx(csConfig.Hub); err != nil {
  124. log.Info("Run 'sudo cscli hub update' to get the hub index")
  125. log.Fatalf("Failed to load hub index : %s", err)
  126. }
  127. scenarios, err := cwhub.GetInstalledScenariosAsString()
  128. if err != nil {
  129. log.Fatalf("failed to get scenarios : %s", err.Error())
  130. }
  131. if len(scenarios) == 0 {
  132. log.Fatalf("no scenarios installed, abort")
  133. }
  134. Client, err = apiclient.NewDefaultClient(apiurl, CAPIURLPrefix, fmt.Sprintf("crowdsec/%s", cwversion.VersionStr()), nil)
  135. if err != nil {
  136. log.Fatalf("init default client: %s", err)
  137. }
  138. t := models.WatcherAuthRequest{
  139. MachineID: &csConfig.API.Server.OnlineClient.Credentials.Login,
  140. Password: &password,
  141. Scenarios: scenarios,
  142. }
  143. log.Infof("Loaded credentials from %s", csConfig.API.Server.OnlineClient.CredentialsFilePath)
  144. log.Infof("Trying to authenticate with username %s on %s", csConfig.API.Server.OnlineClient.Credentials.Login, apiurl)
  145. _, err = Client.Auth.AuthenticateWatcher(context.Background(), t)
  146. if err != nil {
  147. log.Fatalf("Failed to authenticate to Central API (CAPI) : %s", err)
  148. }
  149. log.Infof("You can successfully interact with Central API (CAPI)")
  150. },
  151. }
  152. cmdCapi.AddCommand(cmdCapiStatus)
  153. return cmdCapi
  154. }