exprlib.go 7.6 KB

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