lapi.go 5.3 KB

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