Files

97 lines
2.9 KiB
Go

package middleware
import (
"errors"
"net/http"
"runtime/debug"
"time"
"github.com/gin-gonic/gin"
"github.com/phishingclub/phishingclub/server"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// phishingLogPath is the path the phishing server logs for a request. A
// route with parameters is logged as its pattern, since the remote browser
// routes carry the campaign recipient id in the path. Any other path is
// logged as it was requested, with a lure code at its end left out.
func phishingLogPath(c *gin.Context, lp *server.LogPath) string {
if route := c.FullPath(); route != "" {
return route
}
return lp.String()
}
// PhishingAccessLog writes one line per request to the phishing server. The
// query string or the path holds the campaign recipient id or lure code, and
// an anonymous campaign stores neither the IP nor the user agent of a person,
// so the line has none of them. Query, IP and user agent are added only
// while the log level is debug.
func PhishingAccessLog(logger *zap.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
query := c.Request.URL.RawQuery
req, lp := server.WithLogPath(c.Request)
c.Request = req
c.Next()
end := time.Now()
latency := end.Sub(start)
path := phishingLogPath(c, lp)
fields := []zapcore.Field{
zap.Int("status", c.Writer.Status()),
zap.String("method", c.Request.Method),
zap.String("path", path),
zap.Duration("latency", latency),
zap.String("time", end.UTC().Format(time.RFC3339)),
zap.String("host", c.Request.Host),
zap.String("server", "phishing"),
}
if logger.Core().Enabled(zapcore.DebugLevel) {
fields = append(fields,
zap.String("query", query),
zap.String("ip", c.ClientIP()),
zap.String("user-agent", c.Request.UserAgent()),
)
}
if len(c.Errors) > 0 {
// a failed write holds the address of the visitor
for _, e := range c.Errors {
logger.Error(server.ErrorForLog(e.Err), fields...)
}
return
}
logger.Info(path, fields...)
}
}
// PhishingRecovery answers a panic in a phishing server handler with 500 and
// logs it with the stack. The request is logged as method, host and path
// only, for the same reason as in PhishingAccessLog. A handler that panics
// with http.ErrAbortHandler cuts its response on purpose, so that panic is
// raised again.
func PhishingRecovery(logger *zap.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
req, lp := server.WithLogPath(c.Request)
c.Request = req
defer func() {
err := recover()
if err == nil {
return
}
if e, ok := err.(error); ok && errors.Is(e, http.ErrAbortHandler) {
panic(http.ErrAbortHandler)
}
logger.Error("panic in phishing server handler",
zap.Any("error", err),
zap.String("method", c.Request.Method),
zap.String("host", c.Request.Host),
zap.String("path", phishingLogPath(c, lp)),
zap.String("stack", string(debug.Stack())),
)
c.AbortWithStatus(http.StatusInternalServerError)
}()
c.Next()
}
}