lapi.go 5.7 KB

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