explain.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. package main
  2. import (
  3. "bufio"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. log "github.com/sirupsen/logrus"
  11. "github.com/spf13/cobra"
  12. "github.com/crowdsecurity/crowdsec/pkg/dumps"
  13. "github.com/crowdsecurity/crowdsec/pkg/hubtest"
  14. )
  15. func getLineCountForFile(filepath string) (int, error) {
  16. f, err := os.Open(filepath)
  17. if err != nil {
  18. return 0, err
  19. }
  20. defer f.Close()
  21. lc := 0
  22. fs := bufio.NewReader(f)
  23. for {
  24. input, err := fs.ReadBytes('\n')
  25. if len(input) > 1 {
  26. lc++
  27. }
  28. if err != nil && err == io.EOF {
  29. break
  30. }
  31. }
  32. return lc, nil
  33. }
  34. type cliExplain struct{
  35. cfg configGetter
  36. flags struct {
  37. logFile string
  38. dsn string
  39. logLine string
  40. logType string
  41. details bool
  42. skipOk bool
  43. onlySuccessfulParsers bool
  44. noClean bool
  45. crowdsec string
  46. labels string
  47. }
  48. }
  49. func NewCLIExplain(cfg configGetter) *cliExplain {
  50. return &cliExplain{
  51. cfg: cfg,
  52. }
  53. }
  54. func (cli *cliExplain) NewCommand() *cobra.Command {
  55. cmd := &cobra.Command{
  56. Use: "explain",
  57. Short: "Explain log pipeline",
  58. Long: `
  59. Explain log pipeline
  60. `,
  61. Example: `
  62. cscli explain --file ./myfile.log --type nginx
  63. cscli explain --log "Sep 19 18:33:22 scw-d95986 sshd[24347]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=1.2.3.4" --type syslog
  64. cscli explain --dsn "file://myfile.log" --type nginx
  65. tail -n 5 myfile.log | cscli explain --type nginx -f -
  66. `,
  67. Args: cobra.ExactArgs(0),
  68. DisableAutoGenTag: true,
  69. RunE: func(_ *cobra.Command, _ []string) error {
  70. return cli.run()
  71. },
  72. PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
  73. if cli.flags.logLine == "" && cli.flags.logFile == "" && cli.flags.dsn == "" {
  74. printHelp(cmd)
  75. fmt.Println()
  76. return fmt.Errorf("please provide --log, --file or --dsn flag")
  77. }
  78. if cli.flags.logType == "" {
  79. printHelp(cmd)
  80. fmt.Println()
  81. return fmt.Errorf("please provide --type flag")
  82. }
  83. fileInfo, _ := os.Stdin.Stat()
  84. if cli.flags.logFile == "-" && ((fileInfo.Mode() & os.ModeCharDevice) == os.ModeCharDevice) {
  85. return fmt.Errorf("the option -f - is intended to work with pipes")
  86. }
  87. return nil
  88. },
  89. }
  90. flags := cmd.Flags()
  91. flags.StringVarP(&cli.flags.logFile, "file", "f", "", "Log file to test")
  92. flags.StringVarP(&cli.flags.dsn, "dsn", "d", "", "DSN to test")
  93. flags.StringVarP(&cli.flags.logLine, "log", "l", "", "Log line to test")
  94. flags.StringVarP(&cli.flags.logType, "type", "t", "", "Type of the acquisition to test")
  95. flags.StringVar(&cli.flags.labels, "labels", "", "Additional labels to add to the acquisition format (key:value,key2:value2)")
  96. flags.BoolVarP(&cli.flags.details, "verbose", "v", false, "Display individual changes")
  97. flags.BoolVar(&cli.flags.skipOk, "failures", false, "Only show failed lines")
  98. flags.BoolVar(&cli.flags.onlySuccessfulParsers, "only-successful-parsers", false, "Only show successful parsers")
  99. flags.StringVar(&cli.flags.crowdsec, "crowdsec", "crowdsec", "Path to crowdsec")
  100. flags.BoolVar(&cli.flags.noClean, "no-clean", false, "Don't clean runtime environment after tests")
  101. return cmd
  102. }
  103. func (cli *cliExplain) run() error {
  104. logFile := cli.flags.logFile
  105. logLine := cli.flags.logLine
  106. logType := cli.flags.logType
  107. dsn := cli.flags.dsn
  108. labels := cli.flags.labels
  109. crowdsec := cli.flags.crowdsec
  110. opts := dumps.DumpOpts{
  111. Details: cli.flags.details,
  112. SkipOk: cli.flags.skipOk,
  113. ShowNotOkParsers: !cli.flags.onlySuccessfulParsers,
  114. }
  115. var f *os.File
  116. // using empty string fallback to /tmp
  117. dir, err := os.MkdirTemp("", "cscli_explain")
  118. if err != nil {
  119. return fmt.Errorf("couldn't create a temporary directory to store cscli explain result: %s", err)
  120. }
  121. defer func() {
  122. if cli.flags.noClean {
  123. return
  124. }
  125. if _, err := os.Stat(dir); !os.IsNotExist(err) {
  126. if err := os.RemoveAll(dir); err != nil {
  127. log.Errorf("unable to delete temporary directory '%s': %s", dir, err)
  128. }
  129. }
  130. }()
  131. // we create a temporary log file if a log line/stdin has been provided
  132. if logLine != "" || logFile == "-" {
  133. tmpFile := filepath.Join(dir, "cscli_test_tmp.log")
  134. f, err = os.Create(tmpFile)
  135. if err != nil {
  136. return err
  137. }
  138. if logLine != "" {
  139. _, err = f.WriteString(logLine)
  140. if err != nil {
  141. return err
  142. }
  143. } else if logFile == "-" {
  144. reader := bufio.NewReader(os.Stdin)
  145. errCount := 0
  146. for {
  147. input, err := reader.ReadBytes('\n')
  148. if err != nil && errors.Is(err, io.EOF) {
  149. break
  150. }
  151. if len(input) > 1 {
  152. _, err = f.Write(input)
  153. }
  154. if err != nil || len(input) <= 1 {
  155. errCount++
  156. }
  157. }
  158. if errCount > 0 {
  159. log.Warnf("Failed to write %d lines to %s", errCount, tmpFile)
  160. }
  161. }
  162. f.Close()
  163. // this is the file that was going to be read by crowdsec anyway
  164. logFile = tmpFile
  165. }
  166. if logFile != "" {
  167. absolutePath, err := filepath.Abs(logFile)
  168. if err != nil {
  169. return fmt.Errorf("unable to get absolute path of '%s', exiting", logFile)
  170. }
  171. dsn = fmt.Sprintf("file://%s", absolutePath)
  172. lineCount, err := getLineCountForFile(absolutePath)
  173. if err != nil {
  174. return err
  175. }
  176. log.Debugf("file %s has %d lines", absolutePath, lineCount)
  177. if lineCount == 0 {
  178. return fmt.Errorf("the log file is empty: %s", absolutePath)
  179. }
  180. if lineCount > 100 {
  181. log.Warnf("%s contains %d lines. This may take a lot of resources.", absolutePath, lineCount)
  182. }
  183. }
  184. if dsn == "" {
  185. return fmt.Errorf("no acquisition (--file or --dsn) provided, can't run cscli test")
  186. }
  187. cmdArgs := []string{"-c", ConfigFilePath, "-type", logType, "-dsn", dsn, "-dump-data", dir, "-no-api"}
  188. if labels != "" {
  189. log.Debugf("adding labels %s", labels)
  190. cmdArgs = append(cmdArgs, "-label", labels)
  191. }
  192. crowdsecCmd := exec.Command(crowdsec, cmdArgs...)
  193. output, err := crowdsecCmd.CombinedOutput()
  194. if err != nil {
  195. fmt.Println(string(output))
  196. return fmt.Errorf("fail to run crowdsec for test: %v", err)
  197. }
  198. parserDumpFile := filepath.Join(dir, hubtest.ParserResultFileName)
  199. bucketStateDumpFile := filepath.Join(dir, hubtest.BucketPourResultFileName)
  200. parserDump, err := dumps.LoadParserDump(parserDumpFile)
  201. if err != nil {
  202. return fmt.Errorf("unable to load parser dump result: %s", err)
  203. }
  204. bucketStateDump, err := dumps.LoadBucketPourDump(bucketStateDumpFile)
  205. if err != nil {
  206. return fmt.Errorf("unable to load bucket dump result: %s", err)
  207. }
  208. dumps.DumpTree(*parserDump, *bucketStateDump, opts)
  209. return nil
  210. }