support.go 13 KB

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