Compare commits
1 Commits
7f4c40caca
...
19e7557e88
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
19e7557e88 |
34
README.md
34
README.md
@@ -725,7 +725,7 @@ webhooker/
|
|||||||
│ ├── logger/
|
│ ├── logger/
|
||||||
│ │ └── logger.go # slog setup with TTY detection
|
│ │ └── logger.go # slog setup with TTY detection
|
||||||
│ ├── middleware/
|
│ ├── middleware/
|
||||||
│ │ ├── middleware.go # Logging, CORS, Auth, Metrics, MetricsAuth, SecurityHeaders, MaxBodySize
|
│ │ ├── middleware.go # Logging, CORS, Auth, Metrics, MetricsAuth
|
||||||
│ │ ├── csrf.go # CSRF protection middleware (session-based tokens)
|
│ │ ├── csrf.go # CSRF protection middleware (session-based tokens)
|
||||||
│ │ └── ratelimit.go # Per-IP rate limiting middleware (login endpoint)
|
│ │ └── ratelimit.go # Per-IP rate limiting middleware (login endpoint)
|
||||||
│ ├── server/
|
│ ├── server/
|
||||||
@@ -778,21 +778,14 @@ Applied to all routes in this order:
|
|||||||
|
|
||||||
1. **Recoverer** — Panic recovery (chi built-in)
|
1. **Recoverer** — Panic recovery (chi built-in)
|
||||||
2. **RequestID** — Generate unique request IDs (chi built-in)
|
2. **RequestID** — Generate unique request IDs (chi built-in)
|
||||||
3. **SecurityHeaders** — Production security headers on every response
|
3. **Logging** — Structured request logging (method, URL, status,
|
||||||
(HSTS, X-Content-Type-Options, X-Frame-Options, CSP, Referrer-Policy,
|
|
||||||
Permissions-Policy)
|
|
||||||
4. **Logging** — Structured request logging (method, URL, status,
|
|
||||||
latency, remote IP, user agent, request ID)
|
latency, remote IP, user agent, request ID)
|
||||||
5. **Metrics** — Prometheus HTTP metrics (if `METRICS_USERNAME` is set)
|
4. **Metrics** — Prometheus HTTP metrics (if `METRICS_USERNAME` is set)
|
||||||
6. **CORS** — Cross-origin resource sharing headers
|
5. **CORS** — Cross-origin resource sharing headers
|
||||||
7. **Timeout** — 60-second request timeout
|
6. **Timeout** — 60-second request timeout
|
||||||
8. **Sentry** — Error reporting to Sentry (if `SENTRY_DSN` is set;
|
7. **Sentry** — Error reporting to Sentry (if `SENTRY_DSN` is set;
|
||||||
configured with `Repanic: true` so panics still reach Recoverer)
|
configured with `Repanic: true` so panics still reach Recoverer)
|
||||||
|
|
||||||
Additionally, form endpoints (`/pages`, `/sources`, `/source/*`) apply a
|
|
||||||
**MaxBodySize** middleware that limits POST/PUT/PATCH request bodies to
|
|
||||||
1 MB using `http.MaxBytesReader`, preventing oversized form submissions.
|
|
||||||
|
|
||||||
### Authentication
|
### Authentication
|
||||||
|
|
||||||
- **Web UI:** Cookie-based sessions using gorilla/sessions with
|
- **Web UI:** Cookie-based sessions using gorilla/sessions with
|
||||||
@@ -807,13 +800,8 @@ Additionally, form endpoints (`/pages`, `/sources`, `/source/*`) apply a
|
|||||||
|
|
||||||
- Passwords hashed with Argon2id (64 MB memory cost)
|
- Passwords hashed with Argon2id (64 MB memory cost)
|
||||||
- Session cookies are HttpOnly, SameSite Lax, Secure (prod only)
|
- Session cookies are HttpOnly, SameSite Lax, Secure (prod only)
|
||||||
- Session regeneration on login to prevent session fixation attacks
|
|
||||||
- Session key is a 32-byte value auto-generated on first startup and
|
- Session key is a 32-byte value auto-generated on first startup and
|
||||||
stored in the database
|
stored in the database
|
||||||
- Production security headers on all responses: HSTS, X-Content-Type-Options
|
|
||||||
(`nosniff`), X-Frame-Options (`DENY`), Content-Security-Policy, Referrer-Policy,
|
|
||||||
and Permissions-Policy
|
|
||||||
- Request body size limits (1 MB) on all form POST endpoints
|
|
||||||
- **CSRF protection** on all state-changing forms (session-based tokens
|
- **CSRF protection** on all state-changing forms (session-based tokens
|
||||||
with constant-time comparison). Applied to `/pages`, `/sources`,
|
with constant-time comparison). Applied to `/pages`, `/sources`,
|
||||||
`/source`, and `/user` routes. Excluded from `/webhook` (inbound
|
`/source`, and `/user` routes. Excluded from `/webhook` (inbound
|
||||||
@@ -897,18 +885,10 @@ linted, tested, and compiled.
|
|||||||
failures per target, opens after 5 failures (30s cooldown),
|
failures per target, opens after 5 failures (30s cooldown),
|
||||||
half-open probe to test recovery
|
half-open probe to test recovery
|
||||||
|
|
||||||
### Completed: Security Hardening
|
|
||||||
- [x] Security headers middleware (HSTS, CSP, X-Frame-Options,
|
|
||||||
X-Content-Type-Options, Referrer-Policy, Permissions-Policy)
|
|
||||||
([#34](https://git.eeqj.de/sneak/webhooker/issues/34))
|
|
||||||
- [x] Session regeneration on login to prevent session fixation
|
|
||||||
([#38](https://git.eeqj.de/sneak/webhooker/issues/38))
|
|
||||||
- [x] Request body size limits on form endpoints
|
|
||||||
([#39](https://git.eeqj.de/sneak/webhooker/issues/39))
|
|
||||||
|
|
||||||
### Remaining: Core Features
|
### Remaining: Core Features
|
||||||
- [ ] Per-webhook rate limiting in the receiver handler
|
- [ ] Per-webhook rate limiting in the receiver handler
|
||||||
- [ ] Webhook signature verification (GitHub, Stripe formats)
|
- [ ] Webhook signature verification (GitHub, Stripe formats)
|
||||||
|
- [ ] Security headers (HSTS, CSP, X-Frame-Options)
|
||||||
- [x] CSRF protection for forms
|
- [x] CSRF protection for forms
|
||||||
([#35](https://git.eeqj.de/sneak/webhooker/issues/35))
|
([#35](https://git.eeqj.de/sneak/webhooker/issues/35))
|
||||||
- [x] SSRF prevention for HTTP delivery targets
|
- [x] SSRF prevention for HTTP delivery targets
|
||||||
|
|||||||
@@ -78,23 +78,14 @@ func (h *Handlers) HandleLoginSubmit() http.HandlerFunc {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the current session (may be pre-existing / attacker-set)
|
// Create session
|
||||||
oldSess, err := h.session.Get(r)
|
sess, err := h.session.Get(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.log.Error("failed to get session", "error", err)
|
h.log.Error("failed to get session", "error", err)
|
||||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Regenerate the session to prevent session fixation attacks.
|
|
||||||
// This destroys the old session ID and creates a new one.
|
|
||||||
sess, err := h.session.Regenerate(r, w, oldSess)
|
|
||||||
if err != nil {
|
|
||||||
h.log.Error("failed to regenerate session", "error", err)
|
|
||||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set user in session
|
// Set user in session
|
||||||
h.session.SetUser(sess, user.ID, user.Username)
|
h.session.SetUser(sess, user.ID, user.Username)
|
||||||
|
|
||||||
|
|||||||
@@ -171,35 +171,3 @@ func (s *Middleware) MetricsAuth() func(http.Handler) http.Handler {
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SecurityHeaders returns middleware that sets production security headers
|
|
||||||
// on every response: HSTS, X-Content-Type-Options, X-Frame-Options, CSP,
|
|
||||||
// Referrer-Policy, and Permissions-Policy.
|
|
||||||
func (s *Middleware) SecurityHeaders() func(http.Handler) http.Handler {
|
|
||||||
return func(next http.Handler) http.Handler {
|
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Header().Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains; preload")
|
|
||||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
||||||
w.Header().Set("X-Frame-Options", "DENY")
|
|
||||||
w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'")
|
|
||||||
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
|
|
||||||
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
|
|
||||||
next.ServeHTTP(w, r)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MaxBodySize returns middleware that limits the request body size for POST
|
|
||||||
// requests. If the body exceeds the given limit in bytes, the server returns
|
|
||||||
// 413 Request Entity Too Large. This prevents clients from sending arbitrarily
|
|
||||||
// large form bodies.
|
|
||||||
func (s *Middleware) MaxBodySize(maxBytes int64) func(http.Handler) http.Handler {
|
|
||||||
return func(next http.Handler) http.Handler {
|
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
if r.Method == http.MethodPost || r.Method == http.MethodPut || r.Method == http.MethodPatch {
|
|
||||||
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
|
|
||||||
}
|
|
||||||
next.ServeHTTP(w, r)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -11,18 +11,12 @@ import (
|
|||||||
"sneak.berlin/go/webhooker/static"
|
"sneak.berlin/go/webhooker/static"
|
||||||
)
|
)
|
||||||
|
|
||||||
// maxFormBodySize is the maximum allowed request body size (in bytes) for
|
|
||||||
// form POST endpoints. 1 MB is generous for any form submission while
|
|
||||||
// preventing abuse from oversized payloads.
|
|
||||||
const maxFormBodySize int64 = 1 * 1024 * 1024 // 1 MB
|
|
||||||
|
|
||||||
func (s *Server) SetupRoutes() {
|
func (s *Server) SetupRoutes() {
|
||||||
s.router = chi.NewRouter()
|
s.router = chi.NewRouter()
|
||||||
|
|
||||||
// Global middleware stack — applied to every request.
|
// Global middleware stack — applied to every request.
|
||||||
s.router.Use(middleware.Recoverer)
|
s.router.Use(middleware.Recoverer)
|
||||||
s.router.Use(middleware.RequestID)
|
s.router.Use(middleware.RequestID)
|
||||||
s.router.Use(s.mw.SecurityHeaders())
|
|
||||||
s.router.Use(s.mw.Logging())
|
s.router.Use(s.mw.Logging())
|
||||||
|
|
||||||
// Metrics middleware (only if credentials are configured)
|
// Metrics middleware (only if credentials are configured)
|
||||||
@@ -64,11 +58,10 @@ func (s *Server) SetupRoutes() {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// pages that are rendered server-side — CSRF-protected, body-size
|
// pages that are rendered server-side — CSRF-protected and with
|
||||||
// limited, and with per-IP rate limiting on the login endpoint.
|
// per-IP rate limiting on the login endpoint.
|
||||||
s.router.Route("/pages", func(r chi.Router) {
|
s.router.Route("/pages", func(r chi.Router) {
|
||||||
r.Use(s.mw.CSRF())
|
r.Use(s.mw.CSRF())
|
||||||
r.Use(s.mw.MaxBodySize(maxFormBodySize))
|
|
||||||
|
|
||||||
// Login page — rate-limited to prevent brute-force attacks
|
// Login page — rate-limited to prevent brute-force attacks
|
||||||
r.Group(func(r chi.Router) {
|
r.Group(func(r chi.Router) {
|
||||||
@@ -91,7 +84,6 @@ func (s *Server) SetupRoutes() {
|
|||||||
s.router.Route("/sources", func(r chi.Router) {
|
s.router.Route("/sources", func(r chi.Router) {
|
||||||
r.Use(s.mw.CSRF())
|
r.Use(s.mw.CSRF())
|
||||||
r.Use(s.mw.RequireAuth())
|
r.Use(s.mw.RequireAuth())
|
||||||
r.Use(s.mw.MaxBodySize(maxFormBodySize))
|
|
||||||
r.Get("/", s.h.HandleSourceList()) // List all webhooks
|
r.Get("/", s.h.HandleSourceList()) // List all webhooks
|
||||||
r.Get("/new", s.h.HandleSourceCreate()) // Show create form
|
r.Get("/new", s.h.HandleSourceCreate()) // Show create form
|
||||||
r.Post("/new", s.h.HandleSourceCreateSubmit()) // Handle create submission
|
r.Post("/new", s.h.HandleSourceCreateSubmit()) // Handle create submission
|
||||||
@@ -100,7 +92,6 @@ func (s *Server) SetupRoutes() {
|
|||||||
s.router.Route("/source/{sourceID}", func(r chi.Router) {
|
s.router.Route("/source/{sourceID}", func(r chi.Router) {
|
||||||
r.Use(s.mw.CSRF())
|
r.Use(s.mw.CSRF())
|
||||||
r.Use(s.mw.RequireAuth())
|
r.Use(s.mw.RequireAuth())
|
||||||
r.Use(s.mw.MaxBodySize(maxFormBodySize))
|
|
||||||
r.Get("/", s.h.HandleSourceDetail()) // View webhook details
|
r.Get("/", s.h.HandleSourceDetail()) // View webhook details
|
||||||
r.Get("/edit", s.h.HandleSourceEdit()) // Show edit form
|
r.Get("/edit", s.h.HandleSourceEdit()) // Show edit form
|
||||||
r.Post("/edit", s.h.HandleSourceEditSubmit()) // Handle edit submission
|
r.Post("/edit", s.h.HandleSourceEditSubmit()) // Handle edit submission
|
||||||
|
|||||||
@@ -135,50 +135,3 @@ func (s *Session) Destroy(sess *sessions.Session) {
|
|||||||
sess.Options.MaxAge = -1
|
sess.Options.MaxAge = -1
|
||||||
s.ClearUser(sess)
|
s.ClearUser(sess)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Regenerate creates a new session with the same values but a fresh ID.
|
|
||||||
// The old session is destroyed (MaxAge = -1) and saved, then a new session
|
|
||||||
// is created. This prevents session fixation attacks by ensuring the
|
|
||||||
// session ID changes after privilege escalation (e.g. login).
|
|
||||||
func (s *Session) Regenerate(r *http.Request, w http.ResponseWriter, oldSess *sessions.Session) (*sessions.Session, error) {
|
|
||||||
// Copy the values from the old session
|
|
||||||
oldValues := make(map[interface{}]interface{})
|
|
||||||
for k, v := range oldSess.Values {
|
|
||||||
oldValues[k] = v
|
|
||||||
}
|
|
||||||
|
|
||||||
// Destroy the old session
|
|
||||||
oldSess.Options.MaxAge = -1
|
|
||||||
s.ClearUser(oldSess)
|
|
||||||
if err := oldSess.Save(r, w); err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to destroy old session: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create a new session (gorilla/sessions generates a new ID)
|
|
||||||
newSess, err := s.store.New(r, SessionName)
|
|
||||||
if err != nil {
|
|
||||||
// store.New may return an error alongside a new empty session
|
|
||||||
// if the old cookie is now invalid. That is expected after we
|
|
||||||
// destroyed it above. Only fail on a nil session.
|
|
||||||
if newSess == nil {
|
|
||||||
return nil, fmt.Errorf("failed to create new session: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Restore the copied values into the new session
|
|
||||||
for k, v := range oldValues {
|
|
||||||
newSess.Values[k] = v
|
|
||||||
}
|
|
||||||
|
|
||||||
// Apply the standard session options (the destroyed old session had
|
|
||||||
// MaxAge = -1, which store.New might inherit from the cookie).
|
|
||||||
newSess.Options = &sessions.Options{
|
|
||||||
Path: "/",
|
|
||||||
MaxAge: 86400 * 7,
|
|
||||||
HttpOnly: true,
|
|
||||||
Secure: !s.config.IsDev(),
|
|
||||||
SameSite: http.SameSiteLaxMode,
|
|
||||||
}
|
|
||||||
|
|
||||||
return newSess, nil
|
|
||||||
}
|
|
||||||
|
|||||||
Reference in New Issue
Block a user