1
0

security.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package middleware
  2. import (
  3. "net/http"
  4. "github.com/mhsanaei/3x-ui/v2/web/session"
  5. "github.com/gin-gonic/gin"
  6. )
  7. // SecurityHeadersMiddleware adds browser hardening headers to panel responses.
  8. func SecurityHeadersMiddleware(directHTTPS bool) gin.HandlerFunc {
  9. return func(c *gin.Context) {
  10. c.Header("X-Content-Type-Options", "nosniff")
  11. c.Header("X-Frame-Options", "DENY")
  12. c.Header("Referrer-Policy", "no-referrer")
  13. c.Header("Content-Security-Policy", "frame-ancestors 'none'; base-uri 'self'; form-action 'self'")
  14. if directHTTPS {
  15. c.Header("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
  16. }
  17. c.Next()
  18. }
  19. }
  20. // CSRFMiddleware rejects unsafe requests that do not include the session CSRF token.
  21. func CSRFMiddleware() gin.HandlerFunc {
  22. return func(c *gin.Context) {
  23. if isSafeMethod(c.Request.Method) {
  24. c.Next()
  25. return
  26. }
  27. if !session.ValidateCSRFToken(c) {
  28. c.AbortWithStatus(http.StatusForbidden)
  29. return
  30. }
  31. c.Next()
  32. }
  33. }
  34. func isSafeMethod(method string) bool {
  35. switch method {
  36. case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodTrace:
  37. return true
  38. default:
  39. return false
  40. }
  41. }