lapi.go 16 KB

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