support.go 13 KB

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