node.go 15 KB

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