Skip to contentSkip to conversation

Security fixes: XSS, bulk change access checks, error disclosure

PATCH New Tim Orling 1 participant 5 messages Oct 20

lore
Share & tools
lore

Tim Orling

author
#0 lore raw

cover Security fixes: XSS, bulk change access checks, error disclosure

These fix security problems found with GitHub CodeQL and manual review. They were held back until layers.openembedded.org had been updated.

1: Reflected XSS in the recipe CSV export: an invalid "fields" value was
echoed back as text/html.
2: The bulk change edit, review and patch views had no login or owner
check, so anyone could view or edit another user's bulk change.
3: Patch generation errors (tracebacks, server paths, BitBake output)
were returned to the browser.
4: A test for the existing protection that an email change on the
profile page needs reactivation through the new address.

Tim Orling (4):
layerindex/views: fix reflected XSS in recipes CSV export
layerindex: restrict bulk changes to their owner layerindex/views: don't expose patch generation errors to users
tests: check that changing the profile email requires reactivation

 layerindex/urls.py              | 10 ++---
 layerindex/views.py             | 39 ++++++++++++++-----
 tests/test_bulkchange_access.py | 64 +++++++++++++++++++++++++++++++
 tests/test_profile_email.py     | 67 +++++++++++++++++++++++++++++++++
 tests/test_recipes_csv.py       | 33 ++++++++++++++++
 5 files changed, 198 insertions(+), 15 deletions(-)
 create mode 100644 tests/test_bulkchange_access.py
 create mode 100644 tests/test_profile_email.py
 create mode 100644 tests/test_recipes_csv.py

base-commit: 5b55c485d56be9a7314b329ca5d2466a72e7ac48

Signature · 1 line
2.56.0
author
#1 lore raw

PATCH 1/4 layerindex/views: fix reflected XSS in recipes CSV export

layer_export_recipes_csv_view echoed an invalid name from the "fields" query parameter back in an HttpResponse with the default text/html content type, so a crafted link could run script on the site without the victim being logged in. Return the error as text/plain with status 400 instead.

Reported by CodeQL (py/reflective-xss).

AI-Generated: Claude Opus 5.5

---
 layerindex/views.py       |  2 +-
 tests/test_recipes_csv.py | 33 +++++++++++++++++++++++++++++++++
 2 files changed, 34 insertions(+), 1 deletion(-)
 create mode 100644 tests/test_recipes_csv.py
layerindex/views.py +1 -1
index dea0a98..c030ae1 100644
@@ -1599,7 +1599,7 @@ def layer_export_recipes_csv_view(request, branch, slug):
     recipe_fields = [f.name for f in Recipe._meta.get_fields() if not (f.auto_created and f.is_relation)]
     for field in fieldlist:
         if field not in recipe_fields:
-            return HttpResponse('Field %s is invalid' % field)
+            return HttpResponse('Field %s is invalid' % field, content_type='text/plain', status=400)
 
     writer = csv.writer(response)
     for recipe in layerbranch.sorted_recipes():
tests/test_recipes_csv.py new file +33 -0
new file mode 100644
index 0000000..9ed9084
@@ -0,0 +1,33 @@
+# layerindex-web - tests for the layer recipes CSV export
+#
+# Licensed under the MIT license, see COPYING.MIT for details
+#
+# SPDX-License-Identifier: MIT
+
+import pytest
+from django.test import TestCase
+from django.urls import reverse
+
+from layerindex.models import Branch, LayerItem, LayerBranch
+
+
[email protected]_db
+class TestRecipesCsv(TestCase):
+
+    def setUp(self):
+        branch = Branch.objects.create(name='master', bitbake_branch='master')
+        layer = LayerItem.objects.create(name='meta-test', status='P', layer_type='A',
+                                         summary='test', description='test',
+                                         vcs_url='git://example.com/meta-test.git')
+        LayerBranch.objects.create(layer=layer, branch=branch)
+        self.url = reverse('layer_export_recipes_csv', args=('master', 'meta-test'))
+
+    def test_valid_fields(self):
+        response = self.client.get(self.url, {'fields': 'pn,pv'})
+        self.assertEqual(response.status_code, 200)
+        self.assertTrue(response['Content-Type'].startswith('text/csv'))
+
+    def test_invalid_field_not_reflected_as_html(self):
+        response = self.client.get(self.url, {'fields': '<script>alert(1)</script>'})
+        self.assertEqual(response.status_code, 400)
+        self.assertTrue(response['Content-Type'].startswith('text/plain'))
Signature · 1 line
2.56.0
author
#2 lore raw

