node.go 17 KB

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