node.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. var groklabel string
  239. if n.Grok.RegexpName == "" {
  240. groklabel = fmt.Sprintf("%5.5s...", n.Grok.RegexpValue)
  241. } else {
  242. groklabel = n.Grok.RegexpName
  243. }
  244. grok := n.Grok.RunTimeRegexp.Parse(gstr)
  245. if len(grok) > 0 {
  246. clog.Debugf("+ Grok '%s' returned %d entries to merge in Parsed", groklabel, len(grok))
  247. //We managed to grok stuff, merged into parse
  248. for k, v := range grok {
  249. clog.Debugf("\t.Parsed['%s'] = '%s'", k, v)
  250. p.Parsed[k] = v
  251. }
  252. // if the grok succeed, process associated statics
  253. err := ProcessStatics(n.Grok.Statics, p, clog)
  254. if err != nil {
  255. clog.Fatalf("(%s) Failed to process statics : %v", n.rn, err)
  256. }
  257. } else {
  258. //grok failed, node failed
  259. clog.Debugf("+ Grok '%s' didn't return data on '%s'", groklabel, gstr)
  260. //clog.Tracef("on '%s'", gstr)
  261. NodeState = false
  262. }
  263. } else {
  264. clog.Tracef("! No grok pattern : %p", n.Grok.RunTimeRegexp)
  265. }
  266. //grok or leafs failed, don't process statics
  267. if !NodeState {
  268. if n.Profiling && n.Name != "" {
  269. NodesHitsKo.With(prometheus.Labels{"source": p.Line.Src, "name": n.Name}).Inc()
  270. }
  271. clog.Debugf("Event leaving node : ko")
  272. return NodeState, nil
  273. }
  274. if n.Profiling && n.Name != "" {
  275. NodesHitsOk.With(prometheus.Labels{"source": p.Line.Src, "name": n.Name}).Inc()
  276. }
  277. if len(n.Statics) > 0 {
  278. clog.Debugf("+ Processing %d statics", len(n.Statics))
  279. // if all else is good, process node's statics
  280. err := ProcessStatics(n.Statics, p, clog)
  281. if err != nil {
  282. clog.Fatalf("Failed to process statics : %v", err)
  283. }
  284. } else {
  285. clog.Tracef("! No node statics")
  286. }
  287. if NodeState {
  288. clog.Debugf("Event leaving node : ok")
  289. log.Tracef("node is successful, check strategy")
  290. if n.OnSuccess == "next_stage" {
  291. idx := stageidx(p.Stage, ctx.Stages)
  292. //we're at the last stage
  293. if idx+1 == len(ctx.Stages) {
  294. clog.Debugf("node reached the last stage : %s", p.Stage)
  295. } else {
  296. clog.Debugf("move Event from stage %s to %s", p.Stage, ctx.Stages[idx+1])
  297. p.Stage = ctx.Stages[idx+1]
  298. }
  299. } else {
  300. clog.Tracef("no strategy on success (%s), continue !", n.OnSuccess)
  301. }
  302. } else {
  303. clog.Debugf("Event leaving node : ko")
  304. }
  305. clog.Tracef("Node successful, continue")
  306. return NodeState, nil
  307. }
  308. func (n *Node) compile(pctx *UnixParserCtx) error {
  309. var err error
  310. var valid bool
  311. valid = false
  312. dumpr := spew.ConfigState{MaxDepth: 1, DisablePointerAddresses: true}
  313. n.rn = seed.Generate()
  314. log.Debugf("compile, node is %s", n.Stage)
  315. /* if the node has debugging enabled, create a specific logger with debug
  316. that will be used only for processing this node ;) */
  317. if n.Debug {
  318. var clog = logrus.New()
  319. if types.ConfigureLogger(clog) != err {
  320. log.Fatalf("While creating bucket-specific logger : %s", err)
  321. }
  322. clog.SetLevel(log.DebugLevel)
  323. n.logger = clog.WithFields(log.Fields{
  324. "id": n.rn,
  325. })
  326. n.logger.Infof("%s has debug enabled", n.Name)
  327. } else {
  328. /* else bind it to the default one (might find something more elegant here)*/
  329. n.logger = log.WithFields(log.Fields{
  330. "id": n.rn,
  331. })
  332. }
  333. /* display info about top-level nodes, they should be the only one with explicit stage name ?*/
  334. n.logger = n.logger.WithFields(log.Fields{"stage": n.Stage, "name": n.Name})
  335. n.logger.Tracef("Compiling : %s", dumpr.Sdump(n))
  336. //compile filter if present
  337. if n.Filter != "" {
  338. n.RunTimeFilter, err = expr.Compile(n.Filter, expr.Env(exprhelpers.GetExprEnv(map[string]interface{}{"evt": &types.Event{}})))
  339. if err != nil {
  340. return fmt.Errorf("compilation of '%s' failed: %v", n.Filter, err)
  341. }
  342. }
  343. /* handle pattern_syntax and groks */
  344. for node, pattern := range n.SubGroks {
  345. n.logger.Debugf("Adding subpattern '%s' : '%s'", node, pattern)
  346. if err := pctx.Grok.Add(node, pattern); err != nil {
  347. n.logger.Errorf("Unable to compile subpattern %s : %v", node, err)
  348. return err
  349. }
  350. }
  351. /* load grok by name or compile in-place */
  352. if n.Grok.RegexpName != "" {
  353. n.logger.Debugf("+ Regexp Compilation '%s'", n.Grok.RegexpName)
  354. n.Grok.RunTimeRegexp, err = pctx.Grok.Get(n.Grok.RegexpName)
  355. if err != nil {
  356. n.logger.Fatalf("Unable to find grok '%s' : %v\n", n.Grok.RegexpName, err)
  357. }
  358. if n.Grok.RunTimeRegexp == nil {
  359. n.logger.Fatalf("Didn't find regexp : %s", n.Grok.RegexpName)
  360. }
  361. n.logger.Debugf("%s regexp: %s", n.Grok.RegexpName, n.Grok.RunTimeRegexp.Regexp.String())
  362. valid = true
  363. } else if n.Grok.RegexpValue != "" {
  364. //n.logger.Debugf("+ Regexp Compilation '%s'", n.Grok.RegexpValue)
  365. n.Grok.RunTimeRegexp, err = pctx.Grok.Compile(n.Grok.RegexpValue)
  366. if err != nil {
  367. n.logger.Fatalf("Failed to compile grok '%s': %v\n", n.Grok.RegexpValue, err)
  368. }
  369. if n.Grok.RunTimeRegexp == nil {
  370. // We shouldn't be here because compilation succeeded, so regexp shouldn't be nil
  371. n.logger.Fatalf("Grok compilation failure: %s", n.Grok.RegexpValue)
  372. }
  373. n.logger.Debugf("%s regexp : %s", n.Grok.RegexpValue, n.Grok.RunTimeRegexp.Regexp.String())
  374. valid = true
  375. }
  376. /* load grok statics */
  377. if len(n.Grok.Statics) > 0 {
  378. //compile expr statics if present
  379. for idx := range n.Grok.Statics {
  380. if n.Grok.Statics[idx].ExpValue != "" {
  381. n.Grok.Statics[idx].RunTimeValue, err = expr.Compile(n.Grok.Statics[idx].ExpValue,
  382. expr.Env(exprhelpers.GetExprEnv(map[string]interface{}{"evt": &types.Event{}})))
  383. if err != nil {
  384. return err
  385. }
  386. }
  387. }
  388. valid = true
  389. }
  390. /* compile leafs if present */
  391. if len(n.SuccessNodes) > 0 {
  392. for idx := range n.SuccessNodes {
  393. if n.SuccessNodes[idx].Name == "" {
  394. n.SuccessNodes[idx].Name = fmt.Sprintf("child-%s", n.Name)
  395. }
  396. /*propagate debug/stats to child nodes*/
  397. if !n.SuccessNodes[idx].Debug && n.Debug {
  398. n.SuccessNodes[idx].Debug = true
  399. }
  400. if !n.SuccessNodes[idx].Profiling && n.Profiling {
  401. n.SuccessNodes[idx].Profiling = true
  402. }
  403. n.SuccessNodes[idx].Stage = n.Stage
  404. err = n.SuccessNodes[idx].compile(pctx)
  405. if err != nil {
  406. return err
  407. }
  408. }
  409. valid = true
  410. }
  411. /* load statics if present */
  412. for idx := range n.Statics {
  413. if n.Statics[idx].ExpValue != "" {
  414. n.Statics[idx].RunTimeValue, err = expr.Compile(n.Statics[idx].ExpValue, expr.Env(exprhelpers.GetExprEnv(map[string]interface{}{"evt": &types.Event{}})))
  415. if err != nil {
  416. n.logger.Errorf("Statics Compilation failed %v.", err)
  417. return err
  418. }
  419. }
  420. valid = true
  421. }
  422. /* compile whitelists if present */
  423. for _, v := range n.Whitelist.Ips {
  424. n.Whitelist.B_Ips = append(n.Whitelist.B_Ips, net.ParseIP(v))
  425. n.logger.Debugf("adding ip %s to whitelists", net.ParseIP(v))
  426. valid = true
  427. }
  428. for _, v := range n.Whitelist.Cidrs {
  429. _, tnet, err := net.ParseCIDR(v)
  430. if err != nil {
  431. n.logger.Fatalf("Unable to parse cidr whitelist '%s' : %v.", v, err)
  432. }
  433. n.Whitelist.B_Cidrs = append(n.Whitelist.B_Cidrs, tnet)
  434. n.logger.Debugf("adding cidr %s to whitelists", tnet)
  435. valid = true
  436. }
  437. for _, v := range n.Whitelist.Exprs {
  438. expr, err := expr.Compile(v, expr.Env(exprhelpers.GetExprEnv(map[string]interface{}{"evt": &types.Event{}})))
  439. if err != nil {
  440. n.logger.Fatalf("Unable to compile whitelist expression '%s' : %v.", v, err)
  441. }
  442. n.Whitelist.B_Exprs = append(n.Whitelist.B_Exprs, expr)
  443. n.logger.Debugf("adding expression %s to whitelists", v)
  444. valid = true
  445. }
  446. if !valid {
  447. /* node is empty, error force return */
  448. n.logger.Infof("Node is empty: %s", spew.Sdump(n))
  449. n.Stage = ""
  450. }
  451. if err := n.validate(pctx); err != nil {
  452. return err
  453. //n.logger.Fatalf("Node is invalid : %s", err)
  454. }
  455. return nil
  456. }