alerts.go 7.2 KB

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