support.go 12 KB

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