support.go 12 KB

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