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