bouncers.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. package main
  2. import (
  3. "encoding/csv"
  4. "encoding/json"
  5. "fmt"
  6. "os"
  7. "slices"
  8. "strings"
  9. "time"
  10. "github.com/AlecAivazis/survey/v2"
  11. "github.com/fatih/color"
  12. log "github.com/sirupsen/logrus"
  13. "github.com/spf13/cobra"
  14. "github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/require"
  15. middlewares "github.com/crowdsecurity/crowdsec/pkg/apiserver/middlewares/v1"
  16. "github.com/crowdsecurity/crowdsec/pkg/database"
  17. "github.com/crowdsecurity/crowdsec/pkg/types"
  18. )
  19. func askYesNo(message string, defaultAnswer bool) (bool, error) {
  20. var answer bool
  21. prompt := &survey.Confirm{
  22. Message: message,
  23. Default: defaultAnswer,
  24. }
  25. if err := survey.AskOne(prompt, &answer); err != nil {
  26. return defaultAnswer, err
  27. }
  28. return answer, nil
  29. }
  30. type cliBouncers struct {
  31. db *database.Client
  32. cfg configGetter
  33. }
  34. func NewCLIBouncers(cfg configGetter) *cliBouncers {
  35. return &cliBouncers{
  36. cfg: cfg,
  37. }
  38. }
  39. func (cli *cliBouncers) NewCommand() *cobra.Command {
  40. cmd := &cobra.Command{
  41. Use: "bouncers [action]",
  42. Short: "Manage bouncers [requires local API]",
  43. Long: `To list/add/delete/prune bouncers.
  44. Note: This command requires database direct access, so is intended to be run on Local API/master.
  45. `,
  46. Args: cobra.MinimumNArgs(1),
  47. Aliases: []string{"bouncer"},
  48. DisableAutoGenTag: true,
  49. PersistentPreRunE: func(_ *cobra.Command, _ []string) error {
  50. var err error
  51. if err = require.LAPI(cli.cfg()); err != nil {
  52. return err
  53. }
  54. cli.db, err = database.NewClient(cli.cfg().DbConfig)
  55. if err != nil {
  56. return fmt.Errorf("can't connect to the database: %s", err)
  57. }
  58. return nil
  59. },
  60. }
  61. cmd.AddCommand(cli.newListCmd())
  62. cmd.AddCommand(cli.newAddCmd())
  63. cmd.AddCommand(cli.newDeleteCmd())
  64. cmd.AddCommand(cli.newPruneCmd())
  65. return cmd
  66. }
  67. func (cli *cliBouncers) list() error {
  68. out := color.Output
  69. bouncers, err := cli.db.ListBouncers()
  70. if err != nil {
  71. return fmt.Errorf("unable to list bouncers: %s", err)
  72. }
  73. switch cli.cfg().Cscli.Output {
  74. case "human":
  75. getBouncersTable(out, bouncers)
  76. case "json":
  77. enc := json.NewEncoder(out)
  78. enc.SetIndent("", " ")
  79. if err := enc.Encode(bouncers); err != nil {
  80. return fmt.Errorf("failed to marshal: %w", err)
  81. }
  82. return nil
  83. case "raw":
  84. csvwriter := csv.NewWriter(out)
  85. if err := csvwriter.Write([]string{"name", "ip", "revoked", "last_pull", "type", "version", "auth_type"}); err != nil {
  86. return fmt.Errorf("failed to write raw header: %w", err)
  87. }
  88. for _, b := range bouncers {
  89. valid := "validated"
  90. if b.Revoked {
  91. valid = "pending"
  92. }
  93. if err := csvwriter.Write([]string{b.Name, b.IPAddress, valid, b.LastPull.Format(time.RFC3339), b.Type, b.Version, b.AuthType}); err != nil {
  94. return fmt.Errorf("failed to write raw: %w", err)
  95. }
  96. }
  97. csvwriter.Flush()
  98. }
  99. return nil
  100. }
  101. func (cli *cliBouncers) newListCmd() *cobra.Command {
  102. cmd := &cobra.Command{
  103. Use: "list",
  104. Short: "list all bouncers within the database",
  105. Example: `cscli bouncers list`,
  106. Args: cobra.ExactArgs(0),
  107. DisableAutoGenTag: true,
  108. RunE: func(_ *cobra.Command, _ []string) error {
  109. return cli.list()
  110. },
  111. }
  112. return cmd
  113. }
  114. func (cli *cliBouncers) add(bouncerName string, key string) error {
  115. var err error
  116. keyLength := 32
  117. if key == "" {
  118. key, err = middlewares.GenerateAPIKey(keyLength)
  119. if err != nil {
  120. return fmt.Errorf("unable to generate api key: %s", err)
  121. }
  122. }
  123. _, err = cli.db.CreateBouncer(bouncerName, "", middlewares.HashSHA512(key), types.ApiKeyAuthType)
  124. if err != nil {
  125. return fmt.Errorf("unable to create bouncer: %s", err)
  126. }
  127. switch cli.cfg().Cscli.Output {
  128. case "human":
  129. fmt.Printf("API key for '%s':\n\n", bouncerName)
  130. fmt.Printf(" %s\n\n", key)
  131. fmt.Print("Please keep this key since you will not be able to retrieve it!\n")
  132. case "raw":
  133. fmt.Print(key)
  134. case "json":
  135. j, err := json.Marshal(key)
  136. if err != nil {
  137. return fmt.Errorf("unable to marshal api key")
  138. }
  139. fmt.Print(string(j))
  140. }
  141. return nil
  142. }
  143. func (cli *cliBouncers) newAddCmd() *cobra.Command {
  144. var key string
  145. cmd := &cobra.Command{
  146. Use: "add MyBouncerName",
  147. Short: "add a single bouncer to the database",
  148. Example: `cscli bouncers add MyBouncerName
  149. cscli bouncers add MyBouncerName --key <random-key>`,
  150. Args: cobra.ExactArgs(1),
  151. DisableAutoGenTag: true,
  152. RunE: func(_ *cobra.Command, args []string) error {
  153. return cli.add(args[0], key)
  154. },
  155. }
  156. flags := cmd.Flags()
  157. flags.StringP("length", "l", "", "length of the api key")
  158. flags.MarkDeprecated("length", "use --key instead")
  159. flags.StringVarP(&key, "key", "k", "", "api key for the bouncer")
  160. return cmd
  161. }
  162. func (cli *cliBouncers) deleteValid(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
  163. bouncers, err := cli.db.ListBouncers()
  164. if err != nil {
  165. cobra.CompError("unable to list bouncers " + err.Error())
  166. }
  167. ret := []string{}
  168. for _, bouncer := range bouncers {
  169. if strings.Contains(bouncer.Name, toComplete) && !slices.Contains(args, bouncer.Name) {
  170. ret = append(ret, bouncer.Name)
  171. }
  172. }
  173. return ret, cobra.ShellCompDirectiveNoFileComp
  174. }
  175. func (cli *cliBouncers) delete(bouncers []string) error {
  176. for _, bouncerID := range bouncers {
  177. err := cli.db.DeleteBouncer(bouncerID)
  178. if err != nil {
  179. return fmt.Errorf("unable to delete bouncer '%s': %s", bouncerID, err)
  180. }
  181. log.Infof("bouncer '%s' deleted successfully", bouncerID)
  182. }
  183. return nil
  184. }
  185. func (cli *cliBouncers) newDeleteCmd() *cobra.Command {
  186. cmd := &cobra.Command{
  187. Use: "delete MyBouncerName",
  188. Short: "delete bouncer(s) from the database",
  189. Args: cobra.MinimumNArgs(1),
  190. Aliases: []string{"remove"},
  191. DisableAutoGenTag: true,
  192. ValidArgsFunction: cli.deleteValid,
  193. RunE: func(_ *cobra.Command, args []string) error {
  194. return cli.delete(args)
  195. },
  196. }
  197. return cmd
  198. }
  199. func (cli *cliBouncers) prune(duration time.Duration, force bool) error {
  200. if duration < 2*time.Minute {
  201. if yes, err := askYesNo(
  202. "The duration you provided is less than 2 minutes. " +
  203. "This may remove active bouncers. Continue?", false); err != nil {
  204. return err
  205. } else if !yes {
  206. fmt.Println("User aborted prune. No changes were made.")
  207. return nil
  208. }
  209. }
  210. bouncers, err := cli.db.QueryBouncersLastPulltimeLT(time.Now().UTC().Add(duration))
  211. if err != nil {
  212. return fmt.Errorf("unable to query bouncers: %w", err)
  213. }
  214. if len(bouncers) == 0 {
  215. fmt.Println("No bouncers to prune.")
  216. return nil
  217. }
  218. getBouncersTable(color.Output, bouncers)
  219. if !force {
  220. if yes, err := askYesNo(
  221. "You are about to PERMANENTLY remove the above bouncers from the database. " +
  222. "These will NOT be recoverable. Continue?", false); err != nil {
  223. return err
  224. } else if !yes {
  225. fmt.Println("User aborted prune. No changes were made.")
  226. return nil
  227. }
  228. }
  229. deleted, err := cli.db.BulkDeleteBouncers(bouncers)
  230. if err != nil {
  231. return fmt.Errorf("unable to prune bouncers: %s", err)
  232. }
  233. fmt.Fprintf(os.Stderr, "Successfully deleted %d bouncers\n", deleted)
  234. return nil
  235. }
  236. func (cli *cliBouncers) newPruneCmd() *cobra.Command {
  237. var (
  238. duration time.Duration
  239. force bool
  240. )
  241. const defaultDuration = 60 * time.Minute
  242. cmd := &cobra.Command{
  243. Use: "prune",
  244. Short: "prune multiple bouncers from the database",
  245. Args: cobra.NoArgs,
  246. DisableAutoGenTag: true,
  247. Example: `cscli bouncers prune -d 45m
  248. cscli bouncers prune -d 45m --force`,
  249. RunE: func(_ *cobra.Command, _ []string) error {
  250. return cli.prune(duration, force)
  251. },
  252. }
  253. flags := cmd.Flags()
  254. flags.DurationVarP(&duration, "duration", "d", defaultDuration, "duration of time since last pull")
  255. flags.BoolVar(&force, "force", false, "force prune without asking for confirmation")
  256. return cmd
  257. }