node.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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. SuccessNodes []Node `yaml:"nodes,omitempty"`
  42. //Flag used to describe when to 'break' or return an 'error'
  43. // BreakBehaviour string `yaml:"break,omitempty"`
  44. // Error string `yaml:"error,omitempty"`
  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 map[string]string `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) 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.Debugf("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")
  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.Debugf("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 src 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. if p.Type == types.LOG {
  142. if _, ok := p.Meta["source_ip"]; ok {
  143. src = net.ParseIP(p.Meta["source_ip"])
  144. }
  145. } else if p.Type == types.OVFLW {
  146. src = net.ParseIP(p.Overflow.Source_ip)
  147. }
  148. if src != nil {
  149. for _, v := range n.Whitelist.B_Ips {
  150. if v.Equal(src) {
  151. clog.Debugf("Event from [%s] is whitelisted by Ips !", src)
  152. p.Whitelisted = true
  153. isWhitelisted = true
  154. } else {
  155. clog.Debugf("whitelist: %s is not eq [%s]", src, v)
  156. }
  157. hasWhitelist = true
  158. }
  159. for _, v := range n.Whitelist.B_Cidrs {
  160. if v.Contains(src) {
  161. clog.Debugf("Event from [%s] is whitelisted by Cidrs !", src)
  162. p.Whitelisted = true
  163. isWhitelisted = true
  164. } else {
  165. clog.Debugf("whitelist: %s not in [%s]", src, v)
  166. }
  167. hasWhitelist = true
  168. }
  169. } else {
  170. clog.Debugf("no ip in event, cidr/ip whitelists not checked")
  171. }
  172. /* run whitelist expression tests anyway */
  173. for eidx, e := range n.Whitelist.B_Exprs {
  174. output, err := expr.Run(e.Filter, exprhelpers.GetExprEnv(map[string]interface{}{"evt": p}))
  175. if err != nil {
  176. clog.Warningf("failed to run whitelist expr : %v", err)
  177. clog.Debugf("Event leaving node : ko")
  178. return false, nil
  179. }
  180. switch out := output.(type) {
  181. case bool:
  182. if n.Debug {
  183. e.ExprDebugger.Run(clog, out, exprhelpers.GetExprEnv(map[string]interface{}{"evt": p}))
  184. }
  185. if out {
  186. clog.Debugf("Event is whitelisted by Expr !")
  187. p.Whitelisted = true
  188. isWhitelisted = true
  189. }
  190. hasWhitelist = true
  191. default:
  192. log.Errorf("unexpected type %t (%v) while running '%s'", output, output, n.Whitelist.Exprs[eidx])
  193. }
  194. }
  195. if isWhitelisted {
  196. p.WhiteListReason = n.Whitelist.Reason
  197. /*huglily wipe the ban order if the event is whitelisted and it's an overflow */
  198. if p.Type == types.OVFLW { /*don't do this at home kids */
  199. // p.Overflow.OverflowAction = ""
  200. //Break this for now. Souldn't have been done this way, but that's not taht serious
  201. /*only display logs when we discard ban to avoid spam*/
  202. clog.Infof("Ban for %s whitelisted, reason [%s]", p.Overflow.Source.Ip.String(), n.Whitelist.Reason)
  203. p.Overflow.Whitelisted = true
  204. }
  205. }
  206. //Iterate on leafs
  207. if len(n.SuccessNodes) > 0 {
  208. for _, leaf := range n.SuccessNodes {
  209. //clog.Debugf("Processing sub-node %d/%d : %s", idx, len(n.SuccessNodes), leaf.rn)
  210. ret, err := leaf.process(p, ctx)
  211. if err != nil {
  212. clog.Tracef("\tNode (%s) failed : %v", leaf.rn, err)
  213. clog.Debugf("Event leaving node : ko")
  214. return false, err
  215. }
  216. clog.Tracef("\tsub-node (%s) ret : %v (strategy:%s)", leaf.rn, ret, n.OnSuccess)
  217. if ret {
  218. NodeState = true
  219. /* if chil is successful, stop processing */
  220. if n.OnSuccess == "next_stage" {
  221. clog.Debugf("child is success, OnSuccess=next_stage, skip")
  222. break
  223. }
  224. } else {
  225. NodeState = false
  226. }
  227. }
  228. }
  229. /*todo : check if a node made the state change ?*/
  230. /* should the childs inherit the on_success behaviour */
  231. clog.Tracef("State after nodes : %v", NodeState)
  232. //Process grok if present, should be exclusive with nodes :)
  233. gstr := ""
  234. if n.Grok.RunTimeRegexp != nil {
  235. clog.Tracef("Processing grok pattern : %s : %p", n.Grok.RegexpName, n.Grok.RunTimeRegexp)
  236. //for unparsed, parsed etc. set sensible defaults to reduce user hassle
  237. if n.Grok.TargetField == "" {
  238. clog.Fatalf("not default field and no specified on stage '%s'", n.Stage)
  239. } else {
  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. //return false, nil
  249. }
  250. }
  251. var groklabel string
  252. if n.Grok.RegexpName == "" {
  253. groklabel = fmt.Sprintf("%5.5s...", n.Grok.RegexpValue)
  254. } else {
  255. groklabel = n.Grok.RegexpName
  256. }
  257. grok := n.Grok.RunTimeRegexp.Parse(gstr)
  258. if len(grok) > 0 {
  259. clog.Debugf("+ Grok '%s' returned %d entries to merge in Parsed", groklabel, len(grok))
  260. //We managed to grok stuff, merged into parse
  261. for k, v := range grok {
  262. clog.Debugf("\t.Parsed['%s'] = '%s'", k, v)
  263. p.Parsed[k] = v
  264. }
  265. // if the grok succeed, process associated statics
  266. err := ProcessStatics(n.Grok.Statics, p, clog)
  267. if err != nil {
  268. clog.Fatalf("(%s) Failed to process statics : %v", n.rn, err)
  269. }
  270. } else {
  271. //grok failed, node failed
  272. clog.Debugf("+ Grok '%s' didn't return data on '%s'", groklabel, gstr)
  273. //clog.Tracef("on '%s'", gstr)
  274. NodeState = false
  275. }
  276. } else {
  277. clog.Tracef("! No grok pattern : %p", n.Grok.RunTimeRegexp)
  278. }
  279. //grok or leafs failed, don't process statics
  280. if !NodeState {
  281. if n.Name != "" {
  282. NodesHitsKo.With(prometheus.Labels{"source": p.Line.Src, "name": n.Name}).Inc()
  283. }
  284. clog.Debugf("Event leaving node : ko")
  285. return NodeState, nil
  286. }
  287. if n.Name != "" {
  288. NodesHitsOk.With(prometheus.Labels{"source": p.Line.Src, "name": n.Name}).Inc()
  289. }
  290. if hasWhitelist && isWhitelisted && len(n.Statics) > 0 || len(n.Statics) > 0 && !hasWhitelist {
  291. clog.Debugf("+ Processing %d statics", len(n.Statics))
  292. // if all else is good in whitelist, process node's statics
  293. err := ProcessStatics(n.Statics, p, clog)
  294. if err != nil {
  295. clog.Fatalf("Failed to process statics : %v", err)
  296. }
  297. } else {
  298. clog.Tracef("! No node statics")
  299. }
  300. if NodeState {
  301. clog.Debugf("Event leaving node : ok")
  302. log.Tracef("node is successful, check strategy")
  303. if n.OnSuccess == "next_stage" {
  304. idx := stageidx(p.Stage, ctx.Stages)
  305. //we're at the last stage
  306. if idx+1 == len(ctx.Stages) {
  307. clog.Debugf("node reached the last stage : %s", p.Stage)
  308. } else {
  309. clog.Debugf("move Event from stage %s to %s", p.Stage, ctx.Stages[idx+1])
  310. p.Stage = ctx.Stages[idx+1]
  311. }
  312. } else {
  313. clog.Tracef("no strategy on success (%s), continue !", n.OnSuccess)
  314. }
  315. } else {
  316. clog.Debugf("Event leaving node : ko")
  317. }
  318. clog.Tracef("Node successful, continue")
  319. return NodeState, nil
  320. }
  321. func (n *Node) compile(pctx *UnixParserCtx) error {
  322. var err error
  323. var valid bool
  324. valid = false
  325. dumpr := spew.ConfigState{MaxDepth: 1, DisablePointerAddresses: true}
  326. n.rn = seed.Generate()
  327. log.Debugf("compile, node is %s", n.Stage)
  328. /* if the node has debugging enabled, create a specific logger with debug
  329. that will be used only for processing this node ;) */
  330. if n.Debug {
  331. var clog = logrus.New()
  332. if err := types.ConfigureLogger(clog); err != nil {
  333. log.Fatalf("While creating bucket-specific logger : %s", err)
  334. }
  335. clog.SetLevel(log.DebugLevel)
  336. n.logger = clog.WithFields(log.Fields{
  337. "id": n.rn,
  338. })
  339. n.logger.Infof("%s has debug enabled", n.Name)
  340. } else {
  341. /* else bind it to the default one (might find something more elegant here)*/
  342. n.logger = log.WithFields(log.Fields{
  343. "id": n.rn,
  344. })
  345. }
  346. /* display info about top-level nodes, they should be the only one with explicit stage name ?*/
  347. n.logger = n.logger.WithFields(log.Fields{"stage": n.Stage, "name": n.Name})
  348. n.logger.Tracef("Compiling : %s", dumpr.Sdump(n))
  349. //compile filter if present
  350. if n.Filter != "" {
  351. n.RunTimeFilter, err = expr.Compile(n.Filter, expr.Env(exprhelpers.GetExprEnv(map[string]interface{}{"evt": &types.Event{}})))
  352. if err != nil {
  353. return fmt.Errorf("compilation of '%s' failed: %v", n.Filter, err)
  354. }
  355. if n.Debug {
  356. n.ExprDebugger, err = exprhelpers.NewDebugger(n.Filter, expr.Env(exprhelpers.GetExprEnv(map[string]interface{}{"evt": &types.Event{}})))
  357. if err != nil {
  358. log.Errorf("unable to build debug filter for '%s' : %s", n.Filter, err)
  359. }
  360. }
  361. }
  362. /* handle pattern_syntax and groks */
  363. for node, pattern := range n.SubGroks {
  364. n.logger.Debugf("Adding subpattern '%s' : '%s'", node, pattern)
  365. if err := pctx.Grok.Add(node, pattern); err != nil {
  366. n.logger.Errorf("Unable to compile subpattern %s : %v", node, err)
  367. return err
  368. }
  369. }
  370. /* load grok by name or compile in-place */
  371. if n.Grok.RegexpName != "" {
  372. n.logger.Debugf("+ Regexp Compilation '%s'", n.Grok.RegexpName)
  373. n.Grok.RunTimeRegexp, err = pctx.Grok.Get(n.Grok.RegexpName)
  374. if err != nil {
  375. return fmt.Errorf("Unable to find grok '%s' : %v", n.Grok.RegexpName, err)
  376. }
  377. if n.Grok.RunTimeRegexp == nil {
  378. return fmt.Errorf("Empty grok '%s'", n.Grok.RegexpName)
  379. }
  380. n.logger.Debugf("%s regexp: %s", n.Grok.RegexpName, n.Grok.RunTimeRegexp.Regexp.String())
  381. valid = true
  382. } else if n.Grok.RegexpValue != "" {
  383. if strings.HasSuffix(n.Grok.RegexpValue, "\n") {
  384. n.logger.Debugf("Beware, pattern ends with \\n : '%s'", n.Grok.RegexpValue)
  385. }
  386. //n.logger.Debugf("+ Regexp Compilation '%s'", n.Grok.RegexpValue)
  387. n.Grok.RunTimeRegexp, err = pctx.Grok.Compile(n.Grok.RegexpValue)
  388. if err != nil {
  389. return fmt.Errorf("Failed to compile grok '%s': %v\n", n.Grok.RegexpValue, err)
  390. }
  391. if n.Grok.RunTimeRegexp == nil {
  392. // We shouldn't be here because compilation succeeded, so regexp shouldn't be nil
  393. return fmt.Errorf("Grok compilation failure: %s", n.Grok.RegexpValue)
  394. }
  395. n.logger.Debugf("%s regexp : %s", n.Grok.RegexpValue, n.Grok.RunTimeRegexp.Regexp.String())
  396. valid = true
  397. }
  398. /* load grok statics */
  399. if len(n.Grok.Statics) > 0 {
  400. //compile expr statics if present
  401. for idx := range n.Grok.Statics {
  402. if n.Grok.Statics[idx].ExpValue != "" {
  403. n.Grok.Statics[idx].RunTimeValue, err = expr.Compile(n.Grok.Statics[idx].ExpValue,
  404. expr.Env(exprhelpers.GetExprEnv(map[string]interface{}{"evt": &types.Event{}})))
  405. if err != nil {
  406. return err
  407. }
  408. }
  409. }
  410. valid = true
  411. }
  412. /* compile leafs if present */
  413. if len(n.SuccessNodes) > 0 {
  414. for idx := range n.SuccessNodes {
  415. if n.SuccessNodes[idx].Name == "" {
  416. n.SuccessNodes[idx].Name = fmt.Sprintf("child-%s", n.Name)
  417. }
  418. /*propagate debug/stats to child nodes*/
  419. if !n.SuccessNodes[idx].Debug && n.Debug {
  420. n.SuccessNodes[idx].Debug = true
  421. }
  422. if !n.SuccessNodes[idx].Profiling && n.Profiling {
  423. n.SuccessNodes[idx].Profiling = true
  424. }
  425. n.SuccessNodes[idx].Stage = n.Stage
  426. err = n.SuccessNodes[idx].compile(pctx)
  427. if err != nil {
  428. return err
  429. }
  430. }
  431. valid = true
  432. }
  433. /* load statics if present */
  434. for idx := range n.Statics {
  435. if n.Statics[idx].ExpValue != "" {
  436. n.Statics[idx].RunTimeValue, err = expr.Compile(n.Statics[idx].ExpValue, expr.Env(exprhelpers.GetExprEnv(map[string]interface{}{"evt": &types.Event{}})))
  437. if err != nil {
  438. n.logger.Errorf("Statics Compilation failed %v.", err)
  439. return err
  440. }
  441. }
  442. valid = true
  443. }
  444. /* compile whitelists if present */
  445. for _, v := range n.Whitelist.Ips {
  446. n.Whitelist.B_Ips = append(n.Whitelist.B_Ips, net.ParseIP(v))
  447. n.logger.Debugf("adding ip %s to whitelists", net.ParseIP(v))
  448. valid = true
  449. }
  450. for _, v := range n.Whitelist.Cidrs {
  451. _, tnet, err := net.ParseCIDR(v)
  452. if err != nil {
  453. n.logger.Fatalf("Unable to parse cidr whitelist '%s' : %v.", v, err)
  454. }
  455. n.Whitelist.B_Cidrs = append(n.Whitelist.B_Cidrs, tnet)
  456. n.logger.Debugf("adding cidr %s to whitelists", tnet)
  457. valid = true
  458. }
  459. for _, filter := range n.Whitelist.Exprs {
  460. expression := &types.ExprWhitelist{}
  461. expression.Filter, err = expr.Compile(filter, expr.Env(exprhelpers.GetExprEnv(map[string]interface{}{"evt": &types.Event{}})))
  462. if err != nil {
  463. n.logger.Fatalf("Unable to compile whitelist expression '%s' : %v.", filter, err)
  464. }
  465. expression.ExprDebugger, err = exprhelpers.NewDebugger(filter, expr.Env(exprhelpers.GetExprEnv(map[string]interface{}{"evt": &types.Event{}})))
  466. if err != nil {
  467. log.Errorf("unable to build debug filter for '%s' : %s", filter, err)
  468. }
  469. n.Whitelist.B_Exprs = append(n.Whitelist.B_Exprs, expression)
  470. n.logger.Debugf("adding expression %s to whitelists", filter)
  471. valid = true
  472. }
  473. if !valid {
  474. /* node is empty, error force return */
  475. n.logger.Infof("Node is empty: %s", spew.Sdump(n))
  476. n.Stage = ""
  477. }
  478. if err := n.validate(pctx); err != nil {
  479. return err
  480. //n.logger.Fatalf("Node is invalid : %s", err)
  481. }
  482. return nil
  483. }