lapi.go 16 KB

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