node.go 15 KB

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