PATCH 2/4 layerindex: restrict bulk changes to their owner

In reply to Tim Orling

The bulk change search and delete views only allow the user who owns the changeset, but the edit, review and patch views did not check ownership or require a login. Anyone could view or edit another user's bulk change, or start patch generation for it.

Require a login for all of these views and look the changeset up by owner, so other users' changesets return 404 as the delete view already does. Also require a login for the delete view, which otherwise failed for anonymous users.

AI-Generated: Claude Opus 5.5

---
 layerindex/urls.py              | 10 +++----
 layerindex/views.py             | 23 ++++++++++++--
 tests/test_bulkchange_access.py | 53 +++++++++++++++++++++++++++++++++
 3 files changed, 78 insertions(+), 8 deletions(-)
 create mode 100644 tests/test_bulkchange_access.py
layerindex/urls.py +4 -6
index 51a832d..92f419f 100644
@@ -6,18 +6,18 @@
 #
 # SPDX-License-Identifier: MIT
 
-from django.views.generic import TemplateView, DetailView, ListView, RedirectView
+from django.views.generic import TemplateView, ListView, RedirectView
 from django.views.defaults import page_not_found
 from django.urls import include, re_path, reverse_lazy
 from layerindex.views import LayerListView, LayerReviewListView, LayerReviewDetailView, RecipeSearchView, \
     MachineSearchView, LayerDetailView, edit_layer_view, delete_layer_view, edit_layernote_view, delete_layernote_view, \
     HistoryListView, EditProfileFormView, AdvancedRecipeSearchView, BulkChangeView, BulkChangeSearchView, \
-    bulk_change_edit_view, bulk_change_patch_view, BulkChangeDeleteView, RecipeDetailView, RedirectParamsView, \
+    bulk_change_edit_view, bulk_change_patch_view, BulkChangeReviewView, BulkChangeDeleteView, RecipeDetailView, RedirectParamsView, \
     ClassicRecipeSearchView, ClassicRecipeDetailView, ClassicRecipeStatsView, LayerUpdateDetailView, UpdateListView, \
     UpdateDetailView, StatsView, publish_view, LayerCheckListView, BBClassCheckListView, TaskStatusView, \
     ComparisonRecipeSelectView, ComparisonRecipeSelectDetailView, task_log_view, task_stop_view, email_test_view, \
     BranchCompareView, RecipeDependenciesView, update_layer_view
-from layerindex.models import LayerItem, Recipe, RecipeChangeset
+from layerindex.models import LayerItem, Recipe
 from rest_framework import routers
 from . import restviews
 
@@ -97,9 +97,7 @@ urlpatterns = [
     re_path(r'^bulkchange/(?P<pk>\d+)/edit/$',
         bulk_change_edit_view, {'template_name': 'layerindex/bulkchangeedit.html'}, name="bulk_change_edit"),
     re_path(r'^bulkchange/(?P<pk>\d+)/review/$',
-        DetailView.as_view(
-            model=RecipeChangeset,
-            context_object_name='changeset',
+        BulkChangeReviewView.as_view(
             template_name='layerindex/bulkchangereview.html'),
         name="bulk_change_review"),
     re_path(r'^bulkchange/(?P<pk>\d+)/patches/$',
layerindex/views.py +21 -2
index c030ae1..42722bf 100644
@@ -307,8 +307,9 @@ def edit_layer_view(request, template_name, branch='master', slug=None):
         'return_url': return_url,
     })
 
+@login_required
 def bulk_change_edit_view(request, template_name, pk):
-    changeset = get_object_or_404(RecipeChangeset, pk=pk)
+    changeset = get_object_or_404(RecipeChangeset, pk=pk, user=request.user)
 
     if request.method == 'POST':
         formset = BulkChangeEditFormSet(request.POST, queryset=changeset.recipechange_set.all())
@@ -322,8 +323,9 @@ def bulk_change_edit_view(request, template_name, pk):
         'formset': formset,
     })
 
