support.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. package main
  2. import (
  3. "archive/zip"
  4. "bytes"
  5. "context"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "path/filepath"
  12. "regexp"
  13. "strings"
  14. "github.com/blackfireio/osinfo"
  15. "github.com/go-openapi/strfmt"
  16. log "github.com/sirupsen/logrus"
  17. "github.com/spf13/cobra"
  18. "github.com/crowdsecurity/crowdsec/pkg/apiclient"
  19. "github.com/crowdsecurity/crowdsec/pkg/cwhub"
  20. "github.com/crowdsecurity/crowdsec/pkg/cwversion"
  21. "github.com/crowdsecurity/crowdsec/pkg/database"
  22. "github.com/crowdsecurity/crowdsec/pkg/models"
  23. "github.com/crowdsecurity/crowdsec/pkg/types"
  24. )
  25. const (
  26. SUPPORT_METRICS_HUMAN_PATH = "metrics/metrics.human"
  27. SUPPORT_METRICS_PROMETHEUS_PATH = "metrics/metrics.prometheus"
  28. SUPPORT_VERSION_PATH = "version.txt"
  29. SUPPORT_OS_INFO_PATH = "osinfo.txt"
  30. SUPPORT_PARSERS_PATH = "hub/parsers.txt"
  31. SUPPORT_SCENARIOS_PATH = "hub/scenarios.txt"
  32. SUPPORT_COLLECTIONS_PATH = "hub/collections.txt"
  33. SUPPORT_POSTOVERFLOWS_PATH = "hub/postoverflows.txt"
  34. SUPPORT_BOUNCERS_PATH = "lapi/bouncers.txt"
  35. SUPPORT_AGENTS_PATH = "lapi/agents.txt"
  36. SUPPORT_CROWDSEC_CONFIG_PATH = "config/crowdsec.yaml"
  37. SUPPORT_LAPI_STATUS_PATH = "lapi_status.txt"
  38. SUPPORT_CAPI_STATUS_PATH = "capi_status.txt"
  39. SUPPORT_ACQUISITION_CONFIG_BASE_PATH = "config/acquis/"
  40. SUPPORT_CROWDSEC_PROFILE_PATH = "config/profiles.yaml"
  41. )
  42. func collectMetrics() ([]byte, []byte, error) {
  43. log.Info("Collecting prometheus metrics")
  44. err := csConfig.LoadPrometheus()
  45. if err != nil {
  46. return nil, nil, err
  47. }
  48. if csConfig.Cscli.PrometheusUrl == "" {
  49. log.Warn("No Prometheus URL configured, metrics will not be collected")
  50. return nil, nil, fmt.Errorf("prometheus_uri is not set")
  51. }
  52. humanMetrics := bytes.NewBuffer(nil)
  53. err = FormatPrometheusMetrics(humanMetrics, csConfig.Cscli.PrometheusUrl+"/metrics", "human")
  54. if err != nil {
  55. return nil, nil, fmt.Errorf("could not fetch promtheus metrics: %s", err)
  56. }
  57. req, err := http.NewRequest(http.MethodGet, csConfig.Cscli.PrometheusUrl+"/metrics", nil)
  58. if err != nil {
  59. return nil, nil, fmt.Errorf("could not create requests to prometheus endpoint: %s", err)
  60. }
  61. client := &http.Client{}
  62. resp, err := client.Do(req)
  63. if err != nil {
  64. return nil, nil, fmt.Errorf("could not get metrics from prometheus endpoint: %s", err)
  65. }
  66. defer resp.Body.Close()
  67. body, err := io.ReadAll(resp.Body)
  68. if err != nil {
  69. return nil, nil, fmt.Errorf("could not read metrics from prometheus endpoint: %s", err)
  70. }
  71. return humanMetrics.Bytes(), body, nil
  72. }
  73. func collectVersion() []byte {
  74. log.Info("Collecting version")
  75. return []byte(cwversion.ShowStr())
  76. }
  77. func collectOSInfo() ([]byte, error) {
  78. log.Info("Collecting OS info")
  79. info, err := osinfo.GetOSInfo()
  80. if err != nil {
  81. return nil, err
  82. }
  83. w := bytes.NewBuffer(nil)
  84. w.WriteString(fmt.Sprintf("Architecture: %s\n", info.Architecture))
  85. w.WriteString(fmt.Sprintf("Family: %s\n", info.Family))
  86. w.WriteString(fmt.Sprintf("ID: %s\n", info.ID))
  87. w.WriteString(fmt.Sprintf("Name: %s\n", info.Name))
  88. w.WriteString(fmt.Sprintf("Codename: %s\n", info.Codename))
  89. w.WriteString(fmt.Sprintf("Version: %s\n", info.Version))
  90. w.WriteString(fmt.Sprintf("Build: %s\n", info.Build))
  91. return w.Bytes(), nil
  92. }
  93. func initHub() error {
  94. if err := csConfig.LoadHub(); err != nil {
  95. return fmt.Errorf("cannot load hub: %s", err)
  96. }
  97. if csConfig.Hub == nil {
  98. return fmt.Errorf("hub not configured")
  99. }
  100. if err := cwhub.SetHubBranch(); err != nil {
  101. return fmt.Errorf("cannot set hub branch: %s", err)
  102. }
  103. if err := cwhub.GetHubIdx(csConfig.Hub); err != nil {
  104. return fmt.Errorf("no hub index found: %s", err)
  105. }
  106. return nil
  107. }
  108. func collectHubItems(itemType string) []byte {
  109. out := bytes.NewBuffer(nil)
  110. log.Infof("Collecting %s list", itemType)
  111. ListItems(out, []string{itemType}, []string{}, false, true, all)
  112. return out.Bytes()
  113. }
  114. func collectBouncers(dbClient *database.Client) ([]byte, error) {
  115. out := bytes.NewBuffer(nil)
  116. err := getBouncers(out, dbClient)
  117. if err != nil {
  118. return nil, err
  119. }
  120. return out.Bytes(), nil
  121. }
  122. func collectAgents(dbClient *database.Client) ([]byte, error) {
  123. out := bytes.NewBuffer(nil)
  124. err := getAgents(out, dbClient)
  125. if err != nil {
  126. return nil, err
  127. }
  128. return out.Bytes(), nil
  129. }
  130. func collectAPIStatus(login string, password string, endpoint string, prefix string) []byte {
  131. if csConfig.API.Client == nil || csConfig.API.Client.Credentials == nil {
  132. return []byte("No agent credentials found, are we LAPI ?")
  133. }
  134. pwd := strfmt.Password(password)
  135. apiurl, err := url.Parse(endpoint)
  136. if err != nil {
  137. return []byte(fmt.Sprintf("cannot parse API URL: %s", err.Error()))
  138. }
  139. scenarios, err := cwhub.GetInstalledScenariosAsString()
  140. if err != nil {
  141. return []byte(fmt.Sprintf("could not collect scenarios: %s", err.Error()))
  142. }
  143. Client, err = apiclient.NewDefaultClient(apiurl,
  144. prefix,
  145. fmt.Sprintf("crowdsec/%s", cwversion.VersionStr()),
  146. nil)
  147. if err != nil {
  148. return []byte(fmt.Sprintf("could not init client: %s", err.Error()))
  149. }
  150. t := models.WatcherAuthRequest{
  151. MachineID: &login,
  152. Password: &pwd,
  153. Scenarios: scenarios,
  154. }
  155. _, err = Client.Auth.AuthenticateWatcher(context.Background(), t)
  156. if err != nil {
  157. return []byte(fmt.Sprintf("Could not authenticate to API: %s", err))
  158. } else {
  159. return []byte("Successfully authenticated to LAPI")
  160. }
  161. }
  162. func collectCrowdsecConfig() []byte {
  163. log.Info("Collecting crowdsec config")
  164. config, err := os.ReadFile(*csConfig.FilePath)
  165. if err != nil {
  166. return []byte(fmt.Sprintf("could not read config file: %s", err))
  167. }
  168. r := regexp.MustCompile(`(\s+password:|\s+user:|\s+host:)\s+.*`)
  169. return r.ReplaceAll(config, []byte("$1 ****REDACTED****"))
  170. }
  171. func collectCrowdsecProfile() []byte {
  172. log.Info("Collecting crowdsec profile")
  173. config, err := os.ReadFile(csConfig.API.Server.ProfilesPath)
  174. if err != nil {
  175. return []byte(fmt.Sprintf("could not read profile file: %s", err))
  176. }
  177. return config
  178. }
  179. func collectAcquisitionConfig() map[string][]byte {
  180. log.Info("Collecting acquisition config")
  181. ret := make(map[string][]byte)
  182. for _, filename := range csConfig.Crowdsec.AcquisitionFiles {
  183. fileContent, err := os.ReadFile(filename)
  184. if err != nil {
  185. ret[filename] = []byte(fmt.Sprintf("could not read file: %s", err))
  186. } else {
  187. ret[filename] = fileContent
  188. }
  189. }
  190. return ret
  191. }
  192. func NewSupportCmd() *cobra.Command {
  193. var cmdSupport = &cobra.Command{
  194. Use: "support [action]",
  195. Short: "Provide commands to help during support",
  196. Args: cobra.MinimumNArgs(1),
  197. DisableAutoGenTag: true,
  198. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  199. return nil
  200. },
  201. }
  202. var outFile string
  203. cmdDump := &cobra.Command{
  204. Use: "dump",
  205. Short: "Dump all your configuration to a zip file for easier support",
  206. Long: `Dump the following informations:
  207. - Crowdsec version
  208. - OS version
  209. - Installed collections list
  210. - Installed parsers list
  211. - Installed scenarios list
  212. - Installed postoverflows list
  213. - Bouncers list
  214. - Machines list
  215. - CAPI status
  216. - LAPI status
  217. - Crowdsec config (sensitive information like username and password are redacted)
  218. - Crowdsec metrics`,
  219. Example: `cscli support dump
  220. cscli support dump -f /tmp/crowdsec-support.zip
  221. `,
  222. Args: cobra.NoArgs,
  223. DisableAutoGenTag: true,
  224. Run: func(cmd *cobra.Command, args []string) {
  225. var err error
  226. var skipHub, skipDB, skipCAPI, skipLAPI, skipAgent bool
  227. infos := map[string][]byte{
  228. SUPPORT_VERSION_PATH: collectVersion(),
  229. }
  230. if outFile == "" {
  231. outFile = "/tmp/crowdsec-support.zip"
  232. }
  233. dbClient, err = database.NewClient(csConfig.DbConfig)
  234. if err != nil {
  235. log.Warnf("Could not connect to database: %s", err)
  236. skipDB = true
  237. infos[SUPPORT_BOUNCERS_PATH] = []byte(err.Error())
  238. infos[SUPPORT_AGENTS_PATH] = []byte(err.Error())
  239. }
  240. if err := csConfig.LoadAPIServer(); err != nil {
  241. log.Warnf("could not load LAPI, skipping CAPI check")
  242. skipLAPI = true
  243. infos[SUPPORT_CAPI_STATUS_PATH] = []byte(err.Error())
  244. }
  245. if err := csConfig.LoadCrowdsec(); err != nil {
  246. log.Warnf("could not load agent config, skipping crowdsec config check")
  247. skipAgent = true
  248. }
  249. err = initHub()
  250. if err != nil {
  251. log.Warn("Could not init hub, running on LAPI ? Hub related information will not be collected")
  252. skipHub = true
  253. infos[SUPPORT_PARSERS_PATH] = []byte(err.Error())
  254. infos[SUPPORT_SCENARIOS_PATH] = []byte(err.Error())
  255. infos[SUPPORT_POSTOVERFLOWS_PATH] = []byte(err.Error())
  256. infos[SUPPORT_COLLECTIONS_PATH] = []byte(err.Error())
  257. }
  258. if csConfig.API.Client == nil || csConfig.API.Client.Credentials == nil {
  259. log.Warn("no agent credentials found, skipping LAPI connectivity check")
  260. if _, ok := infos[SUPPORT_LAPI_STATUS_PATH]; ok {
  261. infos[SUPPORT_LAPI_STATUS_PATH] = append(infos[SUPPORT_LAPI_STATUS_PATH], []byte("\nNo LAPI credentials found")...)
  262. }
  263. skipLAPI = true
  264. }
  265. if csConfig.API.Server == nil || csConfig.API.Server.OnlineClient.Credentials == nil {
  266. log.Warn("no CAPI credentials found, skipping CAPI connectivity check")
  267. skipCAPI = true
  268. }
  269. infos[SUPPORT_METRICS_HUMAN_PATH], infos[SUPPORT_METRICS_PROMETHEUS_PATH], err = collectMetrics()
  270. if err != nil {
  271. log.Warnf("could not collect prometheus metrics information: %s", err)
  272. infos[SUPPORT_METRICS_HUMAN_PATH] = []byte(err.Error())
  273. infos[SUPPORT_METRICS_PROMETHEUS_PATH] = []byte(err.Error())
  274. }
  275. infos[SUPPORT_OS_INFO_PATH], err = collectOSInfo()
  276. if err != nil {
  277. log.Warnf("could not collect OS information: %s", err)
  278. infos[SUPPORT_OS_INFO_PATH] = []byte(err.Error())
  279. }
  280. infos[SUPPORT_CROWDSEC_CONFIG_PATH] = collectCrowdsecConfig()
  281. if !skipHub {
  282. infos[SUPPORT_PARSERS_PATH] = collectHubItems(cwhub.PARSERS)
  283. infos[SUPPORT_SCENARIOS_PATH] = collectHubItems(cwhub.SCENARIOS)
  284. infos[SUPPORT_POSTOVERFLOWS_PATH] = collectHubItems(cwhub.PARSERS_OVFLW)
  285. infos[SUPPORT_COLLECTIONS_PATH] = collectHubItems(cwhub.COLLECTIONS)
  286. }
  287. if !skipDB {
  288. infos[SUPPORT_BOUNCERS_PATH], err = collectBouncers(dbClient)
  289. if err != nil {
  290. log.Warnf("could not collect bouncers information: %s", err)
  291. infos[SUPPORT_BOUNCERS_PATH] = []byte(err.Error())
  292. }
  293. infos[SUPPORT_AGENTS_PATH], err = collectAgents(dbClient)
  294. if err != nil {
  295. log.Warnf("could not collect agents information: %s", err)
  296. infos[SUPPORT_AGENTS_PATH] = []byte(err.Error())
  297. }
  298. }
  299. if !skipCAPI {
  300. log.Info("Collecting CAPI status")
  301. infos[SUPPORT_CAPI_STATUS_PATH] = collectAPIStatus(csConfig.API.Server.OnlineClient.Credentials.Login,
  302. csConfig.API.Server.OnlineClient.Credentials.Password,
  303. csConfig.API.Server.OnlineClient.Credentials.URL,
  304. CAPIURLPrefix)
  305. }
  306. if !skipLAPI {
  307. log.Info("Collection LAPI status")
  308. infos[SUPPORT_LAPI_STATUS_PATH] = collectAPIStatus(csConfig.API.Client.Credentials.Login,
  309. csConfig.API.Client.Credentials.Password,
  310. csConfig.API.Client.Credentials.URL,
  311. LAPIURLPrefix)
  312. infos[SUPPORT_CROWDSEC_PROFILE_PATH] = collectCrowdsecProfile()
  313. }
  314. if !skipAgent {
  315. acquis := collectAcquisitionConfig()
  316. for filename, content := range acquis {
  317. fname := strings.ReplaceAll(filename, string(filepath.Separator), "___")
  318. infos[SUPPORT_ACQUISITION_CONFIG_BASE_PATH+fname] = content
  319. }
  320. }
  321. w := bytes.NewBuffer(nil)
  322. zipWriter := zip.NewWriter(w)
  323. for filename, data := range infos {
  324. fw, err := zipWriter.Create(filename)
  325. if err != nil {
  326. log.Errorf("Could not add zip entry for %s: %s", filename, err)
  327. continue
  328. }
  329. fw.Write([]byte(types.StripAnsiString(string(data))))
  330. }
  331. err = zipWriter.Close()
  332. if err != nil {
  333. log.Fatalf("could not finalize zip file: %s", err)
  334. }
  335. err = os.WriteFile(outFile, w.Bytes(), 0600)
  336. if err != nil {
  337. log.Fatalf("could not write zip file to %s: %s", outFile, err)
  338. }
  339. log.Infof("Written zip file to %s", outFile)
  340. },
  341. }
  342. cmdDump.Flags().StringVarP(&outFile, "outFile", "f", "", "File to dump the information to")
  343. cmdSupport.AddCommand(cmdDump)
  344. return cmdSupport
  345. }