alerts.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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/csprofiles"
  10. "github.com/crowdsecurity/crowdsec/pkg/database/ent"
  11. "github.com/crowdsecurity/crowdsec/pkg/models"
  12. "github.com/gin-gonic/gin"
  13. "github.com/go-openapi/strfmt"
  14. log "github.com/sirupsen/logrus"
  15. )
  16. func FormatOneAlert(alert *ent.Alert) *models.Alert {
  17. var outputAlert models.Alert
  18. var machineID string
  19. startAt := alert.StartedAt.String()
  20. StopAt := alert.StoppedAt.String()
  21. if alert.Edges.Owner == nil {
  22. machineID = "N/A"
  23. } else {
  24. machineID = alert.Edges.Owner.MachineId
  25. }
  26. outputAlert = models.Alert{
  27. ID: int64(alert.ID),
  28. MachineID: machineID,
  29. CreatedAt: alert.CreatedAt.Format(time.RFC3339),
  30. Scenario: &alert.Scenario,
  31. ScenarioVersion: &alert.ScenarioVersion,
  32. ScenarioHash: &alert.ScenarioHash,
  33. Message: &alert.Message,
  34. EventsCount: &alert.EventsCount,
  35. StartAt: &startAt,
  36. StopAt: &StopAt,
  37. Capacity: &alert.Capacity,
  38. Leakspeed: &alert.LeakSpeed,
  39. Simulated: &alert.Simulated,
  40. Source: &models.Source{
  41. Scope: &alert.SourceScope,
  42. Value: &alert.SourceValue,
  43. IP: alert.SourceIp,
  44. Range: alert.SourceRange,
  45. AsNumber: alert.SourceAsNumber,
  46. AsName: alert.SourceAsName,
  47. Cn: alert.SourceCountry,
  48. Latitude: alert.SourceLatitude,
  49. Longitude: alert.SourceLongitude,
  50. },
  51. }
  52. for _, eventItem := range alert.Edges.Events {
  53. var Metas models.Meta
  54. timestamp := eventItem.Time.String()
  55. if err := json.Unmarshal([]byte(eventItem.Serialized), &Metas); err != nil {
  56. log.Errorf("unable to unmarshall events meta '%s' : %s", eventItem.Serialized, err)
  57. }
  58. outputAlert.Events = append(outputAlert.Events, &models.Event{
  59. Timestamp: &timestamp,
  60. Meta: Metas,
  61. })
  62. }
  63. for _, metaItem := range alert.Edges.Metas {
  64. outputAlert.Meta = append(outputAlert.Meta, &models.MetaItems0{
  65. Key: metaItem.Key,
  66. Value: metaItem.Value,
  67. })
  68. }
  69. for _, decisionItem := range alert.Edges.Decisions {
  70. duration := decisionItem.Until.Sub(time.Now()).String()
  71. outputAlert.Decisions = append(outputAlert.Decisions, &models.Decision{
  72. Duration: &duration, // transform into time.Time ?
  73. Scenario: &decisionItem.Scenario,
  74. Type: &decisionItem.Type,
  75. Scope: &decisionItem.Scope,
  76. Value: &decisionItem.Value,
  77. Origin: &decisionItem.Origin,
  78. Simulated: outputAlert.Simulated,
  79. ID: int64(decisionItem.ID),
  80. })
  81. }
  82. return &outputAlert
  83. }
  84. // FormatAlerts : Format results from the database to be swagger model compliant
  85. func FormatAlerts(result []*ent.Alert) models.AddAlertsRequest {
  86. var data models.AddAlertsRequest
  87. for _, alertItem := range result {
  88. data = append(data, FormatOneAlert(alertItem))
  89. }
  90. return data
  91. }
  92. // CreateAlert : write received alerts in body to the database
  93. func (c *Controller) CreateAlert(gctx *gin.Context) {
  94. var input models.AddAlertsRequest
  95. claims := jwt.ExtractClaims(gctx)
  96. /*TBD : use defines rather than hardcoded key to find back owner*/
  97. machineID := claims["id"].(string)
  98. if err := gctx.ShouldBindJSON(&input); err != nil {
  99. gctx.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
  100. return
  101. }
  102. if err := input.Validate(strfmt.Default); err != nil {
  103. c.HandleDBErrors(gctx, err)
  104. return
  105. }
  106. for _, alert := range input {
  107. if len(alert.Decisions) == 0 {
  108. decisions, err := csprofiles.EvaluateProfiles(c.Profiles, alert)
  109. if err != nil {
  110. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  111. return
  112. }
  113. alert.Decisions = decisions
  114. }
  115. }
  116. alerts, err := c.DBClient.CreateAlert(machineID, input)
  117. if err != nil {
  118. c.HandleDBErrors(gctx, err)
  119. return
  120. }
  121. for _, alert := range input {
  122. alert.MachineID = machineID
  123. }
  124. select {
  125. case c.CAPIChan <- input:
  126. log.Debugf("alert send to CAPI channel")
  127. default:
  128. log.Warningf("Cannot send alert to Central API channel")
  129. }
  130. gctx.JSON(http.StatusCreated, alerts)
  131. return
  132. }
  133. // FindAlerts : return alerts from database based on the specified filter
  134. func (c *Controller) FindAlerts(gctx *gin.Context) {
  135. result, err := c.DBClient.QueryAlertWithFilter(gctx.Request.URL.Query())
  136. if err != nil {
  137. c.HandleDBErrors(gctx, err)
  138. return
  139. }
  140. data := FormatAlerts(result)
  141. if gctx.Request.Method == "HEAD" {
  142. gctx.String(http.StatusOK, "")
  143. return
  144. }
  145. gctx.JSON(http.StatusOK, data)
  146. return
  147. }
  148. // FindAlertByID return the alert assiocated to the ID
  149. func (c *Controller) FindAlertByID(gctx *gin.Context) {
  150. alertIDStr := gctx.Param("alert_id")
  151. alertID, err := strconv.Atoi(alertIDStr)
  152. if err != nil {
  153. gctx.JSON(http.StatusBadRequest, gin.H{"message": "alert_id must be valid integer"})
  154. return
  155. }
  156. result, err := c.DBClient.GetAlertByID(alertID)
  157. if err != nil {
  158. c.HandleDBErrors(gctx, err)
  159. return
  160. }
  161. data := FormatOneAlert(result)
  162. if gctx.Request.Method == "HEAD" {
  163. gctx.String(http.StatusOK, "")
  164. return
  165. }
  166. gctx.JSON(http.StatusOK, data)
  167. return
  168. }
  169. // DeleteAlerts : delete alerts from database based on the specified filter
  170. func (c *Controller) DeleteAlerts(gctx *gin.Context) {
  171. if gctx.ClientIP() != "127.0.0.1" && gctx.ClientIP() != "::1" {
  172. gctx.JSON(http.StatusForbidden, gin.H{"message": fmt.Sprintf("access forbidden from this IP (%s)", gctx.ClientIP())})
  173. return
  174. }
  175. var err error
  176. nbDeleted, err := c.DBClient.DeleteAlertWithFilter(gctx.Request.URL.Query())
  177. if err != nil {
  178. c.HandleDBErrors(gctx, err)
  179. }
  180. deleteAlertsResp := models.DeleteAlertsResponse{
  181. NbDeleted: strconv.Itoa(nbDeleted),
  182. }
  183. gctx.JSON(http.StatusOK, deleteAlertsResp)
  184. return
  185. }