support.go 12 KB

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