utils.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package main
  2. import (
  3. "fmt"
  4. "net"
  5. "strings"
  6. log "github.com/sirupsen/logrus"
  7. "github.com/spf13/cobra"
  8. "github.com/crowdsecurity/crowdsec/pkg/database"
  9. "github.com/crowdsecurity/crowdsec/pkg/types"
  10. )
  11. func printHelp(cmd *cobra.Command) {
  12. err := cmd.Help()
  13. if err != nil {
  14. log.Fatalf("unable to print help(): %s", err)
  15. }
  16. }
  17. func manageCliDecisionAlerts(ip *string, ipRange *string, scope *string, value *string) error {
  18. /*if a range is provided, change the scope*/
  19. if *ipRange != "" {
  20. _, _, err := net.ParseCIDR(*ipRange)
  21. if err != nil {
  22. return fmt.Errorf("%s isn't a valid range", *ipRange)
  23. }
  24. }
  25. if *ip != "" {
  26. ipRepr := net.ParseIP(*ip)
  27. if ipRepr == nil {
  28. return fmt.Errorf("%s isn't a valid ip", *ip)
  29. }
  30. }
  31. //avoid confusion on scope (ip vs Ip and range vs Range)
  32. switch strings.ToLower(*scope) {
  33. case "ip":
  34. *scope = types.Ip
  35. case "range":
  36. *scope = types.Range
  37. case "country":
  38. *scope = types.Country
  39. case "as":
  40. *scope = types.AS
  41. }
  42. return nil
  43. }
  44. func getDBClient() (*database.Client, error) {
  45. var err error
  46. if err := csConfig.LoadAPIServer(); err != nil || csConfig.DisableAPI {
  47. return nil, err
  48. }
  49. ret, err := database.NewClient(csConfig.DbConfig)
  50. if err != nil {
  51. return nil, err
  52. }
  53. return ret, nil
  54. }
  55. func removeFromSlice(val string, slice []string) []string {
  56. var i int
  57. var value string
  58. valueFound := false
  59. // get the index
  60. for i, value = range slice {
  61. if value == val {
  62. valueFound = true
  63. break
  64. }
  65. }
  66. if valueFound {
  67. slice[i] = slice[len(slice)-1]
  68. slice[len(slice)-1] = ""
  69. slice = slice[:len(slice)-1]
  70. }
  71. return slice
  72. }