+@login_required
 def bulk_change_patch_view(request, pk):
-    changeset = get_object_or_404(RecipeChangeset, pk=pk)
+    changeset = get_object_or_404(RecipeChangeset, pk=pk, user=request.user)
     # FIXME this couples the web server and machine running the update script together,
     # but given that it's a separate script the way is open to decouple them in future
     try:
@@ -855,10 +857,27 @@ class BaseDeleteView(DeleteView):
         return context
 
 
+class BulkChangeReviewView(DetailView):
+    model = RecipeChangeset
+    context_object_name = 'changeset'
+
+    @method_decorator(login_required)
+    def dispatch(self, request, *args, **kwargs):
+        return super(BulkChangeReviewView, self).dispatch(request, *args, **kwargs)
+
+    def get_queryset(self):
+        qs = super(BulkChangeReviewView, self).get_queryset()
+        return qs.filter(user=self.request.user)
+
+
 class BulkChangeDeleteView(BaseDeleteView):
     model = RecipeChangeset
     success_url = reverse_lazy('bulk_change')
 
+    @method_decorator(login_required)
+    def dispatch(self, request, *args, **kwargs):
+        return super(BulkChangeDeleteView, self).dispatch(request, *args, **kwargs)
+
     def get_queryset(self):
         qs = super(BulkChangeDeleteView, self).get_queryset()
         return qs.filter(user=self.request.user)
tests/test_bulkchange_access.py new file +53 -0

53 lines not on this page · raw message

Signature · 1 line
2.56.0
author
#3 lore raw

PATCH 3/4 layerindex/views: don't expose patch generation errors to users

In reply to Tim Orling

bulk_change_patch_view returned the output of the failing bulkchange.py run, or the exception text, in the HTTP response. That can include tracebacks, server paths and bitbake output. Log the details instead and return a generic error with status 500. The lock timeout message is kept, since it tells the user what to do and reveals nothing.

Reported by CodeQL (py/stack-trace-exposure).

AI-Generated: Claude Opus 5.5

---
 layerindex/views.py             | 14 ++++++++------
 tests/test_bulkchange_access.py | 11 +++++++++++
 2 files changed, 19 insertions(+), 6 deletions(-)
layerindex/views.py +8 -6
index 42722bf..592311f 100644
@@ -6,6 +6,7 @@
 #
 # SPDX-License-Identifier: MIT
 
+import logging
 import os
 import sys
 import re
