Просмотр исходного кода

fix(http): cap request body size and skip multipart parsing before login

Incoming requests had no body size limit. The CSRF middleware called
r.FormValue on every state-changing request, including POST /login
before authentication, so anonymous clients could make Miniflux parse
multipart bodies of any size. File parts beyond 32 MiB are written to
temporary files, and those files were never removed: net/http only
cleans up the multipart form of the original request, while Miniflux
handlers receive copies made by WithContext.

- Add HTTP_SERVER_MAX_BODY_SIZE (15 MiB by default) and apply it to all
  application routes with http.MaxBytesHandler.
- Check the X-Csrf-Token header before reading the body, read the form
  token from the body only, and parse multipart forms only for
  authenticated users.
- Remove multipart temporary files in the CSRF and Fever middlewares
  once the request has been handled.
Frédéric Guillot 18 часов назад
Родитель
Сommit
cc92123b5c

+ 12 - 0
internal/config/options.go

@@ -291,6 +291,14 @@ func NewConfigOptions() *configOptions {
 				rawValue:          "",
 				rawValue:          "",
 				valueType:         stringType,
 				valueType:         stringType,
 			},
 			},
+			"HTTP_SERVER_MAX_BODY_SIZE": {
+				parsedInt64Value: 15,
+				rawValue:         "15",
+				valueType:        int64Type,
+				validator: func(rawValue string) error {
+					return validateGreaterOrEqualThan(rawValue, 1)
+				},
+			},
 			"HTTP_SERVER_TIMEOUT": {
 			"HTTP_SERVER_TIMEOUT": {
 				parsedDuration: 300 * time.Second,
 				parsedDuration: 300 * time.Second,
 				rawValue:       "300",
 				rawValue:       "300",
@@ -815,6 +823,10 @@ func (c *configOptions) HTTPClientUserAgent() string {
 	return defaultHTTPClientUserAgent
 	return defaultHTTPClientUserAgent
 }
 }
 
 
+func (c *configOptions) HTTPServerMaxBodySize() int64 {
+	return c.options["HTTP_SERVER_MAX_BODY_SIZE"].parsedInt64Value * 1024 * 1024
+}
+
 func (c *configOptions) HTTPServerTimeout() time.Duration {
 func (c *configOptions) HTTPServerTimeout() time.Duration {
 	return c.options["HTTP_SERVER_TIMEOUT"].parsedDuration
 	return c.options["HTTP_SERVER_TIMEOUT"].parsedDuration
 }
 }

+ 22 - 0
internal/config/options_parsing_test.go

@@ -618,6 +618,28 @@ func TestHTTPClientMaxBodySizeOptionParsing(t *testing.T) {
 	}
 	}
 }
 }
 
 
