lapi.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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 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 crowdsec API 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. Run: func(cmd *cobra.Command, args []string) {
  46. var err error
  47. if lapiUser == "" {
  48. lapiUser, err = generateID()
  49. if err != nil {
  50. log.Fatalf("unable to generate machine id: %s", err)
  51. }
  52. }
  53. password := strfmt.Password(generatePassword(passwordLength))
  54. if apiURL == "" {
  55. if csConfig.API.Client != nil && csConfig.API.Client.Credentials != nil && csConfig.API.Client.Credentials.URL != "" {
  56. apiURL = csConfig.API.Client.Credentials.URL
  57. } else {
  58. log.Fatalf("No Local API URL. Please provide it in your configuration or with the -u parameter")
  59. }
  60. }
  61. /*URL needs to end with /, but user doesn't care*/
  62. if !strings.HasSuffix(apiURL, "/") {
  63. apiURL += "/"
  64. }
  65. /*URL needs to start with http://, but user doesn't care*/
  66. if !strings.HasPrefix(apiURL, "http://") && !strings.HasPrefix(apiURL, "https://") {
  67. apiURL = "http://" + apiURL
  68. }
  69. apiurl, err := url.Parse(apiURL)
  70. if err != nil {
  71. log.Fatalf("parsing api url: %s", err)
  72. }
  73. _, err = apiclient.RegisterClient(&apiclient.Config{
  74. MachineID: lapiUser,
  75. Password: password,
  76. UserAgent: fmt.Sprintf("crowdsec/%s", cwversion.VersionStr()),
  77. URL: apiurl,
  78. VersionPrefix: LAPIURLPrefix,
  79. }, nil)
  80. if err != nil {
  81. log.Fatalf("api client register: %s", err)
  82. }
  83. log.Printf("Successfully registered to Local API (LAPI)")
  84. var dumpFile string
  85. if outputFile != "" {
  86. dumpFile = outputFile
  87. } else if csConfig.API.Client.CredentialsFilePath != "" {
  88. dumpFile = csConfig.API.Client.CredentialsFilePath
  89. } else {
  90. dumpFile = ""
  91. }
  92. apiCfg := csconfig.ApiCredentialsCfg{
  93. Login: lapiUser,
  94. Password: password.String(),
  95. URL: apiURL,
  96. }
  97. apiConfigDump, err := yaml.Marshal(apiCfg)
  98. if err != nil {
  99. log.Fatalf("unable to marshal api credentials: %s", err)
  100. }
  101. if dumpFile != "" {
  102. err = ioutil.WriteFile(dumpFile, apiConfigDump, 0644)
  103. if err != nil {
  104. log.Fatalf("write api credentials in '%s' failed: %s", dumpFile, err)
  105. }
  106. log.Printf("Local API credentials dumped to '%s'", dumpFile)
  107. } else {
  108. fmt.Printf("%s\n", string(apiConfigDump))
  109. }
  110. log.Warningf(ReloadMessage())
  111. },
  112. }
  113. cmdLapiRegister.Flags().StringVarP(&apiURL, "url", "u", "", "URL of the API (ie. http://127.0.0.1)")
  114. cmdLapiRegister.Flags().StringVarP(&outputFile, "file", "f", "", "output file destination")
  115. cmdLapiRegister.Flags().StringVar(&lapiUser, "machine", "", "Name of the machine to register with")
  116. cmdLapi.AddCommand(cmdLapiRegister)
  117. var cmdLapiStatus = &cobra.Command{
  118. Use: "status",
  119. Short: "Check authentication to Local API (LAPI)",
  120. Args: cobra.MinimumNArgs(0),
  121. Run: func(cmd *cobra.Command, args []string) {
  122. var err error
  123. password := strfmt.Password(csConfig.API.Client.Credentials.Password)
  124. apiurl, err := url.Parse(csConfig.API.Client.Credentials.URL)
  125. login := csConfig.API.Client.Credentials.Login
  126. if err != nil {
  127. log.Fatalf("parsing api url ('%s'): %s", apiurl, err)
  128. }
  129. if err := csConfig.LoadHub(); err != nil {
  130. log.Fatalf(err.Error())
  131. }
  132. if err := cwhub.GetHubIdx(csConfig.Hub); err != nil {
  133. log.Fatalf("Failed to load hub index : %s", err)
  134. log.Infoln("Run 'sudo cscli hub update' to get the hub index")
  135. }
  136. scenarios, err := cwhub.GetUpstreamInstalledScenariosAsString()
  137. if err != nil {
  138. log.Fatalf("failed to get scenarios : %s", err.Error())
  139. }
  140. Client, err = apiclient.NewDefaultClient(apiurl,
  141. LAPIURLPrefix,
  142. fmt.Sprintf("crowdsec/%s", cwversion.VersionStr()),
  143. nil)
  144. if err != nil {
  145. log.Fatalf("init default client: %s", err)
  146. }
  147. t := models.WatcherAuthRequest{
  148. MachineID: &login,
  149. Password: &password,
  150. Scenarios: scenarios,
  151. }
  152. log.Infof("Loaded credentials from %s", csConfig.API.Client.CredentialsFilePath)
  153. log.Infof("Trying to authenticate with username %s on %s", login, apiurl)
  154. resp, err := Client.Auth.AuthenticateWatcher(context.Background(), t)
  155. if err != nil {
  156. log.Fatalf("Failed to authenticate to Local API (LAPI) : %s", err)
  157. } else {
  158. log.Infof("You can successfully interact with Local API (LAPI)")
  159. }
  160. for k, v := range resp.Response.Header {
  161. log.Debugf("[headers] %s : %s", k, v)
  162. }
  163. dump, _ := httputil.DumpResponse(resp.Response, true)
  164. log.Debugf("Response: %s", string(dump))
  165. },
  166. }
  167. cmdLapi.AddCommand(cmdLapiStatus)
  168. return cmdLapi
  169. }