diff --git a/Caddyfile b/Caddyfile index 4667cd8e51..373fcdc901 100644 --- a/Caddyfile +++ b/Caddyfile @@ -6,6 +6,29 @@ {$BASEROW_CADDY_GLOBAL_CONF} } +(baserow_media_files) { + handle_path /media/* { + @downloads { + query dl=* + } + header @downloads Content-Disposition "attachment; filename={query.dl}" + header X-Content-Type-Options "nosniff" + header Content-Security-Policy "sandbox; default-src 'none'; script-src 'none'; object-src 'none'; base-uri 'none'" + + # Allow to call head from public url to get size + header { + Access-Control-Allow-Origin {$BASEROW_PUBLIC_URL:http://localhost} + Access-Control-Allow-Methods "GET, HEAD, OPTIONS" + Access-Control-Allow-Headers "*" + Access-Control-Expose-Headers "Content-Length, Content-Type" + } + + file_server { + root {$MEDIA_ROOT:/baserow/media/} + } + } +} + {$BASEROW_CADDY_ADDRESSES} { tls { on_demand @@ -20,30 +43,27 @@ ` } + @is_baserow_media { + path /media/* + expression ` + "{$MEDIA_URL:}".startsWith("http://" + {http.request.host} + "/") || + "{$MEDIA_URL:}".startsWith("https://" + {http.request.host} + "/") || + "{$MEDIA_URL:}".startsWith("http://" + {http.request.host} + ":") || + "{$MEDIA_URL:}".startsWith("https://" + {http.request.host} + ":") + ` + } + + handle @is_baserow_media { + import baserow_media_files + } + handle @is_baserow_tool { @backend_routes path /api/* /ws/* /mcp/* /assistant/* {$BASEROW_CADDY_BACKEND_EXTRA_ROUTES:} handle @backend_routes { reverse_proxy {$PRIVATE_BACKEND_URL:localhost:8000} } - handle_path /media/* { - @downloads { - query dl=* - } - header @downloads Content-disposition "attachment; filename={query.dl}" - - # Allow to call head from public url to get size - header { - Access-Control-Allow-Origin {$BASEROW_PUBLIC_URL:http://localhost} - Access-Control-Allow-Methods "GET, HEAD, OPTIONS" - Access-Control-Allow-Headers "*" - Access-Control-Expose-Headers "Content-Length, Content-Type" - } - - file_server { - root {$MEDIA_ROOT:/baserow/media/} - } - } + import baserow_media_files handle_path /static/* { file_server { diff --git a/Caddyfile.dev b/Caddyfile.dev index a8d9ac84d8..3d342eebea 100644 --- a/Caddyfile.dev +++ b/Caddyfile.dev @@ -9,7 +9,9 @@ @downloads { query dl=* } - header @downloads Content-disposition "attachment; filename={query.dl}" + header @downloads Content-Disposition "attachment; filename={query.dl}" + header X-Content-Type-Options "nosniff" + header Content-Security-Policy "sandbox; default-src 'none'; script-src 'none'; object-src 'none'; base-uri 'none'" header { Access-Control-Allow-Origin {$PUBLIC_WEB_FRONTEND_URL:http://localhost:3000} diff --git a/backend/src/baserow/api/user_files/views.py b/backend/src/baserow/api/user_files/views.py index 46a5be76c8..c07d335f4d 100644 --- a/backend/src/baserow/api/user_files/views.py +++ b/backend/src/baserow/api/user_files/views.py @@ -10,6 +10,7 @@ from baserow.api.decorators import map_exceptions, validate_body from baserow.api.schemas import get_error_schema from baserow.contrib.database.api.tokens.authentications import TokenAuthentication from baserow.core.user_files.exceptions import ( + ActiveContentBlockedUserFileError, FileSizeTooLargeError, FileURLCouldNotBeReached, InvalidFileStreamError, @@ -49,6 +50,7 @@ class UploadFileView(APIView): { InvalidFileStreamError: ERROR_INVALID_FILE, FileSizeTooLargeError: ERROR_FILE_SIZE_TOO_LARGE, + ActiveContentBlockedUserFileError: ERROR_INVALID_FILE, } ) def post(self, request): @@ -93,6 +95,7 @@ class UploadViaURLView(APIView): FileSizeTooLargeError: ERROR_FILE_SIZE_TOO_LARGE, FileURLCouldNotBeReached: ERROR_FILE_URL_COULD_NOT_BE_REACHED, InvalidFileURLError: ERROR_INVALID_FILE_URL, + ActiveContentBlockedUserFileError: ERROR_INVALID_FILE, } ) @validate_body(UserFileUploadViaURLRequestSerializer) diff --git a/backend/src/baserow/config/settings/base.py b/backend/src/baserow/config/settings/base.py index 9f04b9b4ab..6f8a8c823f 100644 --- a/backend/src/baserow/config/settings/base.py +++ b/backend/src/baserow/config/settings/base.py @@ -611,6 +611,15 @@ BASEROW_FILE_UPLOAD_SIZE_LIMIT_MB = int( Decimal(os.getenv("BASEROW_FILE_UPLOAD_SIZE_LIMIT_MB", 1024 * 1024)) * 1024 * 1024 ) # ~1TB by default +FILE_UPLOAD_ACTIVE_CONTENT_POLICY = os.getenv( + "BASEROW_FILE_UPLOAD_ACTIVE_CONTENT_POLICY", "download" +).lower() +if FILE_UPLOAD_ACTIVE_CONTENT_POLICY not in ("download", "block"): + raise ImproperlyConfigured( + "BASEROW_FILE_UPLOAD_ACTIVE_CONTENT_POLICY must be set to " + "'download' or 'block'." + ) + BASEROW_OPENAI_UPLOADED_FILE_SIZE_LIMIT_MB = int( os.getenv("BASEROW_OPENAI_UPLOADED_FILE_SIZE_LIMIT_MB", 512) ) @@ -778,15 +787,22 @@ BASEROW_EMBEDDED_SHARE_URL = os.getenv("BASEROW_EMBEDDED_SHARE_URL") if not BASEROW_EMBEDDED_SHARE_URL: BASEROW_EMBEDDED_SHARE_URL = PUBLIC_WEB_FRONTEND_URL +MEDIA_URL_PATH = "/media/" +MEDIA_URL = os.getenv("MEDIA_URL", urljoin(PUBLIC_BACKEND_URL, MEDIA_URL_PATH)) + PRIVATE_BACKEND_URL = os.getenv("PRIVATE_BACKEND_URL", "http://backend:8000") PUBLIC_BACKEND_HOSTNAME = urlparse(PUBLIC_BACKEND_URL).hostname PUBLIC_WEB_FRONTEND_HOSTNAME = urlparse(PUBLIC_WEB_FRONTEND_URL).hostname BASEROW_EMBEDDED_SHARE_HOSTNAME = urlparse(BASEROW_EMBEDDED_SHARE_URL).hostname +MEDIA_URL_HOSTNAME = urlparse(MEDIA_URL).hostname PRIVATE_BACKEND_HOSTNAME = urlparse(PRIVATE_BACKEND_URL).hostname if PUBLIC_BACKEND_HOSTNAME: ALLOWED_HOSTS.append(PUBLIC_BACKEND_HOSTNAME) +if MEDIA_URL_HOSTNAME: + ALLOWED_HOSTS.append(MEDIA_URL_HOSTNAME) + if PRIVATE_BACKEND_HOSTNAME: ALLOWED_HOSTS.append(PRIVATE_BACKEND_HOSTNAME) @@ -951,8 +967,6 @@ BASEROW_INITIAL_CREATE_SYNC_TABLE_DATA_LIMIT = int( os.getenv("BASEROW_INITIAL_CREATE_SYNC_TABLE_DATA_LIMIT", 5000) ) -MEDIA_URL_PATH = "/media/" -MEDIA_URL = os.getenv("MEDIA_URL", urljoin(PUBLIC_BACKEND_URL, MEDIA_URL_PATH)) MEDIA_ROOT = os.getenv("MEDIA_ROOT", "/baserow/media") # Indicates the directory where the user files and user thumbnails are stored. diff --git a/backend/src/baserow/contrib/builder/api/domains/views.py b/backend/src/baserow/contrib/builder/api/domains/views.py index 8a0a0b79af..481c5f3a47 100644 --- a/backend/src/baserow/contrib/builder/api/domains/views.py +++ b/backend/src/baserow/contrib/builder/api/domains/views.py @@ -401,6 +401,8 @@ class AskPublicBuilderDomainExistsView(APIView): + settings.EXTRA_PUBLIC_BACKEND_HOSTNAMES + settings.EXTRA_PUBLIC_WEB_FRONTEND_HOSTNAMES ) + if settings.MEDIA_URL_HOSTNAME: + allowed_domain.add(settings.MEDIA_URL_HOSTNAME) if domain_name in allowed_domain: return Response(None, status=200) diff --git a/backend/src/baserow/core/user_files/exceptions.py b/backend/src/baserow/core/user_files/exceptions.py index 3c0cd7d077..b08165ab9b 100644 --- a/backend/src/baserow/core/user_files/exceptions.py +++ b/backend/src/baserow/core/user_files/exceptions.py @@ -15,6 +15,10 @@ class FileSizeTooLargeError(Exception): super().__init__(*args, **kwargs) +class ActiveContentBlockedUserFileError(Exception): + """Raised when the file upload active content policy blocks a file.""" + + class FileURLCouldNotBeReached(Exception): """ Raised when the provided URL could not be reached or points to an internal diff --git a/backend/src/baserow/core/user_files/handler.py b/backend/src/baserow/core/user_files/handler.py index e214db7481..20b1842983 100644 --- a/backend/src/baserow/core/user_files/handler.py +++ b/backend/src/baserow/core/user_files/handler.py @@ -31,6 +31,7 @@ from baserow.core.storage import ( from baserow.core.utils import random_string, sha256_hash, stream_size, truncate_middle from .exceptions import ( + ActiveContentBlockedUserFileError, FileSizeTooLargeError, FileURLCouldNotBeReached, InvalidFileStreamError, @@ -43,9 +44,66 @@ if TYPE_CHECKING: from PIL import Image MIME_TYPE_UNKNOWN = "application/octet-stream" +ACTIVE_CONTENT_EXTENSIONS = {"html", "htm", "xhtml", "xml", "svg", "svgz"} +ACTIVE_CONTENT_MIME_TYPES = { + "application/xhtml+xml", + "application/xml", + "image/svg+xml", + "text/html", + "text/xml", +} class UserFileHandler: + def _is_active_content_extension(self, extension: str) -> bool: + return extension.lower() in ACTIVE_CONTENT_EXTENSIONS + + def _is_active_content_mime_type(self, mime_type: str) -> bool: + return mime_type.lower() in ACTIVE_CONTENT_MIME_TYPES + + def _resolve_mime_type_and_active_content( + self, file_name: str, extension: str, stream + ) -> tuple[str, bool]: + """ + Resolves the MIME type for an uploaded file and decides whether it should be + treated as active content. + + Both the filename-derived MIME type and the client-supplied `content_type` are + checked independently against the active-content blocklist so that a malicious + client cannot bypass the gate by pairing an innocuous extension with a dangerous + Content-Type header (or vice versa). + + :param file_name: The name of the uploaded file. + :param extension: The file extension of the uploaded file. + :param stream: The file content stream of the uploaded file, which may have a + `content_type` attribute. + :return: A tuple of the resolved MIME type and whether the file is considered + active content. + """ + + guessed_mime_type = mimetypes.guess_type(file_name)[0] + uploaded_mime_type = getattr(stream, "content_type", None) + mime_type = guessed_mime_type or uploaded_mime_type or MIME_TYPE_UNKNOWN + is_active_content = ( + self._is_active_content_extension(extension) + or ( + guessed_mime_type is not None + and self._is_active_content_mime_type(guessed_mime_type) + ) + or ( + uploaded_mime_type is not None + and self._is_active_content_mime_type(uploaded_mime_type) + ) + ) + return mime_type, is_active_content + + def _neutralize_active_content(self, user_file: UserFile) -> UserFile: + user_file.mime_type = MIME_TYPE_UNKNOWN + user_file.is_image = False + user_file.image_width = None + user_file.image_height = None + return user_file + def is_user_file_name(self, user_file_name: str) -> bool: """ Checks if the given name is a user file name. @@ -266,6 +324,15 @@ class UserFileHandler: storage = storage or get_default_storage() stream_hash = sha256_hash(stream) file_name = truncate_middle(file_name, 64) + extension = pathlib.Path(file_name).suffix[1:].lower() + mime_type, is_active_content = self._resolve_mime_type_and_active_content( + file_name, extension, stream + ) + + if is_active_content and settings.FILE_UPLOAD_ACTIVE_CONTENT_POLICY == "block": + raise ActiveContentBlockedUserFileError( + "The provided file type is not allowed." + ) existing_user_file = UserFile.objects.filter( original_name=file_name, @@ -274,14 +341,18 @@ class UserFileHandler: ).first() if existing_user_file: + if is_active_content: + self._neutralize_active_content(existing_user_file) + existing_user_file.save( + update_fields=[ + "mime_type", + "is_image", + "image_width", + "image_height", + ] + ) return existing_user_file - extension = pathlib.Path(file_name).suffix[1:].lower() - mime_type = ( - mimetypes.guess_type(file_name)[0] - or getattr(stream, "content_type", None) - or MIME_TYPE_UNKNOWN - ) unique = self.generate_unique(stream_hash, extension) user_file = UserFile( original_name=file_name, @@ -293,26 +364,30 @@ class UserFileHandler: sha256_hash=stream_hash, ) - image = None - try: - image = Image.open(stream) - user_file.mime_type = f"image/{image.format}".lower() - self.generate_and_save_image_thumbnails( - image, user_file.name, storage=storage - ) - # Skip marking as images if thumbnails cannot be generated (i.e. PSD files). - user_file.is_image = True - user_file.image_width = image.width - user_file.image_height = image.height - except IOError: - pass # Not an image - except Exception as exc: - logger.warning( - f"Failed to generate thumbnails for user file of type {mime_type}: {exc}" - ) - finally: - if image is not None: - del image + if is_active_content: + self._neutralize_active_content(user_file) + else: + image = None + try: + image = Image.open(stream) + user_file.mime_type = f"image/{image.format}".lower() + self.generate_and_save_image_thumbnails( + image, user_file.name, storage=storage + ) + # Skip marking as images if thumbnails cannot be generated (i.e. PSD files). + user_file.is_image = True + user_file.image_width = image.width + user_file.image_height = image.height + except IOError: + pass # Not an image + except Exception as exc: + logger.warning( + f"Failed to generate thumbnails for user file of type " + f"{mime_type}: {exc}" + ) + finally: + if image is not None: + del image user_file.save() diff --git a/backend/tests/baserow/api/user_files/test_user_files_views.py b/backend/tests/baserow/api/user_files/test_user_files_views.py index 2310d92d80..fbf0c7c7c8 100644 --- a/backend/tests/baserow/api/user_files/test_user_files_views.py +++ b/backend/tests/baserow/api/user_files/test_user_files_views.py @@ -4,6 +4,7 @@ from django.conf import settings from django.core.files.storage import FileSystemStorage from django.core.files.uploadedfile import SimpleUploadedFile from django.shortcuts import reverse +from django.test import override_settings import pytest import responses @@ -19,6 +20,22 @@ from baserow.contrib.database.tokens.handler import TokenHandler from baserow.core.models import UserFile +@pytest.mark.django_db +@override_settings(FILE_UPLOAD_ACTIVE_CONTENT_POLICY="block") +def test_upload_file_active_content_blocked(api_client, data_fixture): + user, token = data_fixture.create_user_and_token() + + response = api_client.post( + reverse("api:user_files:upload_file"), + data={"file": SimpleUploadedFile("index.html", b"")}, + format="multipart", + HTTP_AUTHORIZATION=f"JWT {token}", + ) + + assert response.status_code == HTTP_400_BAD_REQUEST + assert response.json()["error"] == "ERROR_INVALID_FILE" + + @pytest.mark.django_db def test_upload_file_with_jwt_auth(api_client, data_fixture, tmpdir): user, token = data_fixture.create_user_and_token( diff --git a/backend/tests/baserow/contrib/builder/api/domains/test_domain_public_views.py b/backend/tests/baserow/contrib/builder/api/domains/test_domain_public_views.py index 63e375f9c7..05ef30024b 100644 --- a/backend/tests/baserow/contrib/builder/api/domains/test_domain_public_views.py +++ b/backend/tests/baserow/contrib/builder/api/domains/test_domain_public_views.py @@ -646,6 +646,7 @@ def test_ask_public_builder_domain_exists(api_client, data_fixture): @override_settings( PUBLIC_BACKEND_HOSTNAME="backend.localhost", PUBLIC_WEB_FRONTEND_HOSTNAME="web-frontend.localhost", + MEDIA_URL_HOSTNAME="media.localhost", ) def test_ask_public_builder_domain_exists_with_public_backend_and_web_frontend_domains( api_client, data_fixture @@ -662,6 +663,10 @@ def test_ask_public_builder_domain_exists_with_public_backend_and_web_frontend_d response = api_client.get(url) assert response.status_code == 200 + url = reverse("api:builder:domains:ask_exists") + "?domain=media.localhost" + response = api_client.get(url) + assert response.status_code == 200 + @pytest.mark.django_db @override_settings( diff --git a/backend/tests/baserow/core/user_file/test_user_file_handler.py b/backend/tests/baserow/core/user_file/test_user_file_handler.py index b4b0a53a89..82e1b8f4b5 100644 --- a/backend/tests/baserow/core/user_file/test_user_file_handler.py +++ b/backend/tests/baserow/core/user_file/test_user_file_handler.py @@ -8,6 +8,8 @@ from django.conf import settings from django.core.exceptions import SuspiciousFileOperation from django.core.files.base import ContentFile from django.core.files.storage import FileSystemStorage +from django.core.files.uploadedfile import SimpleUploadedFile +from django.test import override_settings import pytest import responses @@ -18,13 +20,14 @@ from PIL import Image from baserow.core.models import UserFile from baserow.core.storage import ExportZipFile from baserow.core.user_files.exceptions import ( + ActiveContentBlockedUserFileError, FileSizeTooLargeError, FileURLCouldNotBeReached, InvalidFileStreamError, InvalidFileURLError, MaximumUniqueTriesError, ) -from baserow.core.user_files.handler import UserFileHandler +from baserow.core.user_files.handler import MIME_TYPE_UNKNOWN, UserFileHandler GENERATED_FILE_NAME_LENGTH = 16 # 12 hexdigest + '.' + ext @@ -286,6 +289,60 @@ def test_upload_user_file_with_unsupported_image_format( assert not file_path.isfile() +@pytest.mark.django_db +@override_settings(FILE_UPLOAD_ACTIVE_CONTENT_POLICY="download") +def test_upload_user_file_active_content_download_policy(data_fixture, tmpdir): + user = data_fixture.create_user() + storage = FileSystemStorage(location=str(tmpdir), base_url="http://localhost") + handler = UserFileHandler() + + user_file = handler.upload_user_file( + user, + "logo.svg", + ContentFile(b''), + storage=storage, + ) + + assert user_file.original_extension == "svg" + assert user_file.mime_type == MIME_TYPE_UNKNOWN + assert user_file.is_image is False + assert user_file.image_width is None + assert user_file.image_height is None + assert tmpdir.join("user_files", user_file.name).isfile() + assert not tmpdir.join("thumbnails", "tiny", user_file.name).isfile() + + +@pytest.mark.django_db +@override_settings(FILE_UPLOAD_ACTIVE_CONTENT_POLICY="block") +@pytest.mark.parametrize( + "file_name", + ["index.html", "index.htm", "page.xhtml", "feed.xml", "logo.svg", "logo.svgz"], +) +def test_upload_user_file_active_content_block_policy(data_fixture, tmpdir, file_name): + user = data_fixture.create_user() + storage = FileSystemStorage(location=str(tmpdir), base_url="http://localhost") + + with pytest.raises(ActiveContentBlockedUserFileError): + UserFileHandler().upload_user_file( + user, file_name, ContentFile(b"active content"), storage=storage + ) + + +@pytest.mark.django_db +@override_settings(FILE_UPLOAD_ACTIVE_CONTENT_POLICY="block") +def test_upload_user_file_active_content_block_policy_uses_mime_type( + data_fixture, tmpdir +): + user = data_fixture.create_user() + storage = FileSystemStorage(location=str(tmpdir), base_url="http://localhost") + file = SimpleUploadedFile( + "active-content.txt", b"", content_type="text/html" + ) + + with pytest.raises(ActiveContentBlockedUserFileError): + UserFileHandler().upload_user_file(user, file.name, file, storage=storage) + + @pytest.mark.django_db @responses.activate def test_upload_user_file_by_url(data_fixture, tmpdir): diff --git a/changelog/entries/unreleased/bug/harden_user_file_media_serving.json b/changelog/entries/unreleased/bug/harden_user_file_media_serving.json new file mode 100644 index 0000000000..575a79b48e --- /dev/null +++ b/changelog/entries/unreleased/bug/harden_user_file_media_serving.json @@ -0,0 +1,9 @@ +{ + "type": "bug", + "message": "Hardened user uploaded media serving and neutralized active-content file uploads by default.", + "issue_origin": "github", + "issue_number": null, + "domain": "core", + "bullet_points": [], + "created_at": "2026-04-28" +} diff --git a/deploy/all-in-one/docker-compose.yml b/deploy/all-in-one/docker-compose.yml index ae520e1dbd..38613a7052 100644 --- a/deploy/all-in-one/docker-compose.yml +++ b/deploy/all-in-one/docker-compose.yml @@ -11,6 +11,8 @@ services: EMAIL_SMTP_HOST: 'mailhog' EMAIL_SMTP_PORT: '1025' BASEROW_PUBLIC_URL: + MEDIA_URL: + BASEROW_FILE_UPLOAD_ACTIVE_CONTENT_POLICY: ports: - "80:80" - "443:443" diff --git a/deploy/apache/no-caddy/sub-domain.conf b/deploy/apache/no-caddy/sub-domain.conf index 1f842d0142..a381413346 100644 --- a/deploy/apache/no-caddy/sub-domain.conf +++ b/deploy/apache/no-caddy/sub-domain.conf @@ -5,11 +5,13 @@ ProxyPreserveHost On # Replace with your sub domain ServerName example.localhost -# Serve user uploaded files and add the Content-Disposition header when the filename -# query param is set. +# Serve user uploaded files with download and sandboxing headers. +RewriteRule ^/media/.* - [E=IS_MEDIA:1] RewriteCond %{QUERY_STRING} (?:^|&)dl=([^&]+) RewriteRule ^/media/.* - [E=FILENAME:%1] Header set "Content-Disposition" "attachment; filename=\"%{FILENAME}e\"" env=FILENAME +Header set "X-Content-Type-Options" "nosniff" env=IS_MEDIA +Header set "Content-Security-Policy" "sandbox; default-src 'none'; script-src 'none'; object-src 'none'; base-uri 'none'" env=IS_MEDIA ProxyPass /media ! Alias /media /baserow/media diff --git a/deploy/nginx/no-caddy/nginx.conf b/deploy/nginx/no-caddy/nginx.conf index e5f4fe6a56..469e91b2a2 100644 --- a/deploy/nginx/no-caddy/nginx.conf +++ b/deploy/nginx/no-caddy/nginx.conf @@ -7,6 +7,12 @@ error_log /dev/stdout info; http { access_log /dev/stdout; client_max_body_size 20m; + + map $arg_dl $baserow_media_content_disposition { + default "attachment; filename=$arg_dl"; + "" ""; + } + server { server_name example.localhost; @@ -22,9 +28,9 @@ http { } location /media/ { - if ($arg_dl) { - add_header Content-disposition "attachment; filename=$arg_dl"; - } + add_header Content-Disposition $baserow_media_content_disposition always; + add_header X-Content-Type-Options "nosniff" always; + add_header Content-Security-Policy "sandbox; default-src 'none'; script-src 'none'; object-src 'none'; base-uri 'none'" always; # TODO Change to your media folder location! alias /baserow/media/; } diff --git a/docker-compose.no-caddy.yml b/docker-compose.no-caddy.yml index 88855be98b..43a4e00281 100644 --- a/docker-compose.no-caddy.yml +++ b/docker-compose.no-caddy.yml @@ -82,6 +82,7 @@ x-backend-variables: BATCH_ROWS_SIZE_LIMIT: INITIAL_TABLE_DATA_LIMIT: BASEROW_FILE_UPLOAD_SIZE_LIMIT_MB: + BASEROW_FILE_UPLOAD_ACTIVE_CONTENT_POLICY: BASEROW_OPENAI_UPLOADED_FILE_SIZE_LIMIT_MB: BASEROW_UNIQUE_ROW_VALUES_SIZE_LIMIT: @@ -225,6 +226,7 @@ services: - "${HOST_PUBLISH_IP:-127.0.0.1}:3000:3000" environment: BASEROW_PUBLIC_URL: + MEDIA_URL: PRIVATE_BACKEND_URL: ${PRIVATE_BACKEND_URL:-http://backend:8000} PUBLIC_BACKEND_URL: PUBLIC_WEB_FRONTEND_URL: diff --git a/docker-compose.yml b/docker-compose.yml index 4f30b0014e..f6a789787e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -96,6 +96,7 @@ x-backend-variables: BATCH_ROWS_SIZE_LIMIT: INITIAL_TABLE_DATA_LIMIT: BASEROW_FILE_UPLOAD_SIZE_LIMIT_MB: + BASEROW_FILE_UPLOAD_ACTIVE_CONTENT_POLICY: BASEROW_OPENAI_UPLOADED_FILE_SIZE_LIMIT_MB: BASEROW_UNIQUE_ROW_VALUES_SIZE_LIMIT: @@ -273,6 +274,7 @@ services: PRIVATE_WEB_FRONTEND_URL: ${PRIVATE_WEB_FRONTEND_URL:-http://web-frontend:3000} PRIVATE_BACKEND_URL: ${PRIVATE_BACKEND_URL:-http://backend:8000} BASEROW_PUBLIC_URL: ${BASEROW_PUBLIC_URL:-} + MEDIA_URL: ${MEDIA_URL:-} ports: - "${HOST_PUBLISH_IP:-0.0.0.0}:${WEB_FRONTEND_PORT:-80}:80" - "${HOST_PUBLISH_IP:-0.0.0.0}:${WEB_FRONTEND_SSL_PORT:-443}:443" @@ -303,6 +305,7 @@ services: restart: unless-stopped environment: BASEROW_PUBLIC_URL: ${BASEROW_PUBLIC_URL-http://localhost} + MEDIA_URL: BASEROW_EXTRA_PUBLIC_URLS: PRIVATE_BACKEND_URL: ${PRIVATE_BACKEND_URL:-http://backend:8000} PUBLIC_BACKEND_URL: diff --git a/docs/installation/configuration-files/nginx.conf b/docs/installation/configuration-files/nginx.conf index 5ffa15fbd4..9f7ae9e288 100644 --- a/docs/installation/configuration-files/nginx.conf +++ b/docs/installation/configuration-files/nginx.conf @@ -62,6 +62,11 @@ server { } # Media +map $arg_dl $baserow_media_content_disposition { + default "attachment; filename=$arg_dl"; + "" ""; +} + server { listen 80; server_name "*YOUR_MEDIA_DOMAIN*"; @@ -71,24 +76,23 @@ server { gzip_disable "msie6"; location / { - if ($arg_dl) { - add_header Content-disposition "attachment; filename=$arg_dl"; - } + add_header Content-Disposition $baserow_media_content_disposition always; + add_header X-Content-Type-Options "nosniff" always; + add_header Content-Security-Policy "sandbox; default-src 'none'; script-src 'none'; object-src 'none'; base-uri 'none'" always; root /baserow/media; } location /user_files { - if ($arg_dl) { - add_header Content-disposition "attachment; filename=$arg_dl"; - } + add_header Content-Disposition $baserow_media_content_disposition always; + add_header X-Content-Type-Options "nosniff" always; + add_header Content-Security-Policy "sandbox; default-src 'none'; script-src 'none'; object-src 'none'; base-uri 'none'" always; root /baserow/media; } location /export_files { - if ($arg_dl) { - add_header Content-disposition "attachment; filename=$arg_dl"; - } + add_header Content-Disposition $baserow_media_content_disposition always; + add_header X-Content-Type-Options "nosniff" always; + add_header Content-Security-Policy "sandbox; default-src 'none'; script-src 'none'; object-src 'none'; base-uri 'none'" always; root /baserow/media; } } - diff --git a/docs/installation/configuration.md b/docs/installation/configuration.md index 4b96496f12..841e9f066d 100644 --- a/docs/installation/configuration.md +++ b/docs/installation/configuration.md @@ -55,6 +55,7 @@ The installation methods referred to in the variable descriptions are: | INITIAL\_TABLE\_DATA\_LIMIT | The amount of rows that can be imported when creating a table. Defaults to empty which means unlimited rows. | | | BASEROW\_ROW\_PAGE\_SIZE\_LIMIT | The maximum number of rows that can be requested at once. | 200 | | BASEROW\_FILE_UPLOAD\_SIZE\_LIMIT\_MB | The max file size in MB allowed to be uploaded by users into a Baserow File Field. | 1048576 (1 TB or 1024*1024) | +| BASEROW\_FILE\_UPLOAD\_ACTIVE\_CONTENT\_POLICY | Controls how uploads with active-content extensions (`.html`, `.htm`, `.xhtml`, `.xml`, `.svg`, `.svgz`) or MIME types (`text/html`, `text/xml`, `application/xml`, `application/xhtml+xml`, `image/svg+xml`) are handled. Set to `download` to allow them but store them as `application/octet-stream` without image previews. Set to `block` to reject them. | download | | BASEROW\_OPENAI\_UPLOADED\_FILE\_SIZE\_LIMIT\_MB | The max file size in MB allowed to be loaded in RAM and uploaded to OpenAI servers. See also [OpenAI docs](https://platform.openai.com/docs/api-reference/files/create). | 512 | | BATCH\_ROWS\_SIZE\_LIMIT | Controls how many rows can be created, deleted or updated at once using the batch endpoints. | 200 | | BATCH\_ROWS\_SIZE\_LIMIT | Controls how many rows can be created, deleted or updated at once using the batch endpoints. | 200 | @@ -305,7 +306,7 @@ domain than your Baserow, you need to make sure CORS is configured correctly. | Name | Description | Defaults | |----------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------| -| MEDIA\_URL | **INTERNAL** The URL at which user uploaded media files will be made available | $PUBLIC\_BACKEND\_URL/media/ | +| MEDIA\_URL | The URL at which user uploaded media files will be made available. Set this to a different origin, for example `https://media.baserow.example.com/media/`, to serve user uploads from an isolated media domain. | $PUBLIC\_BACKEND\_URL/media/ | | MEDIA\_ROOT | **INTERNAL** The folder in which the backend will store user uploaded files | /baserow/media or $DATA_DIR/media for the `baserow/baserow` all-in-one image | | **
** | | | | AWS\_ACCESS\_KEY\_ID | The access key for your AWS account. When set to anything other than empty will switch Baserow to use a S3 compatible bucket for storing user file uploads. | | diff --git a/docs/installation/install-behind-apache.md b/docs/installation/install-behind-apache.md index 645db490ac..0be54723f8 100644 --- a/docs/installation/install-behind-apache.md +++ b/docs/installation/install-behind-apache.md @@ -180,11 +180,13 @@ ProxyPreserveHost On # Replace with your sub domain ServerName example.localhost -# Serve user uploaded files and add the Content-Disposition header when the filename -# query param is set. +# Serve user uploaded files with download and sandboxing headers. +RewriteRule ^/media/.* - [E=IS_MEDIA:1] RewriteCond %{QUERY_STRING} (?:^|&)dl=([^&]+) RewriteRule ^/media/.* - [E=FILENAME:%1] Header set "Content-Disposition" "attachment; filename=\"%{FILENAME}e\"" env=FILENAME +Header set "X-Content-Type-Options" "nosniff" env=IS_MEDIA +Header set "Content-Security-Policy" "sandbox; default-src 'none'; script-src 'none'; object-src 'none'; base-uri 'none'" env=IS_MEDIA ProxyPass /media ! Alias /media /var/www @@ -229,4 +231,3 @@ them (you are getting 403 denied errors when accessing the files) then: your Apache user by running `cd /var/web && chmod 755 *`. * Fix any file permissions found inside the `/var/web` sub-folders to be readable by your Apache user. - diff --git a/docs/installation/install-behind-nginx.md b/docs/installation/install-behind-nginx.md index bd0007996d..7e9de4e937 100644 --- a/docs/installation/install-behind-nginx.md +++ b/docs/installation/install-behind-nginx.md @@ -61,6 +61,11 @@ Create a new `baserow.conf` in `/etc/nginx/sites-available/` with the following > your particular Baserow deployment. ``` +map $arg_dl $baserow_media_content_disposition { + default "attachment; filename=$arg_dl"; + "" ""; +} + server { server_name baserow.example.com; @@ -168,9 +173,9 @@ server { } location /media/ { - if ($arg_dl) { - add_header Content-disposition "attachment; filename=$arg_dl"; - } + add_header Content-Disposition $baserow_media_content_disposition always; + add_header X-Content-Type-Options "nosniff" always; + add_header Content-Security-Policy "sandbox; default-src 'none'; script-src 'none'; object-src 'none'; base-uri 'none'" always; # TODO Change to your media folder location! alias /var/www/; } @@ -207,4 +212,3 @@ them (you are getting 403 denied errors when accessing the files) then: your Nginx user by running `cd /var/web && chmod 755 *`. * Fix any file permissions found inside the `/var/web` sub-folders to be readable by your Nginx user. - diff --git a/docs/installation/install-using-standalone-images.md b/docs/installation/install-using-standalone-images.md index a28cd684c2..d82fed2231 100644 --- a/docs/installation/install-using-standalone-images.md +++ b/docs/installation/install-using-standalone-images.md @@ -54,9 +54,11 @@ images: * Redirect `/api/` and `/ws/` requests to the backend gunicorn service without dropping these prefixes. * Serve the files in the `/baserow/media` folder in the backend gunicorn service - (share with your proxy using a volume) at the `/media` endpoint. Ensure - that requests with a `dl` query parameter have a `Content-disposition` header added - with the value of `attachment; filename=THE_DL_QUERY_PARAM_VALUE` + (share with your proxy using a volume) at the `/media` endpoint. Ensure all media + responses have `X-Content-Type-Options: nosniff` and + `Content-Security-Policy: sandbox; default-src 'none'; script-src 'none'; object-src 'none'; base-uri 'none'`. + Requests with a `dl` query parameter can use + `Content-Disposition: attachment; filename=THE_DL_QUERY_PARAM_VALUE`. * Send all other requests to the web-frontend service. * You must provide all email related environment variables to both the backend and celery-worker services. This is because the `celery-worker` service is the one diff --git a/e2e-tests/fixtures/e2e-db.dump b/e2e-tests/fixtures/e2e-db.dump index 1af0563b1a..5a05f18fc4 100644 Binary files a/e2e-tests/fixtures/e2e-db.dump and b/e2e-tests/fixtures/e2e-db.dump differ