support.go 14 KB

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