node.go 15 KB

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