alerts.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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()).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. for _, alert := range input {
  118. if len(alert.Decisions) != 0 {
  119. for pIdx, profile := range c.Profiles {
  120. _, matched, err := csprofiles.EvaluateProfile(profile, alert)
  121. if err != nil {
  122. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  123. return
  124. }
  125. if !matched {
  126. continue
  127. }
  128. c.sendAlertToPluginChannel(alert, uint(pIdx))
  129. if profile.OnSuccess == "break" {
  130. break
  131. }
  132. }
  133. continue
  134. }
  135. for pIdx, profile := range c.Profiles {
  136. profileDecisions, matched, err := csprofiles.EvaluateProfile(profile, alert)
  137. if err != nil {
  138. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  139. return
  140. }
  141. if !matched {
  142. continue
  143. }
  144. alert.Decisions = append(alert.Decisions, profileDecisions...)
  145. profileAlert := *alert
  146. c.sendAlertToPluginChannel(&profileAlert, uint(pIdx))
  147. if profile.OnSuccess == "break" {
  148. break
  149. }
  150. }
  151. }
  152. alerts, err := c.DBClient.CreateAlert(machineID, input)
  153. if err != nil {
  154. c.HandleDBErrors(gctx, err)
  155. return
  156. }
  157. for _, alert := range input {
  158. alert.MachineID = machineID
  159. }
  160. if c.CAPIChan != nil {
  161. select {
  162. case c.CAPIChan <- input:
  163. log.Debug("alert sent to CAPI channel")
  164. default:
  165. log.Warning("Cannot send alert to Central API channel")
  166. }
  167. }
  168. gctx.JSON(http.StatusCreated, alerts)
  169. return
  170. }
  171. // FindAlerts : return alerts from database based on the specified filter
  172. func (c *Controller) FindAlerts(gctx *gin.Context) {
  173. result, err := c.DBClient.QueryAlertWithFilter(gctx.Request.URL.Query())
  174. if err != nil {
  175. c.HandleDBErrors(gctx, err)
  176. return
  177. }
  178. data := FormatAlerts(result)
  179. if gctx.Request.Method == "HEAD" {
  180. gctx.String(http.StatusOK, "")
  181. return
  182. }
  183. gctx.JSON(http.StatusOK, data)
  184. return
  185. }
  186. // FindAlertByID return the alert assiocated to the ID
  187. func (c *Controller) FindAlertByID(gctx *gin.Context) {
  188. alertIDStr := gctx.Param("alert_id")
  189. alertID, err := strconv.Atoi(alertIDStr)
  190. if err != nil {
  191. gctx.JSON(http.StatusBadRequest, gin.H{"message": "alert_id must be valid integer"})
  192. return
  193. }
  194. result, err := c.DBClient.GetAlertByID(alertID)
  195. if err != nil {
  196. c.HandleDBErrors(gctx, err)
  197. return
  198. }
  199. data := FormatOneAlert(result)
  200. if gctx.Request.Method == "HEAD" {
  201. gctx.String(http.StatusOK, "")
  202. return
  203. }
  204. gctx.JSON(http.StatusOK, data)
  205. return
  206. }
  207. // DeleteAlerts : delete alerts from database based on the specified filter
  208. func (c *Controller) DeleteAlerts(gctx *gin.Context) {
  209. if gctx.ClientIP() != "127.0.0.1" && gctx.ClientIP() != "::1" {
  210. gctx.JSON(http.StatusForbidden, gin.H{"message": fmt.Sprintf("access forbidden from this IP (%s)", gctx.ClientIP())})
  211. return
  212. }
  213. var err error
  214. nbDeleted, err := c.DBClient.DeleteAlertWithFilter(gctx.Request.URL.Query())
  215. if err != nil {
  216. c.HandleDBErrors(gctx, err)
  217. return
  218. }
  219. deleteAlertsResp := models.DeleteAlertsResponse{
  220. NbDeleted: strconv.Itoa(nbDeleted),
  221. }
  222. gctx.JSON(http.StatusOK, deleteAlertsResp)
  223. return
  224. }