runtime.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. package parser
  2. /*
  3. This file contains
  4. - the runtime parsing routines
  5. */
  6. import (
  7. "errors"
  8. "fmt"
  9. "reflect"
  10. "strings"
  11. "time"
  12. "github.com/crowdsecurity/crowdsec/pkg/exprhelpers"
  13. "github.com/crowdsecurity/crowdsec/pkg/types"
  14. "strconv"
  15. "github.com/mohae/deepcopy"
  16. "github.com/prometheus/client_golang/prometheus"
  17. log "github.com/sirupsen/logrus"
  18. "github.com/antonmedv/expr"
  19. )
  20. /* ok, this is kinda experimental, I don't know how bad of an idea it is .. */
  21. func SetTargetByName(target string, value string, evt *types.Event) bool {
  22. if evt == nil {
  23. return false
  24. }
  25. //it's a hack, we do it for the user
  26. target = strings.TrimPrefix(target, "evt.")
  27. log.Debugf("setting target %s to %s", target, value)
  28. defer func() {
  29. if r := recover(); r != nil {
  30. log.Errorf("Runtime error while trying to set '%s': %+v", target, r)
  31. return
  32. }
  33. }()
  34. iter := reflect.ValueOf(evt).Elem()
  35. if (iter == reflect.Value{}) || iter.IsZero() {
  36. log.Tracef("event is nill")
  37. //event is nill
  38. return false
  39. }
  40. for _, f := range strings.Split(target, ".") {
  41. /*
  42. ** According to current Event layout we only have to handle struct and map
  43. */
  44. switch iter.Kind() {
  45. case reflect.Map:
  46. tmp := iter.MapIndex(reflect.ValueOf(f))
  47. /*if we're in a map and the field doesn't exist, the user wants to add it :) */
  48. if (tmp == reflect.Value{}) || tmp.IsZero() {
  49. log.Debugf("map entry is zero in '%s'", target)
  50. }
  51. iter.SetMapIndex(reflect.ValueOf(f), reflect.ValueOf(value))
  52. return true
  53. case reflect.Struct:
  54. tmp := iter.FieldByName(f)
  55. if !tmp.IsValid() {
  56. log.Debugf("'%s' is not a valid target because '%s' is not valid", target, f)
  57. return false
  58. }
  59. if tmp.Kind() == reflect.Ptr {
  60. tmp = reflect.Indirect(tmp)
  61. }
  62. iter = tmp
  63. break
  64. case reflect.Ptr:
  65. tmp := iter.Elem()
  66. iter = reflect.Indirect(tmp.FieldByName(f))
  67. default:
  68. log.Errorf("unexpected type %s in '%s'", iter.Kind(), target)
  69. return false
  70. }
  71. }
  72. //now we should have the final member :)
  73. if !iter.CanSet() {
  74. log.Errorf("'%s' can't be set", target)
  75. return false
  76. }
  77. if iter.Kind() != reflect.String {
  78. log.Errorf("Expected string, got %v when handling '%s'", iter.Kind(), target)
  79. return false
  80. }
  81. iter.Set(reflect.ValueOf(value))
  82. return true
  83. }
  84. func printStaticTarget(static types.ExtraField) string {
  85. if static.Method != "" {
  86. return static.Method
  87. } else if static.Parsed != "" {
  88. return fmt.Sprintf(".Parsed[%s]", static.Parsed)
  89. } else if static.Meta != "" {
  90. return fmt.Sprintf(".Meta[%s]", static.Meta)
  91. } else if static.Enriched != "" {
  92. return fmt.Sprintf(".Enriched[%s]", static.Enriched)
  93. } else if static.TargetByName != "" {
  94. return static.TargetByName
  95. } else {
  96. return "?"
  97. }
  98. }
  99. func (n *Node) ProcessStatics(statics []types.ExtraField, event *types.Event) error {
  100. //we have a few cases :
  101. //(meta||key) + (static||reference||expr)
  102. var value string
  103. clog := n.Logger
  104. cachedExprEnv := exprhelpers.GetExprEnv(map[string]interface{}{"evt": event})
  105. for _, static := range statics {
  106. value = ""
  107. if static.Value != "" {
  108. value = static.Value
  109. } else if static.RunTimeValue != nil {
  110. output, err := expr.Run(static.RunTimeValue, cachedExprEnv)
  111. if err != nil {
  112. clog.Warningf("failed to run RunTimeValue : %v", err)
  113. continue
  114. }
  115. switch out := output.(type) {
  116. case string:
  117. value = out
  118. case int:
  119. value = strconv.Itoa(out)
  120. default:
  121. clog.Fatalf("unexpected return type for RunTimeValue : %T", output)
  122. return errors.New("unexpected return type for RunTimeValue")
  123. }
  124. }
  125. if value == "" {
  126. //allow ParseDate to have empty input
  127. if static.Method != "ParseDate" {
  128. clog.Debugf("Empty value for %s, skip.", printStaticTarget(static))
  129. continue
  130. }
  131. }
  132. if static.Method != "" {
  133. processed := false
  134. /*still way too hackish, but : inject all the results in enriched, and */
  135. if enricherPlugin, ok := n.EnrichFunctions.Registered[static.Method]; ok {
  136. clog.Tracef("Found method '%s'", static.Method)
  137. ret, err := enricherPlugin.EnrichFunc(value, event, enricherPlugin.Ctx)
  138. if err != nil {
  139. clog.Errorf("method '%s' returned an error : %v", static.Method, err)
  140. }
  141. processed = true
  142. clog.Debugf("+ Method %s('%s') returned %d entries to merge in .Enriched\n", static.Method, value, len(ret))
  143. if len(ret) == 0 {
  144. clog.Debugf("+ Method '%s' empty response on '%s'", static.Method, value)
  145. }
  146. for k, v := range ret {
  147. clog.Debugf("\t.Enriched[%s] = '%s'\n", k, v)
  148. event.Enriched[k] = v
  149. }
  150. } else {
  151. clog.Debugf("method '%s' doesn't exist or plugin not initialized", static.Method)
  152. }
  153. if !processed {
  154. clog.Debugf("method '%s' doesn't exist", static.Method)
  155. }
  156. } else if static.Parsed != "" {
  157. clog.Debugf(".Parsed[%s] = '%s'", static.Parsed, value)
  158. event.Parsed[static.Parsed] = value
  159. } else if static.Meta != "" {
  160. clog.Debugf(".Meta[%s] = '%s'", static.Meta, value)
  161. event.Meta[static.Meta] = value
  162. } else if static.Enriched != "" {
  163. clog.Debugf(".Enriched[%s] = '%s'", static.Enriched, value)
  164. event.Enriched[static.Enriched] = value
  165. } else if static.TargetByName != "" {
  166. if !SetTargetByName(static.TargetByName, value, event) {
  167. clog.Errorf("Unable to set value of '%s'", static.TargetByName)
  168. } else {
  169. clog.Debugf("%s = '%s'", static.TargetByName, value)
  170. }
  171. } else {
  172. clog.Fatal("unable to process static : unknown target")
  173. }
  174. }
  175. return nil
  176. }
  177. var NodesHits = prometheus.NewCounterVec(
  178. prometheus.CounterOpts{
  179. Name: "cs_node_hits_total",
  180. Help: "Total events entered node.",
  181. },
  182. []string{"source", "type", "name"},
  183. )
  184. var NodesHitsOk = prometheus.NewCounterVec(
  185. prometheus.CounterOpts{
  186. Name: "cs_node_hits_ok_total",
  187. Help: "Total events successfully exited node.",
  188. },
  189. []string{"source", "type", "name"},
  190. )
  191. var NodesHitsKo = prometheus.NewCounterVec(
  192. prometheus.CounterOpts{
  193. Name: "cs_node_hits_ko_total",
  194. Help: "Total events unsuccessfully exited node.",
  195. },
  196. []string{"source", "type", "name"},
  197. )
  198. func stageidx(stage string, stages []string) int {
  199. for i, v := range stages {
  200. if stage == v {
  201. return i
  202. }
  203. }
  204. return -1
  205. }
  206. type ParserResult struct {
  207. Evt types.Event
  208. Success bool
  209. }
  210. var ParseDump bool
  211. var DumpFolder string
  212. var StageParseCache map[string]map[string][]ParserResult
  213. func Parse(ctx UnixParserCtx, xp types.Event, nodes []Node) (types.Event, error) {
  214. var event types.Event = xp
  215. /* the stage is undefined, probably line is freshly acquired, set to first stage !*/
  216. if event.Stage == "" && len(ctx.Stages) > 0 {
  217. event.Stage = ctx.Stages[0]
  218. log.Tracef("no stage, set to : %s", event.Stage)
  219. }
  220. event.Process = false
  221. if event.Time.IsZero() {
  222. event.Time = time.Now().UTC()
  223. }
  224. if event.Parsed == nil {
  225. event.Parsed = make(map[string]string)
  226. }
  227. if event.Enriched == nil {
  228. event.Enriched = make(map[string]string)
  229. }
  230. if event.Meta == nil {
  231. event.Meta = make(map[string]string)
  232. }
  233. if event.Type == types.LOG {
  234. log.Tracef("INPUT '%s'", event.Line.Raw)
  235. }
  236. cachedExprEnv := exprhelpers.GetExprEnv(map[string]interface{}{"evt": &event})
  237. if ParseDump {
  238. if StageParseCache == nil {
  239. StageParseCache = make(map[string]map[string][]ParserResult)
  240. StageParseCache["success"] = make(map[string][]ParserResult)
  241. StageParseCache["success"][""] = make([]ParserResult, 0)
  242. }
  243. }
  244. for _, stage := range ctx.Stages {
  245. if ParseDump {
  246. if _, ok := StageParseCache[stage]; !ok {
  247. StageParseCache[stage] = make(map[string][]ParserResult)
  248. }
  249. }
  250. /* if the node is forward in stages, seek to this stage */
  251. /* this is for example used by testing system to inject logs in post-syslog-parsing phase*/
  252. if stageidx(event.Stage, ctx.Stages) > stageidx(stage, ctx.Stages) {
  253. log.Tracef("skipping stage, we are already at [%s] expecting [%s]", event.Stage, stage)
  254. continue
  255. }
  256. log.Tracef("node stage : %s, current stage : %s", event.Stage, stage)
  257. /* if the stage is wrong, it means that the log didn't manage "pass" a stage with a onsuccess: next_stage tag */
  258. if event.Stage != stage {
  259. log.Debugf("Event not parsed, expected stage '%s' got '%s', abort", stage, event.Stage)
  260. event.Process = false
  261. return event, nil
  262. }
  263. isStageOK := false
  264. for idx, node := range nodes {
  265. //Only process current stage's nodes
  266. if event.Stage != node.Stage {
  267. continue
  268. }
  269. clog := log.WithFields(log.Fields{
  270. "node-name": node.rn,
  271. "stage": event.Stage,
  272. })
  273. clog.Tracef("Processing node %d/%d -> %s", idx, len(nodes), node.rn)
  274. if ctx.Profiling {
  275. node.Profiling = true
  276. }
  277. ret, err := node.process(&event, ctx, cachedExprEnv)
  278. if err != nil {
  279. clog.Fatalf("Error while processing node : %v", err)
  280. }
  281. clog.Tracef("node (%s) ret : %v", node.rn, ret)
  282. if ParseDump {
  283. if len(StageParseCache[stage][node.Name]) == 0 {
  284. StageParseCache[stage][node.Name] = make([]ParserResult, 0)
  285. }
  286. evtcopy := deepcopy.Copy(event)
  287. parserInfo := ParserResult{Evt: evtcopy.(types.Event), Success: ret}
  288. StageParseCache[stage][node.Name] = append(StageParseCache[stage][node.Name], parserInfo)
  289. }
  290. if ret {
  291. isStageOK = true
  292. }
  293. if ret && node.OnSuccess == "next_stage" {
  294. clog.Debugf("node successful, stop end stage %s", stage)
  295. break
  296. }
  297. //the parsed object moved onto the next phase
  298. if event.Stage != stage {
  299. clog.Tracef("node moved stage, break and redo")
  300. break
  301. }
  302. }
  303. if !isStageOK {
  304. log.Debugf("Log didn't finish stage %s", event.Stage)
  305. event.Process = false
  306. return event, nil
  307. }
  308. }
  309. event.Process = true
  310. return event, nil
  311. }