node.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. package parser
  2. import (
  3. "fmt"
  4. "net"
  5. "strings"
  6. "time"
  7. "github.com/antonmedv/expr"
  8. "github.com/crowdsecurity/grokky"
  9. "github.com/pkg/errors"
  10. yaml "gopkg.in/yaml.v2"
  11. "github.com/antonmedv/expr/vm"
  12. "github.com/crowdsecurity/crowdsec/pkg/cache"
  13. "github.com/crowdsecurity/crowdsec/pkg/exprhelpers"
  14. "github.com/crowdsecurity/crowdsec/pkg/types"
  15. "github.com/davecgh/go-spew/spew"
  16. "github.com/prometheus/client_golang/prometheus"
  17. "github.com/sirupsen/logrus"
  18. log "github.com/sirupsen/logrus"
  19. )
  20. type Node struct {
  21. FormatVersion string `yaml:"format"`
  22. //Enable config + runtime debug of node via config o/
  23. Debug bool `yaml:"debug,omitempty"`
  24. //If enabled, the node (and its child) will report their own statistics
  25. Profiling bool `yaml:"profiling,omitempty"`
  26. //Name, author, description and reference(s) for parser pattern
  27. Name string `yaml:"name,omitempty"`
  28. Author string `yaml:"author,omitempty"`
  29. Description string `yaml:"description,omitempty"`
  30. References []string `yaml:"references,omitempty"`
  31. //if debug is present in the node, keep its specific Logger in runtime structure
  32. Logger *log.Entry `yaml:"-"`
  33. //This is mostly a hack to make writing less repetitive.
  34. //relying on stage, we know which field to parse, and we
  35. //can also promote log to next stage on success
  36. Stage string `yaml:"stage,omitempty"`
  37. //OnSuccess allows to tag a node to be able to move log to next stage on success
  38. OnSuccess string `yaml:"onsuccess,omitempty"`
  39. rn string //this is only for us in debug, a random generated name for each node
  40. //Filter is executed at runtime (with current log line as context)
  41. //and must succeed or node is exited
  42. Filter string `yaml:"filter,omitempty"`
  43. RunTimeFilter *vm.Program `yaml:"-" json:"-"` //the actual compiled filter
  44. ExprDebugger *exprhelpers.ExprDebugger `yaml:"-" json:"-"` //used to debug expression by printing the content of each variable of the expression
  45. //If node has leafs, execute all of them until one asks for a 'break'
  46. LeavesNodes []Node `yaml:"nodes,omitempty"`
  47. //Flag used to describe when to 'break' or return an 'error'
  48. EnrichFunctions EnricherCtx
  49. /* If the node is actually a leaf, it can have : grok, enrich, statics */
  50. //pattern_syntax are named grok patterns that are re-utilized over several grok patterns
  51. SubGroks yaml.MapSlice `yaml:"pattern_syntax,omitempty"`
  52. //Holds a grok pattern
  53. Grok types.GrokPattern `yaml:"grok,omitempty"`
  54. //Statics can be present in any type of node and is executed last
  55. Statics []types.ExtraField `yaml:"statics,omitempty"`
  56. //Stash allows to capture data from the log line and store it in an accessible cache
  57. Stash []types.DataCapture `yaml:"stash,omitempty"`
  58. //Whitelists
  59. Whitelist Whitelist `yaml:"whitelist,omitempty"`
  60. Data []*types.DataSource `yaml:"data,omitempty"`
  61. }
  62. func (n *Node) validate(pctx *UnixParserCtx, ectx EnricherCtx) error {
  63. //stage is being set automagically
  64. if n.Stage == "" {
  65. return fmt.Errorf("stage needs to be an existing stage")
  66. }
  67. /* "" behaves like continue */
  68. if n.OnSuccess != "continue" && n.OnSuccess != "next_stage" && n.OnSuccess != "" {
  69. return fmt.Errorf("onsuccess '%s' not continue,next_stage", n.OnSuccess)
  70. }
  71. if n.Filter != "" && n.RunTimeFilter == nil {
  72. return fmt.Errorf("non-empty filter '%s' was not compiled", n.Filter)
  73. }
  74. if n.Grok.RunTimeRegexp != nil || n.Grok.TargetField != "" {
  75. if n.Grok.TargetField == "" && n.Grok.ExpValue == "" {
  76. return fmt.Errorf("grok requires 'expression' or 'apply_on'")
  77. }
  78. if n.Grok.RegexpName == "" && n.Grok.RegexpValue == "" {
  79. return fmt.Errorf("grok needs 'pattern' or 'name'")
  80. }
  81. }
  82. for idx, static := range n.Statics {
  83. if static.Method != "" {
  84. if static.ExpValue == "" {
  85. return fmt.Errorf("static %d : when method is set, expression must be present", idx)
  86. }
  87. if _, ok := ectx.Registered[static.Method]; !ok {
  88. log.Warningf("the method '%s' doesn't exist or the plugin has not been initialized", static.Method)
  89. }
  90. } else {
  91. if static.Meta == "" && static.Parsed == "" && static.TargetByName == "" {
  92. return fmt.Errorf("static %d : at least one of meta/event/target must be set", idx)
  93. }
  94. if static.Value == "" && static.RunTimeValue == nil {
  95. return fmt.Errorf("static %d value or expression must be set", idx)
  96. }
  97. }
  98. }
  99. for idx, stash := range n.Stash {
  100. if stash.Name == "" {
  101. return fmt.Errorf("stash %d : name must be set", idx)
  102. }
  103. if stash.Value == "" {
  104. return fmt.Errorf("stash %s : value expression must be set", stash.Name)
  105. }
  106. if stash.Key == "" {
  107. return fmt.Errorf("stash %s : key expression must be set", stash.Name)
  108. }
  109. if stash.TTL == "" {
  110. return fmt.Errorf("stash %s : ttl must be set", stash.Name)
  111. }
  112. if stash.Strategy == "" {
  113. stash.Strategy = "LRU"
  114. }
  115. //should be configurable
  116. if stash.MaxMapSize == 0 {
  117. stash.MaxMapSize = 100
  118. }
  119. }
  120. return nil
  121. }
  122. func (n *Node) process(p *types.Event, ctx UnixParserCtx, expressionEnv map[string]interface{}) (bool, error) {
  123. var NodeState bool
  124. var NodeHasOKGrok bool
  125. clog := n.Logger
  126. cachedExprEnv := expressionEnv
  127. clog.Tracef("Event entering node")
  128. if n.RunTimeFilter != nil {
  129. //Evaluate node's filter
  130. output, err := expr.Run(n.RunTimeFilter, cachedExprEnv)
  131. if err != nil {
  132. clog.Warningf("failed to run filter : %v", err)
  133. clog.Debugf("Event leaving node : ko")
  134. return false, nil
  135. }
  136. switch out := output.(type) {
  137. case bool:
  138. if n.Debug {
  139. n.ExprDebugger.Run(clog, out, cachedExprEnv)
  140. }
  141. if !out {
  142. clog.Debugf("Event leaving node : ko (failed filter)")
  143. return false, nil
  144. }
  145. default:
  146. clog.Warningf("Expr '%s' returned non-bool, abort : %T", n.Filter, output)
  147. clog.Debugf("Event leaving node : ko")
  148. return false, nil
  149. }
  150. NodeState = true
  151. } else {
  152. clog.Tracef("Node has not filter, enter")
  153. NodeState = true
  154. }
  155. if n.Name != "" {
  156. NodesHits.With(prometheus.Labels{"source": p.Line.Src, "type": p.Line.Module, "name": n.Name}).Inc()
  157. }
  158. isWhitelisted := false
  159. hasWhitelist := false
  160. var srcs []net.IP
  161. /*overflow and log don't hold the source ip in the same field, should be changed */
  162. /* perform whitelist checks for ips, cidr accordingly */
  163. /* TODO move whitelist elsewhere */
  164. if p.Type == types.LOG {
  165. if _, ok := p.Meta["source_ip"]; ok {
  166. srcs = append(srcs, net.ParseIP(p.Meta["source_ip"]))
  167. }
  168. } else if p.Type == types.OVFLW {
  169. for k := range p.Overflow.Sources {
  170. srcs = append(srcs, net.ParseIP(k))
  171. }
  172. }
  173. for _, src := range srcs {
  174. if isWhitelisted {
  175. break
  176. }
  177. for _, v := range n.Whitelist.B_Ips {
  178. if v.Equal(src) {
  179. clog.Debugf("Event from [%s] is whitelisted by IP (%s), reason [%s]", src, v, n.Whitelist.Reason)
  180. isWhitelisted = true
  181. } else {
  182. clog.Tracef("whitelist: %s is not eq [%s]", src, v)
  183. }
  184. hasWhitelist = true
  185. }
  186. for _, v := range n.Whitelist.B_Cidrs {
  187. if v.Contains(src) {
  188. clog.Debugf("Event from [%s] is whitelisted by CIDR (%s), reason [%s]", src, v, n.Whitelist.Reason)
  189. isWhitelisted = true
  190. } else {
  191. clog.Tracef("whitelist: %s not in [%s]", src, v)
  192. }
  193. hasWhitelist = true
  194. }
  195. }
  196. if isWhitelisted {
  197. p.Whitelisted = true
  198. }
  199. /* run whitelist expression tests anyway */
  200. for eidx, e := range n.Whitelist.B_Exprs {
  201. output, err := expr.Run(e.Filter, cachedExprEnv)
  202. if err != nil {
  203. clog.Warningf("failed to run whitelist expr : %v", err)
  204. clog.Debug("Event leaving node : ko")
  205. return false, nil
  206. }
  207. switch out := output.(type) {
  208. case bool:
  209. if n.Debug {
  210. e.ExprDebugger.Run(clog, out, cachedExprEnv)
  211. }
  212. if out {
  213. clog.Debugf("Event is whitelisted by expr, reason [%s]", n.Whitelist.Reason)
  214. p.Whitelisted = true
  215. isWhitelisted = true
  216. }
  217. hasWhitelist = true
  218. default:
  219. log.Errorf("unexpected type %t (%v) while running '%s'", output, output, n.Whitelist.Exprs[eidx])
  220. }
  221. }
  222. if isWhitelisted {
  223. p.WhitelistReason = n.Whitelist.Reason
  224. /*huglily wipe the ban order if the event is whitelisted and it's an overflow */
  225. if p.Type == types.OVFLW { /*don't do this at home kids */
  226. ips := []string{}
  227. for _, src := range srcs {
  228. ips = append(ips, src.String())
  229. }
  230. clog.Infof("Ban for %s whitelisted, reason [%s]", strings.Join(ips, ","), n.Whitelist.Reason)
  231. p.Overflow.Whitelisted = true
  232. }
  233. }
  234. //Process grok if present, should be exclusive with nodes :)
  235. gstr := ""
  236. if n.Grok.RunTimeRegexp != nil {
  237. clog.Tracef("Processing grok pattern : %s : %p", n.Grok.RegexpName, n.Grok.RunTimeRegexp)
  238. //for unparsed, parsed etc. set sensible defaults to reduce user hassle
  239. if n.Grok.TargetField != "" {
  240. //it's a hack to avoid using real reflect
  241. if n.Grok.TargetField == "Line.Raw" {
  242. gstr = p.Line.Raw
  243. } else if val, ok := p.Parsed[n.Grok.TargetField]; ok {
  244. gstr = val
  245. } else {
  246. clog.Debugf("(%s) target field '%s' doesn't exist in %v", n.rn, n.Grok.TargetField, p.Parsed)
  247. NodeState = false
  248. }
  249. } else if n.Grok.RunTimeValue != nil {
  250. output, err := expr.Run(n.Grok.RunTimeValue, cachedExprEnv)
  251. if err != nil {
  252. clog.Warningf("failed to run RunTimeValue : %v", err)
  253. NodeState = false
  254. }
  255. switch out := output.(type) {
  256. case string:
  257. gstr = out
  258. default:
  259. clog.Errorf("unexpected return type for RunTimeValue : %T", output)
  260. }
  261. }
  262. var groklabel string
  263. if n.Grok.RegexpName == "" {
  264. groklabel = fmt.Sprintf("%5.5s...", n.Grok.RegexpValue)
  265. } else {
  266. groklabel = n.Grok.RegexpName
  267. }
  268. grok := n.Grok.RunTimeRegexp.Parse(gstr)
  269. if len(grok) > 0 {
  270. /*tag explicitly that the *current* node had a successful grok pattern. it's important to know success state*/
  271. NodeHasOKGrok = true
  272. clog.Debugf("+ Grok '%s' returned %d entries to merge in Parsed", groklabel, len(grok))
  273. //We managed to grok stuff, merged into parse
  274. for k, v := range grok {
  275. clog.Debugf("\t.Parsed['%s'] = '%s'", k, v)
  276. p.Parsed[k] = v
  277. }
  278. // if the grok succeed, process associated statics
  279. err := n.ProcessStatics(n.Grok.Statics, p)
  280. if err != nil {
  281. clog.Errorf("(%s) Failed to process statics : %v", n.rn, err)
  282. return false, err
  283. }
  284. } else {
  285. //grok failed, node failed
  286. clog.Debugf("+ Grok '%s' didn't return data on '%s'", groklabel, gstr)
  287. NodeState = false
  288. }
  289. } else {
  290. clog.Tracef("! No grok pattern : %p", n.Grok.RunTimeRegexp)
  291. }
  292. //Process the stash (data collection) if : a grok was present and succeeded, or if there is no grok
  293. if NodeHasOKGrok || n.Grok.RunTimeRegexp == nil {
  294. for idx, stash := range n.Stash {
  295. var value string
  296. var key string
  297. if stash.ValueExpression == nil {
  298. clog.Warningf("Stash %d has no value expression, skipping", idx)
  299. continue
  300. }
  301. if stash.KeyExpression == nil {
  302. clog.Warningf("Stash %d has no key expression, skipping", idx)
  303. continue
  304. }
  305. //collect the data
  306. output, err := expr.Run(stash.ValueExpression, cachedExprEnv)
  307. if err != nil {
  308. clog.Warningf("Error while running stash val expression : %v", err)
  309. }
  310. //can we expect anything else than a string ?
  311. switch output := output.(type) {
  312. case string:
  313. value = output
  314. default:
  315. clog.Warningf("unexpected type %t (%v) while running '%s'", output, output, stash.Value)
  316. continue
  317. }
  318. //collect the key
  319. output, err = expr.Run(stash.KeyExpression, cachedExprEnv)
  320. if err != nil {
  321. clog.Warningf("Error while running stash key expression : %v", err)
  322. }
  323. //can we expect anything else than a string ?
  324. switch output := output.(type) {
  325. case string:
  326. key = output
  327. default:
  328. clog.Warningf("unexpected type %t (%v) while running '%s'", output, output, stash.Key)
  329. continue
  330. }
  331. cache.SetKey(stash.Name, key, value, &stash.TTLVal)
  332. }
  333. }
  334. //Iterate on leafs
  335. if len(n.LeavesNodes) > 0 {
  336. for _, leaf := range n.LeavesNodes {
  337. ret, err := leaf.process(p, ctx, cachedExprEnv)
  338. if err != nil {
  339. clog.Tracef("\tNode (%s) failed : %v", leaf.rn, err)
  340. clog.Debugf("Event leaving node : ko")
  341. return false, err
  342. }
  343. clog.Tracef("\tsub-node (%s) ret : %v (strategy:%s)", leaf.rn, ret, n.OnSuccess)
  344. if ret {
  345. NodeState = true
  346. /* if child is successful, stop processing */
  347. if n.OnSuccess == "next_stage" {
  348. clog.Debugf("child is success, OnSuccess=next_stage, skip")
  349. break
  350. }
  351. } else if !NodeHasOKGrok {
  352. /*
  353. If the parent node has a successful grok pattern, it's state will stay successful even if one or more chil fails.
  354. If the parent node is a skeleton node (no grok pattern), then at least one child must be successful for it to be a success.
  355. */
  356. NodeState = false
  357. }
  358. }
  359. }
  360. /*todo : check if a node made the state change ?*/
  361. /* should the childs inherit the on_success behavior */
  362. clog.Tracef("State after nodes : %v", NodeState)
  363. //grok or leafs failed, don't process statics
  364. if !NodeState {
  365. if n.Name != "" {
  366. NodesHitsKo.With(prometheus.Labels{"source": p.Line.Src, "type": p.Line.Module, "name": n.Name}).Inc()
  367. }
  368. clog.Debugf("Event leaving node : ko")
  369. return NodeState, nil
  370. }
  371. if n.Name != "" {
  372. NodesHitsOk.With(prometheus.Labels{"source": p.Line.Src, "type": p.Line.Module, "name": n.Name}).Inc()
  373. }
  374. /*
  375. Please kill me. this is to apply statics when the node *has* whitelists that successfully matched the node.
  376. */
  377. if hasWhitelist && isWhitelisted && len(n.Statics) > 0 || len(n.Statics) > 0 && !hasWhitelist {
  378. clog.Debugf("+ Processing %d statics", len(n.Statics))
  379. // if all else is good in whitelist, process node's statics
  380. err := n.ProcessStatics(n.Statics, p)
  381. if err != nil {
  382. clog.Errorf("Failed to process statics : %v", err)
  383. return false, err
  384. }
  385. } else {
  386. clog.Tracef("! No node statics")
  387. }
  388. if NodeState {
  389. clog.Debugf("Event leaving node : ok")
  390. log.Tracef("node is successful, check strategy")
  391. if n.OnSuccess == "next_stage" {
  392. idx := stageidx(p.Stage, ctx.Stages)
  393. //we're at the last stage
  394. if idx+1 == len(ctx.Stages) {
  395. clog.Debugf("node reached the last stage : %s", p.Stage)
  396. } else {
  397. clog.Debugf("move Event from stage %s to %s", p.Stage, ctx.Stages[idx+1])
  398. p.Stage = ctx.Stages[idx+1]
  399. }
  400. } else {
  401. clog.Tracef("no strategy on success (%s), continue !", n.OnSuccess)
  402. }
  403. } else {
  404. clog.Debugf("Event leaving node : ko")
  405. }
  406. clog.Tracef("Node successful, continue")
  407. return NodeState, nil
  408. }
  409. func (n *Node) compile(pctx *UnixParserCtx, ectx EnricherCtx) error {
  410. var err error
  411. var valid bool
  412. valid = false
  413. dumpr := spew.ConfigState{MaxDepth: 1, DisablePointerAddresses: true}
  414. n.rn = seed.Generate()
  415. n.EnrichFunctions = ectx
  416. log.Tracef("compile, node is %s", n.Stage)
  417. /* if the node has debugging enabled, create a specific logger with debug
  418. that will be used only for processing this node ;) */
  419. if n.Debug {
  420. var clog = logrus.New()
  421. if err := types.ConfigureLogger(clog); err != nil {
  422. log.Fatalf("While creating bucket-specific logger : %s", err)
  423. }
  424. clog.SetLevel(log.DebugLevel)
  425. n.Logger = clog.WithFields(log.Fields{
  426. "id": n.rn,
  427. })
  428. n.Logger.Infof("%s has debug enabled", n.Name)
  429. } else {
  430. /* else bind it to the default one (might find something more elegant here)*/
  431. n.Logger = log.WithFields(log.Fields{
  432. "id": n.rn,
  433. })
  434. }
  435. /* display info about top-level nodes, they should be the only one with explicit stage name ?*/
  436. n.Logger = n.Logger.WithFields(log.Fields{"stage": n.Stage, "name": n.Name})
  437. n.Logger.Tracef("Compiling : %s", dumpr.Sdump(n))
  438. //compile filter if present
  439. if n.Filter != "" {
  440. n.RunTimeFilter, err = expr.Compile(n.Filter, expr.Env(exprhelpers.GetExprEnv(map[string]interface{}{"evt": &types.Event{}})))
  441. if err != nil {
  442. return fmt.Errorf("compilation of '%s' failed: %v", n.Filter, err)
  443. }
  444. if n.Debug {
  445. n.ExprDebugger, err = exprhelpers.NewDebugger(n.Filter, expr.Env(exprhelpers.GetExprEnv(map[string]interface{}{"evt": &types.Event{}})))
  446. if err != nil {
  447. log.Errorf("unable to build debug filter for '%s' : %s", n.Filter, err)
  448. }
  449. }
  450. }
  451. /* handle pattern_syntax and groks */
  452. for _, pattern := range n.SubGroks {
  453. n.Logger.Tracef("Adding subpattern '%s' : '%s'", pattern.Key, pattern.Value)
  454. if err := pctx.Grok.Add(pattern.Key.(string), pattern.Value.(string)); err != nil {
  455. if errors.Is(err, grokky.ErrAlreadyExist) {
  456. n.Logger.Warningf("grok '%s' already registred", pattern.Key)
  457. continue
  458. }
  459. n.Logger.Errorf("Unable to compile subpattern %s : %v", pattern.Key, err)
  460. return err
  461. }
  462. }
  463. /* load grok by name or compile in-place */
  464. if n.Grok.RegexpName != "" {
  465. n.Logger.Tracef("+ Regexp Compilation '%s'", n.Grok.RegexpName)
  466. n.Grok.RunTimeRegexp, err = pctx.Grok.Get(n.Grok.RegexpName)
  467. if err != nil {
  468. return fmt.Errorf("unable to find grok '%s' : %v", n.Grok.RegexpName, err)
  469. }
  470. if n.Grok.RunTimeRegexp == nil {
  471. return fmt.Errorf("empty grok '%s'", n.Grok.RegexpName)
  472. }
  473. n.Logger.Tracef("%s regexp: %s", n.Grok.RegexpName, n.Grok.RunTimeRegexp.Regexp.String())
  474. valid = true
  475. } else if n.Grok.RegexpValue != "" {
  476. if strings.HasSuffix(n.Grok.RegexpValue, "\n") {
  477. n.Logger.Debugf("Beware, pattern ends with \\n : '%s'", n.Grok.RegexpValue)
  478. }
  479. n.Grok.RunTimeRegexp, err = pctx.Grok.Compile(n.Grok.RegexpValue)
  480. if err != nil {
  481. return fmt.Errorf("failed to compile grok '%s': %v", n.Grok.RegexpValue, err)
  482. }
  483. if n.Grok.RunTimeRegexp == nil {
  484. // We shouldn't be here because compilation succeeded, so regexp shouldn't be nil
  485. return fmt.Errorf("grok compilation failure: %s", n.Grok.RegexpValue)
  486. }
  487. n.Logger.Tracef("%s regexp : %s", n.Grok.RegexpValue, n.Grok.RunTimeRegexp.Regexp.String())
  488. valid = true
  489. }
  490. /*if grok source is an expression*/
  491. if n.Grok.ExpValue != "" {
  492. n.Grok.RunTimeValue, err = expr.Compile(n.Grok.ExpValue,
  493. expr.Env(exprhelpers.GetExprEnv(map[string]interface{}{"evt": &types.Event{}})))
  494. if err != nil {
  495. return errors.Wrap(err, "while compiling grok's expression")
  496. }
  497. }
  498. /* load grok statics */
  499. if len(n.Grok.Statics) > 0 {
  500. //compile expr statics if present
  501. for idx := range n.Grok.Statics {
  502. if n.Grok.Statics[idx].ExpValue != "" {
  503. n.Grok.Statics[idx].RunTimeValue, err = expr.Compile(n.Grok.Statics[idx].ExpValue,
  504. expr.Env(exprhelpers.GetExprEnv(map[string]interface{}{"evt": &types.Event{}})))
  505. if err != nil {
  506. return err
  507. }
  508. }
  509. }
  510. valid = true
  511. }
  512. /* load data capture (stash) */
  513. for i, stash := range n.Stash {
  514. n.Stash[i].ValueExpression, err = expr.Compile(stash.Value,
  515. expr.Env(exprhelpers.GetExprEnv(map[string]interface{}{"evt": &types.Event{}})))
  516. if err != nil {
  517. return errors.Wrap(err, "while compiling stash value expression")
  518. }
  519. n.Stash[i].KeyExpression, err = expr.Compile(stash.Key,
  520. expr.Env(exprhelpers.GetExprEnv(map[string]interface{}{"evt": &types.Event{}})))
  521. if err != nil {
  522. return errors.Wrap(err, "while compiling stash key expression")
  523. }
  524. n.Stash[i].TTLVal, err = time.ParseDuration(stash.TTL)
  525. if err != nil {
  526. return errors.Wrap(err, "while parsing stash ttl")
  527. }
  528. logLvl := n.Logger.Logger.GetLevel()
  529. //init the cache, does it make sense to create it here just to be sure everything is fine ?
  530. if err := cache.CacheInit(cache.CacheCfg{
  531. Size: n.Stash[i].MaxMapSize,
  532. TTL: n.Stash[i].TTLVal,
  533. Name: n.Stash[i].Name,
  534. Strategy: n.Stash[i].Strategy,
  535. LogLevel: &logLvl,
  536. }); err != nil {
  537. return errors.Wrap(err, "while initializing cache")
  538. }
  539. }
  540. /* compile leafs if present */
  541. if len(n.LeavesNodes) > 0 {
  542. for idx := range n.LeavesNodes {
  543. if n.LeavesNodes[idx].Name == "" {
  544. n.LeavesNodes[idx].Name = fmt.Sprintf("child-%s", n.Name)
  545. }
  546. /*propagate debug/stats to child nodes*/
  547. if !n.LeavesNodes[idx].Debug && n.Debug {
  548. n.LeavesNodes[idx].Debug = true
  549. }
  550. if !n.LeavesNodes[idx].Profiling && n.Profiling {
  551. n.LeavesNodes[idx].Profiling = true
  552. }
  553. n.LeavesNodes[idx].Stage = n.Stage
  554. err = n.LeavesNodes[idx].compile(pctx, ectx)
  555. if err != nil {
  556. return err
  557. }
  558. }
  559. valid = true
  560. }
  561. /* load statics if present */
  562. for idx := range n.Statics {
  563. if n.Statics[idx].ExpValue != "" {
  564. n.Statics[idx].RunTimeValue, err = expr.Compile(n.Statics[idx].ExpValue, expr.Env(exprhelpers.GetExprEnv(map[string]interface{}{"evt": &types.Event{}})))
  565. if err != nil {
  566. n.Logger.Errorf("Statics Compilation failed %v.", err)
  567. return err
  568. }
  569. }
  570. valid = true
  571. }
  572. /* compile whitelists if present */
  573. for _, v := range n.Whitelist.Ips {
  574. n.Whitelist.B_Ips = append(n.Whitelist.B_Ips, net.ParseIP(v))
  575. n.Logger.Debugf("adding ip %s to whitelists", net.ParseIP(v))
  576. valid = true
  577. }
  578. for _, v := range n.Whitelist.Cidrs {
  579. _, tnet, err := net.ParseCIDR(v)
  580. if err != nil {
  581. n.Logger.Fatalf("Unable to parse cidr whitelist '%s' : %v.", v, err)
  582. }
  583. n.Whitelist.B_Cidrs = append(n.Whitelist.B_Cidrs, tnet)
  584. n.Logger.Debugf("adding cidr %s to whitelists", tnet)
  585. valid = true
  586. }
  587. for _, filter := range n.Whitelist.Exprs {
  588. expression := &ExprWhitelist{}
  589. expression.Filter, err = expr.Compile(filter, expr.Env(exprhelpers.GetExprEnv(map[string]interface{}{"evt": &types.Event{}})))
  590. if err != nil {
  591. n.Logger.Fatalf("Unable to compile whitelist expression '%s' : %v.", filter, err)
  592. }
  593. expression.ExprDebugger, err = exprhelpers.NewDebugger(filter, expr.Env(exprhelpers.GetExprEnv(map[string]interface{}{"evt": &types.Event{}})))
  594. if err != nil {
  595. log.Errorf("unable to build debug filter for '%s' : %s", filter, err)
  596. }
  597. n.Whitelist.B_Exprs = append(n.Whitelist.B_Exprs, expression)
  598. n.Logger.Debugf("adding expression %s to whitelists", filter)
  599. valid = true
  600. }
  601. if !valid {
  602. /* node is empty, error force return */
  603. n.Logger.Error("Node is empty or invalid, abort")
  604. n.Stage = ""
  605. return fmt.Errorf("Node is empty")
  606. }
  607. if err := n.validate(pctx, ectx); err != nil {
  608. return err
  609. }
  610. return nil
  611. }