-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcoraza.go
54 lines (49 loc) · 1.27 KB
/
coraza.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package coraza
import (
"io"
"net/http"
"github.com/corazawaf/coraza/v2"
"github.com/gin-gonic/gin"
)
func Coraza(waf *coraza.Waf) gin.HandlerFunc {
return func(c *gin.Context) {
tx := waf.NewTransaction()
defer func(){
tx.ProcessLogging()
if err := tx.Clean(); err != nil {
// do some error management
}
}()
if it, err := tx.ProcessRequest(c.Request); err != nil {
renderError(c, "Coraza: Failed to process request")
return
} else if it != nil {
forbidden(c, tx)
return
}
oldwriter := c.Writer
c.Writer = &responseWriter{
tx: tx,
ResponseWriter: oldwriter,
}
c.Next()
if it, err := tx.ProcessResponseBody(); err != nil {
renderError(c, "Coraza: Failed to process response body")
} else if it != nil {
forbidden(c, tx)
}
// we dump the body to the writer
reader, err := tx.ResponseBodyBuffer.Reader()
if err != nil {
renderError(c, "Coraza: Failed to get response body reader")
return
}
io.Copy(oldwriter, reader)
}
}
func renderError(c *gin.Context, content string) {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "msg": content})
}
func forbidden(c *gin.Context, tx *coraza.Transaction) {
c.JSON(http.StatusForbidden, gin.H{"status": "interrupted", "transaction": tx.ID})
}