lapi.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "io/ioutil"
  6. "net/url"
  7. "strings"
  8. "github.com/crowdsecurity/crowdsec/pkg/apiclient"
  9. "github.com/crowdsecurity/crowdsec/pkg/csconfig"
  10. "github.com/crowdsecurity/crowdsec/pkg/cwhub"
  11. "github.com/crowdsecurity/crowdsec/pkg/cwversion"
  12. "github.com/crowdsecurity/crowdsec/pkg/models"
  13. "github.com/go-openapi/strfmt"
  14. "github.com/pkg/errors"
  15. log "github.com/sirupsen/logrus"
  16. "github.com/spf13/cobra"
  17. "gopkg.in/yaml.v2"
  18. )
  19. var LAPIURLPrefix string = "v1"
  20. var lapiUser string
  21. func NewLapiCmd() *cobra.Command {
  22. var cmdLapi = &cobra.Command{
  23. Use: "lapi [action]",
  24. Short: "Manage interaction with Local API (LAPI)",
  25. Args: cobra.MinimumNArgs(1),
  26. DisableAutoGenTag: true,
  27. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  28. if err := csConfig.LoadAPIClient(); err != nil {
  29. return errors.Wrap(err, "loading api client")
  30. }
  31. return nil
  32. },
  33. }
  34. var cmdLapiRegister = &cobra.Command{
  35. Use: "register",
  36. Short: "Register a machine to Local API (LAPI)",
  37. Long: `Register you machine to the Local API (LAPI).
  38. Keep in mind the machine needs to be validated by an administrator on LAPI side to be effective.`,
  39. Args: cobra.MinimumNArgs(0),
  40. DisableAutoGenTag: true,
  41. Run: func(cmd *cobra.Command, args []string) {
  42. var err error
  43. if lapiUser == "" {
  44. lapiUser, err = generateID("")
  45. if err != nil {
  46. log.Fatalf("unable to generate machine id: %s", err)
  47. }
  48. }
  49. password := strfmt.Password(generatePassword(passwordLength))
  50. if apiURL == "" {
  51. if csConfig.API.Client != nil && csConfig.API.Client.Credentials != nil && csConfig.API.Client.Credentials.URL != "" {
  52. apiURL = csConfig.API.Client.Credentials.URL
  53. } else {
  54. log.Fatalf("No Local API URL. Please provide it in your configuration or with the -u parameter")
  55. }
  56. }
  57. /*URL needs to end with /, but user doesn't care*/
  58. if !strings.HasSuffix(apiURL, "/") {
  59. apiURL += "/"
  60. }
  61. /*URL needs to start with http://, but user doesn't care*/
  62. if !strings.HasPrefix(apiURL, "http://") && !strings.HasPrefix(apiURL, "https://") {
  63. apiURL = "http://" + apiURL
  64. }
  65. apiurl, err := url.Parse(apiURL)
  66. if err != nil {
  67. log.Fatalf("parsing api url: %s", err)
  68. }
  69. _, err = apiclient.RegisterClient(&apiclient.Config{
  70. MachineID: lapiUser,
  71. Password: password,
  72. UserAgent: fmt.Sprintf("crowdsec/%s", cwversion.VersionStr()),
  73. URL: apiurl,
  74. VersionPrefix: LAPIURLPrefix,
  75. }, nil)
  76. if err != nil {
  77. log.Fatalf("api client register: %s", err)
  78. }
  79. log.Printf("Successfully registered to Local API (LAPI)")
  80. var dumpFile string
  81. if outputFile != "" {
  82. dumpFile = outputFile
  83. } else if csConfig.API.Client.CredentialsFilePath != "" {
  84. dumpFile = csConfig.API.Client.CredentialsFilePath
  85. } else {
  86. dumpFile = ""
  87. }
  88. apiCfg := csconfig.ApiCredentialsCfg{
  89. Login: lapiUser,
  90. Password: password.String(),
  91. URL: apiURL,
  92. }
  93. apiConfigDump, err := yaml.Marshal(apiCfg)
  94. if err != nil {
  95. log.Fatalf("unable to marshal api credentials: %s", err)
  96. }
  97. if dumpFile != "" {
  98. err = ioutil.WriteFile(dumpFile, apiConfigDump, 0644)
  99. if err != nil {
  100. log.Fatalf("write api credentials in '%s' failed: %s", dumpFile, err)
  101. }
  102. log.Printf("Local API credentials dumped to '%s'", dumpFile)
  103. } else {
  104. fmt.Printf("%s\n", string(apiConfigDump))
  105. }
  106. log.Warningf(ReloadMessage())
  107. },
  108. }
  109. cmdLapiRegister.Flags().StringVarP(&apiURL, "url", "u", "", "URL of the API (ie. http://127.0.0.1)")
  110. cmdLapiRegister.Flags().StringVarP(&outputFile, "file", "f", "", "output file destination")
  111. cmdLapiRegister.Flags().StringVar(&lapiUser, "machine", "", "Name of the machine to register with")
  112. cmdLapi.AddCommand(cmdLapiRegister)
  113. var cmdLapiStatus = &cobra.Command{
  114. Use: "status",
  115. Short: "Check authentication to Local API (LAPI)",
  116. Args: cobra.MinimumNArgs(0),
  117. DisableAutoGenTag: true,
  118. Run: func(cmd *cobra.Command, args []string) {
  119. var err error
  120. password := strfmt.Password(csConfig.API.Client.Credentials.Password)
  121. apiurl, err := url.Parse(csConfig.API.Client.Credentials.URL)
  122. login := csConfig.API.Client.Credentials.Login
  123. if err != nil {
  124. log.Fatalf("parsing api url ('%s'): %s", apiurl, err)
  125. }
  126. if err := csConfig.LoadHub(); err != nil {
  127. log.Fatal(err)
  128. }
  129. if err := cwhub.GetHubIdx(csConfig.Hub); err != nil {
  130. log.Info("Run 'sudo cscli hub update' to get the hub index")
  131. log.Fatalf("Failed to load hub index : %s", err)
  132. }
  133. scenarios, err := cwhub.GetInstalledScenariosAsString()
  134. if err != nil {
  135. log.Fatalf("failed to get scenarios : %s", err.Error())
  136. }
  137. Client, err = apiclient.NewDefaultClient(apiurl,
  138. LAPIURLPrefix,
  139. fmt.Sprintf("crowdsec/%s", cwversion.VersionStr()),
  140. nil)
  141. if err != nil {
  142. log.Fatalf("init default client: %s", err)
  143. }
  144. t := models.WatcherAuthRequest{
  145. MachineID: &login,
  146. Password: &password,
  147. Scenarios: scenarios,
  148. }
  149. log.Infof("Loaded credentials from %s", csConfig.API.Client.CredentialsFilePath)
  150. log.Infof("Trying to authenticate with username %s on %s", login, apiurl)
  151. _, err = Client.Auth.AuthenticateWatcher(context.Background(), t)
  152. if err != nil {
  153. log.Fatalf("Failed to authenticate to Local API (LAPI) : %s", err)
  154. } else {
  155. log.Infof("You can successfully interact with Local API (LAPI)")
  156. }
  157. },
  158. }
  159. cmdLapi.AddCommand(cmdLapiStatus)
  160. return cmdLapi
  161. }