support.go 12 KB

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