diff --git a/internal/server/handlers.go b/internal/server/handlers.go index 96dfee5..ec04556 100644 --- a/internal/server/handlers.go +++ b/internal/server/handlers.go @@ -1,6 +1,7 @@ package server import ( + "crypto/subtle" "database/sql" "encoding/json" "fmt" @@ -124,8 +125,12 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { username := r.FormValue("username") password := r.FormValue("password") - // Verify Admin Credentials using Bcrypt - if username == s.cfg.Admin.Username && bcrypt.CompareHashAndPassword([]byte(s.cfg.Admin.PasswordHash), []byte(password)) == nil { + // Verify Admin Credentials using Bcrypt. Compare the username in constant + // time and always run the bcrypt check so response timing does not reveal + // whether the username was valid. + usernameOK := subtle.ConstantTimeCompare([]byte(username), []byte(s.cfg.Admin.Username)) == 1 + passwordOK := bcrypt.CompareHashAndPassword([]byte(s.cfg.Admin.PasswordHash), []byte(password)) == nil + if usernameOK && passwordOK { token, err := s.sessions.Create() if err != nil { http.Error(w, "Session creation failed", http.StatusInternalServerError) diff --git a/internal/server/mcp.go b/internal/server/mcp.go index c3f0374..5aa85ad 100644 --- a/internal/server/mcp.go +++ b/internal/server/mcp.go @@ -47,7 +47,16 @@ func (s *Server) handleMCP(w http.ResponseWriter, r *http.Request) { writeMCPHTTPError(w, nil, http.StatusForbidden, -32000, "Forbidden origin") return } + // Rate limit credential guessing: IPs with a recent failed auth attempt + // are blocked before credentials are even checked. Successful requests + // are never throttled. + ip := clientIP(r) + if s.limiter.Blocked(ip) { + writeMCPHTTPError(w, nil, http.StatusTooManyRequests, -32000, "Too many failed authentication attempts. Please wait.") + return + } if !s.authorizeMCP(r) { + s.limiter.Record(ip) w.Header().Set("WWW-Authenticate", `Bearer realm="Solis MCP", Basic realm="Solis MCP"`) writeMCPHTTPError(w, nil, http.StatusUnauthorized, -32000, "Unauthorized") return @@ -109,10 +118,14 @@ func (s *Server) authorizeMCP(r *http.Request) bool { } username, password, ok := r.BasicAuth() - if !ok || username != s.cfg.Admin.Username { + if !ok { return false } - return bcrypt.CompareHashAndPassword([]byte(s.cfg.Admin.PasswordHash), []byte(password)) == nil + // Constant-time username check and unconditional bcrypt comparison so + // response timing does not reveal whether the username was valid. + usernameOK := constantTimeEqual(username, s.cfg.Admin.Username) + passwordOK := bcrypt.CompareHashAndPassword([]byte(s.cfg.Admin.PasswordHash), []byte(password)) == nil + return usernameOK && passwordOK } func (s *Server) validMCPOrigin(r *http.Request) bool { diff --git a/internal/server/mcp_test.go b/internal/server/mcp_test.go index 6ceaf20..8cadfb2 100644 --- a/internal/server/mcp_test.go +++ b/internal/server/mcp_test.go @@ -6,16 +6,20 @@ import ( "path/filepath" "strings" "testing" + "time" "Solis/internal/config" "Solis/internal/db" ) func TestMCPRequiresAuthentication(t *testing.T) { - srv := &Server{cfg: &config.Config{ - Server: config.ServerConfig{BaseURL: "http://localhost:8889"}, - MCP: config.MCPConfig{Enabled: true, APIKey: "test-key"}, - }} + srv := &Server{ + cfg: &config.Config{ + Server: config.ServerConfig{BaseURL: "http://localhost:8889"}, + MCP: config.MCPConfig{Enabled: true, APIKey: "test-key"}, + }, + limiter: newRateLimiter(2 * time.Second), + } req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/list"}`)) rec := httptest.NewRecorder() @@ -28,10 +32,13 @@ func TestMCPRequiresAuthentication(t *testing.T) { } func TestMCPListsToolsWithAPIKey(t *testing.T) { - srv := &Server{cfg: &config.Config{ - Server: config.ServerConfig{BaseURL: "http://localhost:8889"}, - MCP: config.MCPConfig{Enabled: true, APIKey: "test-key"}, - }} + srv := &Server{ + cfg: &config.Config{ + Server: config.ServerConfig{BaseURL: "http://localhost:8889"}, + MCP: config.MCPConfig{Enabled: true, APIKey: "test-key"}, + }, + limiter: newRateLimiter(2 * time.Second), + } req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/list"}`)) req.Header.Set("Authorization", "Bearer test-key") @@ -48,10 +55,13 @@ func TestMCPListsToolsWithAPIKey(t *testing.T) { } func TestMCPRejectsUnexpectedOrigin(t *testing.T) { - srv := &Server{cfg: &config.Config{ - Server: config.ServerConfig{BaseURL: "http://localhost:8889"}, - MCP: config.MCPConfig{Enabled: true, APIKey: "test-key"}, - }} + srv := &Server{ + cfg: &config.Config{ + Server: config.ServerConfig{BaseURL: "http://localhost:8889"}, + MCP: config.MCPConfig{Enabled: true, APIKey: "test-key"}, + }, + limiter: newRateLimiter(2 * time.Second), + } req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/list"}`)) req.Header.Set("Authorization", "Bearer test-key") diff --git a/internal/server/middleware.go b/internal/server/middleware.go index c5296ee..e976ff6 100644 --- a/internal/server/middleware.go +++ b/internal/server/middleware.go @@ -97,12 +97,19 @@ func (s *Server) csrfToken(w http.ResponseWriter, r *http.Request) string { return c.Value } b := make([]byte, 32) - rand.Read(b) + if _, err := rand.Read(b); err != nil { + // Never issue a predictable token; fail closed with an empty token + // that can never match a submitted value. + return "" + } token := hex.EncodeToString(b) + // HttpOnly is safe here: the frontend reads the token from the page's + // tag, never from the cookie itself. http.SetCookie(w, &http.Cookie{ Name: "csrf", Value: token, Path: "/", + HttpOnly: true, Secure: s.isHTTPS(), SameSite: http.SameSiteLaxMode, MaxAge: 86400, @@ -112,7 +119,7 @@ func (s *Server) csrfToken(w http.ResponseWriter, r *http.Request) string { func verifyCSRF(r *http.Request) bool { cookie, err := r.Cookie("csrf") - if err != nil { + if err != nil || cookie.Value == "" { return false } @@ -162,7 +169,31 @@ func (rl *rateLimiter) Allow(ip string) bool { return false } rl.clients[ip] = now - // Lazy cleanup: purge stale entries when map grows large + rl.purgeLocked(now) + return true +} + +// Blocked reports whether the IP is inside the rate-limit window without +// consuming a slot. Used to gate endpoints where only failures should count. +func (rl *rateLimiter) Blocked(ip string) bool { + rl.mu.Lock() + defer rl.mu.Unlock() + last, ok := rl.clients[ip] + return ok && time.Since(last) < rl.window +} + +// Record marks a (failed) attempt for the IP, starting its rate-limit window. +func (rl *rateLimiter) Record(ip string) { + rl.mu.Lock() + defer rl.mu.Unlock() + now := time.Now() + rl.clients[ip] = now + rl.purgeLocked(now) +} + +// purgeLocked lazily removes stale entries when the map grows large. +// Caller must hold rl.mu. +func (rl *rateLimiter) purgeLocked(now time.Time) { if len(rl.clients) > 1000 { for k, v := range rl.clients { if now.Sub(v) > rl.window*10 { @@ -170,17 +201,17 @@ func (rl *rateLimiter) Allow(ip string) bool { } } } - return true } func clientIP(r *http.Request) string { host, _, _ := net.SplitHostPort(r.RemoteAddr) if isPrivateIP(host) { + // Use the RIGHTMOST X-Forwarded-For entry: it is the one appended by + // our own (trusted) reverse proxy. Earlier entries are client-supplied + // and trivially spoofable, which would defeat rate limiting. 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) + parts := strings.Split(xff, ",") + return strings.TrimSpace(parts[len(parts)-1]) } if xri := r.Header.Get("X-Real-Ip"); xri != "" { return strings.TrimSpace(xri) diff --git a/internal/server/qr.go b/internal/server/qr.go index 7bd9d93..5a21d78 100644 --- a/internal/server/qr.go +++ b/internal/server/qr.go @@ -44,6 +44,7 @@ func (s *Server) handleQR(w http.ResponseWriter, r *http.Request) { // Write PNG to response w.Header().Set("Content-Type", "image/png") - w.Header().Set("Cache-Control", "public, max-age=86400") // Cache for 24h as QR codes are static + // private: this is an authenticated route, so shared caches must not store it + w.Header().Set("Cache-Control", "private, max-age=86400") w.Write(pngData) } diff --git a/internal/server/server.go b/internal/server/server.go index c61d602..ace4f48 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -200,8 +200,10 @@ func (s *Server) handleServeUploads(w http.ResponseWriter, r *http.Request) { filename := filepath.Base(r.URL.Path) filePath := filepath.Join(s.cfg.Upload.Dir, filename) - // Validate path is strictly inside s.cfg.Upload.Dir - if !strings.HasPrefix(filepath.Clean(filePath), filepath.Clean(s.cfg.Upload.Dir)) { + // Validate path is strictly inside s.cfg.Upload.Dir (the trailing + // separator prevents sibling-directory matches like "uploads-evil") + uploadRoot := filepath.Clean(s.cfg.Upload.Dir) + string(filepath.Separator) + if !strings.HasPrefix(filepath.Clean(filePath), uploadRoot) { http.Error(w, "Access Denied", http.StatusForbidden) return }