decisions.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. package main
  2. import (
  3. "context"
  4. "encoding/csv"
  5. "encoding/json"
  6. "fmt"
  7. "net/url"
  8. "os"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/crowdsecurity/crowdsec/pkg/apiclient"
  14. "github.com/crowdsecurity/crowdsec/pkg/cwversion"
  15. "github.com/crowdsecurity/crowdsec/pkg/models"
  16. "github.com/crowdsecurity/crowdsec/pkg/types"
  17. "github.com/go-openapi/strfmt"
  18. "github.com/jszwec/csvutil"
  19. "github.com/olekukonko/tablewriter"
  20. log "github.com/sirupsen/logrus"
  21. "github.com/spf13/cobra"
  22. )
  23. var Client *apiclient.ApiClient
  24. var (
  25. defaultDuration = "4h"
  26. defaultScope = "ip"
  27. defaultType = "ban"
  28. defaultReason = "manual"
  29. )
  30. func DecisionsToTable(alerts *models.GetAlertsResponse) error {
  31. /*here we cheat a bit : to make it more readable for the user, we dedup some entries*/
  32. var spamLimit map[string]bool = make(map[string]bool)
  33. var skipped = 0
  34. for aIdx := 0; aIdx < len(*alerts); aIdx++ {
  35. alertItem := (*alerts)[aIdx]
  36. newDecisions := make([]*models.Decision, 0)
  37. for _, decisionItem := range alertItem.Decisions {
  38. spamKey := fmt.Sprintf("%t:%s:%s:%s", *decisionItem.Simulated, *decisionItem.Type, *decisionItem.Scope, *decisionItem.Value)
  39. if _, ok := spamLimit[spamKey]; ok {
  40. skipped++
  41. continue
  42. }
  43. spamLimit[spamKey] = true
  44. newDecisions = append(newDecisions, decisionItem)
  45. }
  46. alertItem.Decisions = newDecisions
  47. }
  48. if csConfig.Cscli.Output == "raw" {
  49. csvwriter := csv.NewWriter(os.Stdout)
  50. err := csvwriter.Write([]string{"id", "source", "ip", "reason", "action", "country", "as", "events_count", "expiration", "simulated", "alert_id"})
  51. if err != nil {
  52. return err
  53. }
  54. for _, alertItem := range *alerts {
  55. for _, decisionItem := range alertItem.Decisions {
  56. err := csvwriter.Write([]string{
  57. fmt.Sprintf("%d", decisionItem.ID),
  58. *decisionItem.Origin,
  59. *decisionItem.Scope + ":" + *decisionItem.Value,
  60. *decisionItem.Scenario,
  61. *decisionItem.Type,
  62. alertItem.Source.Cn,
  63. alertItem.Source.AsNumber + " " + alertItem.Source.AsName,
  64. fmt.Sprintf("%d", *alertItem.EventsCount),
  65. *decisionItem.Duration,
  66. fmt.Sprintf("%t", *decisionItem.Simulated),
  67. fmt.Sprintf("%d", alertItem.ID),
  68. })
  69. if err != nil {
  70. return err
  71. }
  72. }
  73. }
  74. csvwriter.Flush()
  75. } else if csConfig.Cscli.Output == "json" {
  76. x, _ := json.MarshalIndent(alerts, "", " ")
  77. fmt.Printf("%s", string(x))
  78. } else if csConfig.Cscli.Output == "human" {
  79. table := tablewriter.NewWriter(os.Stdout)
  80. table.SetHeader([]string{"ID", "Source", "Scope:Value", "Reason", "Action", "Country", "AS", "Events", "expiration", "Alert ID"})
  81. if len(*alerts) == 0 {
  82. fmt.Println("No active decisions")
  83. return nil
  84. }
  85. for _, alertItem := range *alerts {
  86. for _, decisionItem := range alertItem.Decisions {
  87. if *alertItem.Simulated {
  88. *decisionItem.Type = fmt.Sprintf("(simul)%s", *decisionItem.Type)
  89. }
  90. table.Append([]string{
  91. strconv.Itoa(int(decisionItem.ID)),
  92. *decisionItem.Origin,
  93. *decisionItem.Scope + ":" + *decisionItem.Value,
  94. *decisionItem.Scenario,
  95. *decisionItem.Type,
  96. alertItem.Source.Cn,
  97. alertItem.Source.AsNumber + " " + alertItem.Source.AsName,
  98. strconv.Itoa(int(*alertItem.EventsCount)),
  99. *decisionItem.Duration,
  100. strconv.Itoa(int(alertItem.ID)),
  101. })
  102. }
  103. }
  104. table.Render() // Send output
  105. if skipped > 0 {
  106. fmt.Printf("%d duplicated entries skipped\n", skipped)
  107. }
  108. }
  109. return nil
  110. }
  111. func NewDecisionsCmd() *cobra.Command {
  112. /* ---- DECISIONS COMMAND */
  113. var cmdDecisions = &cobra.Command{
  114. Use: "decisions [action]",
  115. Short: "Manage decisions",
  116. Long: `Add/List/Delete/Import decisions from LAPI`,
  117. Example: `cscli decisions [action] [filter]`,
  118. /*TBD example*/
  119. Args: cobra.MinimumNArgs(1),
  120. DisableAutoGenTag: true,
  121. PersistentPreRun: func(cmd *cobra.Command, args []string) {
  122. if err := csConfig.LoadAPIClient(); err != nil {
  123. log.Fatalf(err.Error())
  124. }
  125. if csConfig.API.Client == nil {
  126. log.Fatalln("There is no configuration on 'api_client:'")
  127. }
  128. if csConfig.API.Client.Credentials == nil {
  129. log.Fatalf("Please provide credentials for the API in '%s'", csConfig.API.Client.CredentialsFilePath)
  130. }
  131. password := strfmt.Password(csConfig.API.Client.Credentials.Password)
  132. apiurl, err := url.Parse(csConfig.API.Client.Credentials.URL)
  133. if err != nil {
  134. log.Fatalf("parsing api url ('%s'): %s", csConfig.API.Client.Credentials.URL, err)
  135. }
  136. Client, err = apiclient.NewClient(&apiclient.Config{
  137. MachineID: csConfig.API.Client.Credentials.Login,
  138. Password: password,
  139. UserAgent: fmt.Sprintf("crowdsec/%s", cwversion.VersionStr()),
  140. URL: apiurl,
  141. VersionPrefix: "v1",
  142. })
  143. if err != nil {
  144. log.Fatalf("creating api client : %s", err)
  145. }
  146. },
  147. }
  148. var filter = apiclient.AlertsListOpts{
  149. ValueEquals: new(string),
  150. ScopeEquals: new(string),
  151. ScenarioEquals: new(string),
  152. OriginEquals: new(string),
  153. IPEquals: new(string),
  154. RangeEquals: new(string),
  155. Since: new(string),
  156. Until: new(string),
  157. TypeEquals: new(string),
  158. IncludeCAPI: new(bool),
  159. Limit: new(int),
  160. }
  161. NoSimu := new(bool)
  162. contained := new(bool)
  163. var cmdDecisionsList = &cobra.Command{
  164. Use: "list [options]",
  165. Short: "List decisions from LAPI",
  166. Example: `cscli decisions list -i 1.2.3.4
  167. cscli decisions list -r 1.2.3.0/24
  168. cscli decisions list -s crowdsecurity/ssh-bf
  169. cscli decisions list -t ban
  170. `,
  171. Args: cobra.ExactArgs(0),
  172. DisableAutoGenTag: true,
  173. Run: func(cmd *cobra.Command, args []string) {
  174. var err error
  175. /*take care of shorthand options*/
  176. if err := manageCliDecisionAlerts(filter.IPEquals, filter.RangeEquals, filter.ScopeEquals, filter.ValueEquals); err != nil {
  177. log.Fatalf("%s", err)
  178. }
  179. filter.ActiveDecisionEquals = new(bool)
  180. *filter.ActiveDecisionEquals = true
  181. if NoSimu != nil && *NoSimu {
  182. filter.IncludeSimulated = new(bool)
  183. }
  184. /*nulify the empty entries to avoid bad filter*/
  185. if *filter.Until == "" {
  186. filter.Until = nil
  187. } else {
  188. /*time.ParseDuration support hours 'h' as bigger unit, let's make the user's life easier*/
  189. if strings.HasSuffix(*filter.Until, "d") {
  190. realDuration := strings.TrimSuffix(*filter.Until, "d")
  191. days, err := strconv.Atoi(realDuration)
  192. if err != nil {
  193. cmd.Help()
  194. log.Fatalf("Can't parse duration %s, valid durations format: 1d, 4h, 4h15m", *filter.Until)
  195. }
  196. *filter.Until = fmt.Sprintf("%d%s", days*24, "h")
  197. }
  198. }
  199. if *filter.Since == "" {
  200. filter.Since = nil
  201. } else {
  202. /*time.ParseDuration support hours 'h' as bigger unit, let's make the user's life easier*/
  203. if strings.HasSuffix(*filter.Since, "d") {
  204. realDuration := strings.TrimSuffix(*filter.Since, "d")
  205. days, err := strconv.Atoi(realDuration)
  206. if err != nil {
  207. cmd.Help()
  208. log.Fatalf("Can't parse duration %s, valid durations format: 1d, 4h, 4h15m", *filter.Until)
  209. }
  210. *filter.Since = fmt.Sprintf("%d%s", days*24, "h")
  211. }
  212. }
  213. if *filter.IncludeCAPI {
  214. *filter.Limit = 0
  215. }
  216. if *filter.TypeEquals == "" {
  217. filter.TypeEquals = nil
  218. }
  219. if *filter.ValueEquals == "" {
  220. filter.ValueEquals = nil
  221. }
  222. if *filter.ScopeEquals == "" {
  223. filter.ScopeEquals = nil
  224. }
  225. if *filter.ScenarioEquals == "" {
  226. filter.ScenarioEquals = nil
  227. }
  228. if *filter.IPEquals == "" {
  229. filter.IPEquals = nil
  230. }
  231. if *filter.RangeEquals == "" {
  232. filter.RangeEquals = nil
  233. }
  234. if *filter.OriginEquals == "" {
  235. filter.OriginEquals = nil
  236. }
  237. if contained != nil && *contained {
  238. filter.Contains = new(bool)
  239. }
  240. alerts, _, err := Client.Alerts.List(context.Background(), filter)
  241. if err != nil {
  242. log.Fatalf("Unable to list decisions : %v", err.Error())
  243. }
  244. err = DecisionsToTable(alerts)
  245. if err != nil {
  246. log.Fatalf("unable to list decisions : %v", err.Error())
  247. }
  248. },
  249. }
  250. cmdDecisionsList.Flags().SortFlags = false
  251. cmdDecisionsList.Flags().BoolVarP(filter.IncludeCAPI, "all", "a", false, "Include decisions from Central API")
  252. cmdDecisionsList.Flags().StringVar(filter.Since, "since", "", "restrict to alerts newer than since (ie. 4h, 30d)")
  253. cmdDecisionsList.Flags().StringVar(filter.Until, "until", "", "restrict to alerts older than until (ie. 4h, 30d)")
  254. cmdDecisionsList.Flags().StringVarP(filter.TypeEquals, "type", "t", "", "restrict to this decision type (ie. ban,captcha)")
  255. cmdDecisionsList.Flags().StringVar(filter.ScopeEquals, "scope", "", "restrict to this scope (ie. ip,range,session)")
  256. cmdDecisionsList.Flags().StringVar(filter.OriginEquals, "origin", "", "restrict to this origin (ie. lists,CAPI,cscli)")
  257. cmdDecisionsList.Flags().StringVarP(filter.ValueEquals, "value", "v", "", "restrict to this value (ie. 1.2.3.4,userName)")
  258. cmdDecisionsList.Flags().StringVarP(filter.ScenarioEquals, "scenario", "s", "", "restrict to this scenario (ie. crowdsecurity/ssh-bf)")
  259. cmdDecisionsList.Flags().StringVarP(filter.IPEquals, "ip", "i", "", "restrict to alerts from this source ip (shorthand for --scope ip --value <IP>)")
  260. cmdDecisionsList.Flags().StringVarP(filter.RangeEquals, "range", "r", "", "restrict to alerts from this source range (shorthand for --scope range --value <RANGE>)")
  261. cmdDecisionsList.Flags().IntVarP(filter.Limit, "limit", "l", 100, "number of alerts to get (use 0 to remove the limit)")
  262. cmdDecisionsList.Flags().BoolVar(NoSimu, "no-simu", false, "exclude decisions in simulation mode")
  263. cmdDecisionsList.Flags().BoolVar(contained, "contained", false, "query decisions contained by range")
  264. cmdDecisions.AddCommand(cmdDecisionsList)
  265. var (
  266. addIP string
  267. addRange string
  268. addDuration string
  269. addValue string
  270. addScope string
  271. addReason string
  272. addType string
  273. )
  274. var cmdDecisionsAdd = &cobra.Command{
  275. Use: "add [options]",
  276. Short: "Add decision to LAPI",
  277. Example: `cscli decisions add --ip 1.2.3.4
  278. cscli decisions add --range 1.2.3.0/24
  279. cscli decisions add --ip 1.2.3.4 --duration 24h --type captcha
  280. cscli decisions add --scope username --value foobar
  281. `,
  282. /*TBD : fix long and example*/
  283. Args: cobra.ExactArgs(0),
  284. DisableAutoGenTag: true,
  285. Run: func(cmd *cobra.Command, args []string) {
  286. var err error
  287. var ipRange string
  288. alerts := models.AddAlertsRequest{}
  289. origin := "cscli"
  290. capacity := int32(0)
  291. leakSpeed := "0"
  292. eventsCount := int32(1)
  293. empty := ""
  294. simulated := false
  295. startAt := time.Now().UTC().Format(time.RFC3339)
  296. stopAt := time.Now().UTC().Format(time.RFC3339)
  297. createdAt := time.Now().UTC().Format(time.RFC3339)
  298. /*take care of shorthand options*/
  299. if err := manageCliDecisionAlerts(&addIP, &addRange, &addScope, &addValue); err != nil {
  300. log.Fatalf("%s", err)
  301. }
  302. if addIP != "" {
  303. addValue = addIP
  304. addScope = types.Ip
  305. } else if addRange != "" {
  306. addValue = addRange
  307. addScope = types.Range
  308. } else if addValue == "" {
  309. cmd.Help()
  310. log.Errorf("Missing arguments, a value is required (--ip, --range or --scope and --value)")
  311. return
  312. }
  313. if addReason == "" {
  314. addReason = fmt.Sprintf("manual '%s' from '%s'", addType, csConfig.API.Client.Credentials.Login)
  315. }
  316. decision := models.Decision{
  317. Duration: &addDuration,
  318. Scope: &addScope,
  319. Value: &addValue,
  320. Type: &addType,
  321. Scenario: &addReason,
  322. Origin: &origin,
  323. }
  324. alert := models.Alert{
  325. Capacity: &capacity,
  326. Decisions: []*models.Decision{&decision},
  327. Events: []*models.Event{},
  328. EventsCount: &eventsCount,
  329. Leakspeed: &leakSpeed,
  330. Message: &addReason,
  331. ScenarioHash: &empty,
  332. Scenario: &addReason,
  333. ScenarioVersion: &empty,
  334. Simulated: &simulated,
  335. Source: &models.Source{
  336. AsName: empty,
  337. AsNumber: empty,
  338. Cn: empty,
  339. IP: addValue,
  340. Range: ipRange,
  341. Scope: &addScope,
  342. Value: &addValue,
  343. },
  344. StartAt: &startAt,
  345. StopAt: &stopAt,
  346. CreatedAt: createdAt,
  347. }
  348. alerts = append(alerts, &alert)
  349. _, _, err = Client.Alerts.Add(context.Background(), alerts)
  350. if err != nil {
  351. log.Fatalf(err.Error())
  352. }
  353. log.Info("Decision successfully added")
  354. },
  355. }
  356. cmdDecisionsAdd.Flags().SortFlags = false
  357. cmdDecisionsAdd.Flags().StringVarP(&addIP, "ip", "i", "", "Source ip (shorthand for --scope ip --value <IP>)")
  358. cmdDecisionsAdd.Flags().StringVarP(&addRange, "range", "r", "", "Range source ip (shorthand for --scope range --value <RANGE>)")
  359. cmdDecisionsAdd.Flags().StringVarP(&addDuration, "duration", "d", "4h", "Decision duration (ie. 1h,4h,30m)")
  360. cmdDecisionsAdd.Flags().StringVarP(&addValue, "value", "v", "", "The value (ie. --scope username --value foobar)")
  361. cmdDecisionsAdd.Flags().StringVar(&addScope, "scope", types.Ip, "Decision scope (ie. ip,range,username)")
  362. cmdDecisionsAdd.Flags().StringVarP(&addReason, "reason", "R", "", "Decision reason (ie. scenario-name)")
  363. cmdDecisionsAdd.Flags().StringVarP(&addType, "type", "t", "ban", "Decision type (ie. ban,captcha,throttle)")
  364. cmdDecisions.AddCommand(cmdDecisionsAdd)
  365. var delFilter = apiclient.DecisionsDeleteOpts{
  366. ScopeEquals: new(string),
  367. ValueEquals: new(string),
  368. TypeEquals: new(string),
  369. IPEquals: new(string),
  370. RangeEquals: new(string),
  371. }
  372. var delDecisionId string
  373. var delDecisionAll bool
  374. var cmdDecisionsDelete = &cobra.Command{
  375. Use: "delete [options]",
  376. Short: "Delete decisions",
  377. DisableAutoGenTag: true,
  378. Example: `cscli decisions delete -r 1.2.3.0/24
  379. cscli decisions delete -i 1.2.3.4
  380. cscli decisions delete -s crowdsecurity/ssh-bf
  381. cscli decisions delete --id 42
  382. cscli decisions delete --type captcha
  383. `,
  384. /*TBD : refaire le Long/Example*/
  385. PreRun: func(cmd *cobra.Command, args []string) {
  386. if delDecisionAll {
  387. return
  388. }
  389. if *delFilter.ScopeEquals == "" && *delFilter.ValueEquals == "" &&
  390. *delFilter.TypeEquals == "" && *delFilter.IPEquals == "" &&
  391. *delFilter.RangeEquals == "" && delDecisionId == "" {
  392. cmd.Usage()
  393. log.Fatalln("At least one filter or --all must be specified")
  394. }
  395. },
  396. Run: func(cmd *cobra.Command, args []string) {
  397. var err error
  398. var decisions *models.DeleteDecisionResponse
  399. /*take care of shorthand options*/
  400. if err := manageCliDecisionAlerts(delFilter.IPEquals, delFilter.RangeEquals, delFilter.ScopeEquals, delFilter.ValueEquals); err != nil {
  401. log.Fatalf("%s", err)
  402. }
  403. if *delFilter.ScopeEquals == "" {
  404. delFilter.ScopeEquals = nil
  405. }
  406. if *delFilter.ValueEquals == "" {
  407. delFilter.ValueEquals = nil
  408. }
  409. if *delFilter.TypeEquals == "" {
  410. delFilter.TypeEquals = nil
  411. }
  412. if *delFilter.IPEquals == "" {
  413. delFilter.IPEquals = nil
  414. }
  415. if *delFilter.RangeEquals == "" {
  416. delFilter.RangeEquals = nil
  417. }
  418. if contained != nil && *contained {
  419. delFilter.Contains = new(bool)
  420. }
  421. if delDecisionId == "" {
  422. decisions, _, err = Client.Decisions.Delete(context.Background(), delFilter)
  423. if err != nil {
  424. log.Fatalf("Unable to delete decisions : %v", err.Error())
  425. }
  426. } else {
  427. decisions, _, err = Client.Decisions.DeleteOne(context.Background(), delDecisionId)
  428. if err != nil {
  429. log.Fatalf("Unable to delete decision : %v", err.Error())
  430. }
  431. }
  432. log.Infof("%s decision(s) deleted", decisions.NbDeleted)
  433. },
  434. }
  435. cmdDecisionsDelete.Flags().SortFlags = false
  436. cmdDecisionsDelete.Flags().StringVarP(delFilter.IPEquals, "ip", "i", "", "Source ip (shorthand for --scope ip --value <IP>)")
  437. cmdDecisionsDelete.Flags().StringVarP(delFilter.RangeEquals, "range", "r", "", "Range source ip (shorthand for --scope range --value <RANGE>)")
  438. cmdDecisionsDelete.Flags().StringVar(&delDecisionId, "id", "", "decision id")
  439. cmdDecisionsDelete.Flags().StringVarP(delFilter.TypeEquals, "type", "t", "", "the decision type (ie. ban,captcha)")
  440. cmdDecisionsDelete.Flags().StringVarP(delFilter.ValueEquals, "value", "v", "", "the value to match for in the specified scope")
  441. cmdDecisionsDelete.Flags().BoolVar(&delDecisionAll, "all", false, "delete all decisions")
  442. cmdDecisionsDelete.Flags().BoolVar(contained, "contained", false, "query decisions contained by range")
  443. cmdDecisions.AddCommand(cmdDecisionsDelete)
  444. var (
  445. importDuration string
  446. importScope string
  447. importReason string
  448. importType string
  449. importFile string
  450. )
  451. var cmdDecisionImport = &cobra.Command{
  452. Use: "import [options]",
  453. Short: "Import decisions from json or csv file",
  454. Long: "expected format :\n" +
  455. "csv : any of duration,origin,reason,scope,type,value, with a header line\n" +
  456. `json : {"duration" : "24h", "origin" : "my-list", "reason" : "my_scenario", "scope" : "ip", "type" : "ban", "value" : "x.y.z.z"}`,
  457. DisableAutoGenTag: true,
  458. Example: `decisions.csv :
  459. duration,scope,value
  460. 24h,ip,1.2.3.4
  461. cscsli decisions import -i decisions.csv
  462. decisions.json :
  463. [{"duration" : "4h", "scope" : "ip", "type" : "ban", "value" : "1.2.3.4"}]
  464. `,
  465. Run: func(cmd *cobra.Command, args []string) {
  466. if importFile == "" {
  467. log.Fatalf("Please provide a input file contaning decisions with -i flag")
  468. }
  469. csvData, err := os.ReadFile(importFile)
  470. if err != nil {
  471. log.Fatalf("unable to open '%s': %s", importFile, err)
  472. }
  473. type decisionRaw struct {
  474. Duration string `csv:"duration,omitempty" json:"duration,omitempty"`
  475. Origin string `csv:"origin,omitempty" json:"origin,omitempty"`
  476. Scenario string `csv:"reason,omitempty" json:"reason,omitempty"`
  477. Scope string `csv:"scope,omitempty" json:"scope,omitempty"`
  478. Type string `csv:"type,omitempty" json:"type,omitempty"`
  479. Value string `csv:"value" json:"value"`
  480. }
  481. var decisionsListRaw []decisionRaw
  482. switch fileFormat := filepath.Ext(importFile); fileFormat {
  483. case ".json":
  484. if err := json.Unmarshal(csvData, &decisionsListRaw); err != nil {
  485. log.Fatalf("unable to unmarshall json: '%s'", err)
  486. }
  487. case ".csv":
  488. if err := csvutil.Unmarshal(csvData, &decisionsListRaw); err != nil {
  489. log.Fatalf("unable to unmarshall csv: '%s'", err)
  490. }
  491. default:
  492. log.Fatalf("file format not supported for '%s'. supported format are 'json' and 'csv'", importFile)
  493. }
  494. decisionsList := make([]*models.Decision, 0)
  495. for i, decisionLine := range decisionsListRaw {
  496. line := i + 2
  497. if decisionLine.Value == "" {
  498. log.Fatalf("please provide a 'value' in your csv line %d", line)
  499. }
  500. /*deal with defaults and cli-override*/
  501. if decisionLine.Duration == "" {
  502. decisionLine.Duration = defaultDuration
  503. log.Debugf("No 'duration' line %d, using default value: '%s'", line, defaultDuration)
  504. }
  505. if importDuration != "" {
  506. decisionLine.Duration = importDuration
  507. log.Debugf("'duration' line %d, using supplied value: '%s'", line, importDuration)
  508. }
  509. decisionLine.Origin = "cscli-import"
  510. if decisionLine.Scenario == "" {
  511. decisionLine.Scenario = defaultReason
  512. log.Debugf("No 'reason' line %d, using value: '%s'", line, decisionLine.Scenario)
  513. }
  514. if importReason != "" {
  515. decisionLine.Scenario = importReason
  516. log.Debugf("No 'reason' line %d, using supplied value: '%s'", line, importReason)
  517. }
  518. if decisionLine.Type == "" {
  519. decisionLine.Type = defaultType
  520. log.Debugf("No 'type' line %d, using default value: '%s'", line, decisionLine.Type)
  521. }
  522. if importType != "" {
  523. decisionLine.Type = importType
  524. log.Debugf("'type' line %d, using supplied value: '%s'", line, importType)
  525. }
  526. if decisionLine.Scope == "" {
  527. decisionLine.Scope = defaultScope
  528. log.Debugf("No 'scope' line %d, using default value: '%s'", line, decisionLine.Scope)
  529. }
  530. if importScope != "" {
  531. decisionLine.Scope = importScope
  532. log.Debugf("'scope' line %d, using supplied value: '%s'", line, importScope)
  533. }
  534. decision := models.Decision{
  535. Value: types.StrPtr(decisionLine.Value),
  536. Duration: types.StrPtr(decisionLine.Duration),
  537. Origin: types.StrPtr(decisionLine.Origin),
  538. Scenario: types.StrPtr(decisionLine.Scenario),
  539. Type: types.StrPtr(decisionLine.Type),
  540. Scope: types.StrPtr(decisionLine.Scope),
  541. Simulated: new(bool),
  542. }
  543. decisionsList = append(decisionsList, &decision)
  544. }
  545. alerts := models.AddAlertsRequest{}
  546. importAlert := models.Alert{
  547. CreatedAt: time.Now().UTC().Format(time.RFC3339),
  548. Scenario: types.StrPtr(fmt.Sprintf("add: %d IPs", len(decisionsList))),
  549. Message: types.StrPtr(""),
  550. Events: []*models.Event{},
  551. Source: &models.Source{
  552. Scope: types.StrPtr("cscli/manual-import"),
  553. Value: types.StrPtr(""),
  554. },
  555. StartAt: types.StrPtr(time.Now().UTC().Format(time.RFC3339)),
  556. StopAt: types.StrPtr(time.Now().UTC().Format(time.RFC3339)),
  557. Capacity: types.Int32Ptr(0),
  558. Simulated: types.BoolPtr(false),
  559. EventsCount: types.Int32Ptr(int32(len(decisionsList))),
  560. Leakspeed: types.StrPtr(""),
  561. ScenarioHash: types.StrPtr(""),
  562. ScenarioVersion: types.StrPtr(""),
  563. Decisions: decisionsList,
  564. }
  565. alerts = append(alerts, &importAlert)
  566. if len(decisionsList) > 1000 {
  567. log.Infof("You are about to add %d decisions, this may take a while", len(decisionsList))
  568. }
  569. _, _, err = Client.Alerts.Add(context.Background(), alerts)
  570. if err != nil {
  571. log.Fatalf(err.Error())
  572. }
  573. log.Infof("%d decisions successfully imported", len(decisionsList))
  574. },
  575. }
  576. cmdDecisionImport.Flags().SortFlags = false
  577. cmdDecisionImport.Flags().StringVarP(&importFile, "input", "i", "", "Input file")
  578. cmdDecisionImport.Flags().StringVarP(&importDuration, "duration", "d", "", "Decision duration (ie. 1h,4h,30m)")
  579. cmdDecisionImport.Flags().StringVar(&importScope, "scope", types.Ip, "Decision scope (ie. ip,range,username)")
  580. cmdDecisionImport.Flags().StringVarP(&importReason, "reason", "R", "", "Decision reason (ie. scenario-name)")
  581. cmdDecisionImport.Flags().StringVarP(&importType, "type", "t", "", "Decision type (ie. ban,captcha,throttle)")
  582. cmdDecisions.AddCommand(cmdDecisionImport)
  583. return cmdDecisions
  584. }