alerts.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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/crowdsecurity/crowdsec/pkg/types"
  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. StartIP: decisionItem.StartIP,
  77. EndIP: decisionItem.EndIP,
  78. Scope: &decisionItem.Scope,
  79. Value: &decisionItem.Value,
  80. Origin: &decisionItem.Origin,
  81. Simulated: outputAlert.Simulated,
  82. ID: int64(decisionItem.ID),
  83. })
  84. }
  85. return &outputAlert
  86. }
  87. // FormatAlerts : Format results from the database to be swagger model compliant
  88. func FormatAlerts(result []*ent.Alert) models.AddAlertsRequest {
  89. var data models.AddAlertsRequest
  90. for _, alertItem := range result {
  91. data = append(data, FormatOneAlert(alertItem))
  92. }
  93. return data
  94. }
  95. // CreateAlert : write received alerts in body to the database
  96. func (c *Controller) CreateAlert(gctx *gin.Context) {
  97. defer types.CatchPanic("crowdsec/controllersV1/CreateAlert")
  98. var input models.AddAlertsRequest
  99. claims := jwt.ExtractClaims(gctx)
  100. /*TBD : use defines rather than hardcoded key to find back owner*/
  101. machineID := claims["id"].(string)
  102. if err := gctx.ShouldBindJSON(&input); err != nil {
  103. gctx.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
  104. return
  105. }
  106. if err := input.Validate(strfmt.Default); err != nil {
  107. c.HandleDBErrors(gctx, err)
  108. return
  109. }
  110. for _, alert := range input {
  111. if len(alert.Decisions) > 0 {
  112. log.Debugf("alert %s already has decisions, don't apply profiles", *alert.Message)
  113. } else {
  114. decisions, err := csprofiles.EvaluateProfiles(c.Profiles, alert)
  115. if err != nil {
  116. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  117. return
  118. }
  119. alert.Decisions = decisions
  120. }
  121. }
  122. alerts, err := c.DBClient.CreateAlert(machineID, input)
  123. if err != nil {
  124. c.HandleDBErrors(gctx, err)
  125. return
  126. }
  127. for _, alert := range input {
  128. alert.MachineID = machineID
  129. }
  130. select {
  131. case c.CAPIChan <- input:
  132. log.Debugf("alert send to CAPI channel")
  133. default:
  134. log.Warningf("Cannot send alert to Central API channel")
  135. }
  136. gctx.JSON(http.StatusCreated, alerts)
  137. return
  138. }
  139. // FindAlerts : return alerts from database based on the specified filter
  140. func (c *Controller) FindAlerts(gctx *gin.Context) {
  141. defer types.CatchPanic("crowdsec/controllersV1/FindAlerts")
  142. result, err := c.DBClient.QueryAlertWithFilter(gctx.Request.URL.Query())
  143. if err != nil {
  144. c.HandleDBErrors(gctx, err)
  145. return
  146. }
  147. data := FormatAlerts(result)
  148. if gctx.Request.Method == "HEAD" {
  149. gctx.String(http.StatusOK, "")
  150. return
  151. }
  152. gctx.JSON(http.StatusOK, data)
  153. return
  154. }
  155. // FindAlertByID return the alert assiocated to the ID
  156. func (c *Controller) FindAlertByID(gctx *gin.Context) {
  157. defer types.CatchPanic("crowdsec/controllersV1/FindAlertByID")
  158. alertIDStr := gctx.Param("alert_id")
  159. alertID, err := strconv.Atoi(alertIDStr)
  160. if err != nil {
  161. gctx.JSON(http.StatusBadRequest, gin.H{"message": "alert_id must be valid integer"})
  162. return
  163. }
  164. result, err := c.DBClient.GetAlertByID(alertID)
  165. if err != nil {
  166. c.HandleDBErrors(gctx, err)
  167. return
  168. }
  169. data := FormatOneAlert(result)
  170. if gctx.Request.Method == "HEAD" {
  171. gctx.String(http.StatusOK, "")
  172. return
  173. }
  174. gctx.JSON(http.StatusOK, data)
  175. return
  176. }
  177. // DeleteAlerts : delete alerts from database based on the specified filter
  178. func (c *Controller) DeleteAlerts(gctx *gin.Context) {
  179. defer types.CatchPanic("crowdsec/controllersV1/DeleteAlerts")
  180. if gctx.ClientIP() != "127.0.0.1" && gctx.ClientIP() != "::1" {
  181. gctx.JSON(http.StatusForbidden, gin.H{"message": fmt.Sprintf("access forbidden from this IP (%s)", gctx.ClientIP())})
  182. return
  183. }
  184. var err error
  185. nbDeleted, err := c.DBClient.DeleteAlertWithFilter(gctx.Request.URL.Query())
  186. if err != nil {
  187. c.HandleDBErrors(gctx, err)
  188. }
  189. deleteAlertsResp := models.DeleteAlertsResponse{
  190. NbDeleted: strconv.Itoa(nbDeleted),
  191. }
  192. gctx.JSON(http.StatusOK, deleteAlertsResp)
  193. return
  194. }