apic.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  1. package apiserver
  2. import (
  3. "context"
  4. "fmt"
  5. "math/rand"
  6. "net"
  7. "net/http"
  8. "net/url"
  9. "slices"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/go-openapi/strfmt"
  15. "github.com/pkg/errors"
  16. log "github.com/sirupsen/logrus"
  17. "gopkg.in/tomb.v2"
  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. var filter map[string][]string
  352. var nbDeleted int
  353. for _, decision := range deletedDecisions {
  354. if strings.ToLower(*decision.Scope) == "ip" {
  355. filter = make(map[string][]string, 1)
  356. filter["value"] = []string{*decision.Value}
  357. } else {
  358. filter = make(map[string][]string, 3)
  359. filter["value"] = []string{*decision.Value}
  360. filter["type"] = []string{*decision.Type}
  361. filter["scopes"] = []string{*decision.Scope}
  362. }
  363. filter["origin"] = []string{*decision.Origin}
  364. dbCliRet, _, err := a.dbClient.SoftDeleteDecisionsWithFilter(filter)
  365. if err != nil {
  366. return 0, fmt.Errorf("deleting decisions error: %w", err)
  367. }
  368. dbCliDel, err := strconv.Atoi(dbCliRet)
  369. if err != nil {
  370. return 0, fmt.Errorf("converting db ret %d: %w", dbCliDel, err)
  371. }
  372. updateCounterForDecision(delete_counters, decision.Origin, decision.Scenario, dbCliDel)
  373. nbDeleted += dbCliDel
  374. }
  375. return nbDeleted, nil
  376. }
  377. func (a *apic) HandleDeletedDecisionsV3(deletedDecisions []*modelscapi.GetDecisionsStreamResponseDeletedItem, delete_counters map[string]map[string]int) (int, error) {
  378. var filter map[string][]string
  379. var nbDeleted int
  380. for _, decisions := range deletedDecisions {
  381. scope := decisions.Scope
  382. for _, decision := range decisions.Decisions {
  383. if strings.ToLower(*scope) == "ip" {
  384. filter = make(map[string][]string, 1)
  385. filter["value"] = []string{decision}
  386. } else {
  387. filter = make(map[string][]string, 2)
  388. filter["value"] = []string{decision}
  389. filter["scopes"] = []string{*scope}
  390. }
  391. filter["origin"] = []string{types.CAPIOrigin}
  392. dbCliRet, _, err := a.dbClient.SoftDeleteDecisionsWithFilter(filter)
  393. if err != nil {
  394. return 0, fmt.Errorf("deleting decisions error: %w", err)
  395. }
  396. dbCliDel, err := strconv.Atoi(dbCliRet)
  397. if err != nil {
  398. return 0, fmt.Errorf("converting db ret %d: %w", dbCliDel, err)
  399. }
  400. updateCounterForDecision(delete_counters, ptr.Of(types.CAPIOrigin), nil, dbCliDel)
  401. nbDeleted += dbCliDel
  402. }
  403. }
  404. return nbDeleted, nil
  405. }
  406. func createAlertsForDecisions(decisions []*models.Decision) []*models.Alert {
  407. newAlerts := make([]*models.Alert, 0)
  408. for _, decision := range decisions {
  409. found := false
  410. for _, sub := range newAlerts {
  411. if sub.Source.Scope == nil {
  412. log.Warningf("nil scope in %+v", sub)
  413. continue
  414. }
  415. if *decision.Origin == types.CAPIOrigin {
  416. if *sub.Source.Scope == types.CAPIOrigin {
  417. found = true
  418. break
  419. }
  420. } else if *decision.Origin == types.ListOrigin {
  421. if *sub.Source.Scope == *decision.Origin {
  422. if sub.Scenario == nil {
  423. log.Warningf("nil scenario in %+v", sub)
  424. }
  425. if *sub.Scenario == *decision.Scenario {
  426. found = true
  427. break
  428. }
  429. }
  430. } else {
  431. log.Warningf("unknown origin %s : %+v", *decision.Origin, decision)
  432. }
  433. }
  434. if !found {
  435. log.Debugf("Create entry for origin:%s scenario:%s", *decision.Origin, *decision.Scenario)
  436. newAlerts = append(newAlerts, createAlertForDecision(decision))
  437. }
  438. }
  439. return newAlerts
  440. }
  441. func createAlertForDecision(decision *models.Decision) *models.Alert {
  442. newAlert := &models.Alert{}
  443. newAlert.Source = &models.Source{}
  444. newAlert.Source.Scope = ptr.Of("")
  445. if *decision.Origin == types.CAPIOrigin { //to make things more user friendly, we replace CAPI with community-blocklist
  446. newAlert.Scenario = ptr.Of(types.CAPIOrigin)
  447. newAlert.Source.Scope = ptr.Of(types.CAPIOrigin)
  448. } else if *decision.Origin == types.ListOrigin {
  449. newAlert.Scenario = ptr.Of(*decision.Scenario)
  450. newAlert.Source.Scope = ptr.Of(types.ListOrigin)
  451. } else {
  452. log.Warningf("unknown origin %s", *decision.Origin)
  453. }
  454. newAlert.Message = ptr.Of("")
  455. newAlert.Source.Value = ptr.Of("")
  456. newAlert.StartAt = ptr.Of(time.Now().UTC().Format(time.RFC3339))
  457. newAlert.StopAt = ptr.Of(time.Now().UTC().Format(time.RFC3339))
  458. newAlert.Capacity = ptr.Of(int32(0))
  459. newAlert.Simulated = ptr.Of(false)
  460. newAlert.EventsCount = ptr.Of(int32(0))
  461. newAlert.Leakspeed = ptr.Of("")
  462. newAlert.ScenarioHash = ptr.Of("")
  463. newAlert.ScenarioVersion = ptr.Of("")
  464. newAlert.MachineID = database.CapiMachineID
  465. return newAlert
  466. }
  467. // This function takes in list of parent alerts and decisions and then pairs them up.
  468. func fillAlertsWithDecisions(alerts []*models.Alert, decisions []*models.Decision, add_counters map[string]map[string]int) []*models.Alert {
  469. for _, decision := range decisions {
  470. //count and create separate alerts for each list
  471. updateCounterForDecision(add_counters, decision.Origin, decision.Scenario, 1)
  472. /*CAPI might send lower case scopes, unify it.*/
  473. switch strings.ToLower(*decision.Scope) {
  474. case "ip":
  475. *decision.Scope = types.Ip
  476. case "range":
  477. *decision.Scope = types.Range
  478. }
  479. found := false
  480. //add the individual decisions to the right list
  481. for idx, alert := range alerts {
  482. if *decision.Origin == types.CAPIOrigin {
  483. if *alert.Source.Scope == types.CAPIOrigin {
  484. alerts[idx].Decisions = append(alerts[idx].Decisions, decision)
  485. found = true
  486. break
  487. }
  488. } else if *decision.Origin == types.ListOrigin {
  489. if *alert.Source.Scope == types.ListOrigin && *alert.Scenario == *decision.Scenario {
  490. alerts[idx].Decisions = append(alerts[idx].Decisions, decision)
  491. found = true
  492. break
  493. }
  494. } else {
  495. log.Warningf("unknown origin %s", *decision.Origin)
  496. }
  497. }
  498. if !found {
  499. log.Warningf("Orphaned decision for %s - %s", *decision.Origin, *decision.Scenario)
  500. }
  501. }
  502. return alerts
  503. }
  504. // we receive a list of decisions and links for blocklist and we need to create a list of alerts :
  505. // one alert for "community blocklist"
  506. // one alert per list we're subscribed to
  507. func (a *apic) PullTop(forcePull bool) error {
  508. var err error
  509. //A mutex with TryLock would be a bit simpler
  510. //But go does not guarantee that TryLock will be able to acquire the lock even if it is available
  511. select {
  512. case a.isPulling <- true:
  513. defer func() {
  514. <-a.isPulling
  515. }()
  516. default:
  517. return errors.New("pull already in progress")
  518. }
  519. if !forcePull {
  520. if lastPullIsOld, err := a.CAPIPullIsOld(); err != nil {
  521. return err
  522. } else if !lastPullIsOld {
  523. return nil
  524. }
  525. }
  526. log.Infof("Starting community-blocklist update")
  527. data, _, err := a.apiClient.Decisions.GetStreamV3(context.Background(), apiclient.DecisionsStreamOpts{Startup: a.startup})
  528. if err != nil {
  529. return fmt.Errorf("get stream: %w", err)
  530. }
  531. a.startup = false
  532. /*to count additions/deletions across lists*/
  533. log.Debugf("Received %d new decisions", len(data.New))
  534. log.Debugf("Received %d deleted decisions", len(data.Deleted))
  535. if data.Links != nil {
  536. log.Debugf("Received %d blocklists links", len(data.Links.Blocklists))
  537. }
  538. add_counters, delete_counters := makeAddAndDeleteCounters()
  539. // process deleted decisions
  540. if nbDeleted, err := a.HandleDeletedDecisionsV3(data.Deleted, delete_counters); err != nil {
  541. return err
  542. } else {
  543. log.Printf("capi/community-blocklist : %d explicit deletions", nbDeleted)
  544. }
  545. if len(data.New) == 0 {
  546. log.Infof("capi/community-blocklist : received 0 new entries (expected if you just installed crowdsec)")
  547. return nil
  548. }
  549. // create one alert for community blocklist using the first decision
  550. decisions := a.apiClient.Decisions.GetDecisionsFromGroups(data.New)
  551. //apply APIC specific whitelists
  552. decisions = a.ApplyApicWhitelists(decisions)
  553. alert := createAlertForDecision(decisions[0])
  554. alertsFromCapi := []*models.Alert{alert}
  555. alertsFromCapi = fillAlertsWithDecisions(alertsFromCapi, decisions, add_counters)
  556. err = a.SaveAlerts(alertsFromCapi, add_counters, delete_counters)
  557. if err != nil {
  558. return fmt.Errorf("while saving alerts: %w", err)
  559. }
  560. // update blocklists
  561. if err := a.UpdateBlocklists(data.Links, add_counters); err != nil {
  562. return fmt.Errorf("while updating blocklists: %w", err)
  563. }
  564. return nil
  565. }
  566. // if decisions is whitelisted: return representation of the whitelist ip or cidr
  567. // if not whitelisted: empty string
  568. func (a *apic) whitelistedBy(decision *models.Decision) string {
  569. if decision.Value == nil {
  570. return ""
  571. }
  572. ipval := net.ParseIP(*decision.Value)
  573. for _, cidr := range a.whitelists.Cidrs {
  574. if cidr.Contains(ipval) {
  575. return cidr.String()
  576. }
  577. }
  578. for _, ip := range a.whitelists.Ips {
  579. if ip != nil && ip.Equal(ipval) {
  580. return ip.String()
  581. }
  582. }
  583. return ""
  584. }
  585. func (a *apic) ApplyApicWhitelists(decisions []*models.Decision) []*models.Decision {
  586. if a.whitelists == nil || len(a.whitelists.Cidrs) == 0 && len(a.whitelists.Ips) == 0 {
  587. return decisions
  588. }
  589. //deal with CAPI whitelists for fire. We want to avoid having a second list, so we shrink in place
  590. outIdx := 0
  591. for _, decision := range decisions {
  592. whitelister := a.whitelistedBy(decision)
  593. if whitelister != "" {
  594. log.Infof("%s from %s is whitelisted by %s", *decision.Value, *decision.Scenario, whitelister)
  595. continue
  596. }
  597. decisions[outIdx] = decision
  598. outIdx++
  599. }
  600. //shrink the list, those are deleted items
  601. return decisions[:outIdx]
  602. }
  603. func (a *apic) SaveAlerts(alertsFromCapi []*models.Alert, add_counters map[string]map[string]int, delete_counters map[string]map[string]int) error {
  604. for _, alert := range alertsFromCapi {
  605. setAlertScenario(alert, add_counters, delete_counters)
  606. log.Debugf("%s has %d decisions", *alert.Source.Scope, len(alert.Decisions))
  607. if a.dbClient.Type == "sqlite" && (a.dbClient.WalMode == nil || !*a.dbClient.WalMode) {
  608. log.Warningf("sqlite is not using WAL mode, LAPI might become unresponsive when inserting the community blocklist")
  609. }
  610. alertID, inserted, deleted, err := a.dbClient.UpdateCommunityBlocklist(alert)
  611. if err != nil {
  612. return fmt.Errorf("while saving alert from %s: %w", *alert.Source.Scope, err)
  613. }
  614. log.Printf("%s : added %d entries, deleted %d entries (alert:%d)", *alert.Source.Scope, inserted, deleted, alertID)
  615. }
  616. return nil
  617. }
  618. func (a *apic) ShouldForcePullBlocklist(blocklist *modelscapi.BlocklistLink) (bool, error) {
  619. // we should force pull if the blocklist decisions are about to expire or there's no decision in the db
  620. alertQuery := a.dbClient.Ent.Alert.Query()
  621. alertQuery.Where(alert.SourceScopeEQ(fmt.Sprintf("%s:%s", types.ListOrigin, *blocklist.Name)))
  622. alertQuery.Order(ent.Desc(alert.FieldCreatedAt))
  623. alertInstance, err := alertQuery.First(context.Background())
  624. if err != nil {
  625. if ent.IsNotFound(err) {
  626. log.Debugf("no alert found for %s, force refresh", *blocklist.Name)
  627. return true, nil
  628. }
  629. return false, fmt.Errorf("while getting alert: %w", err)
  630. }
  631. decisionQuery := a.dbClient.Ent.Decision.Query()
  632. decisionQuery.Where(decision.HasOwnerWith(alert.IDEQ(alertInstance.ID)))
  633. firstDecision, err := decisionQuery.First(context.Background())
  634. if err != nil {
  635. if ent.IsNotFound(err) {
  636. log.Debugf("no decision found for %s, force refresh", *blocklist.Name)
  637. return true, nil
  638. }
  639. return false, fmt.Errorf("while getting decision: %w", err)
  640. }
  641. if firstDecision == nil || firstDecision.Until == nil || firstDecision.Until.Sub(time.Now().UTC()) < (a.pullInterval+15*time.Minute) {
  642. log.Debugf("at least one decision found for %s, expire soon, force refresh", *blocklist.Name)
  643. return true, nil
  644. }
  645. return false, nil
  646. }
  647. func (a *apic) updateBlocklist(client *apiclient.ApiClient, blocklist *modelscapi.BlocklistLink, add_counters map[string]map[string]int) error {
  648. if blocklist.Scope == nil {
  649. log.Warningf("blocklist has no scope")
  650. return nil
  651. }
  652. if blocklist.Duration == nil {
  653. log.Warningf("blocklist has no duration")
  654. return nil
  655. }
  656. forcePull, err := a.ShouldForcePullBlocklist(blocklist)
  657. if err != nil {
  658. return fmt.Errorf("while checking if we should force pull blocklist %s: %w", *blocklist.Name, err)
  659. }
  660. blocklistConfigItemName := fmt.Sprintf("blocklist:%s:last_pull", *blocklist.Name)
  661. var lastPullTimestamp *string
  662. if !forcePull {
  663. lastPullTimestamp, err = a.dbClient.GetConfigItem(blocklistConfigItemName)
  664. if err != nil {
  665. return fmt.Errorf("while getting last pull timestamp for blocklist %s: %w", *blocklist.Name, err)
  666. }
  667. }
  668. decisions, hasChanged, err := client.Decisions.GetDecisionsFromBlocklist(context.Background(), blocklist, lastPullTimestamp)
  669. if err != nil {
  670. return fmt.Errorf("while getting decisions from blocklist %s: %w", *blocklist.Name, err)
  671. }
  672. if !hasChanged {
  673. if lastPullTimestamp == nil {
  674. log.Infof("blocklist %s hasn't been modified or there was an error reading it, skipping", *blocklist.Name)
  675. } else {
  676. log.Infof("blocklist %s hasn't been modified since %s, skipping", *blocklist.Name, *lastPullTimestamp)
  677. }
  678. return nil
  679. }
  680. err = a.dbClient.SetConfigItem(blocklistConfigItemName, time.Now().UTC().Format(http.TimeFormat))
  681. if err != nil {
  682. return fmt.Errorf("while setting last pull timestamp for blocklist %s: %w", *blocklist.Name, err)
  683. }
  684. if len(decisions) == 0 {
  685. log.Infof("blocklist %s has no decisions", *blocklist.Name)
  686. return nil
  687. }
  688. //apply APIC specific whitelists
  689. decisions = a.ApplyApicWhitelists(decisions)
  690. alert := createAlertForDecision(decisions[0])
  691. alertsFromCapi := []*models.Alert{alert}
  692. alertsFromCapi = fillAlertsWithDecisions(alertsFromCapi, decisions, add_counters)
  693. err = a.SaveAlerts(alertsFromCapi, add_counters, nil)
  694. if err != nil {
  695. return fmt.Errorf("while saving alert from blocklist %s: %w", *blocklist.Name, err)
  696. }
  697. return nil
  698. }
  699. func (a *apic) UpdateBlocklists(links *modelscapi.GetDecisionsStreamResponseLinks, add_counters map[string]map[string]int) error {
  700. if links == nil {
  701. return nil
  702. }
  703. if links.Blocklists == nil {
  704. return nil
  705. }
  706. // 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
  707. // we can use the same baseUrl as the urls are absolute and the parse will take care of it
  708. defaultClient, err := apiclient.NewDefaultClient(a.apiClient.BaseURL, "", "", nil)
  709. if err != nil {
  710. return fmt.Errorf("while creating default client: %w", err)
  711. }
  712. for _, blocklist := range links.Blocklists {
  713. if err := a.updateBlocklist(defaultClient, blocklist, add_counters); err != nil {
  714. return err
  715. }
  716. }
  717. return nil
  718. }
  719. func setAlertScenario(alert *models.Alert, add_counters map[string]map[string]int, delete_counters map[string]map[string]int) {
  720. if *alert.Source.Scope == types.CAPIOrigin {
  721. *alert.Source.Scope = types.CommunityBlocklistPullSourceScope
  722. alert.Scenario = ptr.Of(fmt.Sprintf("update : +%d/-%d IPs", add_counters[types.CAPIOrigin]["all"], delete_counters[types.CAPIOrigin]["all"]))
  723. } else if *alert.Source.Scope == types.ListOrigin {
  724. *alert.Source.Scope = fmt.Sprintf("%s:%s", types.ListOrigin, *alert.Scenario)
  725. alert.Scenario = ptr.Of(fmt.Sprintf("update : +%d/-%d IPs", add_counters[types.ListOrigin][*alert.Scenario], delete_counters[types.ListOrigin][*alert.Scenario]))
  726. }
  727. }
  728. func (a *apic) Pull() error {
  729. defer trace.CatchPanic("lapi/pullFromAPIC")
  730. toldOnce := false
  731. for {
  732. scenario, err := a.FetchScenariosListFromDB()
  733. if err != nil {
  734. log.Errorf("unable to fetch scenarios from db: %s", err)
  735. }
  736. if len(scenario) > 0 {
  737. break
  738. }
  739. if !toldOnce {
  740. log.Warning("scenario list is empty, will not pull yet")
  741. toldOnce = true
  742. }
  743. time.Sleep(1 * time.Second)
  744. }
  745. if err := a.PullTop(false); err != nil {
  746. log.Errorf("capi pull top: %s", err)
  747. }
  748. log.Infof("Start pull from CrowdSec Central API (interval: %s once, then %s)", a.pullIntervalFirst.Round(time.Second), a.pullInterval)
  749. ticker := time.NewTicker(a.pullIntervalFirst)
  750. for {
  751. select {
  752. case <-ticker.C:
  753. ticker.Reset(a.pullInterval)
  754. if err := a.PullTop(false); err != nil {
  755. log.Errorf("capi pull top: %s", err)
  756. continue
  757. }
  758. case <-a.pullTomb.Dying(): // if one apic routine is dying, do we kill the others?
  759. a.metricsTomb.Kill(nil)
  760. a.pushTomb.Kill(nil)
  761. return nil
  762. }
  763. }
  764. }
  765. func (a *apic) Shutdown() {
  766. a.pushTomb.Kill(nil)
  767. a.pullTomb.Kill(nil)
  768. a.metricsTomb.Kill(nil)
  769. }
  770. func makeAddAndDeleteCounters() (map[string]map[string]int, map[string]map[string]int) {
  771. add_counters := make(map[string]map[string]int)
  772. add_counters[types.CAPIOrigin] = make(map[string]int)
  773. add_counters[types.ListOrigin] = make(map[string]int)
  774. delete_counters := make(map[string]map[string]int)
  775. delete_counters[types.CAPIOrigin] = make(map[string]int)
  776. delete_counters[types.ListOrigin] = make(map[string]int)
  777. return add_counters, delete_counters
  778. }
  779. func updateCounterForDecision(counter map[string]map[string]int, origin *string, scenario *string, totalDecisions int) {
  780. if *origin == types.CAPIOrigin {
  781. counter[*origin]["all"] += totalDecisions
  782. } else if *origin == types.ListOrigin {
  783. counter[*origin][*scenario] += totalDecisions
  784. } else {
  785. log.Warningf("Unknown origin %s", *origin)
  786. }
  787. }