|
@@ -1,16 +1,26 @@
|
|
|
import fnmatch
|
|
import fnmatch
|
|
|
import os
|
|
import os
|
|
|
import re
|
|
import re
|
|
|
|
|
+from decimal import Decimal
|
|
|
|
|
+from types import FunctionType
|
|
|
|
|
|
|
|
from django.apps import apps
|
|
from django.apps import apps
|
|
|
|
|
+from django.conf import settings
|
|
|
from django.core.exceptions import ValidationError
|
|
from django.core.exceptions import ValidationError
|
|
|
from django.utils.translation import gettext_lazy as _
|
|
from django.utils.translation import gettext_lazy as _
|
|
|
from jinja2 import BaseLoader, TemplateNotFound
|
|
from jinja2 import BaseLoader, TemplateNotFound
|
|
|
|
|
+from jinja2.environment import TemplateModule
|
|
|
from jinja2.exceptions import TemplateSyntaxError
|
|
from jinja2.exceptions import TemplateSyntaxError
|
|
|
|
|
+from jinja2.filters import _GroupTuple
|
|
|
from jinja2.meta import find_referenced_templates
|
|
from jinja2.meta import find_referenced_templates
|
|
|
-from jinja2.sandbox import SandboxedEnvironment
|
|
|
|
|
|
|
+from jinja2.runtime import BlockReference, LoopContext, Macro, TemplateReference, Undefined
|
|
|
|
|
+from jinja2.sandbox import SandboxedEnvironment, SecurityError
|
|
|
|
|
+from jinja2.utils import Cycler, Joiner, Namespace
|
|
|
|
|
+from markupsafe import Markup
|
|
|
|
|
+from rest_framework.utils.serializer_helpers import ReturnDict, ReturnList
|
|
|
|
|
|
|
|
from netbox.config import get_config
|
|
from netbox.config import get_config
|
|
|
|
|
+from netbox.constants import TEMPLATE_RENDERING_DEFAULT, TEMPLATE_RENDERING_FEATURES
|
|
|
from netbox.registry import registry
|
|
from netbox.registry import registry
|
|
|
|
|
|
|
|
__all__ = (
|
|
__all__ = (
|
|
@@ -18,7 +28,10 @@ __all__ = (
|
|
|
'HTTP_HEADER_INVALID_CHARS_RE',
|
|
'HTTP_HEADER_INVALID_CHARS_RE',
|
|
|
'JINJA2_TEMPLATE_RE',
|
|
'JINJA2_TEMPLATE_RE',
|
|
|
'DataFileLoader',
|
|
'DataFileLoader',
|
|
|
|
|
+ 'RestrictedRenderState',
|
|
|
|
|
+ 'RestrictedSandboxedEnvironment',
|
|
|
'env_filter',
|
|
'env_filter',
|
|
|
|
|
+ 'get_template_rendering_mode',
|
|
|
'render_jinja2',
|
|
'render_jinja2',
|
|
|
'sanitize_http_header',
|
|
'sanitize_http_header',
|
|
|
'validate_jinja2_syntax',
|
|
'validate_jinja2_syntax',
|
|
@@ -93,6 +106,66 @@ class DataFileLoader(BaseLoader):
|
|
|
self._template_cache.update(templates)
|
|
self._template_cache.update(templates)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
+class RestrictedSandboxedEnvironment(SandboxedEnvironment):
|
|
|
|
|
+ """
|
|
|
|
|
+ A sandboxed Jinja2 environment which permits attribute access and method calls only on plain data types.
|
|
|
|
|
+ """
|
|
|
|
|
+ # Matched by exact type, since a subclass may add its own methods
|
|
|
|
|
+ allowed_types = (
|
|
|
|
|
+ dict, list, tuple, str, int, float, Decimal, bool, type(None), range,
|
|
|
|
|
+ ReturnDict, ReturnList, # Serializer output
|
|
|
|
|
+ Markup, _GroupTuple, # Escaped strings and groupby() results
|
|
|
|
|
+ )
|
|
|
|
|
+ # Jinja's own template objects, matched including subclasses (e.g. StrictUndefined)
|
|
|
|
|
+ allowed_template_types = (
|
|
|
|
|
+ BlockReference, Cycler, Joiner, LoopContext, Macro, Namespace, TemplateModule, TemplateReference, Undefined,
|
|
|
|
|
+ )
|
|
|
|
|
+
|
|
|
|
|
+ def __init__(self, *args, **kwargs):
|
|
|
|
|
+ super().__init__(*args, **kwargs)
|
|
|
|
|
+ # Jinja's built-in globals (range, dict, namespace, etc.) are the only functions and classes which may be called
|
|
|
|
|
+ self.allowed_callables = tuple(self.globals.values())
|
|
|
|
|
+
|
|
|
|
|
+ def is_allowed(self, obj):
|
|
|
|
|
+ return type(obj) in self.allowed_types or isinstance(obj, self.allowed_template_types)
|
|
|
|
|
+
|
|
|
|
|
+ def is_safe_attribute(self, obj, attr, value):
|
|
|
|
|
+ return self.is_allowed(obj) and super().is_safe_attribute(obj, attr, value)
|
|
|
|
|
+
|
|
|
|
|
+ def is_safe_callable(self, obj):
|
|
|
|
|
+ if not super().is_safe_callable(obj):
|
|
|
|
|
+ return False
|
|
|
|
|
+ if any(obj is allowed for allowed in self.allowed_callables):
|
|
|
|
|
+ return True
|
|
|
|
|
+ # Unwrap the sandbox's str.format() wrapper, then permit only methods of (or calls to) allowed types
|
|
|
|
|
+ if isinstance(obj, FunctionType):
|
|
|
|
|
+ obj = getattr(obj, '__wrapped__', obj)
|
|
|
|
|
+ return self.is_allowed(getattr(obj, '__self__', obj))
|
|
|
|
|
+
|
|
|
|
|
+ def getattr(self, obj, attribute):
|
|
|
|
|
+ if not self.is_allowed(obj):
|
|
|
|
|
+ return self.unsafe_undefined(obj, attribute)
|
|
|
|
|
+ return super().getattr(obj, attribute)
|
|
|
|
|
+
|
|
|
|
|
+ def getitem(self, obj, argument):
|
|
|
|
|
+ if not self.is_allowed(obj):
|
|
|
|
|
+ return self.unsafe_undefined(obj, argument)
|
|
|
|
|
+ return super().getitem(obj, argument)
|
|
|
|
|
+
|
|
|
|
|
+ def unsafe_undefined(self, obj, attribute):
|
|
|
|
|
+ # Fail rather than rendering an empty string
|
|
|
|
|
+ raise SecurityError(f"Access to attribute {attribute!r} of {type(obj).__name__!r} object is not permitted.")
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+class RestrictedRenderState:
|
|
|
|
|
+ """
|
|
|
|
|
+ State shared across a single restricted render: the user on whose behalf it runs, and a cache of fetched objects.
|
|
|
|
|
+ """
|
|
|
|
|
+ def __init__(self, user=None):
|
|
|
|
|
+ self.user = user
|
|
|
|
|
+ self.cache = {}
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
#
|
|
#
|
|
|
# Utility functions
|
|
# Utility functions
|
|
|
#
|
|
#
|
|
@@ -114,7 +187,19 @@ def _jinja2_filters(filters=None):
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
-def render_jinja2(template_code, context, environment_params=None, data_file=None, debug=False, filters=None):
|
|
|
|
|
|
|
+def get_template_rendering_mode(feature):
|
|
|
|
|
+ """
|
|
|
|
|
+ Return the TEMPLATE_RENDERING mode configured for the given feature (e.g. 'export_templates').
|
|
|
|
|
+ """
|
|
|
|
|
+ if feature not in TEMPLATE_RENDERING_FEATURES:
|
|
|
|
|
+ raise ValueError(f"Unknown template rendering feature: {feature}")
|
|
|
|
|
+ if isinstance(settings.TEMPLATE_RENDERING, str):
|
|
|
|
|
+ return settings.TEMPLATE_RENDERING
|
|
|
|
|
+ return settings.TEMPLATE_RENDERING.get(feature, TEMPLATE_RENDERING_DEFAULT)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def render_jinja2(template_code, context, environment_params=None, data_file=None, debug=False, filters=None,
|
|
|
|
|
+ restricted=None):
|
|
|
"""
|
|
"""
|
|
|
Render a Jinja2 template with the provided context. Return the rendered content.
|
|
Render a Jinja2 template with the provided context. Return the rendered content.
|
|
|
|
|
|
|
@@ -122,8 +207,14 @@ def render_jinja2(template_code, context, environment_params=None, data_file=Non
|
|
|
|
|
|
|
|
The optional `filters` argument is a mapping of additional Jinja2 filters to make available for this render only
|
|
The optional `filters` argument is a mapping of additional Jinja2 filters to make available for this render only
|
|
|
(e.g. context-specific sanitization filters). These take precedence over the default and user-configured filters.
|
|
(e.g. context-specific sanitization filters). These take precedence over the default and user-configured filters.
|
|
|
|
|
+
|
|
|
|
|
+ Pass a RestrictedRenderState as `restricted` to render in the restricted environment.
|
|
|
"""
|
|
"""
|
|
|
|
|
+ if restricted is not None and not isinstance(restricted, RestrictedRenderState):
|
|
|
|
|
+ raise TypeError(f"restricted must be a RestrictedRenderState or None (found {type(restricted).__name__})")
|
|
|
environment_params = dict(environment_params or {})
|
|
environment_params = dict(environment_params or {})
|
|
|
|
|
+ if restricted is not None:
|
|
|
|
|
+ environment_params.pop('finalize', None)
|
|
|
|
|
|
|
|
if debug:
|
|
if debug:
|
|
|
extensions = list(environment_params.get('extensions', []))
|
|
extensions = list(environment_params.get('extensions', []))
|
|
@@ -141,7 +232,8 @@ def render_jinja2(template_code, context, environment_params=None, data_file=Non
|
|
|
loader = BaseLoader()
|
|
loader = BaseLoader()
|
|
|
environment_params['loader'] = loader
|
|
environment_params['loader'] = loader
|
|
|
|
|
|
|
|
- environment = SandboxedEnvironment(**environment_params)
|
|
|
|
|
|
|
+ environment_class = SandboxedEnvironment if restricted is None else RestrictedSandboxedEnvironment
|
|
|
|
|
+ environment = environment_class(**environment_params)
|
|
|
environment.filters.update(_jinja2_filters(filters))
|
|
environment.filters.update(_jinja2_filters(filters))
|
|
|
|
|
|
|
|
if data_file:
|
|
if data_file:
|