apic.go 30 KB

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