+func TestHTTPServerMaxBodySizeOptionParsing(t *testing.T) {
+	configParser := NewConfigParser()
+
+	if configParser.options.HTTPServerMaxBodySize() != 15*1024*1024 {
+		t.Fatalf("Expected HTTP_SERVER_MAX_BODY_SIZE to be 15 by default, got %d", configParser.options.HTTPServerMaxBodySize())
+	}
+
+	if err := configParser.parseLines([]string{"HTTP_SERVER_MAX_BODY_SIZE=25"}); err != nil {
+		t.Fatalf("Unexpected error: %v", err)
+	}
+
+	expectedValue := 25 * 1024 * 1024
+	currentValue := configParser.options.HTTPServerMaxBodySize()
+	if currentValue != int64(expectedValue) {
+		t.Fatalf("Expected HTTP_SERVER_MAX_BODY_SIZE to be %d, got %d", expectedValue, currentValue)
+	}
+
+	if err := configParser.parseLines([]string{"HTTP_SERVER_MAX_BODY_SIZE=0"}); err == nil {
+		t.Fatal("Expected an error for HTTP_SERVER_MAX_BODY_SIZE=0")
+	}
+}
+
 func TestHTTPClientUserAgentOptionParsing(t *testing.T) {
 func TestHTTPClientUserAgentOptionParsing(t *testing.T) {
 	configParser := NewConfigParser()
 	configParser := NewConfigParser()
 
 

+ 9 - 0
internal/fever/middleware.go

@@ -19,6 +19,15 @@ func Middleware(store *storage.Storage) func(http.Handler) http.Handler {
 		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 			clientIP := request.ClientIP(r)
 			clientIP := request.ClientIP(r)
 			apiKey := r.FormValue("api_key")
 			apiKey := r.FormValue("api_key")
+
+			// The request passed down is a copy made by WithContext, so net/http
+			// won't remove the multipart temporary files on its own.
+			defer func() {
+				if r.MultipartForm != nil {
+					r.MultipartForm.RemoveAll()
+				}
+			}()
+
 			if apiKey == "" {
 			if apiKey == "" {
 				slog.Warn("[Fever] No API key provided",
 				slog.Warn("[Fever] No API key provided",
 					slog.Bool("authentication_failed", true),
 					slog.Bool("authentication_failed", true),

+ 1 - 0
internal/http/server/routes.go

@@ -52,6 +52,7 @@ func newRouter(store *storage.Storage, pool *worker.Pool) http.Handler {
 			w.Write([]byte(config.Opts.MaintenanceMessage()))
 			w.Write([]byte(config.Opts.MaintenanceMessage()))
 		})
 		})
 	}
 	}
+	appHandler = http.MaxBytesHandler(appHandler, config.Opts.HTTPServerMaxBodySize())
 	appHandler = middleware(appHandler)
 	appHandler = middleware(appHandler)
 
 
 	// Root router: health probes at root, app routes under base path.
 	// Root router: health probes at root, app routes under base path.

+ 21 - 4
internal/ui/csrf_middleware.go

@@ -26,6 +26,14 @@ func newCSRFMiddleware(basePath string) *csrfMiddleware {
 // in the request context.
 // in the request context.
 func (m *csrfMiddleware) handle(next http.Handler) http.Handler {
 func (m *csrfMiddleware) handle(next http.Handler) http.Handler {
 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		// The request passed down is a copy made by WithContext, so net/http
+		// won't remove the multipart temporary files on its own.
+		defer func() {
+			if r.MultipartForm != nil {
+				r.MultipartForm.RemoveAll()
+			}
+		}()
+
 		switch r.Method {
 		switch r.Method {
 		case http.MethodGet, http.MethodHead, http.MethodOptions:
 		case http.MethodGet, http.MethodHead, http.MethodOptions:
 			// Safe methods don't require CSRF validation.
 			// Safe methods don't require CSRF validation.
@@ -46,10 +54,7 @@ func (m *csrfMiddleware) validate(w http.ResponseWriter, r *http.Request) bool {
 	}
 	}
 
 
 	csrfToken := session.CSRF()
 	csrfToken := session.CSRF()
-	formValue := r.FormValue("csrf")
-	headerValue := r.Header.Get("X-Csrf-Token")
-
-	if crypto.ConstantTimeCmp(csrfToken, formValue) || crypto.ConstantTimeCmp(csrfToken, headerValue) {
+	if crypto.ConstantTimeCmp(csrfToken, r.Header.Get("X-Csrf-Token")) || crypto.ConstantTimeCmp(csrfToken, csrfFormValue(r)) {
 		return true
 		return true
 	}
 	}
 
 
@@ -65,3 +70,15 @@ func (m *csrfMiddleware) validate(w http.ResponseWriter, r *http.Request) bool {
 
 
 	return false
 	return false
 }
 }
+
+// csrfFormValue returns the CSRF token from the request body, parsing multipart forms only for authenticated users.
+func csrfFormValue(r *http.Request) string {
+	if request.IsAuthenticated(r) {
+		return r.PostFormValue("csrf")
+	}
+
+	if err := r.ParseForm(); err != nil {
+		return ""
+	}
+	return r.PostForm.Get("csrf")
+}

+ 214 - 0
internal/ui/csrf_middleware_test.go

@@ -0,0 +1,214 @@
+// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+package ui // import "miniflux.app/v2/internal/ui"
+
+import (
+	"bytes"
+	"context"
+	"mime/multipart"
+	"net/http"
+	"net/http/httptest"
+	"net/url"
+	"os"
+	"strings"
+	"testing"
+
+	"miniflux.app/v2/internal/http/request"
+	"miniflux.app/v2/internal/model"
+)
+
+func newCSRFTestSession(authenticated bool) *model.WebSession {
+	session, _ := model.NewWebSession("test", "127.0.0.1")
+	if authenticated {
+		session.SetUser(&model.User{ID: 1})
+	}
+	return session
+}
+
+func withCSRFTestSession(r *http.Request, session *model.WebSession) *http.Request {
+	return r.WithContext(context.WithValue(r.Context(), request.WebSessionContextKey, session))
+}
+
+func newMultipartBody(t *testing.T, fields map[string]string, fileContent []byte) (*bytes.Buffer, string) {
+	t.Helper()
+
+	body := &bytes.Buffer{}
+	writer := multipart.NewWriter(body)
+	for name, value := range fields {
+		if err := writer.WriteField(name, value); err != nil {
+			t.Fatal(err)
+		}
+	}
+	if fileContent != nil {
+		part, err := writer.CreateFormFile("file", "feeds.opml")
+		if err != nil {
+			t.Fatal(err)
+		}
+		if _, err := part.Write(fileContent); err != nil {
+			t.Fatal(err)
+		}
+	}
+	if err := writer.Close(); err != nil {
+		t.Fatal(err)
+	}
+	return body, writer.FormDataContentType()
+}
+
+func TestCSRFMiddlewareIgnoresMultipartBodyWithoutAuthentication(t *testing.T) {
+	session := newCSRFTestSession(false)
+	body, contentType := newMultipartBody(t, map[string]string{"csrf": session.CSRF()}, []byte("<opml/>"))
+
+	r := httptest.NewRequest(http.MethodPost, "/login", body)
+	r.Header.Set("Content-Type", contentType)
+	r = withCSRFTestSession(r, session)
+
+	handler := newCSRFMiddleware("/base").handle(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		t.Fatal(`The next handler should not be called`)
+	}))
+
+	w := httptest.NewRecorder()
+	handler.ServeHTTP(w, r)
+
+	if w.Code != http.StatusFound {
+		t.Fatalf(`Unexpected status code, got: %d`, w.Code)
+	}
+
+	if location := w.Header().Get("Location"); location != "/base/" {
+		t.Fatalf(`Unexpected redirect location, got: %q`, location)
+	}
+
+	if r.MultipartForm != nil {
+		t.Fatal(`The multipart form should not be parsed before authentication`)
+	}
+}
+
+func TestCSRFMiddlewareAcceptsURLEncodedFormWithoutAuthentication(t *testing.T) {
+	session := newCSRFTestSession(false)
+	form := url.Values{"csrf": {session.CSRF()}, "username": {"admin"}}
+
+	r := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(form.Encode()))
+	r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+	r = withCSRFTestSession(r, session)
+
+	called := false
+	handler := newCSRFMiddleware("").handle(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		called = true
+		if username := r.FormValue("username"); username != "admin" {
+			t.Fatalf(`Unexpected username, got: %q`, username)
+		}
+	}))
+
+	handler.ServeHTTP(httptest.NewRecorder(), r)
+
+	if !called {
+		t.Fatal(`The next handler should be called`)
+	}
+}
+
+func TestCSRFMiddlewareAcceptsHeaderWithoutParsingBody(t *testing.T) {
+	session := newCSRFTestSession(false)
+
+	r := httptest.NewRequest(http.MethodPost, "/webauthn/login/finish", strings.NewReader(`{}`))
+	r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+	r.Header.Set("X-Csrf-Token", session.CSRF())
+	r = withCSRFTestSession(r, session)
+
+	called := false
+	handler := newCSRFMiddleware("").handle(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		called = true
+	}))
+
+	handler.ServeHTTP(httptest.NewRecorder(), r)
+
+	if !called {
+		t.Fatal(`The next handler should be called`)
+	}
+
+	if r.Form != nil {
+		t.Fatal(`The request body should not be parsed when the header token is valid`)
+	}
+}
+
+func TestCSRFMiddlewareAcceptsMultipartFormWhenAuthenticated(t *testing.T) {
+	session := newCSRFTestSession(true)
+	body, contentType := newMultipartBody(t, map[string]string{"csrf": session.CSRF()}, []byte("<opml/>"))
+
+	r := httptest.NewRequest(http.MethodPost, "/upload", body)
+	r.Header.Set("Content-Type", contentType)
+	r = withCSRFTestSession(r, session)
+
+	called := false
+	handler := newCSRFMiddleware("").handle(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		called = true
+		file, _, err := r.FormFile("file")
+		if err != nil {
+			t.Fatalf(`Unable to read the uploaded file: %v`, err)
+		}
+		file.Close()
+	}))
+
+	handler.ServeHTTP(httptest.NewRecorder(), r)
+
+	if !called {
+		t.Fatal(`The next handler should be called`)
+	}
+}
+
+func TestCSRFMiddlewareRejectsQueryStringToken(t *testing.T) {
+	session := newCSRFTestSession(true)
+
+	r := httptest.NewRequest(http.MethodPost, "/feeds/refresh?csrf="+url.QueryEscape(session.CSRF()), nil)
+	r = withCSRFTestSession(r, session)
+
+	handler := newCSRFMiddleware("").handle(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		t.Fatal(`The next handler should not be called`)
+	}))
+
+	w := httptest.NewRecorder()
+	handler.ServeHTTP(w, r)
+
+	if w.Code != http.StatusBadRequest {
+		t.Fatalf(`Unexpected status code, got: %d`, w.Code)
+	}
+}
+
+func TestCSRFMiddlewareRemovesMultipartTemporaryFiles(t *testing.T) {
+	// os.TempDir reads TMPDIR on Unix and TMP on Windows.
+	tempDir := t.TempDir()
+	t.Setenv("TMPDIR", tempDir)
+	t.Setenv("TMP", tempDir)
+
+	session := newCSRFTestSession(true)
+	body, contentType := newMultipartBody(t, nil, bytes.Repeat([]byte("a"), 4096))
+
+	r := httptest.NewRequest(http.MethodPost, "/upload", body)
+	r.Header.Set("Content-Type", contentType)
+	r.Header.Set("X-Csrf-Token", session.CSRF())
+	r = withCSRFTestSession(r, session)
+
+	handler := newCSRFMiddleware("").handle(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		// A tiny memory limit forces the file part to be written to disk.
+		if err := r.ParseMultipartForm(1); err != nil {
+			t.Fatalf(`Unable to parse the multipart form: %v`, err)
+		}
+
+		entries, err := os.ReadDir(tempDir)
+		if err != nil {
+			t.Fatal(err)
+		}
+		if len(entries) == 0 {
+			t.Fatal(`Expected the file part to be stored in a temporary file`)
+		}
+	}))
+
+	handler.ServeHTTP(httptest.NewRecorder(), r)
+
+	entries, err := os.ReadDir(tempDir)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(entries) != 0 {
+		t.Fatalf(`Expected temporary files to be removed, found %d`, len(entries))
+	}
+}

+ 5 - 0
miniflux.1

@@ -364,6 +364,11 @@ that includes the Miniflux version.
 .IP
 .IP
 Default is empty.
 Default is empty.
 .TP
 .TP
+.B HTTP_SERVER_MAX_BODY_SIZE
+Maximum body size for incoming HTTP requests in Mebibyte (MiB).
+.IP
+Default is 15 MiB.
+.TP
 .B HTTP_SERVER_TIMEOUT
 .B HTTP_SERVER_TIMEOUT
 Read, write, and idle timeout in seconds for the HTTP server.
 Read, write, and idle timeout in seconds for the HTTP server.
 .IP
 .IP