lapi.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "net/url"
  6. "os"
  7. "sort"
  8. "strings"
  9. "github.com/go-openapi/strfmt"
  10. log "github.com/sirupsen/logrus"
  11. "github.com/spf13/cobra"
  12. "golang.org/x/exp/slices"
  13. "gopkg.in/yaml.v2"
  14. "github.com/crowdsecurity/go-cs-lib/pkg/version"
  15. "github.com/crowdsecurity/crowdsec/pkg/alertcontext"
  16. "github.com/crowdsecurity/crowdsec/pkg/apiclient"
  17. "github.com/crowdsecurity/crowdsec/pkg/csconfig"
  18. "github.com/crowdsecurity/crowdsec/pkg/cwhub"
  19. "github.com/crowdsecurity/crowdsec/pkg/exprhelpers"
  20. "github.com/crowdsecurity/crowdsec/pkg/models"
  21. "github.com/crowdsecurity/crowdsec/pkg/parser"
  22. )
  23. var LAPIURLPrefix string = "v1"
  24. func runLapiStatus(cmd *cobra.Command, args []string) error {
  25. var err error
  26. password := strfmt.Password(csConfig.API.Client.Credentials.Password)
  27. apiurl, err := url.Parse(csConfig.API.Client.Credentials.URL)
  28. login := csConfig.API.Client.Credentials.Login
  29. if err != nil {
  30. log.Fatalf("parsing api url ('%s'): %s", apiurl, err)
  31. }
  32. if err := csConfig.LoadHub(); err != nil {
  33. log.Fatal(err)
  34. }
  35. if err := cwhub.GetHubIdx(csConfig.Hub); err != nil {
  36. log.Info("Run 'sudo cscli hub update' to get the hub index")
  37. log.Fatalf("Failed to load hub index : %s", err)
  38. }
  39. scenarios, err := cwhub.GetInstalledScenariosAsString()
  40. if err != nil {
  41. log.Fatalf("failed to get scenarios : %s", err)
  42. }
  43. Client, err = apiclient.NewDefaultClient(apiurl,
  44. LAPIURLPrefix,
  45. fmt.Sprintf("crowdsec/%s", version.String()),
  46. nil)
  47. if err != nil {
  48. log.Fatalf("init default client: %s", err)
  49. }
  50. t := models.WatcherAuthRequest{
  51. MachineID: &login,
  52. Password: &password,
  53. Scenarios: scenarios,
  54. }
  55. log.Infof("Loaded credentials from %s", csConfig.API.Client.CredentialsFilePath)
  56. log.Infof("Trying to authenticate with username %s on %s", login, apiurl)
  57. _, _, err = Client.Auth.AuthenticateWatcher(context.Background(), t)
  58. if err != nil {
  59. log.Fatalf("Failed to authenticate to Local API (LAPI) : %s", err)
  60. } else {
  61. log.Infof("You can successfully interact with Local API (LAPI)")
  62. }
  63. return nil
  64. }
  65. func runLapiRegister(cmd *cobra.Command, args []string) error {
  66. var err error
  67. flags := cmd.Flags()
  68. apiURL, err := flags.GetString("url")
  69. if err != nil {
  70. return err
  71. }
  72. outputFile, err := flags.GetString("file")
  73. if err != nil {
  74. return err
  75. }
  76. lapiUser, err := flags.GetString("machine")
  77. if err != nil {
  78. return err
  79. }
  80. if lapiUser == "" {
  81. lapiUser, err = generateID("")
  82. if err != nil {
  83. log.Fatalf("unable to generate machine id: %s", err)
  84. }
  85. }
  86. password := strfmt.Password(generatePassword(passwordLength))
  87. if apiURL == "" {
  88. if csConfig.API.Client != nil && csConfig.API.Client.Credentials != nil && csConfig.API.Client.Credentials.URL != "" {
  89. apiURL = csConfig.API.Client.Credentials.URL
  90. } else {
  91. log.Fatalf("No Local API URL. Please provide it in your configuration or with the -u parameter")
  92. }
  93. }
  94. /*URL needs to end with /, but user doesn't care*/
  95. if !strings.HasSuffix(apiURL, "/") {
  96. apiURL += "/"
  97. }
  98. /*URL needs to start with http://, but user doesn't care*/
  99. if !strings.HasPrefix(apiURL, "http://") && !strings.HasPrefix(apiURL, "https://") {
  100. apiURL = "http://" + apiURL
  101. }
  102. apiurl, err := url.Parse(apiURL)
  103. if err != nil {
  104. log.Fatalf("parsing api url: %s", err)
  105. }
  106. _, err = apiclient.RegisterClient(&apiclient.Config{
  107. MachineID: lapiUser,
  108. Password: password,
  109. UserAgent: fmt.Sprintf("crowdsec/%s", version.String()),
  110. URL: apiurl,
  111. VersionPrefix: LAPIURLPrefix,
  112. }, nil)
  113. if err != nil {
  114. log.Fatalf("api client register: %s", err)
  115. }
  116. log.Printf("Successfully registered to Local API (LAPI)")
  117. var dumpFile string
  118. if outputFile != "" {
  119. dumpFile = outputFile
  120. } else if csConfig.API.Client.CredentialsFilePath != "" {
  121. dumpFile = csConfig.API.Client.CredentialsFilePath
  122. } else {
  123. dumpFile = ""
  124. }
  125. apiCfg := csconfig.ApiCredentialsCfg{
  126. Login: lapiUser,
  127. Password: password.String(),
  128. URL: apiURL,
  129. }
  130. apiConfigDump, err := yaml.Marshal(apiCfg)
  131. if err != nil {
  132. log.Fatalf("unable to marshal api credentials: %s", err)
  133. }
  134. if dumpFile != "" {
  135. err = os.WriteFile(dumpFile, apiConfigDump, 0644)
  136. if err != nil {
  137. log.Fatalf("write api credentials in '%s' failed: %s", dumpFile, err)
  138. }
  139. log.Printf("Local API credentials dumped to '%s'", dumpFile)
  140. } else {
  141. fmt.Printf("%s\n", string(apiConfigDump))
  142. }
  143. log.Warning(ReloadMessage())
  144. return nil
  145. }
  146. func NewLapiStatusCmd() *cobra.Command {
  147. cmdLapiStatus := &cobra.Command{
  148. Use: "status",
  149. Short: "Check authentication to Local API (LAPI)",
  150. Args: cobra.MinimumNArgs(0),
  151. DisableAutoGenTag: true,
  152. RunE: runLapiStatus,
  153. }
  154. return cmdLapiStatus
  155. }
  156. func NewLapiRegisterCmd() *cobra.Command {
  157. cmdLapiRegister := &cobra.Command{
  158. Use: "register",
  159. Short: "Register a machine to Local API (LAPI)",
  160. Long: `Register your machine to the Local API (LAPI).
  161. Keep in mind the machine needs to be validated by an administrator on LAPI side to be effective.`,
  162. Args: cobra.MinimumNArgs(0),
  163. DisableAutoGenTag: true,
  164. RunE: runLapiRegister,
  165. }
  166. flags := cmdLapiRegister.Flags()
  167. flags.StringP("url", "u", "", "URL of the API (ie. http://127.0.0.1)")
  168. flags.StringP("file", "f", "", "output file destination")
  169. flags.String("machine", "", "Name of the machine to register with")
  170. return cmdLapiRegister
  171. }
  172. func NewLapiCmd() *cobra.Command {
  173. var cmdLapi = &cobra.Command{
  174. Use: "lapi [action]",
  175. Short: "Manage interaction with Local API (LAPI)",
  176. Args: cobra.MinimumNArgs(1),
  177. DisableAutoGenTag: true,
  178. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  179. if err := csConfig.LoadAPIClient(); err != nil {
  180. return fmt.Errorf("loading api client: %w", err)
  181. }
  182. return nil
  183. },
  184. }
  185. cmdLapi.AddCommand(NewLapiRegisterCmd())
  186. cmdLapi.AddCommand(NewLapiStatusCmd())
  187. cmdLapi.AddCommand(NewLapiContextCmd())
  188. return cmdLapi
  189. }
  190. func NewLapiContextCmd() *cobra.Command {
  191. cmdContext := &cobra.Command{
  192. Use: "context [command]",
  193. Short: "Manage context to send with alerts",
  194. DisableAutoGenTag: true,
  195. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  196. if err := csConfig.LoadCrowdsec(); err != nil {
  197. fileNotFoundMessage := fmt.Sprintf("failed to open context file: open %s: no such file or directory", csConfig.Crowdsec.ConsoleContextPath)
  198. if err.Error() != fileNotFoundMessage {
  199. log.Fatalf("Unable to load CrowdSec Agent: %s", err)
  200. }
  201. }
  202. if csConfig.DisableAgent {
  203. log.Fatalf("Agent is disabled and lapi context can only be used on the agent")
  204. }
  205. return nil
  206. },
  207. Run: func(cmd *cobra.Command, args []string) {
  208. printHelp(cmd)
  209. },
  210. }
  211. var keyToAdd string
  212. var valuesToAdd []string
  213. cmdContextAdd := &cobra.Command{
  214. Use: "add",
  215. Short: "Add context to send with alerts. You must specify the output key with the expr value you want",
  216. Example: `cscli lapi context add --key source_ip --value evt.Meta.source_ip
  217. cscli lapi context add --key file_source --value evt.Line.Src
  218. `,
  219. DisableAutoGenTag: true,
  220. Run: func(cmd *cobra.Command, args []string) {
  221. if err := alertcontext.ValidateContextExpr(keyToAdd, valuesToAdd); err != nil {
  222. log.Fatalf("invalid context configuration :%s", err)
  223. }
  224. if _, ok := csConfig.Crowdsec.ContextToSend[keyToAdd]; !ok {
  225. csConfig.Crowdsec.ContextToSend[keyToAdd] = make([]string, 0)
  226. log.Infof("key '%s' added", keyToAdd)
  227. }
  228. data := csConfig.Crowdsec.ContextToSend[keyToAdd]
  229. for _, val := range valuesToAdd {
  230. if !slices.Contains(data, val) {
  231. log.Infof("value '%s' added to key '%s'", val, keyToAdd)
  232. data = append(data, val)
  233. }
  234. csConfig.Crowdsec.ContextToSend[keyToAdd] = data
  235. }
  236. if err := csConfig.Crowdsec.DumpContextConfigFile(); err != nil {
  237. log.Fatalf(err.Error())
  238. }
  239. },
  240. }
  241. cmdContextAdd.Flags().StringVarP(&keyToAdd, "key", "k", "", "The key of the different values to send")
  242. cmdContextAdd.Flags().StringSliceVar(&valuesToAdd, "value", []string{}, "The expr fields to associate with the key")
  243. cmdContextAdd.MarkFlagRequired("key")
  244. cmdContextAdd.MarkFlagRequired("value")
  245. cmdContext.AddCommand(cmdContextAdd)
  246. cmdContextStatus := &cobra.Command{
  247. Use: "status",
  248. Short: "List context to send with alerts",
  249. DisableAutoGenTag: true,
  250. Run: func(cmd *cobra.Command, args []string) {
  251. if len(csConfig.Crowdsec.ContextToSend) == 0 {
  252. fmt.Println("No context found on this agent. You can use 'cscli lapi context add' to add context to your alerts.")
  253. return
  254. }
  255. dump, err := yaml.Marshal(csConfig.Crowdsec.ContextToSend)
  256. if err != nil {
  257. log.Fatalf("unable to show context status: %s", err)
  258. }
  259. fmt.Println(string(dump))
  260. },
  261. }
  262. cmdContext.AddCommand(cmdContextStatus)
  263. var detectAll bool
  264. cmdContextDetect := &cobra.Command{
  265. Use: "detect",
  266. Short: "Detect available fields from the installed parsers",
  267. Example: `cscli lapi context detect --all
  268. cscli lapi context detect crowdsecurity/sshd-logs
  269. `,
  270. DisableAutoGenTag: true,
  271. Run: func(cmd *cobra.Command, args []string) {
  272. var err error
  273. if !detectAll && len(args) == 0 {
  274. log.Infof("Please provide parsers to detect or --all flag.")
  275. printHelp(cmd)
  276. }
  277. // to avoid all the log.Info from the loaders functions
  278. log.SetLevel(log.ErrorLevel)
  279. err = exprhelpers.Init(nil)
  280. if err != nil {
  281. log.Fatalf("Failed to init expr helpers : %s", err)
  282. }
  283. // Populate cwhub package tools
  284. if err := cwhub.GetHubIdx(csConfig.Hub); err != nil {
  285. log.Fatalf("Failed to load hub index : %s", err)
  286. }
  287. csParsers := parser.NewParsers()
  288. if csParsers, err = parser.LoadParsers(csConfig, csParsers); err != nil {
  289. log.Fatalf("unable to load parsers: %s", err)
  290. }
  291. fieldByParsers := make(map[string][]string)
  292. for _, node := range csParsers.Nodes {
  293. if !detectAll && !slices.Contains(args, node.Name) {
  294. continue
  295. }
  296. if !detectAll {
  297. args = removeFromSlice(node.Name, args)
  298. }
  299. fieldByParsers[node.Name] = make([]string, 0)
  300. fieldByParsers[node.Name] = detectNode(node, *csParsers.Ctx)
  301. subNodeFields := detectSubNode(node, *csParsers.Ctx)
  302. for _, field := range subNodeFields {
  303. if !slices.Contains(fieldByParsers[node.Name], field) {
  304. fieldByParsers[node.Name] = append(fieldByParsers[node.Name], field)
  305. }
  306. }
  307. }
  308. fmt.Printf("Acquisition :\n\n")
  309. fmt.Printf(" - evt.Line.Module\n")
  310. fmt.Printf(" - evt.Line.Raw\n")
  311. fmt.Printf(" - evt.Line.Src\n")
  312. fmt.Println()
  313. parsersKey := make([]string, 0)
  314. for k := range fieldByParsers {
  315. parsersKey = append(parsersKey, k)
  316. }
  317. sort.Strings(parsersKey)
  318. for _, k := range parsersKey {
  319. if len(fieldByParsers[k]) == 0 {
  320. continue
  321. }
  322. fmt.Printf("%s :\n\n", k)
  323. values := fieldByParsers[k]
  324. sort.Strings(values)
  325. for _, value := range values {
  326. fmt.Printf(" - %s\n", value)
  327. }
  328. fmt.Println()
  329. }
  330. if len(args) > 0 {
  331. for _, parserNotFound := range args {
  332. log.Errorf("parser '%s' not found, can't detect fields", parserNotFound)
  333. }
  334. }
  335. },
  336. }
  337. cmdContextDetect.Flags().BoolVarP(&detectAll, "all", "a", false, "Detect evt field for all installed parser")
  338. cmdContext.AddCommand(cmdContextDetect)
  339. var keysToDelete []string
  340. var valuesToDelete []string
  341. cmdContextDelete := &cobra.Command{
  342. Use: "delete",
  343. Short: "Delete context to send with alerts",
  344. Example: `cscli lapi context delete --key source_ip
  345. cscli lapi context delete --value evt.Line.Src
  346. `,
  347. DisableAutoGenTag: true,
  348. Run: func(cmd *cobra.Command, args []string) {
  349. if len(keysToDelete) == 0 && len(valuesToDelete) == 0 {
  350. log.Fatalf("please provide at least a key or a value to delete")
  351. }
  352. for _, key := range keysToDelete {
  353. if _, ok := csConfig.Crowdsec.ContextToSend[key]; ok {
  354. delete(csConfig.Crowdsec.ContextToSend, key)
  355. log.Infof("key '%s' has been removed", key)
  356. } else {
  357. log.Warningf("key '%s' doesn't exist", key)
  358. }
  359. }
  360. for _, value := range valuesToDelete {
  361. valueFound := false
  362. for key, context := range csConfig.Crowdsec.ContextToSend {
  363. if slices.Contains(context, value) {
  364. valueFound = true
  365. csConfig.Crowdsec.ContextToSend[key] = removeFromSlice(value, context)
  366. log.Infof("value '%s' has been removed from key '%s'", value, key)
  367. }
  368. if len(csConfig.Crowdsec.ContextToSend[key]) == 0 {
  369. delete(csConfig.Crowdsec.ContextToSend, key)
  370. }
  371. }
  372. if !valueFound {
  373. log.Warningf("value '%s' not found", value)
  374. }
  375. }
  376. if err := csConfig.Crowdsec.DumpContextConfigFile(); err != nil {
  377. log.Fatalf(err.Error())
  378. }
  379. },
  380. }
  381. cmdContextDelete.Flags().StringSliceVarP(&keysToDelete, "key", "k", []string{}, "The keys to delete")
  382. cmdContextDelete.Flags().StringSliceVar(&valuesToDelete, "value", []string{}, "The expr fields to delete")
  383. cmdContext.AddCommand(cmdContextDelete)
  384. return cmdContext
  385. }
  386. func detectStaticField(GrokStatics []parser.ExtraField) []string {
  387. ret := make([]string, 0)
  388. for _, static := range GrokStatics {
  389. if static.Parsed != "" {
  390. fieldName := fmt.Sprintf("evt.Parsed.%s", static.Parsed)
  391. if !slices.Contains(ret, fieldName) {
  392. ret = append(ret, fieldName)
  393. }
  394. }
  395. if static.Meta != "" {
  396. fieldName := fmt.Sprintf("evt.Meta.%s", static.Meta)
  397. if !slices.Contains(ret, fieldName) {
  398. ret = append(ret, fieldName)
  399. }
  400. }
  401. if static.TargetByName != "" {
  402. fieldName := static.TargetByName
  403. if !strings.HasPrefix(fieldName, "evt.") {
  404. fieldName = "evt." + fieldName
  405. }
  406. if !slices.Contains(ret, fieldName) {
  407. ret = append(ret, fieldName)
  408. }
  409. }
  410. }
  411. return ret
  412. }
  413. func detectNode(node parser.Node, parserCTX parser.UnixParserCtx) []string {
  414. var ret = make([]string, 0)
  415. if node.Grok.RunTimeRegexp != nil {
  416. for _, capturedField := range node.Grok.RunTimeRegexp.Names() {
  417. fieldName := fmt.Sprintf("evt.Parsed.%s", capturedField)
  418. if !slices.Contains(ret, fieldName) {
  419. ret = append(ret, fieldName)
  420. }
  421. }
  422. }
  423. if node.Grok.RegexpName != "" {
  424. grokCompiled, err := parserCTX.Grok.Get(node.Grok.RegexpName)
  425. if err != nil {
  426. log.Warningf("Can't get subgrok: %s", err)
  427. }
  428. for _, capturedField := range grokCompiled.Names() {
  429. fieldName := fmt.Sprintf("evt.Parsed.%s", capturedField)
  430. if !slices.Contains(ret, fieldName) {
  431. ret = append(ret, fieldName)
  432. }
  433. }
  434. }
  435. if len(node.Grok.Statics) > 0 {
  436. staticsField := detectStaticField(node.Grok.Statics)
  437. for _, staticField := range staticsField {
  438. if !slices.Contains(ret, staticField) {
  439. ret = append(ret, staticField)
  440. }
  441. }
  442. }
  443. if len(node.Statics) > 0 {
  444. staticsField := detectStaticField(node.Statics)
  445. for _, staticField := range staticsField {
  446. if !slices.Contains(ret, staticField) {
  447. ret = append(ret, staticField)
  448. }
  449. }
  450. }
  451. return ret
  452. }
  453. func detectSubNode(node parser.Node, parserCTX parser.UnixParserCtx) []string {
  454. var ret = make([]string, 0)
  455. for _, subnode := range node.LeavesNodes {
  456. if subnode.Grok.RunTimeRegexp != nil {
  457. for _, capturedField := range subnode.Grok.RunTimeRegexp.Names() {
  458. fieldName := fmt.Sprintf("evt.Parsed.%s", capturedField)
  459. if !slices.Contains(ret, fieldName) {
  460. ret = append(ret, fieldName)
  461. }
  462. }
  463. }
  464. if subnode.Grok.RegexpName != "" {
  465. grokCompiled, err := parserCTX.Grok.Get(subnode.Grok.RegexpName)
  466. if err != nil {
  467. log.Warningf("Can't get subgrok: %s", err)
  468. }
  469. for _, capturedField := range grokCompiled.Names() {
  470. fieldName := fmt.Sprintf("evt.Parsed.%s", capturedField)
  471. if !slices.Contains(ret, fieldName) {
  472. ret = append(ret, fieldName)
  473. }
  474. }
  475. }
  476. if len(subnode.Grok.Statics) > 0 {
  477. staticsField := detectStaticField(subnode.Grok.Statics)
  478. for _, staticField := range staticsField {
  479. if !slices.Contains(ret, staticField) {
  480. ret = append(ret, staticField)
  481. }
  482. }
  483. }
  484. if len(subnode.Statics) > 0 {
  485. staticsField := detectStaticField(subnode.Statics)
  486. for _, staticField := range staticsField {
  487. if !slices.Contains(ret, staticField) {
  488. ret = append(ret, staticField)
  489. }
  490. }
  491. }
  492. }
  493. return ret
  494. }