lapi.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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. log.Printf("Successfully registered to Local API (LAPI)")
  81. var dumpFile string
  82. if outputFile != "" {
  83. dumpFile = outputFile
  84. } else if csConfig.API.Client.CredentialsFilePath != "" {
  85. dumpFile = csConfig.API.Client.CredentialsFilePath
  86. } else {
  87. dumpFile = ""
  88. }
  89. apiCfg := csconfig.ApiCredentialsCfg{
  90. Login: lapiUser,
  91. Password: password.String(),
  92. URL: apiURL,
  93. }
  94. apiConfigDump, err := yaml.Marshal(apiCfg)
  95. if err != nil {
  96. log.Fatalf("unable to marshal api credentials: %s", err)
  97. }
  98. if dumpFile != "" {
  99. err = ioutil.WriteFile(dumpFile, apiConfigDump, 0644)
  100. if err != nil {
  101. log.Fatalf("write api credentials in '%s' failed: %s", dumpFile, err)
  102. }
  103. log.Printf("Local API credentials dumped to '%s'", dumpFile)
  104. } else {
  105. fmt.Printf("%s\n", string(apiConfigDump))
  106. }
  107. log.Warningf("Run 'sudo systemctl reload crowdsec' for the new configuration to be effective")
  108. },
  109. }
  110. cmdLapiRegister.Flags().StringVarP(&apiURL, "url", "u", "", "URL of the API (ie. http://127.0.0.1)")
  111. cmdLapiRegister.Flags().StringVarP(&outputFile, "file", "f", "", "output file destination")
  112. cmdLapiRegister.Flags().StringVar(&lapiUser, "machine", "", "Name of the machine to register with")
  113. cmdLapi.AddCommand(cmdLapiRegister)
  114. var cmdLapiStatus = &cobra.Command{
  115. Use: "status",
  116. Short: "Check authentication to Local API (LAPI)",
  117. Args: cobra.MinimumNArgs(0),
  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 := cwhub.GetHubIdx(csConfig.Cscli); err != nil {
  127. log.Fatalf("Failed to load hub index : %s", err)
  128. log.Infoln("Run 'sudo cscli hub update' to get the hub index")
  129. }
  130. scenarios, err := cwhub.GetUpstreamInstalledScenariosAsString()
  131. if err != nil {
  132. log.Fatalf("failed to get scenarios : %s", err.Error())
  133. }
  134. Client, err = apiclient.NewDefaultClient(apiurl,
  135. LAPIURLPrefix,
  136. fmt.Sprintf("crowdsec/%s", cwversion.VersionStr()),
  137. nil)
  138. if err != nil {
  139. log.Fatalf("init default client: %s", err)
  140. }
  141. t := models.WatcherAuthRequest{
  142. MachineID: &login,
  143. Password: &password,
  144. Scenarios: scenarios,
  145. }
  146. log.Infof("Loaded credentials from %s", csConfig.API.Client.CredentialsFilePath)
  147. log.Infof("Trying to authenticate with username %s on %s", login, apiurl)
  148. resp, err := Client.Auth.AuthenticateWatcher(context.Background(), t)
  149. if err != nil {
  150. log.Fatalf("Failed to authenticate to Local API (LAPI) : %s", err)
  151. } else {
  152. log.Infof("You can successfully interact with Local API (LAPI)")
  153. }
  154. for k, v := range resp.Response.Header {
  155. log.Debugf("[headers] %s : %s", k, v)
  156. }
  157. dump, _ := httputil.DumpResponse(resp.Response, true)
  158. log.Debugf("Response: %s", string(dump))
  159. },
  160. }
  161. cmdLapi.AddCommand(cmdLapiStatus)
  162. return cmdLapi
  163. }