alerts.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. package v1
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "time"
  10. jwt "github.com/appleboy/gin-jwt/v2"
  11. "github.com/crowdsecurity/crowdsec/pkg/csplugin"
  12. "github.com/crowdsecurity/crowdsec/pkg/database/ent"
  13. "github.com/crowdsecurity/crowdsec/pkg/models"
  14. "github.com/crowdsecurity/crowdsec/pkg/types"
  15. "github.com/gin-gonic/gin"
  16. "github.com/go-openapi/strfmt"
  17. log "github.com/sirupsen/logrus"
  18. )
  19. func FormatOneAlert(alert *ent.Alert) *models.Alert {
  20. var outputAlert models.Alert
  21. startAt := alert.StartedAt.String()
  22. StopAt := alert.StoppedAt.String()
  23. machineID := "N/A"
  24. if alert.Edges.Owner != nil {
  25. machineID = alert.Edges.Owner.MachineId
  26. }
  27. outputAlert = models.Alert{
  28. ID: int64(alert.ID),
  29. MachineID: machineID,
  30. CreatedAt: alert.CreatedAt.Format(time.RFC3339),
  31. Scenario: &alert.Scenario,
  32. ScenarioVersion: &alert.ScenarioVersion,
  33. ScenarioHash: &alert.ScenarioHash,
  34. Message: &alert.Message,
  35. EventsCount: &alert.EventsCount,
  36. StartAt: &startAt,
  37. StopAt: &StopAt,
  38. Capacity: &alert.Capacity,
  39. Leakspeed: &alert.LeakSpeed,
  40. Simulated: &alert.Simulated,
  41. Source: &models.Source{
  42. Scope: &alert.SourceScope,
  43. Value: &alert.SourceValue,
  44. IP: alert.SourceIp,
  45. Range: alert.SourceRange,
  46. AsNumber: alert.SourceAsNumber,
  47. AsName: alert.SourceAsName,
  48. Cn: alert.SourceCountry,
  49. Latitude: alert.SourceLatitude,
  50. Longitude: alert.SourceLongitude,
  51. },
  52. }
  53. for _, eventItem := range alert.Edges.Events {
  54. var Metas models.Meta
  55. timestamp := eventItem.Time.String()
  56. if err := json.Unmarshal([]byte(eventItem.Serialized), &Metas); err != nil {
  57. log.Errorf("unable to unmarshall events meta '%s' : %s", eventItem.Serialized, err)
  58. }
  59. outputAlert.Events = append(outputAlert.Events, &models.Event{
  60. Timestamp: &timestamp,
  61. Meta: Metas,
  62. })
  63. }
  64. for _, metaItem := range alert.Edges.Metas {
  65. outputAlert.Meta = append(outputAlert.Meta, &models.MetaItems0{
  66. Key: metaItem.Key,
  67. Value: metaItem.Value,
  68. })
  69. }
  70. for _, decisionItem := range alert.Edges.Decisions {
  71. duration := decisionItem.Until.Sub(time.Now().UTC()).String()
  72. outputAlert.Decisions = append(outputAlert.Decisions, &models.Decision{
  73. Duration: &duration, // transform into time.Time ?
  74. Scenario: &decisionItem.Scenario,
  75. Type: &decisionItem.Type,
  76. Scope: &decisionItem.Scope,
  77. Value: &decisionItem.Value,
  78. Origin: &decisionItem.Origin,
  79. Simulated: outputAlert.Simulated,
  80. ID: int64(decisionItem.ID),
  81. })
  82. }
  83. return &outputAlert
  84. }
  85. // FormatAlerts : Format results from the database to be swagger model compliant
  86. func FormatAlerts(result []*ent.Alert) models.AddAlertsRequest {
  87. var data models.AddAlertsRequest
  88. for _, alertItem := range result {
  89. data = append(data, FormatOneAlert(alertItem))
  90. }
  91. return data
  92. }
  93. func (c *Controller) sendAlertToPluginChannel(alert *models.Alert, profileID uint) {
  94. if c.PluginChannel != nil {
  95. RETRY:
  96. for try := 0; try < 3; try++ {
  97. select {
  98. case c.PluginChannel <- csplugin.ProfileAlert{ProfileID: profileID, Alert: alert}:
  99. log.Debugf("alert sent to Plugin channel")
  100. break RETRY
  101. default:
  102. log.Warningf("Cannot send alert to Plugin channel (try: %d)", try)
  103. time.Sleep(time.Millisecond * 50)
  104. }
  105. }
  106. }
  107. }
  108. func normalizeScope(scope string) string {
  109. switch strings.ToLower(scope) {
  110. case "ip":
  111. return types.Ip
  112. case "range":
  113. return types.Range
  114. case "as":
  115. return types.AS
  116. case "country":
  117. return types.Country
  118. default:
  119. return scope
  120. }
  121. }
  122. // CreateAlert writes the alerts received in the body to the database
  123. func (c *Controller) CreateAlert(gctx *gin.Context) {
  124. var input models.AddAlertsRequest
  125. claims := jwt.ExtractClaims(gctx)
  126. // TBD: use defined rather than hardcoded key to find back owner
  127. machineID := claims["id"].(string)
  128. if err := gctx.ShouldBindJSON(&input); err != nil {
  129. gctx.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
  130. return
  131. }
  132. if err := input.Validate(strfmt.Default); err != nil {
  133. c.HandleDBErrors(gctx, err)
  134. return
  135. }
  136. stopFlush := false
  137. for _, alert := range input {
  138. //normalize scope for alert.Source and decisions
  139. if alert.Source.Scope != nil {
  140. *alert.Source.Scope = normalizeScope(*alert.Source.Scope)
  141. }
  142. for _, decision := range alert.Decisions {
  143. if decision.Scope != nil {
  144. *decision.Scope = normalizeScope(*decision.Scope)
  145. }
  146. }
  147. alert.MachineID = machineID
  148. //if coming from cscli, alert already has decisions
  149. if len(alert.Decisions) != 0 {
  150. for pIdx, profile := range c.Profiles {
  151. _, matched, err := profile.EvaluateProfile(alert)
  152. if err != nil {
  153. profile.Logger.Warningf("error while evaluating profile %s : %v", profile.Cfg.Name, err)
  154. continue
  155. }
  156. if !matched {
  157. continue
  158. }
  159. c.sendAlertToPluginChannel(alert, uint(pIdx))
  160. if profile.Cfg.OnSuccess == "break" {
  161. break
  162. }
  163. }
  164. decision := alert.Decisions[0]
  165. if decision.Origin != nil && *decision.Origin == "cscli-import" {
  166. stopFlush = true
  167. }
  168. continue
  169. }
  170. for pIdx, profile := range c.Profiles {
  171. profileDecisions, matched, err := profile.EvaluateProfile(alert)
  172. forceBreak := false
  173. if err != nil {
  174. switch profile.Cfg.OnError {
  175. case "apply":
  176. profile.Logger.Warningf("applying profile %s despite error: %s", profile.Cfg.Name, err)
  177. matched = true
  178. case "continue":
  179. profile.Logger.Warningf("skipping %s profile due to error: %s", profile.Cfg.Name, err)
  180. case "break":
  181. forceBreak = true
  182. case "ignore":
  183. profile.Logger.Warningf("ignoring error: %s", err)
  184. default:
  185. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  186. return
  187. }
  188. }
  189. if !matched {
  190. continue
  191. }
  192. if len(alert.Decisions) == 0 { // non manual decision
  193. alert.Decisions = append(alert.Decisions, profileDecisions...)
  194. }
  195. profileAlert := *alert
  196. c.sendAlertToPluginChannel(&profileAlert, uint(pIdx))
  197. if profile.Cfg.OnSuccess == "break" || forceBreak {
  198. break
  199. }
  200. }
  201. }
  202. if stopFlush {
  203. c.DBClient.CanFlush = false
  204. }
  205. alerts, err := c.DBClient.CreateAlert(machineID, input)
  206. c.DBClient.CanFlush = true
  207. if err != nil {
  208. c.HandleDBErrors(gctx, err)
  209. return
  210. }
  211. if c.CAPIChan != nil {
  212. select {
  213. case c.CAPIChan <- input:
  214. log.Debug("alert sent to CAPI channel")
  215. default:
  216. log.Warning("Cannot send alert to Central API channel")
  217. }
  218. }
  219. gctx.JSON(http.StatusCreated, alerts)
  220. }
  221. // FindAlerts: returns alerts from the database based on the specified filter
  222. func (c *Controller) FindAlerts(gctx *gin.Context) {
  223. result, err := c.DBClient.QueryAlertWithFilter(gctx.Request.URL.Query())
  224. if err != nil {
  225. c.HandleDBErrors(gctx, err)
  226. return
  227. }
  228. data := FormatAlerts(result)
  229. if gctx.Request.Method == http.MethodHead {
  230. gctx.String(http.StatusOK, "")
  231. return
  232. }
  233. gctx.JSON(http.StatusOK, data)
  234. }
  235. // FindAlertByID returns the alert associated with the ID
  236. func (c *Controller) FindAlertByID(gctx *gin.Context) {
  237. alertIDStr := gctx.Param("alert_id")
  238. alertID, err := strconv.Atoi(alertIDStr)
  239. if err != nil {
  240. gctx.JSON(http.StatusBadRequest, gin.H{"message": "alert_id must be valid integer"})
  241. return
  242. }
  243. result, err := c.DBClient.GetAlertByID(alertID)
  244. if err != nil {
  245. c.HandleDBErrors(gctx, err)
  246. return
  247. }
  248. data := FormatOneAlert(result)
  249. if gctx.Request.Method == http.MethodHead {
  250. gctx.String(http.StatusOK, "")
  251. return
  252. }
  253. gctx.JSON(http.StatusOK, data)
  254. }
  255. // DeleteAlertByID delete the alert associated to the ID
  256. func (c *Controller) DeleteAlertByID(gctx *gin.Context) {
  257. var err error
  258. incomingIP := gctx.ClientIP()
  259. if incomingIP != "127.0.0.1" && incomingIP != "::1" && !networksContainIP(c.TrustedIPs, incomingIP) {
  260. gctx.JSON(http.StatusForbidden, gin.H{"message": fmt.Sprintf("access forbidden from this IP (%s)", incomingIP)})
  261. return
  262. }
  263. decisionIDStr := gctx.Param("alert_id")
  264. decisionID, err := strconv.Atoi(decisionIDStr)
  265. if err != nil {
  266. gctx.JSON(http.StatusBadRequest, gin.H{"message": "alert_id must be valid integer"})
  267. return
  268. }
  269. err = c.DBClient.DeleteAlertByID(decisionID)
  270. if err != nil {
  271. c.HandleDBErrors(gctx, err)
  272. return
  273. }
  274. deleteAlertResp := models.DeleteAlertsResponse{
  275. NbDeleted: "1",
  276. }
  277. gctx.JSON(http.StatusOK, deleteAlertResp)
  278. }
  279. // DeleteAlerts deletes alerts from the database based on the specified filter
  280. func (c *Controller) DeleteAlerts(gctx *gin.Context) {
  281. incomingIP := gctx.ClientIP()
  282. if incomingIP != "127.0.0.1" && incomingIP != "::1" && !networksContainIP(c.TrustedIPs, incomingIP) {
  283. gctx.JSON(http.StatusForbidden, gin.H{"message": fmt.Sprintf("access forbidden from this IP (%s)", incomingIP)})
  284. return
  285. }
  286. var err error
  287. nbDeleted, err := c.DBClient.DeleteAlertWithFilter(gctx.Request.URL.Query())
  288. if err != nil {
  289. c.HandleDBErrors(gctx, err)
  290. return
  291. }
  292. deleteAlertsResp := models.DeleteAlertsResponse{
  293. NbDeleted: strconv.Itoa(nbDeleted),
  294. }
  295. gctx.JSON(http.StatusOK, deleteAlertsResp)
  296. }
  297. func networksContainIP(networks []net.IPNet, ip string) bool {
  298. parsedIP := net.ParseIP(ip)
  299. for _, network := range networks {
  300. if network.Contains(parsedIP) {
  301. return true
  302. }
  303. }
  304. return false
  305. }