apic.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  1. package apiserver
  2. import (
  3. "context"
  4. "fmt"
  5. "math/rand"
  6. "net"
  7. "net/http"
  8. "net/url"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "time"
  13. "github.com/go-openapi/strfmt"
  14. "github.com/pkg/errors"
  15. log "github.com/sirupsen/logrus"
  16. "gopkg.in/tomb.v2"
  17. "slices"
  18. "github.com/crowdsecurity/go-cs-lib/ptr"
  19. "github.com/crowdsecurity/go-cs-lib/trace"
  20. "github.com/crowdsecurity/go-cs-lib/version"
  21. "github.com/crowdsecurity/crowdsec/pkg/apiclient"
  22. "github.com/crowdsecurity/crowdsec/pkg/csconfig"
  23. "github.com/crowdsecurity/crowdsec/pkg/database"
  24. "github.com/crowdsecurity/crowdsec/pkg/database/ent"
  25. "github.com/crowdsecurity/crowdsec/pkg/database/ent/alert"
  26. "github.com/crowdsecurity/crowdsec/pkg/database/ent/decision"
  27. "github.com/crowdsecurity/crowdsec/pkg/models"
  28. "github.com/crowdsecurity/crowdsec/pkg/modelscapi"
  29. "github.com/crowdsecurity/crowdsec/pkg/types"
  30. )
  31. const (
  32. // delta values must be smaller than the interval
  33. pullIntervalDefault = time.Hour * 2
  34. pullIntervalDelta = 5 * time.Minute
  35. pushIntervalDefault = time.Second * 10
  36. pushIntervalDelta = time.Second * 7
  37. metricsIntervalDefault = time.Minute * 30
  38. metricsIntervalDelta = time.Minute * 15
  39. )
  40. type apic struct {
  41. // when changing the intervals in tests, always set *First too
  42. // or they can be negative
  43. pullInterval time.Duration
  44. pullIntervalFirst time.Duration
  45. pushInterval time.Duration
  46. pushIntervalFirst time.Duration
  47. metricsInterval time.Duration
  48. metricsIntervalFirst time.Duration
  49. dbClient *database.Client
  50. apiClient *apiclient.ApiClient
  51. AlertsAddChan chan []*models.Alert
  52. mu sync.Mutex
  53. pushTomb tomb.Tomb
  54. pullTomb tomb.Tomb
  55. metricsTomb tomb.Tomb
  56. startup bool
  57. credentials *csconfig.ApiCredentialsCfg
  58. scenarioList []string
  59. consoleConfig *csconfig.ConsoleConfig
  60. isPulling chan bool
  61. whitelists *csconfig.CapiWhitelist
  62. }
  63. // randomDuration returns a duration value between d-delta and d+delta
  64. func randomDuration(d time.Duration, delta time.Duration) time.Duration {
  65. ret := d + time.Duration(rand.Int63n(int64(2*delta))) - delta
  66. // ticker interval must be > 0 (nanoseconds)
  67. if ret <= 0 {
  68. return 1
  69. }
  70. return ret
  71. }
  72. func (a *apic) FetchScenariosListFromDB() ([]string, error) {
  73. scenarios := make([]string, 0)
  74. machines, err := a.dbClient.ListMachines()
  75. if err != nil {
  76. return nil, fmt.Errorf("while listing machines: %w", err)
  77. }
  78. //merge all scenarios together
  79. for _, v := range machines {
  80. machineScenarios := strings.Split(v.Scenarios, ",")
  81. log.Debugf("%d scenarios for machine %d", len(machineScenarios), v.ID)
  82. for _, sv := range machineScenarios {
  83. if !slices.Contains(scenarios, sv) && sv != "" {
  84. scenarios = append(scenarios, sv)
  85. }
  86. }
  87. }
  88. log.Debugf("Returning list of scenarios : %+v", scenarios)
  89. return scenarios, nil
  90. }
  91. func decisionsToApiDecisions(decisions []*models.Decision) models.AddSignalsRequestItemDecisions {
  92. apiDecisions := models.AddSignalsRequestItemDecisions{}
  93. for _, decision := range decisions {
  94. x := &models.AddSignalsRequestItemDecisionsItem{
  95. Duration: ptr.Of(*decision.Duration),
  96. ID: new(int64),
  97. Origin: ptr.Of(*decision.Origin),
  98. Scenario: ptr.Of(*decision.Scenario),
  99. Scope: ptr.Of(*decision.Scope),
  100. //Simulated: *decision.Simulated,
  101. Type: ptr.Of(*decision.Type),
  102. Until: decision.Until,
  103. Value: ptr.Of(*decision.Value),
  104. UUID: decision.UUID,
  105. }
  106. *x.ID = decision.ID
  107. if decision.Simulated != nil {
  108. x.Simulated = *decision.Simulated
  109. }
  110. apiDecisions = append(apiDecisions, x)
  111. }
  112. return apiDecisions
  113. }
  114. func alertToSignal(alert *models.Alert, scenarioTrust string, shareContext bool) *models.AddSignalsRequestItem {
  115. signal := &models.AddSignalsRequestItem{
  116. Message: alert.Message,
  117. Scenario: alert.Scenario,
  118. ScenarioHash: alert.ScenarioHash,
  119. ScenarioVersion: alert.ScenarioVersion,
  120. Source: &models.AddSignalsRequestItemSource{
  121. AsName: alert.Source.AsName,
  122. AsNumber: alert.Source.AsNumber,
  123. Cn: alert.Source.Cn,
  124. IP: alert.Source.IP,
  125. Latitude: alert.Source.Latitude,
  126. Longitude: alert.Source.Longitude,
  127. Range: alert.Source.Range,
  128. Scope: alert.Source.Scope,
  129. Value: alert.Source.Value,
  130. },
  131. StartAt: alert.StartAt,
  132. StopAt: alert.StopAt,
  133. CreatedAt: alert.CreatedAt,
  134. MachineID: alert.MachineID,
  135. ScenarioTrust: scenarioTrust,
  136. Decisions: decisionsToApiDecisions(alert.Decisions),
  137. UUID: alert.UUID,
  138. }
  139. if shareContext {
  140. signal.Context = make([]*models.AddSignalsRequestItemContextItems0, 0)
  141. for _, meta := range alert.Meta {
  142. contextItem := models.AddSignalsRequestItemContextItems0{
  143. Key: meta.Key,
  144. Value: meta.Value,
  145. }
  146. signal.Context = append(signal.Context, &contextItem)
  147. }
  148. }
  149. return signal
  150. }
  151. func NewAPIC(config *csconfig.OnlineApiClientCfg, dbClient *database.Client, consoleConfig *csconfig.ConsoleConfig, apicWhitelist *csconfig.CapiWhitelist) (*apic, error) {
  152. var err error
  153. ret := &apic{
  154. AlertsAddChan: make(chan []*models.Alert),
  155. dbClient: dbClient,
  156. mu: sync.Mutex{},
  157. startup: true,
  158. credentials: config.Credentials,
  159. pullTomb: tomb.Tomb{},
  160. pushTomb: tomb.Tomb{},
  161. metricsTomb: tomb.Tomb{},
  162. scenarioList: make([]string, 0),
  163. consoleConfig: consoleConfig,
  164. pullInterval: pullIntervalDefault,
  165. pullIntervalFirst: randomDuration(pullIntervalDefault, pullIntervalDelta),
  166. pushInterval: pushIntervalDefault,
  167. pushIntervalFirst: randomDuration(pushIntervalDefault, pushIntervalDelta),
  168. metricsInterval: metricsIntervalDefault,
  169. metricsIntervalFirst: randomDuration(metricsIntervalDefault, metricsIntervalDelta),
  170. isPulling: make(chan bool, 1),
  171. whitelists: apicWhitelist,
  172. }
  173. password := strfmt.Password(config.Credentials.Password)
  174. apiURL, err := url.Parse(config.Credentials.URL)
  175. if err != nil {
  176. return nil, fmt.Errorf("while parsing '%s': %w", config.Credentials.URL, err)
  177. }
  178. papiURL, err := url.Parse(config.Credentials.PapiURL)
  179. if err != nil {
  180. return nil, fmt.Errorf("while parsing '%s': %w", config.Credentials.PapiURL, err)
  181. }
  182. ret.scenarioList, err = ret.FetchScenariosListFromDB()
  183. if err != nil {
  184. return nil, fmt.Errorf("while fetching scenarios from db: %w", err)
  185. }
  186. ret.apiClient, err = apiclient.NewClient(&apiclient.Config{
  187. MachineID: config.Credentials.Login,
  188. Password: password,
  189. UserAgent: fmt.Sprintf("crowdsec/%s", version.String()),
  190. URL: apiURL,
  191. PapiURL: papiURL,
  192. VersionPrefix: "v3",
  193. Scenarios: ret.scenarioList,
  194. UpdateScenario: ret.FetchScenariosListFromDB,
  195. })
  196. if err != nil {
  197. return nil, fmt.Errorf("while creating api client: %w", err)
  198. }
  199. // The watcher will be authenticated by the RoundTripper the first time it will call CAPI
  200. // Explicit authentication will provoke a useless supplementary call to CAPI
  201. scenarios, err := ret.FetchScenariosListFromDB()
  202. if err != nil {
  203. return ret, fmt.Errorf("get scenario in db: %w", err)
  204. }
  205. authResp, _, err := ret.apiClient.Auth.AuthenticateWatcher(context.Background(), models.WatcherAuthRequest{
  206. MachineID: &config.Credentials.Login,
  207. Password: &password,
  208. Scenarios: scenarios,
  209. })
  210. if err != nil {
  211. return ret, fmt.Errorf("authenticate watcher (%s): %w", config.Credentials.Login, err)
  212. }
  213. if err := ret.apiClient.GetClient().Transport.(*apiclient.JWTTransport).Expiration.UnmarshalText([]byte(authResp.Expire)); err != nil {
  214. return ret, fmt.Errorf("unable to parse jwt expiration: %w", err)
  215. }
  216. ret.apiClient.GetClient().Transport.(*apiclient.JWTTransport).Token = authResp.Token
  217. return ret, err
  218. }
  219. // keep track of all alerts in cache and push it to CAPI every PushInterval.
  220. func (a *apic) Push() error {
  221. defer trace.CatchPanic("lapi/pushToAPIC")
  222. var cache models.AddSignalsRequest
  223. ticker := time.NewTicker(a.pushIntervalFirst)
  224. log.Infof("Start push to CrowdSec Central API (interval: %s once, then %s)", a.pushIntervalFirst.Round(time.Second), a.pushInterval)
  225. for {
  226. select {
  227. case <-a.pushTomb.Dying(): // if one apic routine is dying, do we kill the others?
  228. a.pullTomb.Kill(nil)
  229. a.metricsTomb.Kill(nil)
  230. log.Infof("push tomb is dying, sending cache (%d elements) before exiting", len(cache))
  231. if len(cache) == 0 {
  232. return nil
  233. }
  234. go a.Send(&cache)
  235. return nil
  236. case <-ticker.C:
  237. ticker.Reset(a.pushInterval)
  238. if len(cache) > 0 {
  239. a.mu.Lock()
  240. cacheCopy := cache
  241. cache = make(models.AddSignalsRequest, 0)
  242. a.mu.Unlock()
  243. log.Infof("Signal push: %d signals to push", len(cacheCopy))
  244. go a.Send(&cacheCopy)
  245. }
  246. case alerts := <-a.AlertsAddChan:
  247. var signals []*models.AddSignalsRequestItem
  248. for _, alert := range alerts {
  249. if ok := shouldShareAlert(alert, a.consoleConfig); ok {
  250. signals = append(signals, alertToSignal(alert, getScenarioTrustOfAlert(alert), *a.consoleConfig.ShareContext))
  251. }
  252. }
  253. a.mu.Lock()
  254. cache = append(cache, signals...)
  255. a.mu.Unlock()
  256. }
  257. }
  258. }
  259. func getScenarioTrustOfAlert(alert *models.Alert) string {
  260. scenarioTrust := "certified"
  261. if alert.ScenarioHash == nil || *alert.ScenarioHash == "" {
  262. scenarioTrust = "custom"
  263. } else if alert.ScenarioVersion == nil || *alert.ScenarioVersion == "" || *alert.ScenarioVersion == "?" {
  264. scenarioTrust = "tainted"
  265. }
  266. if len(alert.Decisions) > 0 {
  267. if *alert.Decisions[0].Origin == types.CscliOrigin {
  268. scenarioTrust = "manual"
  269. }
  270. }
  271. return scenarioTrust
  272. }
  273. func shouldShareAlert(alert *models.Alert, consoleConfig *csconfig.ConsoleConfig) bool {
  274. if *alert.Simulated {
  275. log.Debugf("simulation enabled for alert (id:%d), will not be sent to CAPI", alert.ID)
  276. return false
  277. }
  278. switch scenarioTrust := getScenarioTrustOfAlert(alert); scenarioTrust {
  279. case "manual":
  280. if !*consoleConfig.ShareManualDecisions {
  281. log.Debugf("manual decision generated an alert, doesn't send it to CAPI because options is disabled")
  282. return false
  283. }
  284. case "tainted":
  285. if !*consoleConfig.ShareTaintedScenarios {
  286. log.Debugf("tainted scenario generated an alert, doesn't send it to CAPI because options is disabled")
  287. return false
  288. }
  289. case "custom":
  290. if !*consoleConfig.ShareCustomScenarios {
  291. log.Debugf("custom scenario generated an alert, doesn't send it to CAPI because options is disabled")
  292. return false
  293. }
  294. }
  295. return true
  296. }
  297. func (a *apic) Send(cacheOrig *models.AddSignalsRequest) {
  298. /*we do have a problem with this :
  299. The apic.Push background routine reads from alertToPush chan.
  300. This chan is filled by Controller.CreateAlert
  301. If the chan apic.Send hangs, the alertToPush chan will become full,
  302. with means that Controller.CreateAlert is going to hang, blocking API worker(s).
  303. So instead, we prefer to cancel write.
  304. I don't know enough about gin to tell how much of an issue it can be.
  305. */
  306. var cache []*models.AddSignalsRequestItem = *cacheOrig
  307. var send models.AddSignalsRequest
  308. bulkSize := 50
  309. pageStart := 0
  310. pageEnd := bulkSize
  311. for {
  312. if pageEnd >= len(cache) {
  313. send = cache[pageStart:]
  314. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  315. defer cancel()
  316. _, _, err := a.apiClient.Signal.Add(ctx, &send)
  317. if err != nil {
  318. log.Errorf("sending signal to central API: %s", err)
  319. return
  320. }
  321. break
  322. }
  323. send = cache[pageStart:pageEnd]
  324. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  325. defer cancel()
  326. _, _, err := a.apiClient.Signal.Add(ctx, &send)
  327. if err != nil {
  328. //we log it here as well, because the return value of func might be discarded
  329. log.Errorf("sending signal to central API: %s", err)
  330. }
  331. pageStart += bulkSize
  332. pageEnd += bulkSize
  333. }
  334. }
  335. func (a *apic) CAPIPullIsOld() (bool, error) {
  336. /*only pull community blocklist if it's older than 1h30 */
  337. alerts := a.dbClient.Ent.Alert.Query()
  338. alerts = alerts.Where(alert.HasDecisionsWith(decision.OriginEQ(database.CapiMachineID)))
  339. alerts = alerts.Where(alert.CreatedAtGTE(time.Now().UTC().Add(-time.Duration(1*time.Hour + 30*time.Minute)))) //nolint:unconvert
  340. count, err := alerts.Count(a.dbClient.CTX)
  341. if err != nil {
  342. return false, fmt.Errorf("while looking for CAPI alert: %w", err)
  343. }
  344. if count > 0 {
  345. log.Printf("last CAPI pull is newer than 1h30, skip.")
  346. return false, nil
  347. }
  348. return true, nil
  349. }
  350. func (a *apic) HandleDeletedDecisions(deletedDecisions []*models.Decision, delete_counters map[string]map[string]int) (int, error) {
  351. nbDeleted := 0
  352. for _, decision := range deletedDecisions {
  353. filter := map[string][]string{
  354. "value": {*decision.Value},
  355. "origin": {*decision.Origin},
  356. }
  357. if strings.ToLower(*decision.Scope) != "ip" {
  358. filter["type"] = []string{*decision.Type}
  359. filter["scopes"] = []string{*decision.Scope}
  360. }
  361. dbCliRet, _, err := a.dbClient.SoftDeleteDecisionsWithFilter(filter)
  362. if err != nil {
  363. return 0, fmt.Errorf("deleting decisions error: %w", err)
  364. }
  365. dbCliDel, err := strconv.Atoi(dbCliRet)
  366. if err != nil {
  367. return 0, fmt.Errorf("converting db ret %d: %w", dbCliDel, err)
  368. }
  369. updateCounterForDecision(delete_counters, decision.Origin, decision.Scenario, dbCliDel)
  370. nbDeleted += dbCliDel
  371. }
  372. return nbDeleted, nil
  373. }
  374. func (a *apic) HandleDeletedDecisionsV3(deletedDecisions []*modelscapi.GetDecisionsStreamResponseDeletedItem, delete_counters map[string]map[string]int) (int, error) {
  375. var nbDeleted int
  376. for _, decisions := range deletedDecisions {
  377. scope := decisions.Scope
  378. for _, decision := range decisions.Decisions {
  379. filter := map[string][]string{
  380. "value": {decision},
  381. "origin": {types.CAPIOrigin},
  382. }
  383. if strings.ToLower(*scope) != "ip" {
  384. filter["scopes"] = []string{*scope}
  385. }
  386. dbCliRet, _, err := a.dbClient.SoftDeleteDecisionsWithFilter(filter)
  387. if err != nil {
  388. return 0, fmt.Errorf("deleting decisions error: %w", err)
  389. }
  390. dbCliDel, err := strconv.Atoi(dbCliRet)
  391. if err != nil {
  392. return 0, fmt.Errorf("converting db ret %d: %w", dbCliDel, err)
  393. }
  394. updateCounterForDecision(delete_counters, ptr.Of(types.CAPIOrigin), nil, dbCliDel)
  395. nbDeleted += dbCliDel
  396. }
  397. }
  398. return nbDeleted, nil
  399. }
  400. func createAlertsForDecisions(decisions []*models.Decision) []*models.Alert {
  401. newAlerts := make([]*models.Alert, 0)
  402. for _, decision := range decisions {
  403. found := false
  404. for _, sub := range newAlerts {
  405. if sub.Source.Scope == nil {
  406. log.Warningf("nil scope in %+v", sub)
  407. continue
  408. }
  409. if *decision.Origin == types.CAPIOrigin {
  410. if *sub.Source.Scope == types.CAPIOrigin {
  411. found = true
  412. break
  413. }
  414. } else if *decision.Origin == types.ListOrigin {
  415. if *sub.Source.Scope == *decision.Origin {
  416. if sub.Scenario == nil {
  417. log.Warningf("nil scenario in %+v", sub)
  418. }
  419. if *sub.Scenario == *decision.Scenario {
  420. found = true
  421. break
  422. }
  423. }
  424. } else {
  425. log.Warningf("unknown origin %s : %+v", *decision.Origin, decision)
  426. }
  427. }
  428. if !found {
  429. log.Debugf("Create entry for origin:%s scenario:%s", *decision.Origin, *decision.Scenario)
  430. newAlerts = append(newAlerts, createAlertForDecision(decision))
  431. }
  432. }
  433. return newAlerts
  434. }
  435. func createAlertForDecision(decision *models.Decision) *models.Alert {
  436. var (
  437. scenario string
  438. scope string
  439. )
  440. switch *decision.Origin {
  441. case types.CAPIOrigin:
  442. scenario = types.CAPIOrigin
  443. scope = types.CAPIOrigin
  444. case types.ListOrigin:
  445. scenario = *decision.Scenario
  446. scope = types.ListOrigin
  447. default:
  448. // XXX: this or nil?
  449. scenario = ""
  450. scope = ""
  451. log.Warningf("unknown origin %s", *decision.Origin)
  452. }
  453. return &models.Alert{
  454. Source: &models.Source{
  455. Scope: ptr.Of(scope),
  456. Value: ptr.Of(""),
  457. },
  458. Scenario: ptr.Of(scenario),
  459. Message: ptr.Of(""),
  460. StartAt: ptr.Of(time.Now().UTC().Format(time.RFC3339)),
  461. StopAt: ptr.Of(time.Now().UTC().Format(time.RFC3339)),
  462. Capacity: ptr.Of(int32(0)),
  463. Simulated: ptr.Of(false),
  464. EventsCount: ptr.Of(int32(0)),
  465. Leakspeed: ptr.Of(""),
  466. ScenarioHash: ptr.Of(""),
  467. ScenarioVersion: ptr.Of(""),
  468. MachineID: database.CapiMachineID,
  469. }
  470. }
  471. // This function takes in list of parent alerts and decisions and then pairs them up.
  472. func fillAlertsWithDecisions(alerts []*models.Alert, decisions []*models.Decision, add_counters map[string]map[string]int) []*models.Alert {
  473. for _, decision := range decisions {
  474. //count and create separate alerts for each list
  475. updateCounterForDecision(add_counters, decision.Origin, decision.Scenario, 1)
  476. /*CAPI might send lower case scopes, unify it.*/
  477. switch strings.ToLower(*decision.Scope) {
  478. case "ip":
  479. *decision.Scope = types.Ip
  480. case "range":
  481. *decision.Scope = types.Range
  482. }
  483. found := false
  484. //add the individual decisions to the right list
  485. for idx, alert := range alerts {
  486. if *decision.Origin == types.CAPIOrigin {
  487. if *alert.Source.Scope == types.CAPIOrigin {
  488. alerts[idx].Decisions = append(alerts[idx].Decisions, decision)
  489. found = true
  490. break
  491. }
  492. } else if *decision.Origin == types.ListOrigin {
  493. if *alert.Source.Scope == types.ListOrigin && *alert.Scenario == *decision.Scenario {
  494. alerts[idx].Decisions = append(alerts[idx].Decisions, decision)
  495. found = true
  496. break
  497. }
  498. } else {
  499. log.Warningf("unknown origin %s", *decision.Origin)
  500. }
  501. }
  502. if !found {
  503. log.Warningf("Orphaned decision for %s - %s", *decision.Origin, *decision.Scenario)
  504. }
  505. }
  506. return alerts
  507. }
  508. // we receive a list of decisions and links for blocklist and we need to create a list of alerts :
  509. // one alert for "community blocklist"
  510. // one alert per list we're subscribed to
  511. func (a *apic) PullTop(forcePull bool) error {
  512. var err error
  513. //A mutex with TryLock would be a bit simpler
  514. //But go does not guarantee that TryLock will be able to acquire the lock even if it is available
  515. select {
  516. case a.isPulling <- true:
  517. defer func() {
  518. <-a.isPulling
  519. }()
  520. default:
  521. return errors.New("pull already in progress")
  522. }
  523. if !forcePull {
  524. if lastPullIsOld, err := a.CAPIPullIsOld(); err != nil {
  525. return err
  526. } else if !lastPullIsOld {
  527. return nil
  528. }
  529. }
  530. log.Infof("Starting community-blocklist update")
  531. data, _, err := a.apiClient.Decisions.GetStreamV3(context.Background(), apiclient.DecisionsStreamOpts{Startup: a.startup})
  532. if err != nil {
  533. return fmt.Errorf("get stream: %w", err)
  534. }
  535. a.startup = false
  536. /*to count additions/deletions across lists*/
  537. log.Debugf("Received %d new decisions", len(data.New))
  538. log.Debugf("Received %d deleted decisions", len(data.Deleted))
  539. if data.Links != nil {
  540. log.Debugf("Received %d blocklists links", len(data.Links.Blocklists))
  541. }
  542. add_counters, delete_counters := makeAddAndDeleteCounters()
  543. // process deleted decisions
  544. if nbDeleted, err := a.HandleDeletedDecisionsV3(data.Deleted, delete_counters); err != nil {
  545. return err
  546. } else {
  547. log.Printf("capi/community-blocklist : %d explicit deletions", nbDeleted)
  548. }
  549. if len(data.New) == 0 {
  550. log.Infof("capi/community-blocklist : received 0 new entries (expected if you just installed crowdsec)")
  551. return nil
  552. }
  553. // create one alert for community blocklist using the first decision
  554. decisions := a.apiClient.Decisions.GetDecisionsFromGroups(data.New)
  555. //apply APIC specific whitelists
  556. decisions = a.ApplyApicWhitelists(decisions)
  557. alert := createAlertForDecision(decisions[0])
  558. alertsFromCapi := []*models.Alert{alert}
  559. alertsFromCapi = fillAlertsWithDecisions(alertsFromCapi, decisions, add_counters)
  560. err = a.SaveAlerts(alertsFromCapi, add_counters, delete_counters)
  561. if err != nil {
  562. return fmt.Errorf("while saving alerts: %w", err)
  563. }
  564. // update blocklists
  565. if err := a.UpdateBlocklists(data.Links, add_counters, forcePull); err != nil {
  566. return fmt.Errorf("while updating blocklists: %w", err)
  567. }
  568. return nil
  569. }
  570. // we receive a link to a blocklist, we pull the content of the blocklist and we create one alert
  571. func (a *apic) PullBlocklist(blocklist *modelscapi.BlocklistLink, forcePull bool) error {
  572. add_counters, _ := makeAddAndDeleteCounters()
  573. if err := a.UpdateBlocklists(&modelscapi.GetDecisionsStreamResponseLinks{
  574. Blocklists: []*modelscapi.BlocklistLink{blocklist},
  575. }, add_counters, forcePull); err != nil {
  576. return fmt.Errorf("while pulling blocklist: %w", err)
  577. }
  578. return nil
  579. }
  580. // if decisions is whitelisted: return representation of the whitelist ip or cidr
  581. // if not whitelisted: empty string
  582. func (a *apic) whitelistedBy(decision *models.Decision) string {
  583. if decision.Value == nil {
  584. return ""
  585. }
  586. ipval := net.ParseIP(*decision.Value)
  587. for _, cidr := range a.whitelists.Cidrs {
  588. if cidr.Contains(ipval) {
  589. return cidr.String()
  590. }
  591. }
  592. for _, ip := range a.whitelists.Ips {
  593. if ip != nil && ip.Equal(ipval) {
  594. return ip.String()
  595. }
  596. }
  597. return ""
  598. }
  599. func (a *apic) ApplyApicWhitelists(decisions []*models.Decision) []*models.Decision {
  600. if a.whitelists == nil || len(a.whitelists.Cidrs) == 0 && len(a.whitelists.Ips) == 0 {
  601. return decisions
  602. }
  603. //deal with CAPI whitelists for fire. We want to avoid having a second list, so we shrink in place
  604. outIdx := 0
  605. for _, decision := range decisions {
  606. whitelister := a.whitelistedBy(decision)
  607. if whitelister != "" {
  608. log.Infof("%s from %s is whitelisted by %s", *decision.Value, *decision.Scenario, whitelister)
  609. continue
  610. }
  611. decisions[outIdx] = decision
  612. outIdx++
  613. }
  614. //shrink the list, those are deleted items
  615. return decisions[:outIdx]
  616. }
  617. func (a *apic) SaveAlerts(alertsFromCapi []*models.Alert, add_counters map[string]map[string]int, delete_counters map[string]map[string]int) error {
  618. for _, alert := range alertsFromCapi {
  619. setAlertScenario(alert, add_counters, delete_counters)
  620. log.Debugf("%s has %d decisions", *alert.Source.Scope, len(alert.Decisions))
  621. if a.dbClient.Type == "sqlite" && (a.dbClient.WalMode == nil || !*a.dbClient.WalMode) {
  622. log.Warningf("sqlite is not using WAL mode, LAPI might become unresponsive when inserting the community blocklist")
  623. }
  624. alertID, inserted, deleted, err := a.dbClient.UpdateCommunityBlocklist(alert)
  625. if err != nil {
  626. return fmt.Errorf("while saving alert from %s: %w", *alert.Source.Scope, err)
  627. }
  628. log.Printf("%s : added %d entries, deleted %d entries (alert:%d)", *alert.Source.Scope, inserted, deleted, alertID)
  629. }
  630. return nil
  631. }
  632. func (a *apic) ShouldForcePullBlocklist(blocklist *modelscapi.BlocklistLink) (bool, error) {
  633. // we should force pull if the blocklist decisions are about to expire or there's no decision in the db
  634. alertQuery := a.dbClient.Ent.Alert.Query()
  635. alertQuery.Where(alert.SourceScopeEQ(fmt.Sprintf("%s:%s", types.ListOrigin, *blocklist.Name)))
  636. alertQuery.Order(ent.Desc(alert.FieldCreatedAt))
  637. alertInstance, err := alertQuery.First(context.Background())
  638. if err != nil {
  639. if ent.IsNotFound(err) {
  640. log.Debugf("no alert found for %s, force refresh", *blocklist.Name)
  641. return true, nil
  642. }
  643. return false, fmt.Errorf("while getting alert: %w", err)
  644. }
  645. decisionQuery := a.dbClient.Ent.Decision.Query()
  646. decisionQuery.Where(decision.HasOwnerWith(alert.IDEQ(alertInstance.ID)))
  647. firstDecision, err := decisionQuery.First(context.Background())
  648. if err != nil {
  649. if ent.IsNotFound(err) {
  650. log.Debugf("no decision found for %s, force refresh", *blocklist.Name)
  651. return true, nil
  652. }
  653. return false, fmt.Errorf("while getting decision: %w", err)
  654. }
  655. if firstDecision == nil || firstDecision.Until == nil || firstDecision.Until.Sub(time.Now().UTC()) < (a.pullInterval+15*time.Minute) {
  656. log.Debugf("at least one decision found for %s, expire soon, force refresh", *blocklist.Name)
  657. return true, nil
  658. }
  659. return false, nil
  660. }
  661. func (a *apic) updateBlocklist(client *apiclient.ApiClient, blocklist *modelscapi.BlocklistLink, add_counters map[string]map[string]int, forcePull bool) error {
  662. if blocklist.Scope == nil {
  663. log.Warningf("blocklist has no scope")
  664. return nil
  665. }
  666. if blocklist.Duration == nil {
  667. log.Warningf("blocklist has no duration")
  668. return nil
  669. }
  670. if !forcePull {
  671. _forcePull, err := a.ShouldForcePullBlocklist(blocklist)
  672. if err != nil {
  673. return fmt.Errorf("while checking if we should force pull blocklist %s: %w", *blocklist.Name, err)
  674. }
  675. forcePull = _forcePull
  676. }
  677. blocklistConfigItemName := fmt.Sprintf("blocklist:%s:last_pull", *blocklist.Name)
  678. var lastPullTimestamp *string
  679. var err error
  680. if !forcePull {
  681. lastPullTimestamp, err = a.dbClient.GetConfigItem(blocklistConfigItemName)
  682. if err != nil {
  683. return fmt.Errorf("while getting last pull timestamp for blocklist %s: %w", *blocklist.Name, err)
  684. }
  685. }
  686. decisions, hasChanged, err := client.Decisions.GetDecisionsFromBlocklist(context.Background(), blocklist, lastPullTimestamp)
  687. if err != nil {
  688. return fmt.Errorf("while getting decisions from blocklist %s: %w", *blocklist.Name, err)
  689. }
  690. if !hasChanged {
  691. if lastPullTimestamp == nil {
  692. log.Infof("blocklist %s hasn't been modified or there was an error reading it, skipping", *blocklist.Name)
  693. } else {
  694. log.Infof("blocklist %s hasn't been modified since %s, skipping", *blocklist.Name, *lastPullTimestamp)
  695. }
  696. return nil
  697. }
  698. err = a.dbClient.SetConfigItem(blocklistConfigItemName, time.Now().UTC().Format(http.TimeFormat))
  699. if err != nil {
  700. return fmt.Errorf("while setting last pull timestamp for blocklist %s: %w", *blocklist.Name, err)
  701. }
  702. if len(decisions) == 0 {
  703. log.Infof("blocklist %s has no decisions", *blocklist.Name)
  704. return nil
  705. }
  706. //apply APIC specific whitelists
  707. decisions = a.ApplyApicWhitelists(decisions)
  708. alert := createAlertForDecision(decisions[0])
  709. alertsFromCapi := []*models.Alert{alert}
  710. alertsFromCapi = fillAlertsWithDecisions(alertsFromCapi, decisions, add_counters)
  711. err = a.SaveAlerts(alertsFromCapi, add_counters, nil)
  712. if err != nil {
  713. return fmt.Errorf("while saving alert from blocklist %s: %w", *blocklist.Name, err)
  714. }
  715. return nil
  716. }
  717. func (a *apic) UpdateBlocklists(links *modelscapi.GetDecisionsStreamResponseLinks, add_counters map[string]map[string]int, forcePull bool) error {
  718. if links == nil {
  719. return nil
  720. }
  721. if links.Blocklists == nil {
  722. return nil
  723. }
  724. // we must use a different http client than apiClient's because the transport of apiClient is jwtTransport or here we have signed apis that are incompatibles
  725. // we can use the same baseUrl as the urls are absolute and the parse will take care of it
  726. defaultClient, err := apiclient.NewDefaultClient(a.apiClient.BaseURL, "", "", nil)
  727. if err != nil {
  728. return fmt.Errorf("while creating default client: %w", err)
  729. }
  730. for _, blocklist := range links.Blocklists {
  731. if err := a.updateBlocklist(defaultClient, blocklist, add_counters, forcePull); err != nil {
  732. return err
  733. }
  734. }
  735. return nil
  736. }
  737. func setAlertScenario(alert *models.Alert, add_counters map[string]map[string]int, delete_counters map[string]map[string]int) {
  738. if *alert.Source.Scope == types.CAPIOrigin {
  739. *alert.Source.Scope = types.CommunityBlocklistPullSourceScope
  740. alert.Scenario = ptr.Of(fmt.Sprintf("update : +%d/-%d IPs", add_counters[types.CAPIOrigin]["all"], delete_counters[types.CAPIOrigin]["all"]))
  741. } else if *alert.Source.Scope == types.ListOrigin {
  742. *alert.Source.Scope = fmt.Sprintf("%s:%s", types.ListOrigin, *alert.Scenario)
  743. alert.Scenario = ptr.Of(fmt.Sprintf("update : +%d/-%d IPs", add_counters[types.ListOrigin][*alert.Scenario], delete_counters[types.ListOrigin][*alert.Scenario]))
  744. }
  745. }
  746. func (a *apic) Pull() error {
  747. defer trace.CatchPanic("lapi/pullFromAPIC")
  748. toldOnce := false
  749. for {
  750. scenario, err := a.FetchScenariosListFromDB()
  751. if err != nil {
  752. log.Errorf("unable to fetch scenarios from db: %s", err)
  753. }
  754. if len(scenario) > 0 {
  755. break
  756. }
  757. if !toldOnce {
  758. log.Warning("scenario list is empty, will not pull yet")
  759. toldOnce = true
  760. }
  761. time.Sleep(1 * time.Second)
  762. }
  763. if err := a.PullTop(false); err != nil {
  764. log.Errorf("capi pull top: %s", err)
  765. }
  766. log.Infof("Start pull from CrowdSec Central API (interval: %s once, then %s)", a.pullIntervalFirst.Round(time.Second), a.pullInterval)
  767. ticker := time.NewTicker(a.pullIntervalFirst)
  768. for {
  769. select {
  770. case <-ticker.C:
  771. ticker.Reset(a.pullInterval)
  772. if err := a.PullTop(false); err != nil {
  773. log.Errorf("capi pull top: %s", err)
  774. continue
  775. }
  776. case <-a.pullTomb.Dying(): // if one apic routine is dying, do we kill the others?
  777. a.metricsTomb.Kill(nil)
  778. a.pushTomb.Kill(nil)
  779. return nil
  780. }
  781. }
  782. }
  783. func (a *apic) Shutdown() {
  784. a.pushTomb.Kill(nil)
  785. a.pullTomb.Kill(nil)
  786. a.metricsTomb.Kill(nil)
  787. }
  788. func makeAddAndDeleteCounters() (map[string]map[string]int, map[string]map[string]int) {
  789. add_counters := make(map[string]map[string]int)
  790. add_counters[types.CAPIOrigin] = make(map[string]int)
  791. add_counters[types.ListOrigin] = make(map[string]int)
  792. delete_counters := make(map[string]map[string]int)
  793. delete_counters[types.CAPIOrigin] = make(map[string]int)
  794. delete_counters[types.ListOrigin] = make(map[string]int)
  795. return add_counters, delete_counters
  796. }
  797. func updateCounterForDecision(counter map[string]map[string]int, origin *string, scenario *string, totalDecisions int) {
  798. if *origin == types.CAPIOrigin {
  799. counter[*origin]["all"] += totalDecisions
  800. } else if *origin == types.ListOrigin {
  801. counter[*origin][*scenario] += totalDecisions
  802. } else {
  803. log.Warningf("Unknown origin %s", *origin)
  804. }
  805. }