exprlib.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. package exprhelpers
  2. import (
  3. "bufio"
  4. "fmt"
  5. "net"
  6. "net/url"
  7. "os"
  8. "path"
  9. "regexp"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/c-robinson/iplib"
  14. "github.com/crowdsecurity/crowdsec/pkg/cache"
  15. "github.com/crowdsecurity/crowdsec/pkg/database"
  16. "github.com/davecgh/go-spew/spew"
  17. log "github.com/sirupsen/logrus"
  18. )
  19. var dataFile map[string][]string
  20. var dataFileRegex map[string][]*regexp.Regexp
  21. var dbClient *database.Client
  22. func Atof(x string) float64 {
  23. log.Debugf("debug atof %s", x)
  24. ret, err := strconv.ParseFloat(x, 64)
  25. if err != nil {
  26. log.Warningf("Atof : can't convert float '%s' : %v", x, err)
  27. }
  28. return ret
  29. }
  30. func Upper(s string) string {
  31. return strings.ToUpper(s)
  32. }
  33. func Lower(s string) string {
  34. return strings.ToLower(s)
  35. }
  36. func GetExprEnv(ctx map[string]interface{}) map[string]interface{} {
  37. var ExprLib = map[string]interface{}{
  38. "Atof": Atof,
  39. "JsonExtract": JsonExtract,
  40. "JsonExtractUnescape": JsonExtractUnescape,
  41. "JsonExtractLib": JsonExtractLib,
  42. "JsonExtractSlice": JsonExtractSlice,
  43. "JsonExtractObject": JsonExtractObject,
  44. "ToJsonString": ToJson,
  45. "File": File,
  46. "RegexpInFile": RegexpInFile,
  47. "Upper": Upper,
  48. "Lower": Lower,
  49. "IpInRange": IpInRange,
  50. "TimeNow": TimeNow,
  51. "ParseUri": ParseUri,
  52. "PathUnescape": PathUnescape,
  53. "QueryUnescape": QueryUnescape,
  54. "PathEscape": PathEscape,
  55. "QueryEscape": QueryEscape,
  56. "XMLGetAttributeValue": XMLGetAttributeValue,
  57. "XMLGetNodeValue": XMLGetNodeValue,
  58. "IpToRange": IpToRange,
  59. "IsIPV6": IsIPV6,
  60. "LookupHost": LookupHost,
  61. "GetDecisionsCount": GetDecisionsCount,
  62. "GetDecisionsSinceCount": GetDecisionsSinceCount,
  63. "Sprintf": fmt.Sprintf,
  64. "CrowdsecCTI": CrowdsecCTI,
  65. "ParseUnix": ParseUnix,
  66. "GetFromStash": cache.GetKey,
  67. "SetInStash": cache.SetKey,
  68. }
  69. for k, v := range ctx {
  70. ExprLib[k] = v
  71. }
  72. return ExprLib
  73. }
  74. func Init(databaseClient *database.Client) error {
  75. dataFile = make(map[string][]string)
  76. dataFileRegex = make(map[string][]*regexp.Regexp)
  77. dbClient = databaseClient
  78. return nil
  79. }
  80. func FileInit(fileFolder string, filename string, fileType string) error {
  81. log.Debugf("init (folder:%s) (file:%s) (type:%s)", fileFolder, filename, fileType)
  82. filepath := path.Join(fileFolder, filename)
  83. file, err := os.Open(filepath)
  84. if err != nil {
  85. return err
  86. }
  87. defer file.Close()
  88. if fileType == "" {
  89. log.Debugf("ignored file %s%s because no type specified", fileFolder, filename)
  90. return nil
  91. }
  92. if _, ok := dataFile[filename]; !ok {
  93. dataFile[filename] = []string{}
  94. }
  95. scanner := bufio.NewScanner(file)
  96. for scanner.Scan() {
  97. if strings.HasPrefix(scanner.Text(), "#") { // allow comments
  98. continue
  99. }
  100. if len(scanner.Text()) == 0 { //skip empty lines
  101. continue
  102. }
  103. switch fileType {
  104. case "regex", "regexp":
  105. dataFileRegex[filename] = append(dataFileRegex[filename], regexp.MustCompile(scanner.Text()))
  106. case "string":
  107. dataFile[filename] = append(dataFile[filename], scanner.Text())
  108. default:
  109. return fmt.Errorf("unknown data type '%s' for : '%s'", fileType, filename)
  110. }
  111. }
  112. if err := scanner.Err(); err != nil {
  113. return err
  114. }
  115. return nil
  116. }
  117. func QueryEscape(s string) string {
  118. return url.QueryEscape(s)
  119. }
  120. func PathEscape(s string) string {
  121. return url.PathEscape(s)
  122. }
  123. func PathUnescape(s string) string {
  124. ret, err := url.PathUnescape(s)
  125. if err != nil {
  126. log.Debugf("unable to PathUnescape '%s': %+v", s, err)
  127. return s
  128. }
  129. return ret
  130. }
  131. func QueryUnescape(s string) string {
  132. ret, err := url.QueryUnescape(s)
  133. if err != nil {
  134. log.Debugf("unable to QueryUnescape '%s': %+v", s, err)
  135. return s
  136. }
  137. return ret
  138. }
  139. func File(filename string) []string {
  140. if _, ok := dataFile[filename]; ok {
  141. return dataFile[filename]
  142. }
  143. log.Errorf("file '%s' (type:string) not found in expr library", filename)
  144. log.Errorf("expr library : %s", spew.Sdump(dataFile))
  145. return []string{}
  146. }
  147. func RegexpInFile(data string, filename string) bool {
  148. if _, ok := dataFileRegex[filename]; ok {
  149. for _, re := range dataFileRegex[filename] {
  150. if re.Match([]byte(data)) {
  151. return true
  152. }
  153. }
  154. } else {
  155. log.Errorf("file '%s' (type:regexp) not found in expr library", filename)
  156. log.Errorf("expr library : %s", spew.Sdump(dataFileRegex))
  157. }
  158. return false
  159. }
  160. func IpInRange(ip string, ipRange string) bool {
  161. var err error
  162. var ipParsed net.IP
  163. var ipRangeParsed *net.IPNet
  164. ipParsed = net.ParseIP(ip)
  165. if ipParsed == nil {
  166. log.Debugf("'%s' is not a valid IP", ip)
  167. return false
  168. }
  169. if _, ipRangeParsed, err = net.ParseCIDR(ipRange); err != nil {
  170. log.Debugf("'%s' is not a valid IP Range", ipRange)
  171. return false
  172. }
  173. if ipRangeParsed.Contains(ipParsed) {
  174. return true
  175. }
  176. return false
  177. }
  178. func IsIPV6(ip string) bool {
  179. ipParsed := net.ParseIP(ip)
  180. if ipParsed == nil {
  181. log.Debugf("'%s' is not a valid IP", ip)
  182. return false
  183. }
  184. // If it's a valid IP and can't be converted to IPv4 then it is an IPv6
  185. return ipParsed.To4() == nil
  186. }
  187. func IpToRange(ip string, cidr string) string {
  188. cidr = strings.TrimPrefix(cidr, "/")
  189. mask, err := strconv.Atoi(cidr)
  190. if err != nil {
  191. log.Errorf("bad cidr '%s': %s", cidr, err)
  192. return ""
  193. }
  194. ipAddr := net.ParseIP(ip)
  195. if ipAddr == nil {
  196. log.Errorf("can't parse IP address '%s'", ip)
  197. return ""
  198. }
  199. ipRange := iplib.NewNet(ipAddr, mask)
  200. if ipRange.IP() == nil {
  201. log.Errorf("can't get cidr '%s' of '%s'", cidr, ip)
  202. return ""
  203. }
  204. return ipRange.String()
  205. }
  206. func TimeNow() string {
  207. return time.Now().UTC().Format(time.RFC3339)
  208. }
  209. func ParseUri(uri string) map[string][]string {
  210. ret := make(map[string][]string)
  211. u, err := url.Parse(uri)
  212. if err != nil {
  213. log.Errorf("Could not parse URI: %s", err)
  214. return ret
  215. }
  216. parsed, err := url.ParseQuery(u.RawQuery)
  217. if err != nil {
  218. log.Errorf("Could not parse query uri : %s", err)
  219. return ret
  220. }
  221. for k, v := range parsed {
  222. ret[k] = v
  223. }
  224. return ret
  225. }
  226. func KeyExists(key string, dict map[string]interface{}) bool {
  227. _, ok := dict[key]
  228. return ok
  229. }
  230. func GetDecisionsCount(value string) int {
  231. if dbClient == nil {
  232. log.Error("No database config to call GetDecisionsCount()")
  233. return 0
  234. }
  235. count, err := dbClient.CountDecisionsByValue(value)
  236. if err != nil {
  237. log.Errorf("Failed to get decisions count from value '%s'", value)
  238. return 0
  239. }
  240. return count
  241. }
  242. func GetDecisionsSinceCount(value string, since string) int {
  243. if dbClient == nil {
  244. log.Error("No database config to call GetDecisionsCount()")
  245. return 0
  246. }
  247. sinceDuration, err := time.ParseDuration(since)
  248. if err != nil {
  249. log.Errorf("Failed to parse since parameter '%s' : %s", since, err)
  250. return 0
  251. }
  252. sinceTime := time.Now().UTC().Add(-sinceDuration)
  253. count, err := dbClient.CountDecisionsSinceByValue(value, sinceTime)
  254. if err != nil {
  255. log.Errorf("Failed to get decisions count from value '%s'", value)
  256. return 0
  257. }
  258. return count
  259. }
  260. func LookupHost(value string) []string {
  261. addresses, err := net.LookupHost(value)
  262. if err != nil {
  263. log.Errorf("Failed to lookup host '%s' : %s", value, err)
  264. return []string{}
  265. }
  266. return addresses
  267. }
  268. func ParseUnixTime(value string) (time.Time, error) {
  269. //Splitting string here as some unix timestamp may have milliseconds and break ParseInt
  270. i, err := strconv.ParseInt(strings.Split(value, ".")[0], 10, 64)
  271. if err != nil || i <= 0 {
  272. return time.Time{}, fmt.Errorf("unable to parse %s as unix timestamp", value)
  273. }
  274. return time.Unix(i, 0), nil
  275. }
  276. func ParseUnix(value string) string {
  277. t, err := ParseUnixTime(value)
  278. if err != nil {
  279. log.Error(err)
  280. return ""
  281. }
  282. return t.Format(time.RFC3339)
  283. }