node.go 17 KB

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