alerts.go 7.1 KB

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