utils.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. package main
  2. import (
  3. "encoding/csv"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "math"
  8. "net"
  9. "net/http"
  10. "slices"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/fatih/color"
  15. dto "github.com/prometheus/client_model/go"
  16. "github.com/prometheus/prom2json"
  17. log "github.com/sirupsen/logrus"
  18. "github.com/spf13/cobra"
  19. "github.com/agext/levenshtein"
  20. "gopkg.in/yaml.v2"
  21. "github.com/crowdsecurity/go-cs-lib/trace"
  22. "github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/require"
  23. "github.com/crowdsecurity/crowdsec/pkg/cwhub"
  24. "github.com/crowdsecurity/crowdsec/pkg/database"
  25. "github.com/crowdsecurity/crowdsec/pkg/types"
  26. )
  27. const MaxDistance = 7
  28. func printHelp(cmd *cobra.Command) {
  29. err := cmd.Help()
  30. if err != nil {
  31. log.Fatalf("unable to print help(): %s", err)
  32. }
  33. }
  34. func Suggest(itemType string, baseItem string, suggestItem string, score int, ignoreErr bool) {
  35. errMsg := ""
  36. if score < MaxDistance {
  37. errMsg = fmt.Sprintf("unable to find %s '%s', did you mean %s ?", itemType, baseItem, suggestItem)
  38. } else {
  39. errMsg = fmt.Sprintf("unable to find %s '%s'", itemType, baseItem)
  40. }
  41. if ignoreErr {
  42. log.Error(errMsg)
  43. } else {
  44. log.Fatalf(errMsg)
  45. }
  46. }
  47. func GetDistance(itemType string, itemName string) (*cwhub.Item, int) {
  48. allItems := make([]string, 0)
  49. nearestScore := 100
  50. nearestItem := &cwhub.Item{}
  51. hubItems := cwhub.GetHubStatusForItemType(itemType, "", true)
  52. for _, item := range hubItems {
  53. allItems = append(allItems, item.Name)
  54. }
  55. for _, s := range allItems {
  56. d := levenshtein.Distance(itemName, s, nil)
  57. if d < nearestScore {
  58. nearestScore = d
  59. nearestItem = cwhub.GetItem(itemType, s)
  60. }
  61. }
  62. return nearestItem, nearestScore
  63. }
  64. func compAllItems(itemType string, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  65. if err := require.Hub(csConfig); err != nil {
  66. return nil, cobra.ShellCompDirectiveDefault
  67. }
  68. comp := make([]string, 0)
  69. hubItems := cwhub.GetHubStatusForItemType(itemType, "", true)
  70. for _, item := range hubItems {
  71. if !slices.Contains(args, item.Name) && strings.Contains(item.Name, toComplete) {
  72. comp = append(comp, item.Name)
  73. }
  74. }
  75. cobra.CompDebugln(fmt.Sprintf("%s: %+v", itemType, comp), true)
  76. return comp, cobra.ShellCompDirectiveNoFileComp
  77. }
  78. func compInstalledItems(itemType string, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  79. if err := require.Hub(csConfig); err != nil {
  80. return nil, cobra.ShellCompDirectiveDefault
  81. }
  82. items, err := cwhub.GetInstalledItemsAsString(itemType)
  83. if err != nil {
  84. cobra.CompDebugln(fmt.Sprintf("list installed %s err: %s", itemType, err), true)
  85. return nil, cobra.ShellCompDirectiveDefault
  86. }
  87. comp := make([]string, 0)
  88. if toComplete != "" {
  89. for _, item := range items {
  90. if strings.Contains(item, toComplete) {
  91. comp = append(comp, item)
  92. }
  93. }
  94. } else {
  95. comp = items
  96. }
  97. cobra.CompDebugln(fmt.Sprintf("%s: %+v", itemType, comp), true)
  98. return comp, cobra.ShellCompDirectiveNoFileComp
  99. }
  100. func ListItems(out io.Writer, itemTypes []string, args []string, showType bool, showHeader bool, all bool) {
  101. var hubStatusByItemType = make(map[string][]cwhub.ItemHubStatus)
  102. for _, itemType := range itemTypes {
  103. itemName := ""
  104. if len(args) == 1 {
  105. itemName = args[0]
  106. }
  107. hubStatusByItemType[itemType] = cwhub.GetHubStatusForItemType(itemType, itemName, all)
  108. }
  109. if csConfig.Cscli.Output == "human" {
  110. for _, itemType := range itemTypes {
  111. var statuses []cwhub.ItemHubStatus
  112. var ok bool
  113. if statuses, ok = hubStatusByItemType[itemType]; !ok {
  114. log.Errorf("unknown item type: %s", itemType)
  115. continue
  116. }
  117. listHubItemTable(out, "\n"+strings.ToUpper(itemType), statuses)
  118. }
  119. } else if csConfig.Cscli.Output == "json" {
  120. x, err := json.MarshalIndent(hubStatusByItemType, "", " ")
  121. if err != nil {
  122. log.Fatalf("failed to unmarshal")
  123. }
  124. out.Write(x)
  125. } else if csConfig.Cscli.Output == "raw" {
  126. csvwriter := csv.NewWriter(out)
  127. if showHeader {
  128. header := []string{"name", "status", "version", "description"}
  129. if showType {
  130. header = append(header, "type")
  131. }
  132. err := csvwriter.Write(header)
  133. if err != nil {
  134. log.Fatalf("failed to write header: %s", err)
  135. }
  136. }
  137. for _, itemType := range itemTypes {
  138. var statuses []cwhub.ItemHubStatus
  139. var ok bool
  140. if statuses, ok = hubStatusByItemType[itemType]; !ok {
  141. log.Errorf("unknown item type: %s", itemType)
  142. continue
  143. }
  144. for _, status := range statuses {
  145. if status.LocalVersion == "" {
  146. status.LocalVersion = "n/a"
  147. }
  148. row := []string{
  149. status.Name,
  150. status.Status,
  151. status.LocalVersion,
  152. status.Description,
  153. }
  154. if showType {
  155. row = append(row, itemType)
  156. }
  157. err := csvwriter.Write(row)
  158. if err != nil {
  159. log.Fatalf("failed to write raw output : %s", err)
  160. }
  161. }
  162. }
  163. csvwriter.Flush()
  164. }
  165. }
  166. func InspectItem(name string, objecitemType string) {
  167. hubItem := cwhub.GetItem(objecitemType, name)
  168. if hubItem == nil {
  169. log.Fatalf("unable to retrieve item.")
  170. }
  171. var b []byte
  172. var err error
  173. switch csConfig.Cscli.Output {
  174. case "human", "raw":
  175. b, err = yaml.Marshal(*hubItem)
  176. if err != nil {
  177. log.Fatalf("unable to marshal item : %s", err)
  178. }
  179. case "json":
  180. b, err = json.MarshalIndent(*hubItem, "", " ")
  181. if err != nil {
  182. log.Fatalf("unable to marshal item : %s", err)
  183. }
  184. }
  185. fmt.Printf("%s", string(b))
  186. if csConfig.Cscli.Output == "json" || csConfig.Cscli.Output == "raw" {
  187. return
  188. }
  189. if prometheusURL == "" {
  190. //This is technically wrong to do this, as the prometheus section contains a listen address, not an URL to query prometheus
  191. //But for ease of use, we will use the listen address as the prometheus URL because it will be 127.0.0.1 in the default case
  192. listenAddr := csConfig.Prometheus.ListenAddr
  193. listenPort := csConfig.Prometheus.ListenPort
  194. prometheusURL = fmt.Sprintf("http://%s:%d/metrics", listenAddr, listenPort)
  195. log.Debugf("No prometheus URL provided using: %s", prometheusURL)
  196. }
  197. fmt.Printf("\nCurrent metrics : \n")
  198. ShowMetrics(hubItem)
  199. }
  200. func manageCliDecisionAlerts(ip *string, ipRange *string, scope *string, value *string) error {
  201. /*if a range is provided, change the scope*/
  202. if *ipRange != "" {
  203. _, _, err := net.ParseCIDR(*ipRange)
  204. if err != nil {
  205. return fmt.Errorf("%s isn't a valid range", *ipRange)
  206. }
  207. }
  208. if *ip != "" {
  209. ipRepr := net.ParseIP(*ip)
  210. if ipRepr == nil {
  211. return fmt.Errorf("%s isn't a valid ip", *ip)
  212. }
  213. }
  214. //avoid confusion on scope (ip vs Ip and range vs Range)
  215. switch strings.ToLower(*scope) {
  216. case "ip":
  217. *scope = types.Ip
  218. case "range":
  219. *scope = types.Range
  220. case "country":
  221. *scope = types.Country
  222. case "as":
  223. *scope = types.AS
  224. }
  225. return nil
  226. }
  227. func ShowMetrics(hubItem *cwhub.Item) {
  228. switch hubItem.Type {
  229. case cwhub.PARSERS:
  230. metrics := GetParserMetric(prometheusURL, hubItem.Name)
  231. parserMetricsTable(color.Output, hubItem.Name, metrics)
  232. case cwhub.SCENARIOS:
  233. metrics := GetScenarioMetric(prometheusURL, hubItem.Name)
  234. scenarioMetricsTable(color.Output, hubItem.Name, metrics)
  235. case cwhub.COLLECTIONS:
  236. for _, item := range hubItem.Parsers {
  237. metrics := GetParserMetric(prometheusURL, item)
  238. parserMetricsTable(color.Output, item, metrics)
  239. }
  240. for _, item := range hubItem.Scenarios {
  241. metrics := GetScenarioMetric(prometheusURL, item)
  242. scenarioMetricsTable(color.Output, item, metrics)
  243. }
  244. for _, item := range hubItem.Collections {
  245. hubItem = cwhub.GetItem(cwhub.COLLECTIONS, item)
  246. if hubItem == nil {
  247. log.Fatalf("unable to retrieve item '%s' from collection '%s'", item, hubItem.Name)
  248. }
  249. ShowMetrics(hubItem)
  250. }
  251. default:
  252. log.Errorf("item of type '%s' is unknown", hubItem.Type)
  253. }
  254. }
  255. // GetParserMetric is a complete rip from prom2json
  256. func GetParserMetric(url string, itemName string) map[string]map[string]int {
  257. stats := make(map[string]map[string]int)
  258. result := GetPrometheusMetric(url)
  259. for idx, fam := range result {
  260. if !strings.HasPrefix(fam.Name, "cs_") {
  261. continue
  262. }
  263. log.Tracef("round %d", idx)
  264. for _, m := range fam.Metrics {
  265. metric, ok := m.(prom2json.Metric)
  266. if !ok {
  267. log.Debugf("failed to convert metric to prom2json.Metric")
  268. continue
  269. }
  270. name, ok := metric.Labels["name"]
  271. if !ok {
  272. log.Debugf("no name in Metric %v", metric.Labels)
  273. }
  274. if name != itemName {
  275. continue
  276. }
  277. source, ok := metric.Labels["source"]
  278. if !ok {
  279. log.Debugf("no source in Metric %v", metric.Labels)
  280. } else {
  281. if srctype, ok := metric.Labels["type"]; ok {
  282. source = srctype + ":" + source
  283. }
  284. }
  285. value := m.(prom2json.Metric).Value
  286. fval, err := strconv.ParseFloat(value, 32)
  287. if err != nil {
  288. log.Errorf("Unexpected int value %s : %s", value, err)
  289. continue
  290. }
  291. ival := int(fval)
  292. switch fam.Name {
  293. case "cs_reader_hits_total":
  294. if _, ok := stats[source]; !ok {
  295. stats[source] = make(map[string]int)
  296. stats[source]["parsed"] = 0
  297. stats[source]["reads"] = 0
  298. stats[source]["unparsed"] = 0
  299. stats[source]["hits"] = 0
  300. }
  301. stats[source]["reads"] += ival
  302. case "cs_parser_hits_ok_total":
  303. if _, ok := stats[source]; !ok {
  304. stats[source] = make(map[string]int)
  305. }
  306. stats[source]["parsed"] += ival
  307. case "cs_parser_hits_ko_total":
  308. if _, ok := stats[source]; !ok {
  309. stats[source] = make(map[string]int)
  310. }
  311. stats[source]["unparsed"] += ival
  312. case "cs_node_hits_total":
  313. if _, ok := stats[source]; !ok {
  314. stats[source] = make(map[string]int)
  315. }
  316. stats[source]["hits"] += ival
  317. case "cs_node_hits_ok_total":
  318. if _, ok := stats[source]; !ok {
  319. stats[source] = make(map[string]int)
  320. }
  321. stats[source]["parsed"] += ival
  322. case "cs_node_hits_ko_total":
  323. if _, ok := stats[source]; !ok {
  324. stats[source] = make(map[string]int)
  325. }
  326. stats[source]["unparsed"] += ival
  327. default:
  328. continue
  329. }
  330. }
  331. }
  332. return stats
  333. }
  334. func GetScenarioMetric(url string, itemName string) map[string]int {
  335. stats := make(map[string]int)
  336. stats["instantiation"] = 0
  337. stats["curr_count"] = 0
  338. stats["overflow"] = 0
  339. stats["pour"] = 0
  340. stats["underflow"] = 0
  341. result := GetPrometheusMetric(url)
  342. for idx, fam := range result {
  343. if !strings.HasPrefix(fam.Name, "cs_") {
  344. continue
  345. }
  346. log.Tracef("round %d", idx)
  347. for _, m := range fam.Metrics {
  348. metric, ok := m.(prom2json.Metric)
  349. if !ok {
  350. log.Debugf("failed to convert metric to prom2json.Metric")
  351. continue
  352. }
  353. name, ok := metric.Labels["name"]
  354. if !ok {
  355. log.Debugf("no name in Metric %v", metric.Labels)
  356. }
  357. if name != itemName {
  358. continue
  359. }
  360. value := m.(prom2json.Metric).Value
  361. fval, err := strconv.ParseFloat(value, 32)
  362. if err != nil {
  363. log.Errorf("Unexpected int value %s : %s", value, err)
  364. continue
  365. }
  366. ival := int(fval)
  367. switch fam.Name {
  368. case "cs_bucket_created_total":
  369. stats["instantiation"] += ival
  370. case "cs_buckets":
  371. stats["curr_count"] += ival
  372. case "cs_bucket_overflowed_total":
  373. stats["overflow"] += ival
  374. case "cs_bucket_poured_total":
  375. stats["pour"] += ival
  376. case "cs_bucket_underflowed_total":
  377. stats["underflow"] += ival
  378. default:
  379. continue
  380. }
  381. }
  382. }
  383. return stats
  384. }
  385. func GetPrometheusMetric(url string) []*prom2json.Family {
  386. mfChan := make(chan *dto.MetricFamily, 1024)
  387. // Start with the DefaultTransport for sane defaults.
  388. transport := http.DefaultTransport.(*http.Transport).Clone()
  389. // Conservatively disable HTTP keep-alives as this program will only
  390. // ever need a single HTTP request.
  391. transport.DisableKeepAlives = true
  392. // Timeout early if the server doesn't even return the headers.
  393. transport.ResponseHeaderTimeout = time.Minute
  394. go func() {
  395. defer trace.CatchPanic("crowdsec/GetPrometheusMetric")
  396. err := prom2json.FetchMetricFamilies(url, mfChan, transport)
  397. if err != nil {
  398. log.Fatalf("failed to fetch prometheus metrics : %v", err)
  399. }
  400. }()
  401. result := []*prom2json.Family{}
  402. for mf := range mfChan {
  403. result = append(result, prom2json.NewFamily(mf))
  404. }
  405. log.Debugf("Finished reading prometheus output, %d entries", len(result))
  406. return result
  407. }
  408. type unit struct {
  409. value int64
  410. symbol string
  411. }
  412. var ranges = []unit{
  413. {value: 1e18, symbol: "E"},
  414. {value: 1e15, symbol: "P"},
  415. {value: 1e12, symbol: "T"},
  416. {value: 1e9, symbol: "G"},
  417. {value: 1e6, symbol: "M"},
  418. {value: 1e3, symbol: "k"},
  419. {value: 1, symbol: ""},
  420. }
  421. func formatNumber(num int) string {
  422. goodUnit := unit{}
  423. for _, u := range ranges {
  424. if int64(num) >= u.value {
  425. goodUnit = u
  426. break
  427. }
  428. }
  429. if goodUnit.value == 1 {
  430. return fmt.Sprintf("%d%s", num, goodUnit.symbol)
  431. }
  432. res := math.Round(float64(num)/float64(goodUnit.value)*100) / 100
  433. return fmt.Sprintf("%.2f%s", res, goodUnit.symbol)
  434. }
  435. func getDBClient() (*database.Client, error) {
  436. var err error
  437. if err := csConfig.LoadAPIServer(); err != nil || csConfig.DisableAPI {
  438. return nil, err
  439. }
  440. ret, err := database.NewClient(csConfig.DbConfig)
  441. if err != nil {
  442. return nil, err
  443. }
  444. return ret, nil
  445. }
  446. func removeFromSlice(val string, slice []string) []string {
  447. var i int
  448. var value string
  449. valueFound := false
  450. // get the index
  451. for i, value = range slice {
  452. if value == val {
  453. valueFound = true
  454. break
  455. }
  456. }
  457. if valueFound {
  458. slice[i] = slice[len(slice)-1]
  459. slice[len(slice)-1] = ""
  460. slice = slice[:len(slice)-1]
  461. }
  462. return slice
  463. }