@@ -63,6 +64,8 @@ from layerindex.models import (BBAppend, BBClass, BBClassGlobal, BBClassRecipe,
 
 from . import tasks, utils
 
+logger = logging.getLogger(__name__)
+
 def edit_layernote_view(request, template_name, slug, pk=None):
     layeritem = get_object_or_404(LayerItem, name=slug)
     if layeritem.comparison:
@@ -347,12 +350,11 @@ def bulk_change_patch_view(request, pk):
         return HttpResponse('No patch data generated', content_type='text/plain')
     except Exception as e:
         output = getattr(e, 'output', None)
-        if output:
-            if 'timeout' in output:
-                return HttpResponse('Failed to generate patches: timed out waiting for lock. Please try again shortly.', content_type='text/plain')
-            else:
-                return HttpResponse('Failed to generate patches: %s' % output, content_type='text/plain')
-        return HttpResponse('Failed to generate patches: %s' % e, content_type='text/plain')
+        if output and 'timeout' in output:
+            return HttpResponse('Failed to generate patches: timed out waiting for lock. Please try again shortly.', content_type='text/plain')
+        # Details can include paths and bitbake output, so keep them in the server log
+        logger.exception('Failed to generate patches for bulk change %s: %s', pk, output)
+        return HttpResponse('Failed to generate patches, please contact the site administrator.', content_type='text/plain', status=500)
     # FIXME better error handling
 
 
tests/test_bulkchange_access.py +11 -0
index e85451d..914493c 100644
@@ -51,3 +51,14 @@ class TestBulkChangeAccess(TestCase):
         for name in ('bulk_change_edit', 'bulk_change_review'):
             response = self.client.get(self._url(name))
             self.assertEqual(response.status_code, 200, name)
+
+    def test_patch_error_details_not_exposed(self):
+        import subprocess
+        from unittest import mock
+        self.client.force_login(self.owner)
+        err = subprocess.CalledProcessError(1, 'bulkchange.py', output='Traceback: /opt/secret/path')
+        with mock.patch('layerindex.views.utils.runcmd', side_effect=err), \
+                self.assertLogs('layerindex.views', 'ERROR'):
+            response = self.client.get(self._url('bulk_change_patches'))
+        self.assertEqual(response.status_code, 500)
+        self.assertNotIn(b'/opt/secret/path', response.content)
Signature · 1 line
2.56.0
author
#4 lore raw

PATCH 4/4 tests: check that changing the profile email requires reactivation

In reply to Tim Orling

Layer edit rights are granted by matching a user's email address against the layer's maintainer emails, which are public. Changing the email on the profile page therefore must not take effect until the new address is
confirmed: the user is logged out and deactivated, and the activation link is sent only to the new address. Add a test so this protection cannot be removed without notice.

AI-Generated: Claude Opus 5.5

---
 tests/test_profile_email.py | 67 +++++++++++++++++++++++++++++++++++++
 1 file changed, 67 insertions(+)
 create mode 100644 tests/test_profile_email.py
tests/test_profile_email.py new file +67 -0
new file mode 100644
index 0000000..79e4adf
@@ -0,0 +1,67 @@
+# layerindex-web - tests for changing the email address on the profile page
+#
+# Licensed under the MIT license, see COPYING.MIT for details
+#
+# SPDX-License-Identifier: MIT
+
+import pytest
+from captcha.models import CaptchaStore
+from django.contrib.auth import authenticate
+from django.contrib.auth.models import User
+from django.core import mail
+from django.test import RequestFactory, TestCase
+from django.urls import reverse
+
+from layerindex.models import SecurityQuestion, SecurityQuestionAnswer, UserProfile
+
+
[email protected]_db
+class TestProfileEmailChange(TestCase):
+    """Changing the email address must not take effect without proving
+    ownership of the new address, since layer edit rights are granted by
+    matching the user's email against (public) maintainer emails."""
+
+    def setUp(self):
+        self.user = User.objects.create_user('someone', '[email protected]', 'pw')
+        profile = UserProfile.objects.create(user=self.user)
+        self.questions = [SecurityQuestion.objects.create(question='Question %d' % i) for i in range(3)]
+        for question in self.questions:
+            SecurityQuestionAnswer.objects.create(user=profile, security_question=question, answer='x')
+        self.client.force_login(self.user)
+
+    def _post_profile(self, email):
+        hashkey = CaptchaStore.generate_key()
+        data = {
+            'username': 'someone',
+            'first_name': '',
+            'last_name': '',
+            'email': email,
+            'captcha_0': hashkey,
+            'captcha_1': CaptchaStore.objects.get(hashkey=hashkey).response,
+            'answer_1': '*****',
+            'answer_2': '*****',
+            'answer_3': '*****',
+        }
+        for i, question in enumerate(self.questions, 1):
+            data['security_question_%d' % i] = question.pk
+        return self.client.post(reverse('profile'), data)
+
+    def test_email_change_requires_reactivation(self):
+        response = self._post_profile('[email protected]')
+        self.assertRedirects(response, reverse('reregister'), fetch_redirect_response=False)
+
+        self.user.refresh_from_db()
+        self.assertFalse(self.user.is_active)
+        # Logged out, and an inactive account cannot log back in
+        self.assertNotIn('_auth_user_id', self.client.session)
+        self.assertIsNone(authenticate(RequestFactory().post('/'), username='someone', password='pw'))
+        # The activation link only goes to the new address
+        self.assertEqual(len(mail.outbox), 1)
+        self.assertEqual(mail.outbox[0].to, ['[email protected]'])
+
+    def test_unchanged_email_keeps_account_active(self):
+        response = self._post_profile('[email protected]')
+        self.assertEqual(response.status_code, 302)
+        self.user.refresh_from_db()
+        self.assertTrue(self.user.is_active)
+        self.assertEqual(len(mail.outbox), 0)
Signature · 1 line
2.56.0