Fix security vulnerabilities: XSS, cookie hardening, rate limiter bypass, HSTS, and open redirect
- Fix XSS in showToast() by replacing innerHTML with safe DOM construction via textContent - Add Secure flag to session and CSRF cookies when base_url uses HTTPS - Prevent rate limiter bypass by only trusting X-Forwarded-For/X-Real-IP from private/loopback IPs - Add Strict-Transport-Security header when running behind HTTPS - Validate short link URLs to prevent open redirects (must be http, https, or relative path) - Remove runtime config.toml file write from slug length update handler - Pin Docker base image to alpine:3.20 instead of floating latest tag Co-Authored-By: Claude Opus 4.6 <[email protected]>
This commit is contained in:
1 parent
65e013d728
commit
737a48ac30
5 files changed
+78
-54
No files matched your search
+1
-1
@@ -27,7 +27,7 @@ RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} GOARM=6 \
|
||||
# ==========================================
|
||||
# Final Stage
|
||||
# ==========================================
|
||||
FROM alpine:latest
|
||||
FROM alpine:3.20
|
||||
|
||||
# Install basic certificates and tools
|
||||
RUN apk add --no-cache ca-certificates tzdata
|
||||
|
||||
+27
-26
@@ -9,7 +9,6 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -97,7 +96,7 @@ func (s *Server) handleLoginPage(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
data := PageData{
|
||||
CSRFToken: csrfToken(w, r),
|
||||
CSRFToken: s.csrfToken(w, r),
|
||||
}
|
||||
s.render(w, r, "login.html", data)
|
||||
}
|
||||
@@ -106,7 +105,7 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
ip := clientIP(r)
|
||||
if !s.limiter.Allow(ip) {
|
||||
data := PageData{
|
||||
CSRFToken: csrfToken(w, r),
|
||||
CSRFToken: s.csrfToken(w, r),
|
||||
Error: "Too many login attempts. Please wait.",
|
||||
}
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
@@ -131,12 +130,12 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// Set highly secure session cookie
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "session",
|
||||
Value: token,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: s.isHTTPS(),
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
MaxAge: int(time.Duration(s.cfg.Admin.SessionHours) * time.Hour / time.Second),
|
||||
})
|
||||
@@ -146,7 +145,7 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
data := PageData{
|
||||
CSRFToken: csrfToken(w, r),
|
||||
CSRFToken: s.csrfToken(w, r),
|
||||
Error: "Invalid username or password.",
|
||||
}
|
||||
s.render(w, r, "login.html", data)
|
||||
@@ -175,7 +174,7 @@ func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
|
||||
// ==========================================
|
||||
|
||||
func (s *Server) handleAdminItems(w http.ResponseWriter, r *http.Request) {
|
||||
csrf := csrfToken(w, r)
|
||||
csrf := s.csrfToken(w, r)
|
||||
showRemoved := r.URL.Query().Get("show_removed") == "1"
|
||||
locations, _ := s.db.ListLocations(showRemoved)
|
||||
tags, _ := s.db.ListTags(showRemoved)
|
||||
@@ -295,7 +294,7 @@ func (s *Server) handleItemNew(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
data := PageData{
|
||||
CSRFToken: csrfToken(w, r),
|
||||
CSRFToken: s.csrfToken(w, r),
|
||||
ActiveNav: "items",
|
||||
Locations: locations,
|
||||
Tags: tags,
|
||||
@@ -485,7 +484,7 @@ func (s *Server) handleItemEdit(w http.ResponseWriter, r *http.Request) {
|
||||
customFieldsRaw := formatCustomFields(item.CustomFields)
|
||||
|
||||
data := PageData{
|
||||
CSRFToken: csrfToken(w, r),
|
||||
CSRFToken: s.csrfToken(w, r),
|
||||
ActiveNav: "items",
|
||||
Locations: locations,
|
||||
Tags: tags,
|
||||
@@ -680,7 +679,7 @@ func (s *Server) handleItemPermanentDelete(w http.ResponseWriter, r *http.Reques
|
||||
// ==========================================
|
||||
|
||||
func (s *Server) handleAdminLocations(w http.ResponseWriter, r *http.Request) {
|
||||
csrf := csrfToken(w, r)
|
||||
csrf := s.csrfToken(w, r)
|
||||
showRemoved := r.URL.Query().Get("show_removed") == "1"
|
||||
locations, _ := s.db.ListLocations(showRemoved)
|
||||
|
||||
@@ -792,7 +791,7 @@ func (s *Server) handleLocationPermanentDelete(w http.ResponseWriter, r *http.Re
|
||||
// ==========================================
|
||||
|
||||
func (s *Server) handleAdminTags(w http.ResponseWriter, r *http.Request) {
|
||||
csrf := csrfToken(w, r)
|
||||
csrf := s.csrfToken(w, r)
|
||||
showRemoved := r.URL.Query().Get("show_removed") == "1"
|
||||
tags, _ := s.db.ListTags(showRemoved)
|
||||
|
||||
@@ -894,7 +893,7 @@ func (s *Server) handleTagPermanentDelete(w http.ResponseWriter, r *http.Request
|
||||
// ==========================================
|
||||
|
||||
func (s *Server) handleAdminShortener(w http.ResponseWriter, r *http.Request) {
|
||||
csrf := csrfToken(w, r)
|
||||
csrf := s.csrfToken(w, r)
|
||||
showRemoved := r.URL.Query().Get("show_removed") == "1"
|
||||
links, _ := s.db.ListLinks(showRemoved)
|
||||
|
||||
@@ -936,6 +935,11 @@ func (s *Server) handleLinkCreate(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
if !isValidRedirectURL(urlVal) {
|
||||
http.Redirect(w, r, "/admin/shortener?toast=URL+must+use+http,+https,+or+be+a+relative+path&toast_type=error", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
// Auto generate slug if left blank
|
||||
if slugVal == "" {
|
||||
for i := 0; i < 10; i++ {
|
||||
@@ -986,6 +990,11 @@ func (s *Server) handleLinkSave(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
if !isValidRedirectURL(urlVal) {
|
||||
http.Redirect(w, r, "/admin/shortener?toast=URL+must+use+http,+https,+or+be+a+relative+path&toast_type=error", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if this slug is taken by ANOTHER link ID
|
||||
var existingID int64
|
||||
err = s.db.Conn.QueryRow("SELECT id FROM links WHERE slug = ? AND id != ?", slugVal, id).Scan(&existingID)
|
||||
@@ -1050,20 +1059,8 @@ func (s *Server) handleSlugLengthUpdate(w http.ResponseWriter, r *http.Request)
|
||||
return
|
||||
}
|
||||
|
||||
// Update in-memory config
|
||||
s.cfg.Slugs.Length = length
|
||||
|
||||
// Persist to config.toml
|
||||
configPath := "config.toml"
|
||||
data, err := os.ReadFile(configPath)
|
||||
if err == nil {
|
||||
content := string(data)
|
||||
// Replace the length line in the [slugs] section
|
||||
re := regexp.MustCompile(`(?m)^(\s*length\s*=\s*)\d+`)
|
||||
content = re.ReplaceAllString(content, "${1}"+strconv.Itoa(length))
|
||||
_ = os.WriteFile(configPath, []byte(content), 0644)
|
||||
}
|
||||
|
||||
http.Redirect(w, r, "/admin/shortener?toast=Slug+length+updated+to+"+strconv.Itoa(length)+"+characters&toast_type=success", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
@@ -1072,7 +1069,7 @@ func (s *Server) handleSlugLengthUpdate(w http.ResponseWriter, r *http.Request)
|
||||
// ==========================================
|
||||
|
||||
func (s *Server) handlePrintLabels(w http.ResponseWriter, r *http.Request) {
|
||||
csrf := csrfToken(w, r)
|
||||
csrf := s.csrfToken(w, r)
|
||||
items, err := s.db.ListItems(false)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to load labels", http.StatusInternalServerError)
|
||||
@@ -1194,6 +1191,10 @@ func formatCustomFields(jsonStr string) string {
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
func isValidRedirectURL(u string) bool {
|
||||
return strings.HasPrefix(u, "/") || strings.HasPrefix(u, "http://") || strings.HasPrefix(u, "https://")
|
||||
}
|
||||
|
||||
func (s *Server) resolveRoomTag(locationID int64, tagIDs []int64) []int64 {
|
||||
return tagIDs
|
||||
}
|
||||
@@ -1335,7 +1336,7 @@ func (s *Server) handleFolderView(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
data := PageData{
|
||||
CSRFToken: csrfToken(w, r),
|
||||
CSRFToken: s.csrfToken(w, r),
|
||||
ActiveNav: "locations",
|
||||
CurrentLocation: loc,
|
||||
ChildLocations: childLocs,
|
||||
@@ -1402,7 +1403,7 @@ func (s *Server) handlePublicItemView(w http.ResponseWriter, r *http.Request) {
|
||||
tags, _ := s.db.ListTags(false)
|
||||
|
||||
data := PageData{
|
||||
CSRFToken: csrfToken(w, r),
|
||||
CSRFToken: s.csrfToken(w, r),
|
||||
ActiveNav: "items",
|
||||
Item: item,
|
||||
ViewMode: true,
|
||||
|
||||
@@ -92,9 +92,7 @@ func (srv *Server) requireAuth(next http.HandlerFunc) http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// csrfToken returns the CSRF token for this session, creating one if needed.
|
||||
// Uses a lax cookie, embedded in HTMX meta templates and form files.
|
||||
func csrfToken(w http.ResponseWriter, r *http.Request) string {
|
||||
func (s *Server) csrfToken(w http.ResponseWriter, r *http.Request) string {
|
||||
if c, err := r.Cookie("csrf"); err == nil && len(c.Value) == 64 {
|
||||
return c.Value
|
||||
}
|
||||
@@ -105,6 +103,7 @@ func csrfToken(w http.ResponseWriter, r *http.Request) string {
|
||||
Name: "csrf",
|
||||
Value: token,
|
||||
Path: "/",
|
||||
Secure: s.isHTTPS(),
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
MaxAge: 86400,
|
||||
})
|
||||
@@ -175,15 +174,25 @@ func (rl *rateLimiter) Allow(ip string) bool {
|
||||
}
|
||||
|
||||
func clientIP(r *http.Request) string {
|
||||
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
|
||||
if i := strings.Index(xff, ","); i > 0 {
|
||||
return strings.TrimSpace(xff[:i])
|
||||
}
|
||||
return strings.TrimSpace(xff)
|
||||
}
|
||||
if xri := r.Header.Get("X-Real-Ip"); xri != "" {
|
||||
return strings.TrimSpace(xri)
|
||||
}
|
||||
host, _, _ := net.SplitHostPort(r.RemoteAddr)
|
||||
if isPrivateIP(host) {
|
||||
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
|
||||
if i := strings.Index(xff, ","); i > 0 {
|
||||
return strings.TrimSpace(xff[:i])
|
||||
}
|
||||
return strings.TrimSpace(xff)
|
||||
}
|
||||
if xri := r.Header.Get("X-Real-Ip"); xri != "" {
|
||||
return strings.TrimSpace(xri)
|
||||
}
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
func isPrivateIP(ipStr string) bool {
|
||||
ip := net.ParseIP(ipStr)
|
||||
if ip == nil {
|
||||
return false
|
||||
}
|
||||
return ip.IsLoopback() || ip.IsPrivate()
|
||||
}
|
||||
+17
-11
@@ -39,25 +39,31 @@ func New(cfg *config.Config, database *db.DB) *Server {
|
||||
}
|
||||
}
|
||||
|
||||
func securityHeaders(next http.Handler) http.Handler {
|
||||
func (s *Server) securityHeaders(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Frame-Options", "DENY")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
|
||||
|
||||
// Offline-first CSP: Only allows local static resources and fonts from Google Fonts
|
||||
w.Header().Set("Content-Security-Policy",
|
||||
if s.isHTTPS() {
|
||||
w.Header().Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Security-Policy",
|
||||
"default-src 'self'; "+
|
||||
"script-src 'self' 'unsafe-inline'; "+
|
||||
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "+
|
||||
"font-src 'self' https://fonts.gstatic.com; "+
|
||||
"img-src 'self' data:; "+
|
||||
"connect-src 'self';")
|
||||
|
||||
"script-src 'self' 'unsafe-inline'; "+
|
||||
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "+
|
||||
"font-src 'self' https://fonts.gstatic.com; "+
|
||||
"img-src 'self' data:; "+
|
||||
"connect-src 'self';")
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) isHTTPS() bool {
|
||||
return strings.HasPrefix(s.cfg.Server.BaseURL, "https")
|
||||
}
|
||||
|
||||
// lowercasePath normalises URL paths to lowercase so that short links are case-insensitive.
|
||||
// Admin, uploads, and static routes are excluded to preserve asset names.
|
||||
func lowercasePath(next http.Handler) http.Handler {
|
||||
@@ -165,7 +171,7 @@ func (s *Server) Start() error {
|
||||
addr := fmt.Sprintf(":%d", s.cfg.Server.Port)
|
||||
srv := &http.Server{
|
||||
Addr: addr,
|
||||
Handler: lowercasePath(securityHeaders(mux)),
|
||||
Handler: lowercasePath(s.securityHeaders(mux)),
|
||||
ReadTimeout: s.cfg.Server.ReadTimeoutDuration(),
|
||||
WriteTimeout: s.cfg.Server.WriteTimeoutDuration(),
|
||||
}
|
||||
|
||||
@@ -255,10 +255,18 @@ function showToast(message, type) {
|
||||
|
||||
const toast = document.createElement("div");
|
||||
toast.className = `toast ${type === "success" ? "toast-success" : "toast-error"}`;
|
||||
toast.innerHTML = `
|
||||
<div class="toast-message">${message}</div>
|
||||
<button class="toast-close" onclick="dismissToast(this)">×</button>
|
||||
`;
|
||||
|
||||
const msgDiv = document.createElement("div");
|
||||
msgDiv.className = "toast-message";
|
||||
msgDiv.textContent = message;
|
||||
|
||||
const closeBtn = document.createElement("button");
|
||||
closeBtn.className = "toast-close";
|
||||
closeBtn.textContent = "×";
|
||||
closeBtn.addEventListener("click", function() { dismissToast(closeBtn); });
|
||||
|
||||
toast.appendChild(msgDiv);
|
||||
toast.appendChild(closeBtn);
|
||||
container.appendChild(toast);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user