runtime.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. //nolint: gosimple
  64. break
  65. case reflect.Ptr:
  66. tmp := iter.Elem()
  67. iter = reflect.Indirect(tmp.FieldByName(f))
  68. default:
  69. log.Errorf("unexpected type %s in '%s'", iter.Kind(), target)
  70. return false
  71. }
  72. }
  73. //now we should have the final member :)
  74. if !iter.CanSet() {
  75. log.Errorf("'%s' can't be set", target)
  76. return false
  77. }
  78. if iter.Kind() != reflect.String {
  79. log.Errorf("Expected string, got %v when handling '%s'", iter.Kind(), target)
  80. return false
  81. }
  82. iter.Set(reflect.ValueOf(value))
  83. return true
  84. }
  85. func printStaticTarget(static types.ExtraField) string {
  86. if static.Method != "" {
  87. return static.Method
  88. } else if static.Parsed != "" {
  89. return fmt.Sprintf(".Parsed[%s]", static.Parsed)
  90. } else if static.Meta != "" {
  91. return fmt.Sprintf(".Meta[%s]", static.Meta)
  92. } else if static.Enriched != "" {
  93. return fmt.Sprintf(".Enriched[%s]", static.Enriched)
  94. } else if static.TargetByName != "" {
  95. return static.TargetByName
  96. } else {
  97. return "?"
  98. }
  99. }
  100. func (n *Node) ProcessStatics(statics []types.ExtraField, event *types.Event) error {
  101. //we have a few cases :
  102. //(meta||key) + (static||reference||expr)
  103. var value string
  104. clog := n.Logger
  105. cachedExprEnv := exprhelpers.GetExprEnv(map[string]interface{}{"evt": event})
  106. for _, static := range statics {
  107. value = ""
  108. if static.Value != "" {
  109. value = static.Value
  110. } else if static.RunTimeValue != nil {
  111. output, err := expr.Run(static.RunTimeValue, cachedExprEnv)
  112. if err != nil {
  113. clog.Warningf("failed to run RunTimeValue : %v", err)
  114. continue
  115. }
  116. switch out := output.(type) {
  117. case string:
  118. value = out
  119. case int:
  120. value = strconv.Itoa(out)
  121. case map[string]interface{}:
  122. clog.Warnf("Expression returned a map, please use ToJsonString() to convert it to string if you want to keep it as is, or refine your expression to extract a string")
  123. case []interface{}:
  124. clog.Warnf("Expression returned a map, please use ToJsonString() to convert it to string if you want to keep it as is, or refine your expression to extract a string")
  125. case nil:
  126. clog.Debugf("Expression returned nil, skipping")
  127. default:
  128. clog.Errorf("unexpected return type for RunTimeValue : %T", output)
  129. return errors.New("unexpected return type for RunTimeValue")
  130. }
  131. }
  132. if value == "" {
  133. //allow ParseDate to have empty input
  134. if static.Method != "ParseDate" {
  135. clog.Debugf("Empty value for %s, skip.", printStaticTarget(static))
  136. continue
  137. }
  138. }
  139. if static.Method != "" {
  140. processed := false
  141. /*still way too hackish, but : inject all the results in enriched, and */
  142. if enricherPlugin, ok := n.EnrichFunctions.Registered[static.Method]; ok {
  143. clog.Tracef("Found method '%s'", static.Method)
  144. ret, err := enricherPlugin.EnrichFunc(value, event, enricherPlugin.Ctx, n.Logger)
  145. if err != nil {
  146. clog.Errorf("method '%s' returned an error : %v", static.Method, err)
  147. }
  148. processed = true
  149. clog.Debugf("+ Method %s('%s') returned %d entries to merge in .Enriched\n", static.Method, value, len(ret))
  150. //Hackish check, but those methods do not return any data by design
  151. if len(ret) == 0 && static.Method != "UnmarshalXML" && static.Method != "UnmarshalJSON" {
  152. clog.Debugf("+ Method '%s' empty response on '%s'", static.Method, value)
  153. }
  154. for k, v := range ret {
  155. clog.Debugf("\t.Enriched[%s] = '%s'\n", k, v)
  156. event.Enriched[k] = v
  157. }
  158. } else {
  159. clog.Debugf("method '%s' doesn't exist or plugin not initialized", static.Method)
  160. }
  161. if !processed {
  162. clog.Debugf("method '%s' doesn't exist", static.Method)
  163. }
  164. } else if static.Parsed != "" {
  165. clog.Debugf(".Parsed[%s] = '%s'", static.Parsed, value)
  166. event.Parsed[static.Parsed] = value
  167. } else if static.Meta != "" {
  168. clog.Debugf(".Meta[%s] = '%s'", static.Meta, value)
  169. event.Meta[static.Meta] = value
  170. } else if static.Enriched != "" {
  171. clog.Debugf(".Enriched[%s] = '%s'", static.Enriched, value)
  172. event.Enriched[static.Enriched] = value
  173. } else if static.TargetByName != "" {
  174. if !SetTargetByName(static.TargetByName, value, event) {
  175. clog.Errorf("Unable to set value of '%s'", static.TargetByName)
  176. } else {
  177. clog.Debugf("%s = '%s'", static.TargetByName, value)
  178. }
  179. } else {
  180. clog.Fatal("unable to process static : unknown target")
  181. }
  182. }
  183. return nil
  184. }
  185. var NodesHits = prometheus.NewCounterVec(
  186. prometheus.CounterOpts{
  187. Name: "cs_node_hits_total",
  188. Help: "Total events entered node.",
  189. },
  190. []string{"source", "type", "name"},
  191. )
  192. var NodesHitsOk = prometheus.NewCounterVec(
  193. prometheus.CounterOpts{
  194. Name: "cs_node_hits_ok_total",
  195. Help: "Total events successfully exited node.",
  196. },
  197. []string{"source", "type", "name"},
  198. )
  199. var NodesHitsKo = prometheus.NewCounterVec(
  200. prometheus.CounterOpts{
  201. Name: "cs_node_hits_ko_total",
  202. Help: "Total events unsuccessfully exited node.",
  203. },
  204. []string{"source", "type", "name"},
  205. )
  206. func stageidx(stage string, stages []string) int {
  207. for i, v := range stages {
  208. if stage == v {
  209. return i
  210. }
  211. }
  212. return -1
  213. }
  214. type ParserResult struct {
  215. Evt types.Event
  216. Success bool
  217. }
  218. var ParseDump bool
  219. var DumpFolder string
  220. var StageParseCache map[string]map[string][]ParserResult
  221. func Parse(ctx UnixParserCtx, xp types.Event, nodes []Node) (types.Event, error) {
  222. var event types.Event = xp
  223. /* the stage is undefined, probably line is freshly acquired, set to first stage !*/
  224. if event.Stage == "" && len(ctx.Stages) > 0 {
  225. event.Stage = ctx.Stages[0]
  226. log.Tracef("no stage, set to : %s", event.Stage)
  227. }
  228. event.Process = false
  229. if event.Time.IsZero() {
  230. event.Time = time.Now().UTC()
  231. }
  232. if event.Parsed == nil {
  233. event.Parsed = make(map[string]string)
  234. }
  235. if event.Enriched == nil {
  236. event.Enriched = make(map[string]string)
  237. }
  238. if event.Meta == nil {
  239. event.Meta = make(map[string]string)
  240. }
  241. if event.Type == types.LOG {
  242. log.Tracef("INPUT '%s'", event.Line.Raw)
  243. }
  244. cachedExprEnv := exprhelpers.GetExprEnv(map[string]interface{}{"evt": &event})
  245. if ParseDump {
  246. if StageParseCache == nil {
  247. StageParseCache = make(map[string]map[string][]ParserResult)
  248. StageParseCache["success"] = make(map[string][]ParserResult)
  249. StageParseCache["success"][""] = make([]ParserResult, 0)
  250. }
  251. }
  252. for _, stage := range ctx.Stages {
  253. if ParseDump {
  254. if _, ok := StageParseCache[stage]; !ok {
  255. StageParseCache[stage] = make(map[string][]ParserResult)
  256. }
  257. }
  258. /* if the node is forward in stages, seek to this stage */
  259. /* this is for example used by testing system to inject logs in post-syslog-parsing phase*/
  260. if stageidx(event.Stage, ctx.Stages) > stageidx(stage, ctx.Stages) {
  261. log.Tracef("skipping stage, we are already at [%s] expecting [%s]", event.Stage, stage)
  262. continue
  263. }
  264. log.Tracef("node stage : %s, current stage : %s", event.Stage, stage)
  265. /* if the stage is wrong, it means that the log didn't manage "pass" a stage with a onsuccess: next_stage tag */
  266. if event.Stage != stage {
  267. log.Debugf("Event not parsed, expected stage '%s' got '%s', abort", stage, event.Stage)
  268. event.Process = false
  269. return event, nil
  270. }
  271. isStageOK := false
  272. for idx, node := range nodes {
  273. //Only process current stage's nodes
  274. if event.Stage != node.Stage {
  275. continue
  276. }
  277. clog := log.WithFields(log.Fields{
  278. "node-name": node.rn,
  279. "stage": event.Stage,
  280. })
  281. clog.Tracef("Processing node %d/%d -> %s", idx, len(nodes), node.rn)
  282. if ctx.Profiling {
  283. node.Profiling = true
  284. }
  285. ret, err := node.process(&event, ctx, cachedExprEnv)
  286. if err != nil {
  287. clog.Errorf("Error while processing node : %v", err)
  288. return event, err
  289. }
  290. clog.Tracef("node (%s) ret : %v", node.rn, ret)
  291. if ParseDump {
  292. if len(StageParseCache[stage][node.Name]) == 0 {
  293. StageParseCache[stage][node.Name] = make([]ParserResult, 0)
  294. }
  295. evtcopy := deepcopy.Copy(event)
  296. parserInfo := ParserResult{Evt: evtcopy.(types.Event), Success: ret}
  297. StageParseCache[stage][node.Name] = append(StageParseCache[stage][node.Name], parserInfo)
  298. }
  299. if ret {
  300. isStageOK = true
  301. }
  302. if ret && node.OnSuccess == "next_stage" {
  303. clog.Debugf("node successful, stop end stage %s", stage)
  304. break
  305. }
  306. //the parsed object moved onto the next phase
  307. if event.Stage != stage {
  308. clog.Tracef("node moved stage, break and redo")
  309. break
  310. }
  311. }
  312. if !isStageOK {
  313. log.Debugf("Log didn't finish stage %s", event.Stage)
  314. event.Process = false
  315. return event, nil
  316. }
  317. }
  318. event.Process = true
  319. return event, nil
  320. }