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

Closes #23741: Add restricted rendering mode for export templates

Support the restricted mode of TEMPLATE_RENDERING for export templates.
Templates receive the exported objects as a list of REST API
representations under objects, the exporting user, and query(), in
place of the queryset and model classes. Inline output is sandboxed.
In legacy mode, objects and user are provided alongside the queryset,
so templates can be migrated before switching modes.
Jeremy Stretch 17 часов назад
Родитель
Сommit
9c2c9ca968

+ 1 - 1
docs/configuration/system.md

@@ -442,7 +442,7 @@ TEMPLATE_RENDERING = {
 |---|---|---|
 | Config templates | `config_templates` | No |
 | Custom links | `custom_links` | Yes |
-| Export templates | `export_templates` | No |
+| Export templates | `export_templates` | Yes |
 | Webhooks | `webhooks` | Yes |
 
 NetBox will fail to start if this parameter names an unknown feature or mode, or selects `restricted` for a feature that doesn't support it.

+ 24 - 0
docs/customization/export-templates.md

@@ -37,6 +37,30 @@ The `as_attachment` attribute of an export template controls its behavior when r
 
 A MIME type and file extension can optionally be defined for each export template. The default MIME type is `text/plain`.
 
+## Restricted Rendering
+
+When the [`TEMPLATE_RENDERING`](../configuration/system.md#template_rendering) configuration parameter selects `restricted` mode for export templates, they're rendered in a restricted environment which permits access only to plain data, with the following context:
+
+| Variable  | Description |
+|-----------|-------------|
+| `objects` | The exported objects, each holding its REST API representation, in place of `queryset`. Related objects and reverse relations (e.g. `site.devices`) are fetched as they're accessed, limited to those the user is permitted to view. |
+| `user`    | A dictionary holding the `id` and `username` of the user exporting the objects |
+| `query()` | A function which returns the objects matching the given REST API filters (e.g. `query('ipam.ipaddress', parent=prefix.prefix)`), limited to those the user is permitted to view |
+
+Model classes (e.g. `dcim.Site`) aren't available, and each variable provided by a plugin is included only if its value can be serialized to JSON. A stored `finalize` environment parameter is ignored. Content which isn't served as an attachment is sent with a `Content-Security-Policy: sandbox; default-src 'none'` header, as image attachments are. Any scripts it contains don't run, and inline HTML output can't load images, stylesheets, or fonts.
+
+In legacy mode, `objects` and `user` are also provided, so templates can be migrated one at a time before switching modes. Common changes needed when migrating a template:
+
+| Legacy                                                                 | Restricted                                                                     |
+|------------------------------------------------------------------------|--------------------------------------------------------------------------------|
+| `{% for d in queryset %}`                                              | `{% for d in objects %}`                                                       |
+| `{{ d.cf.foo }}`                                                       | `{{ d.custom_fields.foo }}`                                                    |
+| `{{ d.get_absolute_url() }}`                                           | `{{ d.display_url }}`                                                          |
+| `{{ d.get_status_display() }}`                                         | `{{ d.status.label }}`                                                         |
+| `{{ d.get_config_context() }}`                                         | `{{ d.config_context }}`                                                       |
+| `{{ prefix.get_child_ips().filter(interface__name='Bu1').first() }}`   | `{{ query('ipam.ipaddress', parent=prefix.prefix, interface='Bu1').first() }}` |
+| `{{ prefix.get_child_ranges().first() }}`                              | `{{ query('ipam.iprange', parent=prefix.prefix).first() }}`                    |
+| `{% if prefix.tags.contains(extras.Tag.objects.get(slug='static')) %}` | `{% if 'static' in prefix.tags \| map(attribute='slug') %}`                    |
 
 ## REST API Integration
 

+ 2 - 2
netbox/extras/models/configs.py

@@ -473,13 +473,13 @@ class ConfigTemplate(
         self.template_code = self.validate_synced_value('template_code', self.data_file.data_as_string)
     sync_data.alters_data = True
 
-    def get_environment_params(self):
+    def get_environment_params(self, restricted=False):
         """
         Config templates render plain text (network configs, scripts), not HTML. Force
         autoescape off so environment_params cannot enable it and create a latent XSS sink
         if output is ever rendered in an HTML context.
         """
-        params = super().get_environment_params()
+        params = super().get_environment_params(restricted=restricted)
         params['autoescape'] = False
         return params
 

+ 80 - 13
netbox/extras/models/mixins.py

@@ -1,11 +1,13 @@
 import importlib.abc
 import importlib.util
+import json
 import logging
 import os
 import sys
 import warnings
 from collections import defaultdict
 
+from django.apps import apps as django_apps
 from django.core.exceptions import ValidationError
 from django.core.files.storage import storages
 from django.db import models
@@ -14,11 +16,14 @@ from django.utils.http import content_disposition_header
 from django.utils.module_loading import import_string
 from django.utils.translation import gettext_lazy as _
 from jinja2 import TemplateError
+from rest_framework.utils.encoders import JSONEncoder
 
 from core.models import ObjectType
 from extras.constants import DEFAULT_MIME_TYPE, JINJA_ENV_PARAMS_ALLOWED, SCRIPT_MODULE_NAME_PREFIX
 from extras.utils import filename_from_model, filename_from_object
-from utilities.jinja2 import render_jinja2
+from netbox.constants import TEMPLATE_RENDERING_RESTRICTED
+from netbox.plugins import PluginConfig
+from utilities.jinja2 import RestrictedRenderState, get_template_rendering_mode, render_jinja2
 
 __all__ = (
     'PythonModuleMixin',
@@ -30,6 +35,9 @@ logger = logging.getLogger(__name__)
 # (model name, pk) of templates that have already emitted the stored 'finalize' deprecation warning (#23498)
 _stored_finalize_warned = set()
 
+# (plugin name, context key) of plugin Jinja context values already reported as omitted from restricted rendering
+_plugin_context_warned = set()
+
 
 class CustomStoragesLoader(importlib.abc.Loader):
     """
@@ -133,14 +141,22 @@ class RenderTemplateMixin(models.Model):
         help_text=_("Download file as attachment")
     )
 
+    # The TEMPLATE_RENDERING feature which governs this model's rendering (set by subclasses)
+    template_rendering_feature = None
+
     class Meta:
         abstract = True
 
-    def get_context(self, context=None, queryset=None):
-        from django.apps import apps as django_apps
-
-        from netbox.plugins import PluginConfig
+    def uses_restricted_rendering(self):
+        """
+        Return True if TEMPLATE_RENDERING selects restricted mode for this model's templates.
+        """
+        return (
+            self.template_rendering_feature is not None and
+            get_template_rendering_mode(self.template_rendering_feature) == TEMPLATE_RENDERING_RESTRICTED
+        )
 
+    def get_context(self, context=None, queryset=None, user=None):
         _context = defaultdict(dict)
 
         # Populate all public models for reference within the template
@@ -161,6 +177,38 @@ class RenderTemplateMixin(models.Model):
 
         return _context
 
+    def get_restricted_context(self, state, context=None, queryset=None):
+        """
+        Return the context for rendering in restricted mode: each plugin context value which can be serialized to
+        JSON, and the given context. Model classes aren't included.
+        """
+        _context = {}
+        for app_config in django_apps.get_app_configs():
+            if isinstance(app_config, PluginConfig):
+                try:
+                    plugin_context = dict(app_config.get_jinja_context())
+                except Exception:
+                    logger.exception("Plugin %r raised an exception in get_jinja_context()", app_config.name)
+                    continue
+                omitted = []
+                for key, value in plugin_context.items():
+                    try:
+                        _context[key] = json.loads(json.dumps(value, cls=JSONEncoder))
+                    except (TypeError, ValueError):
+                        if (app_config.name, key) not in _plugin_context_warned:
+                            _plugin_context_warned.add((app_config.name, key))
+                            omitted.append(key)
+                if omitted:
+                    logger.warning(
+                        "Omitting Jinja context from plugin %r which can't be serialized: %s",
+                        app_config.name, ', '.join(omitted)
+                    )
+
+        if context is not None:
+            _context.update(context)
+
+        return _context
+
     def clean(self):
         super().clean()
 
@@ -268,39 +316,58 @@ class RenderTemplateMixin(models.Model):
             )
         return {**params, 'finalize': stored_finalize}
 
-    def get_environment_params(self):
+    def get_environment_params(self, restricted=False):
         """
-        Pre-processing of any defined Jinja environment parameters.
+        Pre-processing of any defined Jinja environment parameters. A stored finalize is ignored in restricted mode.
         """
         # Shallow-copy so resolved values don't replace the strings on the model field.
         params = dict(self.environment_params or {})
         params = self._filter_environment_params(params)
         params = self._resolve_mapped_params(params)
+        if restricted:
+            params.pop('finalize', None)
+            return params
         params = self._restrict_finalize_to_stored(params)
         params = self._resolve_finalize(params)
         return params
 
-    def render(self, context=None, queryset=None):
+    def render(self, context=None, queryset=None, user=None):
         """
         Render the template with the provided context. The context is passed to the Jinja2 environment as a dictionary.
+        In restricted mode, rendering runs on behalf of the given user.
         """
-        context = self.get_context(context=context, queryset=queryset)
-        env_params = self.get_environment_params()
+        state = RestrictedRenderState(user) if self.uses_restricted_rendering() else None
+        if state is None:
+            context = self.get_context(context=context, queryset=queryset, user=user)
+        else:
+            context = self.get_restricted_context(state, context=context, queryset=queryset)
+        env_params = self.get_environment_params(restricted=state is not None)
         debug = getattr(self, 'debug', False)
-        output = render_jinja2(self.template_code, context, env_params, getattr(self, 'data_file', None), debug=debug)
+        output = render_jinja2(
+            self.template_code,
+            context,
+            env_params,
+            getattr(self, 'data_file', None),
+            debug=debug,
+            restricted=state,
+        )
 
         # Replace CRLF-style line terminators
         output = output.replace('\r\n', '\n')
 
         return output
 
-    def render_to_response(self, context=None, queryset=None):
-        output = self.render(context=context, queryset=queryset)
+    def render_to_response(self, context=None, queryset=None, user=None):
+        output = self.render(context=context, queryset=queryset, user=user)
         mime_type = self.mime_type or DEFAULT_MIME_TYPE
 
         # Build the response
         response = HttpResponse(output, content_type=mime_type)
 
+        # Keep any script in output shown inline (e.g. HTML) from running, as for image attachments
+        if not self.as_attachment and self.uses_restricted_rendering():
+            response['Content-Security-Policy'] = "sandbox; default-src 'none'"
+
         if self.as_attachment:
             extension = f'.{self.file_extension}' if self.file_extension else ''
             if self.file_name:

+ 31 - 4
netbox/extras/models/models.py

@@ -55,7 +55,7 @@ from utilities.querydict import dict_to_querydict
 from utilities.querysets import RestrictedQuerySet
 from utilities.request import get_safe_request_context
 from utilities.tables import get_table_for_model
-from utilities.template_objects import TemplateObject, get_template_object, to_plain_data
+from utilities.template_objects import TemplateObject, get_template_object, get_template_objects, to_plain_data
 
 __all__ = (
     'Bookmark',
@@ -537,7 +537,7 @@ class CustomLink(CloningMixin, ExportTemplatesMixin, OwnerMixin, ChangeLoggedMod
             user = state.user or AnonymousUser()
             context.update({
                 'request': to_plain_data(get_safe_request_context(request)),
-                'user': {'id': user.pk, 'username': user.get_username()},
+                'user': _get_user_data(user),
                 'perms': PermWrapper(user),
             })
         return context
@@ -574,6 +574,13 @@ class CustomLink(CloningMixin, ExportTemplatesMixin, OwnerMixin, ChangeLoggedMod
         }
 
 
+def _get_user_data(user):
+    """
+    Return the user's ID and username, for restricted rendering contexts.
+    """
+    return {'id': user.pk, 'username': user.get_username()}
+
+
 class ExportTemplate(
     SyncedDataMixin,
     CloningMixin,
@@ -601,6 +608,8 @@ class ExportTemplate(
         'object_types', 'template_code', 'mime_type', 'file_name', 'file_extension', 'as_attachment',
     )
 
+    template_rendering_feature = 'export_templates'
+
     class Meta:
         ordering = ('name',)
         indexes = (
@@ -634,14 +643,32 @@ class ExportTemplate(
         self.template_code = self.validate_synced_value('template_code', self.data_file.data_as_string)
     sync_data.alters_data = True
 
-    def get_context(self, context=None, queryset=None):
-        _context = super().get_context(context=context, queryset=queryset)
+    def get_context(self, context=None, queryset=None, user=None):
+        _context = super().get_context(context=context, queryset=queryset, user=user)
+        # Provide the user and objects as in restricted mode, so that templates can be migrated before switching modes
+        # (unless the names are already used, e.g. by a plugin)
+        if user is not None:
+            _context.setdefault('user', _get_user_data(user))
+            if queryset is not None and 'objects' not in _context:
+                try:
+                    _context['objects'] = get_template_objects(queryset, RestrictedRenderState(user))
+                except ValueError:
+                    # The model doesn't support restricted rendering (e.g. it has no REST API serializer)
+                    pass
         # Fetch each related object the template reads for the whole queryset at once
         if queryset is not None:
             queryset = queryset.fetch_mode(FETCH_PEERS)
         _context['queryset'] = queryset
         return _context
 
+    def get_restricted_context(self, state, context=None, queryset=None):
+        _context = super().get_restricted_context(state, context=context, queryset=queryset)
+        if state.user is not None:
+            _context['user'] = _get_user_data(state.user)
+        if queryset is not None:
+            _context['objects'] = get_template_objects(queryset, state)
+        return _context
+
 
 class SavedFilter(CloningMixin, ExportTemplatesMixin, OwnerMixin, ChangeLoggedModel):
     """

+ 98 - 0
netbox/extras/tests/test_models.py

@@ -18,6 +18,7 @@ from django.forms import ValidationError
 from django.test import TestCase, override_settings, tag
 from django.test.utils import CaptureQueriesContext
 from jinja2 import DebugUndefined, StrictUndefined, TemplateError, TemplateSyntaxError, UndefinedError
+from jinja2.sandbox import SecurityError
 from PIL import Image
 from rq.queue import Queue
 
@@ -39,6 +40,7 @@ from extras.models import (
 )
 from extras.models.mixins import RenderTemplateMixin
 from tenancy.models import Tenant, TenantGroup
+from users.models import User
 from utilities.exceptions import AbortRequest
 from utilities.jinja2 import env_filter, render_jinja2, sanitize_http_header
 from utilities.tables import get_table_for_model
@@ -1627,6 +1629,102 @@ class ExportTemplateRenderTestCase(TestCase):
         self.assertEqual(response.content.decode(), 'Site A\nSite B\nSite C\n')
 
 
+@override_settings(TEMPLATE_RENDERING={'export_templates': 'restricted'})
+class ExportTemplateRestrictedRenderTestCase(TestCase):
+
+    @classmethod
+    def setUpTestData(cls):
+        tenant = Tenant.objects.create(name='Tenant 1', slug='tenant-1')
+        Site.objects.bulk_create([
+            Site(name='Site A', slug='site-a', tenant=tenant),
+            Site(name='Site B', slug='site-b'),
+        ])
+        cls.user = User.objects.create_user(username='admin', is_superuser=True)
+
+    def render(self, template_code, **kwargs):
+        t = ExportTemplate(name='sites', template_code=template_code, **kwargs)
+        return t.render(queryset=Site.objects.order_by('name'), user=self.user)
+
+    def test_context(self):
+        cases = (
+            ('{% for s in objects %}{{ s.name }}:{{ s.tenant.name }} {% endfor %}', 'Site A:Tenant 1 Site B: '),
+            ('{{ objects | length }} {{ user.username }}', '2 admin'),
+            ('{{ query("tenancy.tenant").first().slug }}', 'tenant-1'),
+            ('{{ dummy_plugin_var }}', 'hello_from_dummy'),
+            ('{{ queryset is defined }} {{ dcim is defined }}', 'False False'),
+        )
+        for template_code, expected in cases:
+            with self.subTest(template_code=template_code):
+                self.assertEqual(self.render(template_code), expected)
+
+    def test_restricted_access(self):
+        with self.assertRaises(SecurityError):
+            self.render('{{ objects._queryset }}')
+
+    @patch('extras.models.mixins._plugin_context_warned', set())
+    def test_plugin_context_must_be_serializable(self):
+        plugin_context = {'site': Site(), 'name': 'x'}
+        with patch('netbox.tests.dummy_plugin.DummyPluginConfig.get_jinja_context', return_value=plugin_context):
+            with self.assertLogs('extras.models.mixins', level='WARNING') as logs:
+                # Only the value which can't be serialized is omitted
+                self.assertEqual(self.render('{{ site is defined }} {{ name }}'), 'False x')
+            self.assertIn("which can't be serialized: site", logs.output[0])
+            # The omission is logged only once
+            with self.assertNoLogs('extras.models.mixins', level='WARNING'):
+                self.render('{{ name }}')
+
+    def test_plugin_context_not_a_dict(self):
+        with (
+            patch('netbox.tests.dummy_plugin.DummyPluginConfig.get_jinja_context', return_value='not_a_dict'),
+            self.assertLogs('extras.models.mixins', level='ERROR'),
+        ):
+            self.assertEqual(self.render('{{ objects | length }}'), '2')
+
+    def test_finalize_is_ignored(self):
+        t = ExportTemplate.objects.create(name='sites', template_code='{{ 1 }}')
+        ExportTemplate.objects.filter(pk=t.pk).update(environment_params={'finalize': 'builtins.repr'})
+        t.refresh_from_db()
+        with warnings.catch_warnings():
+            warnings.simplefilter('error')
+            self.assertEqual(t.render(user=self.user), '1')
+
+    def test_requires_user(self):
+        t = ExportTemplate(name='sites', template_code='{{ objects | length }}')
+        with self.assertRaises(ValueError):
+            t.render(queryset=Site.objects.all())
+
+    def test_inline_output_is_sandboxed(self):
+        t = ExportTemplate(name='sites', template_code='<p>{{ objects | length }}</p>', as_attachment=False)
+        response = t.render_to_response(queryset=Site.objects.all(), user=self.user)
+        self.assertEqual(response['Content-Security-Policy'], "sandbox; default-src 'none'")
+        t.as_attachment = True
+        response = t.render_to_response(queryset=Site.objects.all(), user=self.user)
+        self.assertNotIn('Content-Security-Policy', response)
+
+    @override_settings(TEMPLATE_RENDERING={'export_templates': 'legacy'})
+    def test_legacy_context(self):
+        output = self.render(
+            '{% for s in queryset %}{{ s.name }} {% endfor %}{% for s in objects %}{{ s.tenant.slug }} {% endfor %}'
+            '{{ user.username }}'
+        )
+        self.assertEqual(output, 'Site A Site B tenant-1  admin')
+        t = ExportTemplate(name='sites', template_code='<p></p>', as_attachment=False)
+        self.assertNotIn('Content-Security-Policy', t.render_to_response(queryset=Site.objects.all()))
+
+    @override_settings(TEMPLATE_RENDERING={'export_templates': 'legacy'})
+    def test_legacy_context_without_objects_support(self):
+        # A model which restricted rendering doesn't support still renders in legacy mode, without objects
+        t = ExportTemplate(name='types', template_code='{{ queryset | length }} {{ objects is defined }}')
+        queryset = ContentType.objects.filter(app_label='dcim', model='site')
+        self.assertEqual(t.render(queryset=queryset, user=self.user), '1 False')
+
+    @override_settings(TEMPLATE_RENDERING={'export_templates': 'legacy'})
+    def test_legacy_context_names_in_use(self):
+        t = ExportTemplate(name='sites', template_code='{{ user }} {{ objects }}')
+        output = t.render(context={'user': 'u', 'objects': 'o'}, queryset=Site.objects.all(), user=self.user)
+        self.assertEqual(output, 'u o')
+
+
 class ExportTemplateStoredOnlyFinalizeTestCase(TestCase):
     """
     Tests that render() honors 'finalize' only with the value stored on the template's database record.

+ 15 - 1
netbox/extras/tests/test_views.py

@@ -7,7 +7,7 @@ from unittest.mock import PropertyMock, patch
 
 from django.contrib.contenttypes.models import ContentType
 from django.contrib.messages import get_messages
-from django.test import tag
+from django.test import override_settings, tag
 from django.urls import reverse
 from django.utils.html import escape
 from django.utils.timezone import now
@@ -843,6 +843,20 @@ class ExportTemplateExportFlowTestCase(TestCase):
         rendered_names = set(filter(None, response.content.decode().split('\n')))
         self.assertEqual(rendered_names, {'Site A', 'Site B'})
 
+    @override_settings(TEMPLATE_RENDERING={'export_templates': 'restricted'})
+    def test_restricted_export_template_invocation(self):
+        self.add_permissions('dcim.view_site', 'extras.view_exporttemplate')
+        ExportTemplate.objects.filter(name='Sites Export').update(
+            template_code='{% for obj in objects %}{{ obj.name }}\n{% endfor %}{{ user.username }}'
+        )
+        for url in (reverse('dcim:site_list'), reverse('dcim-api:site-list')):
+            with self.subTest(url=url):
+                response = self.client.get(f'{url}?export=Sites Export')
+                self.assertEqual(response.status_code, 200)
+                lines = response.content.decode().split('\n')
+                self.assertEqual(set(lines[:-1]), {'Site A', 'Site B'})
+                self.assertEqual(lines[-1], self.user.username)
+
     def test_export_template_render_error_redirects(self):
         self.add_permissions('dcim.view_site', 'extras.view_exporttemplate')
         url = reverse('dcim:site_list')

+ 1 - 1
netbox/netbox/api/viewsets/mixins.py

@@ -433,7 +433,7 @@ class ExportTemplatesMixin:
             if et is None:
                 raise Http404
             queryset = self.filter_queryset(self.get_queryset())
-            return et.render_to_response(queryset=queryset)
+            return et.render_to_response(queryset=queryset, user=request.user)
 
         return super().list(request, *args, **kwargs)
 

+ 1 - 1
netbox/netbox/constants.py

@@ -29,7 +29,7 @@ TEMPLATE_RENDERING_DEFAULT = TEMPLATE_RENDERING_LEGACY
 TEMPLATE_RENDERING_FEATURES = {
     'config_templates': (TEMPLATE_RENDERING_LEGACY,),
     'custom_links': (TEMPLATE_RENDERING_LEGACY, TEMPLATE_RENDERING_RESTRICTED),
-    'export_templates': (TEMPLATE_RENDERING_LEGACY,),
+    'export_templates': (TEMPLATE_RENDERING_LEGACY, TEMPLATE_RENDERING_RESTRICTED),
     'webhooks': (TEMPLATE_RENDERING_LEGACY, TEMPLATE_RENDERING_RESTRICTED),
 }
 

+ 1 - 1
netbox/netbox/views/generic/bulk_views.py

@@ -227,7 +227,7 @@ class ObjectListView(BaseMultiObjectView, ActionsMixin, TableMixin):
             request: The current request
         """
         try:
-            return template.render_to_response(queryset=self.queryset)
+            return template.render_to_response(queryset=self.queryset, user=request.user)
         except Exception as e:
             messages.error(
                 request,