helpers.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. package exprhelpers
  2. import (
  3. "bufio"
  4. "encoding/base64"
  5. "fmt"
  6. "math"
  7. "net"
  8. "net/url"
  9. "os"
  10. "path/filepath"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/antonmedv/expr"
  16. "github.com/bluele/gcache"
  17. "github.com/c-robinson/iplib"
  18. "github.com/cespare/xxhash/v2"
  19. "github.com/davecgh/go-spew/spew"
  20. "github.com/prometheus/client_golang/prometheus"
  21. log "github.com/sirupsen/logrus"
  22. "github.com/umahmood/haversine"
  23. "github.com/wasilibs/go-re2"
  24. "github.com/crowdsecurity/go-cs-lib/ptr"
  25. "github.com/crowdsecurity/crowdsec/pkg/cache"
  26. "github.com/crowdsecurity/crowdsec/pkg/database"
  27. "github.com/crowdsecurity/crowdsec/pkg/fflag"
  28. "github.com/crowdsecurity/crowdsec/pkg/types"
  29. )
  30. var dataFile map[string][]string
  31. var dataFileRegex map[string][]*regexp.Regexp
  32. var dataFileRe2 map[string][]*re2.Regexp
  33. // This is used to (optionally) cache regexp results for RegexpInFile operations
  34. var dataFileRegexCache map[string]gcache.Cache = make(map[string]gcache.Cache)
  35. /*prometheus*/
  36. var RegexpCacheMetrics = prometheus.NewGaugeVec(
  37. prometheus.GaugeOpts{
  38. Name: "cs_regexp_cache_size",
  39. Help: "Entries per regexp cache.",
  40. },
  41. []string{"name"},
  42. )
  43. var dbClient *database.Client
  44. var exprFunctionOptions []expr.Option
  45. var keyValuePattern = regexp.MustCompile(`(?P<key>[^=\s]+)=(?:"(?P<quoted_value>[^"\\]*(?:\\.[^"\\]*)*)"|(?P<value>[^=\s]+)|\s*)`)
  46. func GetExprOptions(ctx map[string]interface{}) []expr.Option {
  47. if len(exprFunctionOptions) == 0 {
  48. exprFunctionOptions = []expr.Option{}
  49. for _, function := range exprFuncs {
  50. exprFunctionOptions = append(exprFunctionOptions,
  51. expr.Function(function.name,
  52. function.function,
  53. function.signature...,
  54. ))
  55. }
  56. }
  57. ret := []expr.Option{}
  58. ret = append(ret, exprFunctionOptions...)
  59. ret = append(ret, expr.Env(ctx))
  60. return ret
  61. }
  62. func Init(databaseClient *database.Client) error {
  63. dataFile = make(map[string][]string)
  64. dataFileRegex = make(map[string][]*regexp.Regexp)
  65. dataFileRe2 = make(map[string][]*re2.Regexp)
  66. dbClient = databaseClient
  67. return nil
  68. }
  69. func RegexpCacheInit(filename string, CacheCfg types.DataSource) error {
  70. //cache is explicitly disabled
  71. if CacheCfg.Cache != nil && !*CacheCfg.Cache {
  72. return nil
  73. }
  74. //cache is implicitly disabled if no cache config is provided
  75. if CacheCfg.Strategy == nil && CacheCfg.TTL == nil && CacheCfg.Size == nil {
  76. return nil
  77. }
  78. //cache is enabled
  79. if CacheCfg.Size == nil {
  80. CacheCfg.Size = ptr.Of(50)
  81. }
  82. gc := gcache.New(*CacheCfg.Size)
  83. if CacheCfg.Strategy == nil {
  84. CacheCfg.Strategy = ptr.Of("LRU")
  85. }
  86. switch *CacheCfg.Strategy {
  87. case "LRU":
  88. gc = gc.LRU()
  89. case "LFU":
  90. gc = gc.LFU()
  91. case "ARC":
  92. gc = gc.ARC()
  93. default:
  94. return fmt.Errorf("unknown cache strategy '%s'", *CacheCfg.Strategy)
  95. }
  96. if CacheCfg.TTL != nil {
  97. gc.Expiration(*CacheCfg.TTL)
  98. }
  99. cache := gc.Build()
  100. dataFileRegexCache[filename] = cache
  101. return nil
  102. }
  103. // UpdateCacheMetrics is called directly by the prom handler
  104. func UpdateRegexpCacheMetrics() {
  105. RegexpCacheMetrics.Reset()
  106. for name := range dataFileRegexCache {
  107. RegexpCacheMetrics.With(prometheus.Labels{"name": name}).Set(float64(dataFileRegexCache[name].Len(true)))
  108. }
  109. }
  110. func FileInit(fileFolder string, filename string, fileType string) error {
  111. log.Debugf("init (folder:%s) (file:%s) (type:%s)", fileFolder, filename, fileType)
  112. filepath := filepath.Join(fileFolder, filename)
  113. file, err := os.Open(filepath)
  114. if err != nil {
  115. return err
  116. }
  117. defer file.Close()
  118. if fileType == "" {
  119. log.Debugf("ignored file %s%s because no type specified", fileFolder, filename)
  120. return nil
  121. }
  122. if _, ok := dataFile[filename]; !ok {
  123. dataFile[filename] = []string{}
  124. }
  125. scanner := bufio.NewScanner(file)
  126. for scanner.Scan() {
  127. if strings.HasPrefix(scanner.Text(), "#") { // allow comments
  128. continue
  129. }
  130. if len(scanner.Text()) == 0 { //skip empty lines
  131. continue
  132. }
  133. switch fileType {
  134. case "regex", "regexp":
  135. if fflag.Re2RegexpInfileSupport.IsEnabled() {
  136. dataFileRe2[filename] = append(dataFileRe2[filename], re2.MustCompile(scanner.Text()))
  137. } else {
  138. dataFileRegex[filename] = append(dataFileRegex[filename], regexp.MustCompile(scanner.Text()))
  139. }
  140. case "string":
  141. dataFile[filename] = append(dataFile[filename], scanner.Text())
  142. default:
  143. return fmt.Errorf("unknown data type '%s' for : '%s'", fileType, filename)
  144. }
  145. }
  146. if err := scanner.Err(); err != nil {
  147. return err
  148. }
  149. return nil
  150. }
  151. //Expr helpers
  152. // func Get(arr []string, index int) string {
  153. func Get(params ...any) (any, error) {
  154. arr := params[0].([]string)
  155. index := params[1].(int)
  156. if index >= len(arr) {
  157. return "", nil
  158. }
  159. return arr[index], nil
  160. }
  161. // func Atof(x string) float64 {
  162. func Atof(params ...any) (any, error) {
  163. x := params[0].(string)
  164. log.Debugf("debug atof %s", x)
  165. ret, err := strconv.ParseFloat(x, 64)
  166. if err != nil {
  167. log.Warningf("Atof : can't convert float '%s' : %v", x, err)
  168. }
  169. return ret, nil
  170. }
  171. // func Upper(s string) string {
  172. func Upper(params ...any) (any, error) {
  173. s := params[0].(string)
  174. return strings.ToUpper(s), nil
  175. }
  176. // func Lower(s string) string {
  177. func Lower(params ...any) (any, error) {
  178. s := params[0].(string)
  179. return strings.ToLower(s), nil
  180. }
  181. // func Distance(lat1 string, long1 string, lat2 string, long2 string) (float64, error) {
  182. func Distance(params ...any) (any, error) {
  183. lat1 := params[0].(string)
  184. long1 := params[1].(string)
  185. lat2 := params[2].(string)
  186. long2 := params[3].(string)
  187. lat1f, err := strconv.ParseFloat(lat1, 64)
  188. if err != nil {
  189. log.Warningf("lat1 is not a float : %v", err)
  190. return 0.0, fmt.Errorf("lat1 is not a float : %v", err)
  191. }
  192. long1f, err := strconv.ParseFloat(long1, 64)
  193. if err != nil {
  194. log.Warningf("long1 is not a float : %v", err)
  195. return 0.0, fmt.Errorf("long1 is not a float : %v", err)
  196. }
  197. lat2f, err := strconv.ParseFloat(lat2, 64)
  198. if err != nil {
  199. log.Warningf("lat2 is not a float : %v", err)
  200. return 0.0, fmt.Errorf("lat2 is not a float : %v", err)
  201. }
  202. long2f, err := strconv.ParseFloat(long2, 64)
  203. if err != nil {
  204. log.Warningf("long2 is not a float : %v", err)
  205. return 0.0, fmt.Errorf("long2 is not a float : %v", err)
  206. }
  207. //either set of coordinates is 0,0, return 0 to avoid FPs
  208. if (lat1f == 0.0 && long1f == 0.0) || (lat2f == 0.0 && long2f == 0.0) {
  209. log.Warningf("one of the coordinates is 0,0, returning 0")
  210. return 0.0, nil
  211. }
  212. first := haversine.Coord{Lat: lat1f, Lon: long1f}
  213. second := haversine.Coord{Lat: lat2f, Lon: long2f}
  214. _, km := haversine.Distance(first, second)
  215. return km, nil
  216. }
  217. // func QueryEscape(s string) string {
  218. func QueryEscape(params ...any) (any, error) {
  219. s := params[0].(string)
  220. return url.QueryEscape(s), nil
  221. }
  222. // func PathEscape(s string) string {
  223. func PathEscape(params ...any) (any, error) {
  224. s := params[0].(string)
  225. return url.PathEscape(s), nil
  226. }
  227. // func PathUnescape(s string) string {
  228. func PathUnescape(params ...any) (any, error) {
  229. s := params[0].(string)
  230. ret, err := url.PathUnescape(s)
  231. if err != nil {
  232. log.Debugf("unable to PathUnescape '%s': %+v", s, err)
  233. return s, nil
  234. }
  235. return ret, nil
  236. }
  237. // func QueryUnescape(s string) string {
  238. func QueryUnescape(params ...any) (any, error) {
  239. s := params[0].(string)
  240. ret, err := url.QueryUnescape(s)
  241. if err != nil {
  242. log.Debugf("unable to QueryUnescape '%s': %+v", s, err)
  243. return s, nil
  244. }
  245. return ret, nil
  246. }
  247. // func File(filename string) []string {
  248. func File(params ...any) (any, error) {
  249. filename := params[0].(string)
  250. if _, ok := dataFile[filename]; ok {
  251. return dataFile[filename], nil
  252. }
  253. log.Errorf("file '%s' (type:string) not found in expr library", filename)
  254. log.Errorf("expr library : %s", spew.Sdump(dataFile))
  255. return []string{}, nil
  256. }
  257. // func RegexpInFile(data string, filename string) bool {
  258. func RegexpInFile(params ...any) (any, error) {
  259. data := params[0].(string)
  260. filename := params[1].(string)
  261. var hash uint64
  262. hasCache := false
  263. matched := false
  264. if _, ok := dataFileRegexCache[filename]; ok {
  265. hasCache = true
  266. hash = xxhash.Sum64String(data)
  267. if val, err := dataFileRegexCache[filename].Get(hash); err == nil {
  268. return val.(bool), nil
  269. }
  270. }
  271. switch fflag.Re2RegexpInfileSupport.IsEnabled() {
  272. case true:
  273. if _, ok := dataFileRe2[filename]; ok {
  274. for _, re := range dataFileRe2[filename] {
  275. if re.MatchString(data) {
  276. matched = true
  277. break
  278. }
  279. }
  280. } else {
  281. log.Errorf("file '%s' (type:regexp) not found in expr library", filename)
  282. log.Errorf("expr library : %s", spew.Sdump(dataFileRe2))
  283. }
  284. case false:
  285. if _, ok := dataFileRegex[filename]; ok {
  286. for _, re := range dataFileRegex[filename] {
  287. if re.MatchString(data) {
  288. matched = true
  289. break
  290. }
  291. }
  292. } else {
  293. log.Errorf("file '%s' (type:regexp) not found in expr library", filename)
  294. log.Errorf("expr library : %s", spew.Sdump(dataFileRegex))
  295. }
  296. }
  297. if hasCache {
  298. dataFileRegexCache[filename].Set(hash, matched)
  299. }
  300. return matched, nil
  301. }
  302. // func IpInRange(ip string, ipRange string) bool {
  303. func IpInRange(params ...any) (any, error) {
  304. var err error
  305. var ipParsed net.IP
  306. var ipRangeParsed *net.IPNet
  307. ip := params[0].(string)
  308. ipRange := params[1].(string)
  309. ipParsed = net.ParseIP(ip)
  310. if ipParsed == nil {
  311. log.Debugf("'%s' is not a valid IP", ip)
  312. return false, nil
  313. }
  314. if _, ipRangeParsed, err = net.ParseCIDR(ipRange); err != nil {
  315. log.Debugf("'%s' is not a valid IP Range", ipRange)
  316. return false, nil //nolint:nilerr // This helper did not return an error before the move to expr.Function, we keep this behavior for backward compatibility
  317. }
  318. if ipRangeParsed.Contains(ipParsed) {
  319. return true, nil
  320. }
  321. return false, nil
  322. }
  323. // func IsIPV6(ip string) bool {
  324. func IsIPV6(params ...any) (any, error) {
  325. ip := params[0].(string)
  326. ipParsed := net.ParseIP(ip)
  327. if ipParsed == nil {
  328. log.Debugf("'%s' is not a valid IP", ip)
  329. return false, nil
  330. }
  331. // If it's a valid IP and can't be converted to IPv4 then it is an IPv6
  332. return ipParsed.To4() == nil, nil
  333. }
  334. // func IsIPV4(ip string) bool {
  335. func IsIPV4(params ...any) (any, error) {
  336. ip := params[0].(string)
  337. ipParsed := net.ParseIP(ip)
  338. if ipParsed == nil {
  339. log.Debugf("'%s' is not a valid IP", ip)
  340. return false, nil
  341. }
  342. return ipParsed.To4() != nil, nil
  343. }
  344. // func IsIP(ip string) bool {
  345. func IsIP(params ...any) (any, error) {
  346. ip := params[0].(string)
  347. ipParsed := net.ParseIP(ip)
  348. if ipParsed == nil {
  349. log.Debugf("'%s' is not a valid IP", ip)
  350. return false, nil
  351. }
  352. return true, nil
  353. }
  354. // func IpToRange(ip string, cidr string) string {
  355. func IpToRange(params ...any) (any, error) {
  356. ip := params[0].(string)
  357. cidr := params[1].(string)
  358. cidr = strings.TrimPrefix(cidr, "/")
  359. mask, err := strconv.Atoi(cidr)
  360. if err != nil {
  361. log.Errorf("bad cidr '%s': %s", cidr, err)
  362. return "", nil
  363. }
  364. ipAddr := net.ParseIP(ip)
  365. if ipAddr == nil {
  366. log.Errorf("can't parse IP address '%s'", ip)
  367. return "", nil
  368. }
  369. ipRange := iplib.NewNet(ipAddr, mask)
  370. if ipRange.IP() == nil {
  371. log.Errorf("can't get cidr '%s' of '%s'", cidr, ip)
  372. return "", nil
  373. }
  374. return ipRange.String(), nil
  375. }
  376. // func TimeNow() string {
  377. func TimeNow(params ...any) (any, error) {
  378. return time.Now().UTC().Format(time.RFC3339), nil
  379. }
  380. // func ParseUri(uri string) map[string][]string {
  381. func ParseUri(params ...any) (any, error) {
  382. uri := params[0].(string)
  383. ret := make(map[string][]string)
  384. u, err := url.Parse(uri)
  385. if err != nil {
  386. log.Errorf("Could not parse URI: %s", err)
  387. return ret, nil
  388. }
  389. parsed, err := url.ParseQuery(u.RawQuery)
  390. if err != nil {
  391. log.Errorf("Could not parse query uri : %s", err)
  392. return ret, nil
  393. }
  394. for k, v := range parsed {
  395. ret[k] = v
  396. }
  397. return ret, nil
  398. }
  399. // func KeyExists(key string, dict map[string]interface{}) bool {
  400. func KeyExists(params ...any) (any, error) {
  401. key := params[0].(string)
  402. dict := params[1].(map[string]interface{})
  403. _, ok := dict[key]
  404. return ok, nil
  405. }
  406. // func GetDecisionsCount(value string) int {
  407. func GetDecisionsCount(params ...any) (any, error) {
  408. value := params[0].(string)
  409. if dbClient == nil {
  410. log.Error("No database config to call GetDecisionsCount()")
  411. return 0, nil
  412. }
  413. count, err := dbClient.CountDecisionsByValue(value)
  414. if err != nil {
  415. log.Errorf("Failed to get decisions count from value '%s'", value)
  416. return 0, nil //nolint:nilerr // This helper did not return an error before the move to expr.Function, we keep this behavior for backward compatibility
  417. }
  418. return count, nil
  419. }
  420. // func GetDecisionsSinceCount(value string, since string) int {
  421. func GetDecisionsSinceCount(params ...any) (any, error) {
  422. value := params[0].(string)
  423. since := params[1].(string)
  424. if dbClient == nil {
  425. log.Error("No database config to call GetDecisionsCount()")
  426. return 0, nil
  427. }
  428. sinceDuration, err := time.ParseDuration(since)
  429. if err != nil {
  430. log.Errorf("Failed to parse since parameter '%s' : %s", since, err)
  431. return 0, nil
  432. }
  433. sinceTime := time.Now().UTC().Add(-sinceDuration)
  434. count, err := dbClient.CountDecisionsSinceByValue(value, sinceTime)
  435. if err != nil {
  436. log.Errorf("Failed to get decisions count from value '%s'", value)
  437. return 0, nil //nolint:nilerr // This helper did not return an error before the move to expr.Function, we keep this behavior for backward compatibility
  438. }
  439. return count, nil
  440. }
  441. // func LookupHost(value string) []string {
  442. func LookupHost(params ...any) (any, error) {
  443. value := params[0].(string)
  444. addresses, err := net.LookupHost(value)
  445. if err != nil {
  446. log.Errorf("Failed to lookup host '%s' : %s", value, err)
  447. return []string{}, nil
  448. }
  449. return addresses, nil
  450. }
  451. // func ParseUnixTime(value string) (time.Time, error) {
  452. func ParseUnixTime(params ...any) (any, error) {
  453. value := params[0].(string)
  454. //Splitting string here as some unix timestamp may have milliseconds and break ParseInt
  455. i, err := strconv.ParseInt(strings.Split(value, ".")[0], 10, 64)
  456. if err != nil || i <= 0 {
  457. return time.Time{}, fmt.Errorf("unable to parse %s as unix timestamp", value)
  458. }
  459. return time.Unix(i, 0), nil
  460. }
  461. // func ParseUnix(value string) string {
  462. func ParseUnix(params ...any) (any, error) {
  463. value := params[0].(string)
  464. t, err := ParseUnixTime(value)
  465. if err != nil {
  466. log.Error(err)
  467. return "", nil
  468. }
  469. return t.(time.Time).Format(time.RFC3339), nil
  470. }
  471. // func ToString(value interface{}) string {
  472. func ToString(params ...any) (any, error) {
  473. value := params[0]
  474. s, ok := value.(string)
  475. if !ok {
  476. return "", nil
  477. }
  478. return s, nil
  479. }
  480. // func GetFromStash(cacheName string, key string) (string, error) {
  481. func GetFromStash(params ...any) (any, error) {
  482. cacheName := params[0].(string)
  483. key := params[1].(string)
  484. return cache.GetKey(cacheName, key)
  485. }
  486. // func SetInStash(cacheName string, key string, value string, expiration *time.Duration) any {
  487. func SetInStash(params ...any) (any, error) {
  488. cacheName := params[0].(string)
  489. key := params[1].(string)
  490. value := params[2].(string)
  491. expiration := params[3].(*time.Duration)
  492. return cache.SetKey(cacheName, key, value, expiration), nil
  493. }
  494. func Sprintf(params ...any) (any, error) {
  495. format := params[0].(string)
  496. return fmt.Sprintf(format, params[1:]...), nil
  497. }
  498. // func Match(pattern, name string) bool {
  499. func Match(params ...any) (any, error) {
  500. var matched bool
  501. pattern := params[0].(string)
  502. name := params[1].(string)
  503. if pattern == "" {
  504. return name == "", nil
  505. }
  506. if name == "" {
  507. if pattern == "*" || pattern == "" {
  508. return true, nil
  509. }
  510. return false, nil
  511. }
  512. if pattern[0] == '*' {
  513. for i := 0; i <= len(name); i++ {
  514. matched, _ := Match(pattern[1:], name[i:])
  515. if matched.(bool) {
  516. return matched, nil
  517. }
  518. }
  519. return matched, nil
  520. }
  521. if pattern[0] == '?' || pattern[0] == name[0] {
  522. return Match(pattern[1:], name[1:])
  523. }
  524. return matched, nil
  525. }
  526. func FloatApproxEqual(params ...any) (any, error) {
  527. float1 := params[0].(float64)
  528. float2 := params[1].(float64)
  529. if math.Abs(float1-float2) < 1e-6 {
  530. return true, nil
  531. }
  532. return false, nil
  533. }
  534. func B64Decode(params ...any) (any, error) {
  535. encoded := params[0].(string)
  536. decoded, err := base64.StdEncoding.DecodeString(encoded)
  537. if err != nil {
  538. return "", err
  539. }
  540. return string(decoded), nil
  541. }
  542. func ParseKV(params ...any) (any, error) {
  543. blob := params[0].(string)
  544. target := params[1].(map[string]interface{})
  545. prefix := params[2].(string)
  546. matches := keyValuePattern.FindAllStringSubmatch(blob, -1)
  547. if matches == nil {
  548. log.Errorf("could not find any key/value pair in line")
  549. return nil, fmt.Errorf("invalid input format")
  550. }
  551. if _, ok := target[prefix]; !ok {
  552. target[prefix] = make(map[string]string)
  553. } else {
  554. _, ok := target[prefix].(map[string]string)
  555. if !ok {
  556. log.Errorf("ParseKV: target is not a map[string]string")
  557. return nil, fmt.Errorf("target is not a map[string]string")
  558. }
  559. }
  560. for _, match := range matches {
  561. key := ""
  562. value := ""
  563. for i, name := range keyValuePattern.SubexpNames() {
  564. if name == "key" {
  565. key = match[i]
  566. } else if name == "quoted_value" && match[i] != "" {
  567. value = match[i]
  568. } else if name == "value" && match[i] != "" {
  569. value = match[i]
  570. }
  571. }
  572. target[prefix].(map[string]string)[key] = value
  573. }
  574. log.Tracef("unmarshaled KV: %+v", target[prefix])
  575. return nil, nil
  576. }
  577. func Hostname(params ...any) (any, error) {
  578. hostname, err := os.Hostname()
  579. if err != nil {
  580. return "", err
  581. }
  582. return hostname, nil
  583. }