alerts.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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/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. startAt := alert.StartedAt.String()
  20. StopAt := alert.StoppedAt.String()
  21. machineID := "N/A"
  22. if alert.Edges.Owner != nil {
  23. machineID = alert.Edges.Owner.MachineId
  24. }
  25. outputAlert = models.Alert{
  26. ID: int64(alert.ID),
  27. MachineID: machineID,
  28. CreatedAt: alert.CreatedAt.Format(time.RFC3339),
  29. Scenario: &alert.Scenario,
  30. ScenarioVersion: &alert.ScenarioVersion,
  31. ScenarioHash: &alert.ScenarioHash,
  32. Message: &alert.Message,
  33. EventsCount: &alert.EventsCount,
  34. StartAt: &startAt,
  35. StopAt: &StopAt,
  36. Capacity: &alert.Capacity,
  37. Leakspeed: &alert.LeakSpeed,
  38. Simulated: &alert.Simulated,
  39. Source: &models.Source{
  40. Scope: &alert.SourceScope,
  41. Value: &alert.SourceValue,
  42. IP: alert.SourceIp,
  43. Range: alert.SourceRange,
  44. AsNumber: alert.SourceAsNumber,
  45. AsName: alert.SourceAsName,
  46. Cn: alert.SourceCountry,
  47. Latitude: alert.SourceLatitude,
  48. Longitude: alert.SourceLongitude,
  49. },
  50. }
  51. for _, eventItem := range alert.Edges.Events {
  52. var Metas models.Meta
  53. timestamp := eventItem.Time.String()
  54. if err := json.Unmarshal([]byte(eventItem.Serialized), &Metas); err != nil {
  55. log.Errorf("unable to unmarshall events meta '%s' : %s", eventItem.Serialized, err)
  56. }
  57. outputAlert.Events = append(outputAlert.Events, &models.Event{
  58. Timestamp: &timestamp,
  59. Meta: Metas,
  60. })
  61. }
  62. for _, metaItem := range alert.Edges.Metas {
  63. outputAlert.Meta = append(outputAlert.Meta, &models.MetaItems0{
  64. Key: metaItem.Key,
  65. Value: metaItem.Value,
  66. })
  67. }
  68. for _, decisionItem := range alert.Edges.Decisions {
  69. duration := decisionItem.Until.Sub(time.Now().UTC()).String()
  70. outputAlert.Decisions = append(outputAlert.Decisions, &models.Decision{
  71. Duration: &duration, // transform into time.Time ?
  72. Scenario: &decisionItem.Scenario,
  73. Type: &decisionItem.Type,
  74. Scope: &decisionItem.Scope,
  75. Value: &decisionItem.Value,
  76. Origin: &decisionItem.Origin,
  77. Simulated: outputAlert.Simulated,
  78. ID: int64(decisionItem.ID),
  79. })
  80. }
  81. return &outputAlert
  82. }
  83. // FormatAlerts : Format results from the database to be swagger model compliant
  84. func FormatAlerts(result []*ent.Alert) models.AddAlertsRequest {
  85. var data models.AddAlertsRequest
  86. for _, alertItem := range result {
  87. data = append(data, FormatOneAlert(alertItem))
  88. }
  89. return data
  90. }
  91. func (c *Controller) sendAlertToPluginChannel(alert *models.Alert, profileID uint) {
  92. if c.PluginChannel != nil {
  93. RETRY:
  94. for try := 0; try < 3; try++ {
  95. select {
  96. case c.PluginChannel <- csplugin.ProfileAlert{ProfileID: profileID, Alert: alert}:
  97. log.Debugf("alert sent to Plugin channel")
  98. break RETRY
  99. default:
  100. log.Warningf("Cannot send alert to Plugin channel (try: %d)", try)
  101. time.Sleep(time.Millisecond * 50)
  102. }
  103. }
  104. }
  105. }
  106. // CreateAlert writes the alerts received in the body to the database
  107. func (c *Controller) CreateAlert(gctx *gin.Context) {
  108. var input models.AddAlertsRequest
  109. claims := jwt.ExtractClaims(gctx)
  110. // TBD: use defined rather than hardcoded key to find back owner
  111. machineID := claims["id"].(string)
  112. if err := gctx.ShouldBindJSON(&input); err != nil {
  113. gctx.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
  114. return
  115. }
  116. if err := input.Validate(strfmt.Default); err != nil {
  117. c.HandleDBErrors(gctx, err)
  118. return
  119. }
  120. stopFlush := false
  121. for _, alert := range input {
  122. alert.MachineID = machineID
  123. if len(alert.Decisions) != 0 {
  124. for pIdx, profile := range c.Profiles {
  125. _, matched, err := profile.EvaluateProfile(alert)
  126. if err != nil {
  127. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  128. return
  129. }
  130. if !matched {
  131. continue
  132. }
  133. c.sendAlertToPluginChannel(alert, uint(pIdx))
  134. if profile.Cfg.OnSuccess == "break" {
  135. break
  136. }
  137. }
  138. decision := alert.Decisions[0]
  139. if decision.Origin != nil && *decision.Origin == "cscli-import" {
  140. stopFlush = true
  141. }
  142. continue
  143. }
  144. for pIdx, profile := range c.Profiles {
  145. profileDecisions, matched, err := profile.EvaluateProfile(alert)
  146. if err != nil {
  147. gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
  148. return
  149. }
  150. if !matched {
  151. continue
  152. }
  153. if len(alert.Decisions) == 0 { // non manual decision
  154. alert.Decisions = append(alert.Decisions, profileDecisions...)
  155. }
  156. profileAlert := *alert
  157. c.sendAlertToPluginChannel(&profileAlert, uint(pIdx))
  158. if profile.Cfg.OnSuccess == "break" {
  159. break
  160. }
  161. }
  162. }
  163. if stopFlush {
  164. c.DBClient.CanFlush = false
  165. }
  166. alerts, err := c.DBClient.CreateAlert(machineID, input)
  167. c.DBClient.CanFlush = true
  168. if err != nil {
  169. c.HandleDBErrors(gctx, err)
  170. return
  171. }
  172. if c.CAPIChan != nil {
  173. select {
  174. case c.CAPIChan <- input:
  175. log.Debug("alert sent to CAPI channel")
  176. default:
  177. log.Warning("Cannot send alert to Central API channel")
  178. }
  179. }
  180. gctx.JSON(http.StatusCreated, alerts)
  181. }
  182. // FindAlerts: returns alerts from the database based on the specified filter
  183. func (c *Controller) FindAlerts(gctx *gin.Context) {
  184. result, err := c.DBClient.QueryAlertWithFilter(gctx.Request.URL.Query())
  185. if err != nil {
  186. c.HandleDBErrors(gctx, err)
  187. return
  188. }
  189. data := FormatAlerts(result)
  190. if gctx.Request.Method == http.MethodHead {
  191. gctx.String(http.StatusOK, "")
  192. return
  193. }
  194. gctx.JSON(http.StatusOK, data)
  195. }
  196. // FindAlertByID returns the alert associated with the ID
  197. func (c *Controller) FindAlertByID(gctx *gin.Context) {
  198. alertIDStr := gctx.Param("alert_id")
  199. alertID, err := strconv.Atoi(alertIDStr)
  200. if err != nil {
  201. gctx.JSON(http.StatusBadRequest, gin.H{"message": "alert_id must be valid integer"})
  202. return
  203. }
  204. result, err := c.DBClient.GetAlertByID(alertID)
  205. if err != nil {
  206. c.HandleDBErrors(gctx, err)
  207. return
  208. }
  209. data := FormatOneAlert(result)
  210. if gctx.Request.Method == http.MethodHead {
  211. gctx.String(http.StatusOK, "")
  212. return
  213. }
  214. gctx.JSON(http.StatusOK, data)
  215. }
  216. // DeleteAlerts deletes alerts from the database based on the specified filter
  217. func (c *Controller) DeleteAlerts(gctx *gin.Context) {
  218. incomingIP := gctx.ClientIP()
  219. if incomingIP != "127.0.0.1" && incomingIP != "::1" && !networksContainIP(c.TrustedIPs, incomingIP) {
  220. gctx.JSON(http.StatusForbidden, gin.H{"message": fmt.Sprintf("access forbidden from this IP (%s)", incomingIP)})
  221. return
  222. }
  223. var err error
  224. nbDeleted, err := c.DBClient.DeleteAlertWithFilter(gctx.Request.URL.Query())
  225. if err != nil {
  226. c.HandleDBErrors(gctx, err)
  227. return
  228. }
  229. deleteAlertsResp := models.DeleteAlertsResponse{
  230. NbDeleted: strconv.Itoa(nbDeleted),
  231. }
  232. gctx.JSON(http.StatusOK, deleteAlertsResp)
  233. }
  234. func networksContainIP(networks []net.IPNet, ip string) bool {
  235. parsedIP := net.ParseIP(ip)
  236. for _, network := range networks {
  237. if network.Contains(parsedIP) {
  238. return true
  239. }
  240. }
  241. return false
  242. }