alerts.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. package v1
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "time"
  8. jwt "github.com/appleboy/gin-jwt/v2"
  9. "github.com/crowdsecurity/crowdsec/pkg/csplugin"
  10. "github.com/crowdsecurity/crowdsec/pkg/csprofiles"
  11. "github.com/crowdsecurity/crowdsec/pkg/database/ent"
  12. "github.com/crowdsecurity/crowdsec/pkg/models"
  13. "github.com/gin-gonic/gin"
  14. "github.com/go-openapi/strfmt"
  15. log "github.com/sirupsen/logrus"
  16. )
  17. func FormatOneAlert(alert *ent.Alert) *models.Alert {
  18. var outputAlert models.Alert
  19. var machineID string
  20. startAt := alert.StartedAt.String()
  21. StopAt := alert.StoppedAt.String()
  22. if alert.Edges.Owner == nil {
  23. machineID = "N/A"
  24. } else {
  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. select {
  96. case c.PluginChannel <- csplugin.ProfileAlert{ProfileID: uint(profileID), Alert: alert}:
  97. log.Debugf("alert sent to Plugin channel")
  98. default:
  99. log.Warningf("Cannot send alert to Plugin channel")
  100. }
  101. }
  102. }
  103. // CreateAlert : write received alerts in body to the database
  104. func (c *Controller) CreateAlert(gctx *gin.Context) {
  105. var input models.AddAlertsRequest
  106. claims := jwt.ExtractClaims(gctx)
  107. /*TBD : use defines rather than hardcoded key to find back owner*/
  108. machineID := claims["id"].(string)
  109. if err := gctx.ShouldBindJSON(&input); err != nil {
  110. gctx.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
  111. return
  112. }
  113. if err := input.Validate(strfmt.Default); err != nil {
  114. c.HandleDBErrors(gctx, err)
  115. return
  116. }
  117. stopFlush := false
  118. for _, alert := range input {
  119. alert.MachineID = machineID
  120. if len(alert.Decisions) != 0 {
  121. for pIdx, profile := range c.Profiles {
  122. _, matched, err := csprofiles.EvaluateProfile(profile, alert)
  123. if err != nil {
  124. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  125. return
  126. }
  127. if !matched {
  128. continue
  129. }
  130. c.sendAlertToPluginChannel(alert, uint(pIdx))
  131. if profile.OnSuccess == "break" {
  132. break
  133. }
  134. }
  135. decision := alert.Decisions[0]
  136. if decision.Origin != nil && *decision.Origin == "cscli-import" {
  137. stopFlush = true
  138. }
  139. continue
  140. }
  141. for pIdx, profile := range c.Profiles {
  142. profileDecisions, matched, err := csprofiles.EvaluateProfile(profile, alert)
  143. if err != nil {
  144. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  145. return
  146. }
  147. if !matched {
  148. continue
  149. }
  150. if len(alert.Decisions) == 0 { // non manual decision
  151. alert.Decisions = append(alert.Decisions, profileDecisions...)
  152. }
  153. profileAlert := *alert
  154. c.sendAlertToPluginChannel(&profileAlert, uint(pIdx))
  155. if profile.OnSuccess == "break" {
  156. break
  157. }
  158. }
  159. }
  160. if stopFlush {
  161. c.DBClient.CanFlush = false
  162. }
  163. alerts, err := c.DBClient.CreateAlert(machineID, input)
  164. c.DBClient.CanFlush = true
  165. if err != nil {
  166. c.HandleDBErrors(gctx, err)
  167. return
  168. }
  169. if c.CAPIChan != nil {
  170. select {
  171. case c.CAPIChan <- input:
  172. log.Debug("alert sent to CAPI channel")
  173. default:
  174. log.Warning("Cannot send alert to Central API channel")
  175. }
  176. }
  177. gctx.JSON(http.StatusCreated, alerts)
  178. return
  179. }
  180. // FindAlerts : return alerts from database based on the specified filter
  181. func (c *Controller) FindAlerts(gctx *gin.Context) {
  182. result, err := c.DBClient.QueryAlertWithFilter(gctx.Request.URL.Query())
  183. if err != nil {
  184. c.HandleDBErrors(gctx, err)
  185. return
  186. }
  187. data := FormatAlerts(result)
  188. if gctx.Request.Method == "HEAD" {
  189. gctx.String(http.StatusOK, "")
  190. return
  191. }
  192. gctx.JSON(http.StatusOK, data)
  193. return
  194. }
  195. // FindAlertByID return the alert assiocated to the ID
  196. func (c *Controller) FindAlertByID(gctx *gin.Context) {
  197. alertIDStr := gctx.Param("alert_id")
  198. alertID, err := strconv.Atoi(alertIDStr)
  199. if err != nil {
  200. gctx.JSON(http.StatusBadRequest, gin.H{"message": "alert_id must be valid integer"})
  201. return
  202. }
  203. result, err := c.DBClient.GetAlertByID(alertID)
  204. if err != nil {
  205. c.HandleDBErrors(gctx, err)
  206. return
  207. }
  208. data := FormatOneAlert(result)
  209. if gctx.Request.Method == "HEAD" {
  210. gctx.String(http.StatusOK, "")
  211. return
  212. }
  213. gctx.JSON(http.StatusOK, data)
  214. return
  215. }
  216. // DeleteAlerts : delete alerts from database based on the specified filter
  217. func (c *Controller) DeleteAlerts(gctx *gin.Context) {
  218. if gctx.ClientIP() != "127.0.0.1" && gctx.ClientIP() != "::1" {
  219. gctx.JSON(http.StatusForbidden, gin.H{"message": fmt.Sprintf("access forbidden from this IP (%s)", gctx.ClientIP())})
  220. return
  221. }
  222. var err error
  223. nbDeleted, err := c.DBClient.DeleteAlertWithFilter(gctx.Request.URL.Query())
  224. if err != nil {
  225. c.HandleDBErrors(gctx, err)
  226. return
  227. }
  228. deleteAlertsResp := models.DeleteAlertsResponse{
  229. NbDeleted: strconv.Itoa(nbDeleted),
  230. }
  231. gctx.JSON(http.StatusOK, deleteAlertsResp)
  232. return
  233. }