feat/security
All checks were successful
Build and Publish Docker Image / deploy (push) Successful in 1m44s
All checks were successful
Build and Publish Docker Image / deploy (push) Successful in 1m44s
Reviewed-on: #2
This commit was merged in pull request #2.
This commit is contained in:
@@ -2,11 +2,14 @@ package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"warpbox/lib/alerts"
|
||||
"warpbox/lib/config"
|
||||
"warpbox/lib/security"
|
||||
)
|
||||
|
||||
const adminSessionCookie = "warpbox_admin_session"
|
||||
@@ -59,17 +62,39 @@ func (app *App) handleAdminLoginPost(ctx *gin.Context) {
|
||||
ctx.Redirect(http.StatusSeeOther, "/")
|
||||
return
|
||||
}
|
||||
ip := app.clientIP(ctx)
|
||||
guard := app.securityGuard
|
||||
if app.securityFeaturesEnabled() && guard == nil {
|
||||
guard = security.NewGuard()
|
||||
app.securityGuard = guard
|
||||
}
|
||||
if app.securityFeaturesEnabled() && guard != nil && !guard.IsAdminWhitelisted(ip) && guard.IsBanned(ip) {
|
||||
app.logActivity("auth.admin.block", "high", "Blocked admin login from banned IP", ctx, nil)
|
||||
ctx.HTML(http.StatusTooManyRequests, "admin/login.html", gin.H{
|
||||
"ErrorMessage": "Too many failed attempts. Try again later.",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
username := strings.TrimSpace(ctx.PostForm("username"))
|
||||
password := ctx.PostForm("password")
|
||||
|
||||
if username != app.config.AdminUsername || password != app.config.AdminPassword {
|
||||
if app.securityFeaturesEnabled() && guard != nil && !guard.IsAdminWhitelisted(ip) {
|
||||
banned, attempts := guard.RegisterFailedLogin(ip, app.config.SecurityLoginWindowSeconds, app.config.SecurityLoginMaxAttempts, app.config.SecurityBanSeconds)
|
||||
app.logActivity("auth.admin.failed", "medium", "Failed admin login", ctx, map[string]string{"attempts": strconv.Itoa(attempts)})
|
||||
if banned {
|
||||
app.createAlert("Admin login brute-force blocked", "high", "security", "401", "auth.admin.bruteforce", "Too many failed admin logins triggered temporary ban.", map[string]string{"ip": ip, "attempts": strconv.Itoa(attempts)})
|
||||
app.logActivity("security.ban", "high", "Auto-banned IP after admin login failures", ctx, map[string]string{"attempts": strconv.Itoa(attempts)})
|
||||
}
|
||||
}
|
||||
ctx.HTML(http.StatusUnauthorized, "admin/login.html", gin.H{
|
||||
"ErrorMessage": "Invalid username or password.",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
app.logActivity("auth.admin.success", "low", "Admin login successful", ctx, nil)
|
||||
secure := app.config.AdminCookieSecure
|
||||
maxAge := int(app.config.SessionTTLSeconds)
|
||||
|
||||
@@ -108,9 +133,41 @@ func (app *App) handleAdminAlerts(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
alertsList := []alerts.Alert{}
|
||||
if app.alertStore != nil {
|
||||
var err error
|
||||
alertsList, err = app.alertStore.List(500)
|
||||
if err != nil {
|
||||
ctx.String(http.StatusInternalServerError, "Could not load alerts")
|
||||
return
|
||||
}
|
||||
}
|
||||
openCount := 0
|
||||
highCount := 0
|
||||
ackedCount := 0
|
||||
closedCount := 0
|
||||
for _, alert := range alertsList {
|
||||
switch string(alert.Status) {
|
||||
case "open":
|
||||
openCount++
|
||||
case "acked":
|
||||
ackedCount++
|
||||
case "closed":
|
||||
closedCount++
|
||||
}
|
||||
if alert.Severity == "high" && string(alert.Status) != "closed" {
|
||||
highCount++
|
||||
}
|
||||
}
|
||||
|
||||
ctx.HTML(http.StatusOK, "admin/alerts.html", gin.H{
|
||||
"AdminUsername": app.config.AdminUsername,
|
||||
"AdminEmail": app.config.AdminEmail,
|
||||
"ActivePage": "alerts",
|
||||
"Alerts": alertsList,
|
||||
"OpenCount": strconv.Itoa(openCount),
|
||||
"HighCount": strconv.Itoa(highCount),
|
||||
"AckCount": strconv.Itoa(ackedCount),
|
||||
"ClosedCount": strconv.Itoa(closedCount),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -84,22 +84,41 @@ func (app *App) handleAdminBoxesAction(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if len(request.BoxIDs) == 0 {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "Select one or more boxes first"})
|
||||
return
|
||||
}
|
||||
|
||||
switch request.Action {
|
||||
case "delete", "expire", "bump":
|
||||
case "delete", "expire", "bump", "cleanup_expired":
|
||||
default:
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "Unknown action"})
|
||||
return
|
||||
}
|
||||
|
||||
if request.Action != "cleanup_expired" && len(request.BoxIDs) == 0 {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "Select one or more boxes first"})
|
||||
return
|
||||
}
|
||||
|
||||
if request.Action == "bump" && request.DeltaSeconds <= 0 {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "Missing bump duration"})
|
||||
return
|
||||
}
|
||||
if request.Action == "cleanup_expired" {
|
||||
result, err := app.runExpiredCleanup("admin")
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Expired cleanup job failed"})
|
||||
return
|
||||
}
|
||||
boxes, listErr := app.listAdminBoxes()
|
||||
if listErr != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Cleanup finished, but boxes could not be reloaded"})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, gin.H{
|
||||
"ok": len(result.Warnings) == 0,
|
||||
"message": fmt.Sprintf("Expired cleanup done: deleted %d box(es), skipped %d", result.Deleted, result.Skipped),
|
||||
"warnings": result.Warnings,
|
||||
"boxes": boxes,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
processed := 0
|
||||
warnings := make([]string, 0)
|
||||
@@ -299,6 +318,8 @@ func adminBoxesActionMessage(action string, processed int, deltaSeconds int64) s
|
||||
return fmt.Sprintf("Expired %d box(es)", processed)
|
||||
case "bump":
|
||||
return fmt.Sprintf("Extended %d box(es) by %s", processed, adminBoxesDeltaLabel(deltaSeconds))
|
||||
case "cleanup_expired":
|
||||
return fmt.Sprintf("Expired cleanup processed %d box(es)", processed)
|
||||
default:
|
||||
return "Action complete"
|
||||
}
|
||||
|
||||
331
lib/server/admin_security.go
Normal file
331
lib/server/admin_security.go
Normal file
@@ -0,0 +1,331 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"warpbox/lib/activity"
|
||||
"warpbox/lib/alerts"
|
||||
"warpbox/lib/security"
|
||||
)
|
||||
|
||||
type adminAlertsActionRequest struct {
|
||||
Action string `json:"action"`
|
||||
IDs []string `json:"ids"`
|
||||
}
|
||||
|
||||
type adminSecurityActionRequest struct {
|
||||
Action string `json:"action"`
|
||||
IP string `json:"ip"`
|
||||
IPs []string `json:"ips"`
|
||||
BanUntil string `json:"ban_until"`
|
||||
}
|
||||
|
||||
func (app *App) reloadSecurityConfig() error {
|
||||
if app == nil || app.config == nil {
|
||||
return fmt.Errorf("app or config is nil")
|
||||
}
|
||||
if !app.securityFeaturesEnabled() {
|
||||
if app.securityGuard != nil {
|
||||
_ = app.securityGuard.Close()
|
||||
}
|
||||
app.securityGuard = nil
|
||||
return nil
|
||||
}
|
||||
if app.securityGuard == nil {
|
||||
app.securityGuard = security.NewGuard()
|
||||
}
|
||||
if err := app.securityGuard.EnableBanPersistence(filepath.Join(app.config.DBDir, "bans.badger")); err != nil {
|
||||
return fmt.Errorf("enable ban persistence: %w", err)
|
||||
}
|
||||
if err := app.securityGuard.Reload(security.Config{
|
||||
IPWhitelist: app.config.SecurityIPWhitelist,
|
||||
AdminIPWhitelist: app.config.SecurityAdminIPWhitelist,
|
||||
LoginWindowSeconds: app.config.SecurityLoginWindowSeconds,
|
||||
LoginMaxAttempts: app.config.SecurityLoginMaxAttempts,
|
||||
BanSeconds: app.config.SecurityBanSeconds,
|
||||
ScanWindowSeconds: app.config.SecurityScanWindowSeconds,
|
||||
ScanMaxAttempts: app.config.SecurityScanMaxAttempts,
|
||||
UploadWindowSeconds: app.config.SecurityUploadWindowSeconds,
|
||||
UploadMaxRequests: app.config.SecurityUploadMaxRequests,
|
||||
UploadMaxBytes: app.config.SecurityUploadMaxBytes,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("reload guard config: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (app *App) securityFeaturesEnabled() bool {
|
||||
return app != nil && app.config != nil && app.config.SecurityEnabled
|
||||
}
|
||||
|
||||
func (app *App) logActivity(kind string, severity string, message string, ctx *gin.Context, meta map[string]string) {
|
||||
if app.activityStore == nil {
|
||||
return
|
||||
}
|
||||
event := activity.Event{
|
||||
Kind: kind,
|
||||
Severity: severity,
|
||||
Message: message,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
Meta: meta,
|
||||
}
|
||||
if ctx != nil {
|
||||
event.IP = app.clientIP(ctx)
|
||||
event.Path = ctx.Request.URL.Path
|
||||
event.Method = ctx.Request.Method
|
||||
}
|
||||
_ = app.activityStore.Append(event, app.config.ActivityRetentionSeconds)
|
||||
}
|
||||
|
||||
func (app *App) createAlert(title string, severity string, group string, code string, trace string, message string, meta map[string]string) {
|
||||
if app.alertStore == nil {
|
||||
return
|
||||
}
|
||||
_ = app.alertStore.Add(alerts.Alert{
|
||||
Title: title,
|
||||
Severity: severity,
|
||||
Group: group,
|
||||
Code: code,
|
||||
Trace: trace,
|
||||
Message: message,
|
||||
Status: alerts.StatusOpen,
|
||||
Meta: meta,
|
||||
})
|
||||
}
|
||||
|
||||
func (app *App) securityMiddleware() gin.HandlerFunc {
|
||||
return func(ctx *gin.Context) {
|
||||
if !app.securityFeaturesEnabled() {
|
||||
ctx.Next()
|
||||
return
|
||||
}
|
||||
if app.securityGuard == nil {
|
||||
ctx.Next()
|
||||
return
|
||||
}
|
||||
ip := app.clientIP(ctx)
|
||||
if app.securityGuard.IsWhitelisted(ip) || app.securityGuard.IsAdminWhitelisted(ip) {
|
||||
ctx.Next()
|
||||
return
|
||||
}
|
||||
if app.securityGuard.IsBanned(ip) {
|
||||
app.logActivity("security.block", "high", "Blocked banned IP", ctx, nil)
|
||||
ctx.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "Too many abusive requests. Try again later."})
|
||||
return
|
||||
}
|
||||
ctx.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func (app *App) handleNoRoute(ctx *gin.Context) {
|
||||
if !app.securityFeaturesEnabled() {
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "Not found"})
|
||||
return
|
||||
}
|
||||
if app.securityGuard == nil {
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "Not found"})
|
||||
return
|
||||
}
|
||||
path := strings.ToLower(ctx.Request.URL.Path)
|
||||
suspicious := strings.Contains(path, "../") || strings.Contains(path, ".php") || strings.Contains(path, "wp-admin") || strings.Contains(path, ".env")
|
||||
if suspicious {
|
||||
ip := app.clientIP(ctx)
|
||||
if !app.securityGuard.IsWhitelisted(ip) {
|
||||
banned, attempts := app.securityGuard.RegisterScanAttempt(ip, app.config.SecurityScanWindowSeconds, app.config.SecurityScanMaxAttempts, app.config.SecurityBanSeconds)
|
||||
app.logActivity("security.scan", "medium", "Suspicious path probe detected", ctx, map[string]string{"attempts": intToString(attempts)})
|
||||
if banned {
|
||||
app.createAlert("IP auto-banned after malicious path scans", "high", "security", "410", "security.scan.autoban", "Repeated malicious path scans triggered temporary ban.", map[string]string{"ip": ip, "attempts": intToString(attempts)})
|
||||
app.logActivity("security.ban", "high", "IP auto-banned after scans", ctx, map[string]string{"attempts": intToString(attempts)})
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "Not found"})
|
||||
}
|
||||
|
||||
func (app *App) handleAdminActivity(ctx *gin.Context) {
|
||||
if app.activityStore == nil {
|
||||
ctx.HTML(http.StatusOK, "admin/activity.html", gin.H{
|
||||
"AdminUsername": app.config.AdminUsername,
|
||||
"AdminEmail": app.config.AdminEmail,
|
||||
"ActivePage": "activity",
|
||||
"Events": []activity.Event{},
|
||||
})
|
||||
return
|
||||
}
|
||||
events, err := app.activityStore.List(400, app.config.ActivityRetentionSeconds)
|
||||
if err != nil {
|
||||
ctx.String(http.StatusInternalServerError, "Could not load activity")
|
||||
return
|
||||
}
|
||||
ctx.HTML(http.StatusOK, "admin/activity.html", gin.H{
|
||||
"AdminUsername": app.config.AdminUsername,
|
||||
"AdminEmail": app.config.AdminEmail,
|
||||
"ActivePage": "activity",
|
||||
"Events": events,
|
||||
})
|
||||
}
|
||||
|
||||
func (app *App) handleAdminSecurity(ctx *gin.Context) {
|
||||
if !app.securityFeaturesEnabled() {
|
||||
ctx.String(http.StatusNotFound, "Security features are disabled")
|
||||
return
|
||||
}
|
||||
events := []activity.Event{}
|
||||
alertsList := []alerts.Alert{}
|
||||
if app.activityStore != nil {
|
||||
events, _ = app.activityStore.List(300, app.config.ActivityRetentionSeconds)
|
||||
}
|
||||
if app.alertStore != nil {
|
||||
alertsList, _ = app.alertStore.List(120)
|
||||
}
|
||||
bans := []security.BanEntry{}
|
||||
if app.securityGuard != nil {
|
||||
bans = app.securityGuard.BanList()
|
||||
}
|
||||
ctx.HTML(http.StatusOK, "admin/security.html", gin.H{
|
||||
"AdminUsername": app.config.AdminUsername,
|
||||
"AdminEmail": app.config.AdminEmail,
|
||||
"ActivePage": "security",
|
||||
"Events": events,
|
||||
"Alerts": alertsList,
|
||||
"Bans": bans,
|
||||
})
|
||||
}
|
||||
|
||||
func (app *App) handleAdminAlertsAction(ctx *gin.Context) {
|
||||
if app.alertStore == nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Alert store unavailable"})
|
||||
return
|
||||
}
|
||||
var request adminAlertsActionRequest
|
||||
if err := ctx.ShouldBindJSON(&request); err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid action payload"})
|
||||
return
|
||||
}
|
||||
switch request.Action {
|
||||
case "ack":
|
||||
if err := app.alertStore.SetStatus(request.IDs, alerts.StatusAcked); err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Could not update alerts"})
|
||||
return
|
||||
}
|
||||
case "close":
|
||||
if err := app.alertStore.SetStatus(request.IDs, alerts.StatusClosed); err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Could not update alerts"})
|
||||
return
|
||||
}
|
||||
case "delete":
|
||||
if err := app.alertStore.Delete(request.IDs); err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Could not delete alerts"})
|
||||
return
|
||||
}
|
||||
default:
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "Unknown action"})
|
||||
return
|
||||
}
|
||||
app.logActivity("alerts.action", "low", "Admin changed alert state", ctx, map[string]string{"action": request.Action, "count": intToString(len(request.IDs))})
|
||||
alertsList, _ := app.alertStore.List(500)
|
||||
ctx.JSON(http.StatusOK, gin.H{"ok": true, "alerts": alertsList})
|
||||
}
|
||||
|
||||
func (app *App) recordManualBanAction(ctx *gin.Context, kind string, message string, severity string, ip string, meta map[string]string, alertTitle string, alertSeverity string, code string, trace string, alertMessage string) {
|
||||
metaCopy := map[string]string{"ip": ip}
|
||||
for k, v := range meta {
|
||||
metaCopy[k] = v
|
||||
}
|
||||
app.logActivity(kind, severity, message, ctx, metaCopy)
|
||||
app.createAlert(alertTitle, alertSeverity, "security", code, trace, alertMessage, metaCopy)
|
||||
}
|
||||
|
||||
func (app *App) handleAdminSecurityAction(ctx *gin.Context) {
|
||||
if !app.securityFeaturesEnabled() {
|
||||
ctx.JSON(http.StatusNotFound, gin.H{"error": "Security features are disabled"})
|
||||
return
|
||||
}
|
||||
if app.securityGuard == nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Security guard unavailable"})
|
||||
return
|
||||
}
|
||||
var request adminSecurityActionRequest
|
||||
if err := ctx.ShouldBindJSON(&request); err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid action payload"})
|
||||
return
|
||||
}
|
||||
ip := strings.TrimSpace(request.IP)
|
||||
if ip != "" && net.ParseIP(ip) == nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid IP"})
|
||||
return
|
||||
}
|
||||
|
||||
switch request.Action {
|
||||
case "ban":
|
||||
if ip == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "Missing IP"})
|
||||
return
|
||||
}
|
||||
app.securityGuard.Ban(ip, app.config.SecurityBanSeconds)
|
||||
app.recordManualBanAction(ctx, "security.manual_ban", "Admin banned IP", "high", ip, nil, "IP manually banned by admin", "medium", "420", "security.manual.ban", "Admin manually applied temporary ban.")
|
||||
ctx.JSON(http.StatusOK, gin.H{"ok": true, "message": "IP banned", "bans": app.securityGuard.BanList()})
|
||||
case "ban_until":
|
||||
if ip == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "Missing IP"})
|
||||
return
|
||||
}
|
||||
until, err := time.Parse(time.RFC3339, strings.TrimSpace(request.BanUntil))
|
||||
if err != nil || until.Before(time.Now().UTC()) {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid ban expiration"})
|
||||
return
|
||||
}
|
||||
app.securityGuard.BanUntil(ip, until)
|
||||
meta := map[string]string{"until": until.UTC().Format(time.RFC3339)}
|
||||
app.recordManualBanAction(ctx, "security.manual_ban_until", "Admin set custom ban expiration", "high", ip, meta, "Custom IP ban applied by admin", "medium", "421", "security.manual.ban_until", "Admin set explicit ban expiration date.")
|
||||
ctx.JSON(http.StatusOK, gin.H{"ok": true, "message": "IP ban expiration updated", "bans": app.securityGuard.BanList()})
|
||||
case "unban":
|
||||
if ip == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "Missing IP"})
|
||||
return
|
||||
}
|
||||
app.securityGuard.Unban(ip)
|
||||
app.recordManualBanAction(ctx, "security.manual_unban", "Admin unbanned IP", "medium", ip, nil, "IP unbanned by admin", "low", "422", "security.manual.unban", "Admin manually removed temporary ban.")
|
||||
ctx.JSON(http.StatusOK, gin.H{"ok": true, "message": "IP unbanned", "bans": app.securityGuard.BanList()})
|
||||
case "bulk_unban":
|
||||
if len(request.IPs) == 0 {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "Missing IP list"})
|
||||
return
|
||||
}
|
||||
count := 0
|
||||
for _, candidate := range request.IPs {
|
||||
candidate = strings.TrimSpace(candidate)
|
||||
if net.ParseIP(candidate) == nil {
|
||||
continue
|
||||
}
|
||||
app.securityGuard.Unban(candidate)
|
||||
count++
|
||||
}
|
||||
app.logActivity("security.manual_bulk_unban", "high", "Admin unbanned multiple IPs", ctx, map[string]string{"count": intToString(count)})
|
||||
app.createAlert("Bulk IP unban by admin", "medium", "security", "423", "security.manual.bulk_unban", "Admin manually removed multiple temporary bans.", map[string]string{"count": intToString(count)})
|
||||
ctx.JSON(http.StatusOK, gin.H{"ok": true, "message": "Bulk unban complete", "bans": app.securityGuard.BanList()})
|
||||
case "unban_all":
|
||||
current := app.securityGuard.BanList()
|
||||
for _, ban := range current {
|
||||
app.securityGuard.Unban(ban.IP)
|
||||
}
|
||||
count := len(current)
|
||||
app.logActivity("security.manual_unban_all", "high", "Admin cleared all active bans", ctx, map[string]string{"count": intToString(count)})
|
||||
app.createAlert("All active bans cleared by admin", "medium", "security", "424", "security.manual.unban_all", "Admin manually removed all temporary bans.", map[string]string{"count": intToString(count)})
|
||||
ctx.JSON(http.StatusOK, gin.H{"ok": true, "message": "All bans cleared", "bans": app.securityGuard.BanList()})
|
||||
default:
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "Unknown action"})
|
||||
}
|
||||
}
|
||||
|
||||
func intToString(value int) string {
|
||||
return strconv.Itoa(value)
|
||||
}
|
||||
125
lib/server/admin_security_test.go
Normal file
125
lib/server/admin_security_test.go
Normal file
@@ -0,0 +1,125 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"warpbox/lib/activity"
|
||||
"warpbox/lib/alerts"
|
||||
"warpbox/lib/config"
|
||||
"warpbox/lib/security"
|
||||
)
|
||||
|
||||
func TestAdminSecurityActionsWriteAuditTrail(t *testing.T) {
|
||||
app, router := setupAdminSecurityTest(t)
|
||||
|
||||
for _, body := range []string{
|
||||
`{"action":"ban","ip":"203.0.113.7"}`,
|
||||
`{"action":"unban","ip":"203.0.113.7"}`,
|
||||
} {
|
||||
request := httptest.NewRequest(http.MethodPost, "/admin/security/actions", strings.NewReader(body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.AddCookie(authCookie(app))
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
events, err := app.activityStore.List(100, app.config.ActivityRetentionSeconds)
|
||||
if err != nil {
|
||||
t.Fatalf("activity list error: %v", err)
|
||||
}
|
||||
if len(events) < 2 {
|
||||
t.Fatalf("expected activity events, got %d", len(events))
|
||||
}
|
||||
alertsList, err := app.alertStore.List(100)
|
||||
if err != nil {
|
||||
t.Fatalf("alerts list error: %v", err)
|
||||
}
|
||||
if len(alertsList) < 2 {
|
||||
t.Fatalf("expected alerts for manual actions, got %d", len(alertsList))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminSecurityBulkUnbanAndUnbanAll(t *testing.T) {
|
||||
app, router := setupAdminSecurityTest(t)
|
||||
app.securityGuard.Ban("203.0.113.8", 300)
|
||||
app.securityGuard.Ban("203.0.113.9", 300)
|
||||
|
||||
request := httptest.NewRequest(http.MethodPost, "/admin/security/actions", strings.NewReader(`{"action":"bulk_unban","ips":["203.0.113.8"]}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.AddCookie(authCookie(app))
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("bulk_unban expected 200, got %d", response.Code)
|
||||
}
|
||||
if app.securityGuard.IsBanned("203.0.113.8") {
|
||||
t.Fatal("expected selected IP to be unbanned")
|
||||
}
|
||||
if !app.securityGuard.IsBanned("203.0.113.9") {
|
||||
t.Fatal("expected non-selected IP to remain banned")
|
||||
}
|
||||
|
||||
requestAll := httptest.NewRequest(http.MethodPost, "/admin/security/actions", strings.NewReader(`{"action":"unban_all"}`))
|
||||
requestAll.Header.Set("Content-Type", "application/json")
|
||||
requestAll.AddCookie(authCookie(app))
|
||||
responseAll := httptest.NewRecorder()
|
||||
router.ServeHTTP(responseAll, requestAll)
|
||||
if responseAll.Code != http.StatusOK {
|
||||
t.Fatalf("unban_all expected 200, got %d", responseAll.Code)
|
||||
}
|
||||
if len(app.securityGuard.BanList()) != 0 {
|
||||
t.Fatal("expected all bans to be removed")
|
||||
}
|
||||
}
|
||||
|
||||
func setupAdminSecurityTest(t *testing.T) (*App, *gin.Engine) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
cwd, _ := os.Getwd()
|
||||
root := filepath.Clean(filepath.Join(cwd, "..", ".."))
|
||||
if err := os.Chdir(root); err != nil {
|
||||
t.Fatalf("chdir: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = os.Chdir(cwd) })
|
||||
|
||||
clearAdminSettingsEnv(t)
|
||||
t.Setenv("WARPBOX_DATA_DIR", t.TempDir())
|
||||
t.Setenv("WARPBOX_ADMIN_PASSWORD", "secret")
|
||||
t.Setenv("WARPBOX_ADMIN_ENABLED", "true")
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
t.Fatalf("config load: %v", err)
|
||||
}
|
||||
if err := cfg.EnsureDirectories(); err != nil {
|
||||
t.Fatalf("ensure dirs: %v", err)
|
||||
}
|
||||
|
||||
app := &App{
|
||||
config: cfg,
|
||||
activityStore: activity.NewStore(filepath.Join(cfg.DBDir, "activity.json")),
|
||||
alertStore: alerts.NewStore(filepath.Join(cfg.DBDir, "alerts.json")),
|
||||
securityGuard: security.NewGuard(),
|
||||
}
|
||||
if err := app.reloadSecurityConfig(); err != nil {
|
||||
t.Fatalf("reload security config: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = app.securityGuard.Close() })
|
||||
|
||||
router := gin.New()
|
||||
admin := router.Group("/admin")
|
||||
admin.GET("/login", app.handleAdminLogin)
|
||||
protected := router.Group("/admin", app.adminAuthMiddleware)
|
||||
protected.POST("/security/actions", app.handleAdminSecurityAction)
|
||||
return app, router
|
||||
}
|
||||
@@ -269,6 +269,9 @@ func (app *App) applySettingsOverrideSet(values map[string]string) ([]adminSetti
|
||||
|
||||
app.config = nextCfg
|
||||
applyBoxstoreRuntimeConfig(app.config)
|
||||
if err := app.reloadSecurityConfig(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
rows, _ := app.buildAdminSettingsRows()
|
||||
return rows, warnings, nil
|
||||
}
|
||||
@@ -399,6 +402,8 @@ func settingsCategoryMeta() []settingsCategoryInfo {
|
||||
{Key: "uploads", Label: "Uploads", Icon: "↥"},
|
||||
{Key: "downloads", Label: "Downloads", Icon: "↧"},
|
||||
{Key: "retention", Label: "Retention", Icon: "⌛"},
|
||||
{Key: "security", Label: "Security", Icon: "🔒"},
|
||||
{Key: "activity", Label: "Activity", Icon: "☰"},
|
||||
{Key: "accounts", Label: "Accounts", Icon: "☺"},
|
||||
{Key: "api", Label: "API", Icon: "{ }"},
|
||||
{Key: "storage", Label: "Storage", Icon: "▥"},
|
||||
@@ -428,10 +433,16 @@ func settingsCategoryForKey(key string) string {
|
||||
switch key {
|
||||
case config.SettingGuestUploadsEnabled, config.SettingDefaultUserMaxFileBytes, config.SettingDefaultUserMaxBoxBytes, config.SettingGlobalMaxFileSizeBytes, config.SettingGlobalMaxBoxSizeBytes:
|
||||
return "uploads"
|
||||
case config.SettingSecurityUploadWindowSecs, config.SettingSecurityUploadMaxRequests, config.SettingSecurityUploadMaxGB:
|
||||
return "uploads"
|
||||
case config.SettingZipDownloadsEnabled, config.SettingOneTimeDownloadsEnabled, config.SettingOneTimeDownloadExpirySecs, config.SettingRenewOnDownloadEnabled:
|
||||
return "downloads"
|
||||
case config.SettingRenewOnAccessEnabled, config.SettingDefaultGuestExpirySecs, config.SettingMaxGuestExpirySecs, config.SettingOneTimeDownloadRetryFail:
|
||||
return "retention"
|
||||
case config.SettingSecurityEnabled, config.SettingSecurityIPWhitelist, config.SettingSecurityAdminIPWhitelist, config.SettingSecurityLoginWindowSecs, config.SettingSecurityLoginMaxAttempts, config.SettingSecurityBanSeconds, config.SettingSecurityScanWindowSecs, config.SettingSecurityScanMaxAttempts:
|
||||
return "security"
|
||||
case config.SettingActivityRetentionSeconds:
|
||||
return "activity"
|
||||
case config.SettingSessionTTLSeconds:
|
||||
return "accounts"
|
||||
case config.SettingAPIEnabled:
|
||||
@@ -440,6 +451,8 @@ func settingsCategoryForKey(key string) string {
|
||||
return "storage"
|
||||
case config.SettingBoxPollIntervalMS, config.SettingThumbnailBatchSize, config.SettingThumbnailIntervalSeconds:
|
||||
return "workers"
|
||||
case config.SettingExpiredCleanupIntervalSecs:
|
||||
return "workers"
|
||||
default:
|
||||
return "accounts"
|
||||
}
|
||||
@@ -466,6 +479,19 @@ func settingsDescription(key string) string {
|
||||
config.SettingThumbnailBatchSize: "How many thumbnail jobs the worker handles per batch.",
|
||||
config.SettingThumbnailIntervalSeconds: "Delay between thumbnail worker passes.",
|
||||
config.SettingDataDir: "Root data path. Locked because moving storage roots live is risky.",
|
||||
config.SettingActivityRetentionSeconds: "How long activity events stay stored before automatic prune.",
|
||||
config.SettingSecurityEnabled: "Master switch for security middleware, automated bans, suspicious path detection, and upload throttling.",
|
||||
config.SettingSecurityIPWhitelist: "Comma-separated IPs that bypass generic security bans and rate-limits.",
|
||||
config.SettingSecurityAdminIPWhitelist: "Comma-separated IPs allowed to bypass admin login brute-force controls.",
|
||||
config.SettingSecurityLoginWindowSecs: "Window used for failed admin login counting.",
|
||||
config.SettingSecurityLoginMaxAttempts: "Max failed admin logins per window before temporary ban.",
|
||||
config.SettingSecurityBanSeconds: "Duration for automatic temporary IP bans.",
|
||||
config.SettingSecurityScanWindowSecs: "Window used for malicious path scan detection.",
|
||||
config.SettingSecurityScanMaxAttempts: "Max suspicious path probes per window before temporary ban.",
|
||||
config.SettingSecurityUploadWindowSecs: "Window used for per-IP upload throttling.",
|
||||
config.SettingSecurityUploadMaxRequests: "Max upload requests per IP per upload window.",
|
||||
config.SettingSecurityUploadMaxGB: "Max upload volume in GB per IP per upload window.",
|
||||
config.SettingExpiredCleanupIntervalSecs: "Background interval for deleting expired boxes. Set 0 to disable periodic cleanup.",
|
||||
}
|
||||
return descriptions[key]
|
||||
}
|
||||
|
||||
@@ -265,7 +265,36 @@ func clearAdminSettingsEnv(t *testing.T) {
|
||||
"WARPBOX_BOX_POLL_INTERVAL_MS",
|
||||
"WARPBOX_THUMBNAIL_BATCH_SIZE",
|
||||
"WARPBOX_THUMBNAIL_INTERVAL_SECONDS",
|
||||
"WARPBOX_SECURITY_ENABLED",
|
||||
"WARPBOX_SECURITY_IP_WHITELIST",
|
||||
"WARPBOX_SECURITY_ADMIN_IP_WHITELIST",
|
||||
"WARPBOX_TRUSTED_PROXY_CIDRS",
|
||||
"WARPBOX_SECURITY_LOGIN_WINDOW_SECONDS",
|
||||
"WARPBOX_SECURITY_LOGIN_MAX_ATTEMPTS",
|
||||
"WARPBOX_SECURITY_BAN_SECONDS",
|
||||
"WARPBOX_SECURITY_SCAN_WINDOW_SECONDS",
|
||||
"WARPBOX_SECURITY_SCAN_MAX_ATTEMPTS",
|
||||
"WARPBOX_SECURITY_UPLOAD_WINDOW_SECONDS",
|
||||
"WARPBOX_SECURITY_UPLOAD_MAX_REQUESTS",
|
||||
"WARPBOX_SECURITY_UPLOAD_MAX_GB",
|
||||
"WARPBOX_SECURITY_UPLOAD_MAX_MB",
|
||||
"WARPBOX_SECURITY_UPLOAD_MAX_BYTES",
|
||||
"WARPBOX_EXPIRED_CLEANUP_INTERVAL_SECONDS",
|
||||
} {
|
||||
t.Setenv(name, "")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminSettingsSaveRejectsInvalidTrustedProxyCIDR(t *testing.T) {
|
||||
app, router := setupAdminSettingsTest(t)
|
||||
|
||||
request := httptest.NewRequest(http.MethodPost, "/admin/settings/save", strings.NewReader(`{"values":{"trusted_proxy_cidrs":"not-a-cidr"}}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.AddCookie(authCookie(app))
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
|
||||
if response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d", response.Code)
|
||||
}
|
||||
}
|
||||
|
||||
62
lib/server/cleanup.go
Normal file
62
lib/server/cleanup.go
Normal file
@@ -0,0 +1,62 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"warpbox/lib/boxstore"
|
||||
)
|
||||
|
||||
func (app *App) runExpiredCleanup(trigger string) (boxstore.CleanupExpiredResult, error) {
|
||||
result, err := boxstore.CleanupExpiredBoxes()
|
||||
if err != nil {
|
||||
log.Printf("warpbox cleanup[%s] failed: %v", trigger, err)
|
||||
app.logActivity("boxes.cleanup.failed", "high", "Expired boxes cleanup failed", nil, map[string]string{
|
||||
"trigger": trigger,
|
||||
"error": err.Error(),
|
||||
})
|
||||
return result, err
|
||||
}
|
||||
|
||||
meta := map[string]string{
|
||||
"trigger": trigger,
|
||||
"scanned": intToString(result.Scanned),
|
||||
"deleted": intToString(result.Deleted),
|
||||
"skipped": intToString(result.Skipped),
|
||||
}
|
||||
if len(result.DeletedIDs) > 0 {
|
||||
limit := len(result.DeletedIDs)
|
||||
if limit > 20 {
|
||||
limit = 20
|
||||
}
|
||||
meta["deleted_ids"] = strings.Join(result.DeletedIDs[:limit], ",")
|
||||
}
|
||||
if len(result.Warnings) > 0 {
|
||||
limit := len(result.Warnings)
|
||||
if limit > 3 {
|
||||
limit = 3
|
||||
}
|
||||
meta["warnings"] = strings.Join(result.Warnings[:limit], " | ")
|
||||
}
|
||||
app.logActivity("boxes.cleanup", "medium", "Expired boxes cleanup run completed", nil, meta)
|
||||
log.Printf("warpbox cleanup[%s] scanned=%d deleted=%d skipped=%d", trigger, result.Scanned, result.Deleted, result.Skipped)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (app *App) startExpiredCleanupWorker() {
|
||||
if app == nil || app.config == nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
for {
|
||||
interval := app.config.ExpiredCleanupIntervalSeconds
|
||||
if interval <= 0 {
|
||||
time.Sleep(30 * time.Second)
|
||||
continue
|
||||
}
|
||||
time.Sleep(time.Duration(interval) * time.Second)
|
||||
_, _ = app.runExpiredCleanup("worker")
|
||||
}
|
||||
}()
|
||||
}
|
||||
107
lib/server/ip.go
Normal file
107
lib/server/ip.go
Normal file
@@ -0,0 +1,107 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"warpbox/lib/security"
|
||||
)
|
||||
|
||||
func (app *App) clientIP(ctx *gin.Context) string {
|
||||
if ctx == nil || ctx.Request == nil {
|
||||
return ""
|
||||
}
|
||||
remoteIP := remoteAddrIP(ctx.Request)
|
||||
trusted, err := security.ParseCIDRList(app.config.TrustedProxyCIDRs)
|
||||
if err != nil {
|
||||
return remoteIP
|
||||
}
|
||||
if !remoteIsTrusted(remoteIP, trusted) {
|
||||
return remoteIP
|
||||
}
|
||||
for _, candidate := range headerIPs(ctx.Request.Header) {
|
||||
if isPublicIP(candidate) {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
candidates := headerIPs(ctx.Request.Header)
|
||||
if len(candidates) > 0 {
|
||||
return candidates[0]
|
||||
}
|
||||
return remoteIP
|
||||
}
|
||||
|
||||
func remoteIsTrusted(remoteIP string, trusted []net.IPNet) bool {
|
||||
ip := net.ParseIP(strings.TrimSpace(remoteIP))
|
||||
if ip == nil {
|
||||
return false
|
||||
}
|
||||
for _, prefix := range trusted {
|
||||
if prefix.Contains(ip) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func headerIPs(header http.Header) []string {
|
||||
keys := []string{
|
||||
"X-Forwarded-For",
|
||||
"X-Real-Ip",
|
||||
"CF-Connecting-IP",
|
||||
"X-Envoy-External-Address",
|
||||
"Fly-Client-IP",
|
||||
}
|
||||
out := make([]string, 0, 4)
|
||||
seen := map[string]bool{}
|
||||
for _, key := range keys {
|
||||
raw := strings.TrimSpace(header.Get(key))
|
||||
if raw == "" {
|
||||
continue
|
||||
}
|
||||
for _, part := range strings.Split(raw, ",") {
|
||||
ip := normalizeIP(strings.TrimSpace(part))
|
||||
if ip == "" || seen[ip] {
|
||||
continue
|
||||
}
|
||||
seen[ip] = true
|
||||
out = append(out, ip)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func remoteAddrIP(request *http.Request) string {
|
||||
host, _, err := net.SplitHostPort(strings.TrimSpace(request.RemoteAddr))
|
||||
if err != nil {
|
||||
return normalizeIP(strings.TrimSpace(request.RemoteAddr))
|
||||
}
|
||||
return normalizeIP(host)
|
||||
}
|
||||
|
||||
func normalizeIP(raw string) string {
|
||||
ip := net.ParseIP(strings.TrimSpace(raw))
|
||||
if ip == nil {
|
||||
return ""
|
||||
}
|
||||
return ip.String()
|
||||
}
|
||||
|
||||
func isPublicIP(value string) bool {
|
||||
ip := net.ParseIP(value)
|
||||
if ip == nil || !ip.IsGlobalUnicast() {
|
||||
return false
|
||||
}
|
||||
return !isPrivateOrLoopback(value)
|
||||
}
|
||||
|
||||
func isPrivateOrLoopback(value string) bool {
|
||||
ip := net.ParseIP(value)
|
||||
if ip == nil {
|
||||
return true
|
||||
}
|
||||
return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast()
|
||||
}
|
||||
44
lib/server/ip_test.go
Normal file
44
lib/server/ip_test.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"warpbox/lib/config"
|
||||
)
|
||||
|
||||
func TestClientIPDirectClient(t *testing.T) {
|
||||
app := &App{config: &config.Config{TrustedProxyCIDRs: "10.0.0.0/8"}}
|
||||
ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
ctx.Request = httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
ctx.Request.RemoteAddr = "198.51.100.10:1234"
|
||||
ctx.Request.Header.Set("X-Forwarded-For", "203.0.113.4")
|
||||
if got := app.clientIP(ctx); got != "198.51.100.10" {
|
||||
t.Fatalf("expected direct remote IP, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientIPTrustedProxyChain(t *testing.T) {
|
||||
app := &App{config: &config.Config{TrustedProxyCIDRs: "10.0.0.0/8"}}
|
||||
ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
ctx.Request = httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
ctx.Request.RemoteAddr = "10.1.2.3:8080"
|
||||
ctx.Request.Header.Set("X-Forwarded-For", "203.0.113.44, 10.0.0.5")
|
||||
if got := app.clientIP(ctx); got != "203.0.113.44" {
|
||||
t.Fatalf("expected forwarded public client IP, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientIPSpoofedHeaderFromUntrustedRemote(t *testing.T) {
|
||||
app := &App{config: &config.Config{TrustedProxyCIDRs: "10.0.0.0/8"}}
|
||||
ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
ctx.Request = httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
ctx.Request.RemoteAddr = "203.0.113.200:8080"
|
||||
ctx.Request.Header.Set("X-Forwarded-For", "198.51.100.55")
|
||||
if got := app.clientIP(ctx); got != "203.0.113.200" {
|
||||
t.Fatalf("expected untrusted remote IP, got %q", got)
|
||||
}
|
||||
}
|
||||
@@ -9,14 +9,20 @@ import (
|
||||
"github.com/gin-contrib/gzip"
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"warpbox/lib/activity"
|
||||
"warpbox/lib/alerts"
|
||||
"warpbox/lib/boxstore"
|
||||
"warpbox/lib/config"
|
||||
"warpbox/lib/routing"
|
||||
"warpbox/lib/security"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
config *config.Config
|
||||
settingsOverridesPath string
|
||||
activityStore *activity.Store
|
||||
alertStore *alerts.Store
|
||||
securityGuard *security.Guard
|
||||
}
|
||||
|
||||
func Run(addr string) error {
|
||||
@@ -38,9 +44,20 @@ func Run(addr string) error {
|
||||
|
||||
applyBoxstoreRuntimeConfig(cfg)
|
||||
|
||||
app := &App{config: cfg, settingsOverridesPath: overridesPath}
|
||||
app := &App{
|
||||
config: cfg,
|
||||
settingsOverridesPath: overridesPath,
|
||||
activityStore: activity.NewStore(filepath.Join(cfg.DBDir, "activity_log.json")),
|
||||
alertStore: alerts.NewStore(filepath.Join(cfg.DBDir, "alerts.json")),
|
||||
securityGuard: security.NewGuard(),
|
||||
}
|
||||
if err := app.reloadSecurityConfig(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
router := gin.Default()
|
||||
router.Use(app.securityMiddleware())
|
||||
router.NoRoute(app.handleNoRoute)
|
||||
htmlTemplates, err := loadHTMLTemplates()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -71,6 +88,10 @@ func Run(addr string) error {
|
||||
AdminBoxes: app.handleAdminBoxes,
|
||||
AdminBoxesAction: app.handleAdminBoxesAction,
|
||||
AdminUsers: app.handleAdminUsers,
|
||||
AdminActivity: app.handleAdminActivity,
|
||||
AdminSecurity: app.handleAdminSecurity,
|
||||
AdminAlertsAction: app.handleAdminAlertsAction,
|
||||
AdminSecurityAction: app.handleAdminSecurityAction,
|
||||
AdminSettings: app.handleAdminSettings,
|
||||
AdminSettingsExport: app.handleAdminSettingsExport,
|
||||
AdminSettingsSave: app.handleAdminSettingsSave,
|
||||
@@ -83,6 +104,7 @@ func Run(addr string) error {
|
||||
compressed.Static("/static", "./static")
|
||||
|
||||
boxstore.StartThumbnailWorker(cfg.ThumbnailBatchSize, time.Duration(cfg.ThumbnailIntervalSeconds)*time.Second)
|
||||
app.startExpiredCleanupWorker()
|
||||
|
||||
return router.Run(addr)
|
||||
}
|
||||
|
||||
@@ -39,6 +39,13 @@ func (app *App) handleCreateBox(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
totalSize := int64(0)
|
||||
for _, file := range request.Files {
|
||||
totalSize += file.Size
|
||||
}
|
||||
if !app.enforceUploadRateLimit(ctx, totalSize) {
|
||||
return
|
||||
}
|
||||
|
||||
files, err := boxstore.CreateManifest(boxID, request)
|
||||
if err != nil {
|
||||
@@ -73,6 +80,10 @@ func (app *App) handleManifestFileUpload(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if !app.enforceUploadRateLimit(ctx, file.Size) {
|
||||
boxstore.MarkFileStatus(boxID, fileID, models.FileStatusFailed)
|
||||
return
|
||||
}
|
||||
|
||||
savedFile, err := boxstore.SaveManifestUpload(boxID, fileID, file)
|
||||
if err != nil {
|
||||
@@ -141,6 +152,9 @@ func (app *App) handleDirectBoxUpload(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if !app.enforceUploadRateLimit(ctx, file.Size) {
|
||||
return
|
||||
}
|
||||
|
||||
savedFile, err := boxstore.SaveUpload(boxID, file)
|
||||
if err != nil {
|
||||
@@ -180,6 +194,9 @@ func (app *App) handleLegacyUpload(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if !app.enforceUploadRateLimit(ctx, totalSize) {
|
||||
return
|
||||
}
|
||||
|
||||
boxID, err := boxstore.NewBoxID()
|
||||
if err != nil {
|
||||
|
||||
@@ -3,6 +3,7 @@ package server
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -153,3 +154,39 @@ func (app *App) maxRequestBodyBytes() int64 {
|
||||
}
|
||||
return limit + 10*1024*1024
|
||||
}
|
||||
|
||||
func (app *App) enforceUploadRateLimit(ctx *gin.Context, size int64) bool {
|
||||
if !app.securityFeaturesEnabled() || app.securityGuard == nil {
|
||||
return true
|
||||
}
|
||||
ip := app.clientIP(ctx)
|
||||
if app.securityGuard.IsWhitelisted(ip) || app.securityGuard.IsAdminWhitelisted(ip) {
|
||||
return true
|
||||
}
|
||||
allowed, requestCount, totalBytes := app.securityGuard.AllowUpload(
|
||||
ip,
|
||||
size,
|
||||
app.config.SecurityUploadWindowSeconds,
|
||||
app.config.SecurityUploadMaxRequests,
|
||||
app.config.SecurityUploadMaxBytes,
|
||||
)
|
||||
if allowed {
|
||||
return true
|
||||
}
|
||||
|
||||
app.logActivity("security.upload_limit", "high", "Upload rate limit exceeded", ctx, map[string]string{
|
||||
"requests": strconv.Itoa(requestCount),
|
||||
"bytes": strconv.FormatInt(totalBytes, 10),
|
||||
})
|
||||
app.createAlert(
|
||||
"Upload rate limit triggered",
|
||||
"medium",
|
||||
"security",
|
||||
"430",
|
||||
"security.upload.rate_limit",
|
||||
"Per-IP upload rate limit blocked request.",
|
||||
map[string]string{"ip": ip, "requests": strconv.Itoa(requestCount)},
|
||||
)
|
||||
ctx.JSON(http.StatusTooManyRequests, gin.H{"error": "Too many uploads from this IP. Try again later."})
|
||||
return false
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user