lapi.go 16 KB

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