lapi.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http/httputil"
  7. "net/url"
  8. "strings"
  9. "github.com/crowdsecurity/crowdsec/pkg/apiclient"
  10. "github.com/crowdsecurity/crowdsec/pkg/csconfig"
  11. "github.com/crowdsecurity/crowdsec/pkg/cwhub"
  12. "github.com/crowdsecurity/crowdsec/pkg/cwversion"
  13. "github.com/crowdsecurity/crowdsec/pkg/models"
  14. "github.com/go-openapi/strfmt"
  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. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  27. if csConfig.API.Client == nil {
  28. log.Fatalln("There is no API->client configuration")
  29. }
  30. if csConfig.API.Client.Credentials == nil {
  31. log.Fatalf("no configuration for crowdsec API in '%s'", *csConfig.Self)
  32. }
  33. return nil
  34. },
  35. }
  36. var cmdLapiRegister = &cobra.Command{
  37. Use: "register",
  38. Short: "Register a machine to Local API (LAPI)",
  39. Long: `Register you machine to the Local API (LAPI).
  40. Keep in mind the machine needs to be validated by an administrator on LAPI side to be effective.`,
  41. Args: cobra.MinimumNArgs(0),
  42. Run: func(cmd *cobra.Command, args []string) {
  43. var err error
  44. if lapiUser == "" {
  45. lapiUser, err = generateID()
  46. if err != nil {
  47. log.Fatalf("unable to generate machine id: %s", err)
  48. }
  49. }
  50. password := strfmt.Password(generatePassword(passwordLength))
  51. if apiURL == "" {
  52. if csConfig.API.Client != nil && csConfig.API.Client.Credentials != nil && csConfig.API.Client.Credentials.URL != "" {
  53. apiURL = csConfig.API.Client.Credentials.URL
  54. } else {
  55. log.Fatalf("No Local API URL. Please provide it in your configuration or with the -u parameter")
  56. }
  57. }
  58. /*URL needs to end with /, but user doesn't care*/
  59. if !strings.HasSuffix(apiURL, "/") {
  60. apiURL += "/"
  61. }
  62. /*URL needs to start with http://, but user doesn't care*/
  63. if !strings.HasPrefix(apiURL, "http://") && !strings.HasPrefix(apiURL, "https://") {
  64. apiURL = "http://" + apiURL
  65. }
  66. apiurl, err := url.Parse(apiURL)
  67. if err != nil {
  68. log.Fatalf("parsing api url: %s", err)
  69. }
  70. _, err = apiclient.RegisterClient(&apiclient.Config{
  71. MachineID: lapiUser,
  72. Password: password,
  73. UserAgent: fmt.Sprintf("crowdsec/%s", cwversion.VersionStr()),
  74. URL: apiurl,
  75. VersionPrefix: LAPIURLPrefix,
  76. }, nil)
  77. if err != nil {
  78. log.Fatalf("api client register: %s", err)
  79. }
  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("API credentials dumped to '%s'", dumpFile)
  103. } else {
  104. fmt.Printf("%s\n", string(apiConfigDump))
  105. }
  106. log.Warningf("Run 'sudo systemctl reload crowdsec' for the new configuration to be effective")
  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, "username", "", "output file destination")
  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. Run: func(cmd *cobra.Command, args []string) {
  118. var err error
  119. password := strfmt.Password(csConfig.API.Client.Credentials.Password)
  120. apiurl, err := url.Parse(csConfig.API.Client.Credentials.URL)
  121. login := csConfig.API.Client.Credentials.Login
  122. if err != nil {
  123. log.Fatalf("parsing api url ('%s'): %s", apiurl, err)
  124. }
  125. if err := cwhub.GetHubIdx(csConfig.Cscli); err != nil {
  126. log.Fatalf("Failed to load hub index : %s", err)
  127. log.Infoln("Run 'sudo cscli hub update' to get the hub index")
  128. }
  129. scenarios, err := cwhub.GetUpstreamInstalledScenariosAsString()
  130. if err != nil {
  131. log.Fatalf("failed to get scenarios : %s", err.Error())
  132. }
  133. Client, err = apiclient.NewDefaultClient(apiurl,
  134. LAPIURLPrefix,
  135. fmt.Sprintf("crowdsec/%s", cwversion.VersionStr()),
  136. nil)
  137. if err != nil {
  138. log.Fatalf("init default client: %s", err)
  139. }
  140. t := models.WatcherAuthRequest{
  141. MachineID: &login,
  142. Password: &password,
  143. Scenarios: scenarios,
  144. }
  145. log.Infof("Loaded credentials from %s", csConfig.API.Client.CredentialsFilePath)
  146. log.Infof("Trying to authenticate with username %s on %s", login, apiurl)
  147. resp, err := Client.Auth.AuthenticateWatcher(context.Background(), t)
  148. if err != nil {
  149. log.Fatalf("Failed to authenticate to Local API (LAPI) : %s", err)
  150. } else {
  151. log.Infof("You can successfully interact with Local API (LAPI)")
  152. }
  153. for k, v := range resp.Response.Header {
  154. log.Debugf("[headers] %s : %s", k, v)
  155. }
  156. dump, _ := httputil.DumpResponse(resp.Response, true)
  157. log.Debugf("Response: %s", string(dump))
  158. },
  159. }
  160. cmdLapi.AddCommand(cmdLapiStatus)
  161. return cmdLapi
  162. }