Buckets:

download
raw
25.7 kB
"""
Resource-limited Jinja2 SandboxedEnvironment.
`SandboxedEnvironment` blocks unsafe Python-object access (RCE) but not
CPU/memory exhaustion (`{{ "x" * 10**9 }}`, empty nested `{% for %}`
loops). This module adds: caps on `*`/`**`/`%`/`+`, a generic post-
call/filter size backstop, and a per-render budget on total `{% for %}`
iterations (any iterable, not just `range()`). Pair with
`render_with_output_limit` for cumulative output size.
Imported lazily — `jinja2` is a `cms`-extra dependency, not a base one.
Do not eagerly import this from `deepsel/utils/__init__.py`.
`MAX_OPERATION_RESULT_LENGTH` caps amplification *inputs* (`*`'s repeat
factor, `%`'s literal width) tightly, since no legitimate template needs
those that large. `MAX_CALL_RESULT_LENGTH` covers everything else
(`call()`, filters, `+`) at a higher, output-aligned cap, since those
have to tolerate large legitimate content, not just amplified bombs.
Accepted residual gaps:
- Recursive macros: bounded only by Python's recursion limit.
- `|map`/`|select`: iterate outside any `{% for %}` node, so the
iteration budget doesn't see them (their result still hits the filter
size cap).
- Server-supplied collections now share the same iteration budget as
attacker-authored loops.
`Filter` nodes with literal args are constant-folded at compile time, so
`__init__` wraps `environment.filters` up front. Filters that allocate
memory based on untrusted width/size inputs (``center``, ``indent``,
``format``) are pre-checked *before* calling the underlying function —
preventing the allocation even during constant folding, not just
rejecting the oversized result after the fact.
As defense in depth for untrusted templates, this environment also
defaults `optimized=False` to disable Jinja compile-time optimizer
constant-folding.
"""
import functools
import re
import string
from jinja2 import nodes
from jinja2.exceptions import SecurityError
from jinja2.sandbox import SandboxedEnvironment
from jinja2.visitor import NodeTransformer
# Cap for amplification-specific inputs: `*`'s repetition factor and `%`'s
# literal format width/precision. These are pre-checks on a *multiplier or
# width value*, not on existing content, so a low cap is safe — no
# legitimate template needs a single literal width/repeat-count over
# 10,000. (Results combining two already-capped operands — e.g.
# `.replace()` on two `*`-capped strings — can still reach up to roughly
# the square of this value before the *generic* backstop below,
# MAX_CALL_RESULT_LENGTH, catches them; that backstop is what actually
# bounds the final result size for anything not covered by a dedicated
# pre-check.)
MAX_OPERATION_RESULT_LENGTH = 10_000
# Cap, in bits, for `**` (int power) results. Estimated as
# `abs(exponent) * base.bit_length()` so the (potentially astronomically
# large) result never has to be computed just to measure it. 1,000,000 bits
# is far beyond anything a legitimate template needs (e.g. `2 ** 20` is 21
# bits) but well short of what would meaningfully stall a request.
MAX_POWER_RESULT_BITS = 1_000_000
# Cap for the cumulative size of rendered output. Catches loop-based
# exhaustion (many small chunks rather than one big allocation) that the
# per-operation cap above can't see, by checking a running total as the
# template streams output rather than after render() has already built the
# full string.
MAX_RENDERED_OUTPUT_LENGTH = 1_000_000
# Cap for the total number of `{% for %}` loop iterations across an entire
# render, regardless of what's being iterated over (range(), a string, a
# list, server-supplied query results, ...) or how deeply nested. Closes
# nested-loop CPU exhaustion: two nested loops with empty bodies produce no
# large allocation and no output, so neither the operation cap nor the
# output-length cap can see them, yet they total n*m iterations.
MAX_TOTAL_LOOP_ITERATIONS = 1_000_000
# Name under which the per-render iteration-budgeting wrapper is exposed in
# `self.globals` so compiled template code can call it — see `_parse()`.
# Double-underscored and namespaced to avoid colliding with a real template
# variable of the same name.
_BUDGET_ITER_GLOBAL_NAME = "__deepsel_budget_iter__"
# Name under which safe `~` concatenation is exposed in `self.globals`. The
# parser rewrites every `nodes.Concat` into a call to this helper.
_SAFE_CONCAT_GLOBAL_NAME = "__deepsel_safe_concat__"
# Cap for the generic post-call backstop (`call()`, filters, `+`, and the
# fallback check on `*`/`**`/`%`'s actual result) — deliberately higher
# than MAX_OPERATION_RESULT_LENGTH and aligned with the overall render
# output budget instead: this backstop has to tolerate calls/concatenations
# on realistically large, legitimate content (a blog post body, a page
# header + body) that were never "amplified" from something small, unlike
# the amplification-specific inputs MAX_OPERATION_RESULT_LENGTH guards.
MAX_CALL_RESULT_LENGTH = MAX_RENDERED_OUTPUT_LENGTH
# Matches one old-style `%` conversion token and captures its width and
# precision groups (each either a decimal literal or `*`), supporting both
# positional form (`%10s`, `%*.*f`) and mapping-key form (`%(name)20s`).
#
# Group 1 = width token (`""`, digits, or `"*"`)
# Group 2 = precision token (`None`, `""`, digits, or `"*"`)
_PERCENT_CONVERSION_TOKEN_PATTERN = re.compile(
r"%(?:\([^)]+\))?[-+0 #]*(\*|\d*)(?:\.(\*|\d*))?[a-zA-Z%]"
)
# Decimal-number token extractor used for pre-checking format-spec width /
# precision segments in new-style `str.format` / `str.format_map` specs.
_DECIMAL_TOKEN_PATTERN = re.compile(r"\d+")
# Bound string/bytes methods whose output allocation scales with one
# attacker-controlled integer argument: method -> (arg_position, kwarg_name).
_ALLOCATING_STRING_METHOD_SIZE_ARGS: dict[str, tuple[int, str]] = {
"center": (0, "width"),
"ljust": (0, "width"),
"rjust": (0, "width"),
"zfill": (0, "width"),
"expandtabs": (0, "tabsize"),
}
def _validate_percent_width_precision_tokens(format_string: str, max_size: int) -> None:
"""Validate `%` conversion width/precision tokens in `format_string`.
Rejects dynamic `*` width/precision and rejects numeric width/precision
above `max_size`, so the formatting operation never executes with
allocator-driving parameters that could produce huge intermediate output.
"""
for match in _PERCENT_CONVERSION_TOKEN_PATTERN.finditer(format_string):
for token in match.groups():
if not token:
continue
if not token.isdecimal():
raise SecurityError("Dynamic width/precision token is not allowed")
if int(token) > max_size:
raise SecurityError(
"Width/precision exceeds the maximum allowed size " f"({max_size})"
)
def _validate_newstyle_format_template(format_template: str, max_size: int) -> None:
"""Validate width/precision-driving tokens in `str.format` templates.
Parses replacement fields via `string.Formatter.parse` and rejects:
- nested replacement fields in a `format_spec` (dynamic width/precision)
- decimal tokens in `format_spec` larger than `max_size`
"""
for _, field_name, format_spec, _ in string.Formatter().parse(format_template):
if field_name is None:
continue
if "{" in format_spec or "}" in format_spec:
raise SecurityError("Dynamic nested format spec is not allowed")
for token in _DECIMAL_TOKEN_PATTERN.findall(format_spec):
if int(token) > max_size:
raise SecurityError(
"Format spec width/precision exceeds the maximum allowed "
f"size ({max_size})"
)
def _precheck_allocating_callable(callable_obj, args, kwargs, max_size: int) -> None:
"""Pre-validate known allocating string methods before invocation.
This closes cases where a method can allocate huge output internally
(`str.rjust`, `str.center`, ...) before the generic post-call size
backstop has a chance to run.
In current Jinja versions, `str.format`/`str.format_map` often arrive as
a wrapped function whose bound string instance is exposed via
`callable_obj.__wrapped__.__self__`; those are validated here too.
"""
bound_self = getattr(callable_obj, "__self__", None)
method_name = getattr(callable_obj, "__name__", None)
wrapped = getattr(callable_obj, "__wrapped__", None)
wrapped_self = getattr(wrapped, "__self__", None)
wrapped_name = getattr(wrapped, "__name__", None)
if isinstance(wrapped_self, str) and wrapped_name in {"format", "format_map"}:
_validate_newstyle_format_template(wrapped_self, max_size)
return
if (
isinstance(bound_self, (str, bytes))
and method_name in _ALLOCATING_STRING_METHOD_SIZE_ARGS
):
position, keyword = _ALLOCATING_STRING_METHOD_SIZE_ARGS[method_name]
size = args[position] if len(args) > position else kwargs.get(keyword)
if isinstance(size, int) and size > max_size:
raise SecurityError(
f"String method width argument exceeds the maximum allowed size ({max_size})"
)
def _reject_if_oversized(value, max_length: int = MAX_CALL_RESULT_LENGTH):
"""Raise SecurityError if `value` is a str/bytes/list/tuple/dict larger
than `max_length`. Generic backstop used by `call_binop` and `call` —
see module docstring for what this does and does not close, and for why
the default differs from `MAX_OPERATION_RESULT_LENGTH`."""
if isinstance(value, (str, bytes, list, tuple, dict)) and len(value) > max_length:
raise SecurityError(f"Result exceeds the maximum allowed size ({max_length})")
return value
def _reject_if_int_arg_oversized(
*args, max_size: int = MAX_CALL_RESULT_LENGTH, **kwargs
):
"""Reject oversized positive integer arguments before a filter/call runs.
This is a conservative pre-execution guard for filters that may allocate
proportional to a numeric argument but are not explicitly listed in
`_ALLOCATING_FILTER_SIZE_ARGS`.
"""
for value in args[1:]:
if isinstance(value, int) and value > max_size:
raise SecurityError(
f"Integer argument exceeds the maximum allowed size ({max_size})"
)
for value in kwargs.values():
if isinstance(value, int) and value > max_size:
raise SecurityError(
f"Integer argument exceeds the maximum allowed size ({max_size})"
)
# Maps filter name -> (positional-index-of-size-arg, kwarg-name-of-size-arg).
# Index is from the *full* args tuple (value is index 0, first filter arg is
# index 1, ...) so the pre-check works for both positional and keyword forms.
# Filters listed here allocate memory proportional to the named argument, so
# the argument must be rejected *before* calling the underlying function —
# a post-call size check is too late because the allocation happens inside
# the function, including when Jinja2 constant-folds the expression at
# compile time in ``from_string()`` / ``get_template()``.
_ALLOCATING_FILTER_SIZE_ARGS: dict[str, tuple[int, str]] = {
"center": (1, "width"), # center(value, width=80) → str.center(width)
"indent": (1, "width"), # indent(value, width=4, …) → width spaces per line
}
def _wrap_with_size_check(func, max_length: int = MAX_CALL_RESULT_LENGTH):
"""Wrap `func` so its return value goes through `_reject_if_oversized`.
Uses `functools.wraps` so jinja2's own markers on filter functions
(e.g. `jinja_pass_arg`, set by the `pass_context`/`pass_environment`
decorators and read via `__dict__`) survive onto the wrapper — without
it, filters needing `context`/`environment` passed in would silently
stop receiving it."""
@functools.wraps(func)
def wrapped(*args, **kwargs):
_reject_if_int_arg_oversized(*args, max_size=max_length, **kwargs)
return _reject_if_oversized(func(*args, **kwargs), max_length)
return wrapped
def _wrap_percent_format_filter(func, max_size: int = MAX_CALL_RESULT_LENGTH):
"""Wrap jinja2's ``format`` filter with pre-checks on `%` conversion
width/precision before running the actual formatting operation.
`%` formatting can allocate output proportional to width/precision
(e.g. ``"%1000000000s"``), and in `Filter` constant-folding paths that
allocation happens during ``from_string()`` / ``get_template()`` unless
we reject first.
"""
@functools.wraps(func)
def wrapped(*args, **kwargs):
if args and isinstance(args[0], (str, bytes)):
format_string = (
args[0] if isinstance(args[0], str) else args[0].decode("latin-1")
)
try:
_validate_percent_width_precision_tokens(format_string, max_size)
except SecurityError as exc:
raise SecurityError(f"'format' filter rejected: {exc}") from exc
return _reject_if_oversized(func(*args, **kwargs), max_size)
return wrapped
def _wrap_allocating_filter(
func,
size_arg_index: int,
size_kwarg_name: str,
max_size: int = MAX_CALL_RESULT_LENGTH,
):
"""Like `_wrap_with_size_check` but also pre-checks a numeric size/width
argument *before* calling the underlying function, so filters that
allocate proportionally to that argument (e.g. ``|center(width=N)``)
cannot trigger the allocation at either runtime or Jinja2 constant-
folding time (which occurs inside ``from_string()``/``get_template()``).
``size_arg_index`` is 0-based over the full args tuple (0 = value,
1 = first explicit filter arg, etc.). ``functools.wraps`` is used for
the same reason as in ``_wrap_with_size_check``."""
@functools.wraps(func)
def wrapped(*args, **kwargs):
size = (
args[size_arg_index]
if len(args) > size_arg_index
else kwargs.get(size_kwarg_name)
)
if isinstance(size, int) and size > max_size:
raise SecurityError(
f"Filter size argument exceeds the maximum allowed size ({max_size})"
)
return _reject_if_oversized(func(*args, **kwargs), max_size)
return wrapped
class _BudgetedIterable:
"""
Wraps any iterable so that *iterating* it charges against the owning
environment's shared per-render iteration budget. Applied to every
`{% for %}` loop's source expression (see `_parse()` below) — a single
loop being individually harmless says nothing about how many times it
runs when nested, e.g. two nested loops of 100,000 items each total 10
billion iterations while neither loop is large on its own.
`__len__` delegates to the wrapped object so `loop.length` / `|length`
are unaffected — `LoopContext.length` calls `len()` on the object it
was given, and that alone must not consume budget, only actually
stepping through `__iter__` does. If the wrapped object doesn't support
`len()`, this raises the same `TypeError` it would have, and
`LoopContext.length` falls back to materializing via the iterator
(which does consume budget, one charge per item, same as normal
iteration).
"""
def __init__(self, wrapped, environment: "ResourceLimitedSandboxedEnvironment"):
self._wrapped = wrapped
self._environment = environment
def __len__(self) -> int:
return len(self._wrapped)
def __iter__(self):
for item in self._wrapped:
self._environment._consume_iteration_budget()
yield item
class _SandboxAstTransformer(NodeTransformer):
"""Apply sandbox hardening rewrites to Jinja AST nodes.
- Wrap every `{% for %}` iterable with the shared iteration-budget helper.
- Rewrite every `~` concat expression (`nodes.Concat`) into a call to the
sandbox helper that enforces pre-allocation result-size checks.
"""
def visit_For(self, node, *args, **kwargs):
node = self.generic_visit(node, *args, **kwargs)
node.iter = nodes.Call(
nodes.Name(_BUDGET_ITER_GLOBAL_NAME, "load"),
[node.iter],
[],
None,
None,
).set_lineno(node.iter.lineno)
return node
def visit_Concat(self, node, *args, **kwargs):
node = self.generic_visit(node, *args, **kwargs)
return nodes.Call(
nodes.Name(_SAFE_CONCAT_GLOBAL_NAME, "load"),
[nodes.List(node.nodes)],
[],
None,
None,
).set_lineno(node.lineno)
class ResourceLimitedSandboxedEnvironment(SandboxedEnvironment):
"""
A SandboxedEnvironment that additionally rejects `*` and `**`
expressions whose result would be implausibly large, blocking
single-expression memory/CPU bombs (`"x" * 10**9`, a single huge
exponent) that pure object-traversal sandboxing doesn't address, and
caps the total number of `{% for %}` loop iterations across a render
to block nested-loop CPU exhaustion — see module docstring. Pair with
`render_with_output_limit` to also cap cumulative output size.
A fresh instance must be created per render call: the iteration budget
is instance state, so reusing one environment across renders would leak
a spent (or partially spent) budget into an unrelated render.
"""
intercepted_binops = frozenset({"*", "**", "%", "+"})
def __init__(
self,
*args,
max_loop_iterations: int = MAX_TOTAL_LOOP_ITERATIONS,
**kwargs,
) -> None:
# Untrusted templates must not be constant-folded at compile time.
# Force-disable the optimizer so callers cannot re-enable it via
# `optimized=True`, which would run constant `Filter` expressions
# during `from_string()`/`get_template()`.
kwargs["optimized"] = False
super().__init__(*args, **kwargs)
self._loop_iterations_remaining = max_loop_iterations
self._max_loop_iterations = max_loop_iterations
self.globals[_BUDGET_ITER_GLOBAL_NAME] = self._budget_iterable
self.globals[_SAFE_CONCAT_GLOBAL_NAME] = self._safe_concat
# Filters (`|center`, `|indent`, `|format`, ...) reach a separate dict
# from `call()`. Wrap all of them with a generic post-call backstop,
# and apply extra pre-call checks for known allocators whose size can
# be attacker-controlled. `self.filters` is `DEFAULT_FILTERS.copy()`
# per Environment.__init__, so mutating it here only affects this
# instance.
self.filters = {
name: (
_wrap_allocating_filter(
filter_func, *_ALLOCATING_FILTER_SIZE_ARGS[name]
)
if name in _ALLOCATING_FILTER_SIZE_ARGS
else (
_wrap_percent_format_filter(filter_func)
if name == "format"
else _wrap_with_size_check(filter_func)
)
)
for name, filter_func in self.filters.items()
}
def _parse(self, source, name, filename):
"""
Wraps every `{% for %}` node's source expression with a call to
`self._budget_iterable`, so every iteration of every loop — not
just `range()`-based ones — is charged against the shared budget.
Plain `{% for x in y %}` compiles to an un-mediated Python
`for x in y:` with no `environment`-routed call to intercept
(confirmed by inspecting jinja2's generated source), so this has to
happen at the AST level, before code generation, rather than via
any Environment method override.
Wrapping rewritten operations as `nodes.Call` (not e.g.
`nodes.Filter`) matters: `Call.as_const` is not overridden by jinja2,
so it always raises `Impossible()` and is never evaluated by jinja2's
compile-time constant-folding optimizer.
"""
ast = super()._parse(source, name, filename)
return _SandboxAstTransformer().visit(ast)
def _budget_iterable(self, iterable) -> _BudgetedIterable:
return _BudgetedIterable(iterable, self)
def _safe_concat(self, values) -> str:
"""Safely concatenate values for rewritten `~` expressions.
Builds the result incrementally and enforces `MAX_CALL_RESULT_LENGTH`
before the final large allocation can happen.
"""
parts = []
total_length = 0
for value in values:
text = str(value)
total_length += len(text)
if total_length > MAX_CALL_RESULT_LENGTH:
raise SecurityError(
"Result of '~' exceeds the maximum allowed size "
f"({MAX_CALL_RESULT_LENGTH})"
)
parts.append(text)
return "".join(parts)
def _consume_iteration_budget(self) -> None:
self._loop_iterations_remaining -= 1
if self._loop_iterations_remaining < 0:
raise SecurityError(
"Template exceeded the maximum allowed number of loop "
f"iterations ({self._max_loop_iterations})"
)
def call_binop(self, context, operator, left, right):
if operator == "*":
for sequence, factor in ((left, right), (right, left)):
if isinstance(sequence, (str, bytes, list, tuple)) and isinstance(
factor, int
):
if len(sequence) * max(factor, 0) > MAX_OPERATION_RESULT_LENGTH:
raise SecurityError(
"Result of '*' exceeds the maximum allowed length "
f"({MAX_OPERATION_RESULT_LENGTH})"
)
elif operator == "**":
if (
isinstance(left, int)
and isinstance(right, int)
and abs(left) > 1
and right > 0
and right * left.bit_length() > MAX_POWER_RESULT_BITS
):
raise SecurityError(
"Result of '**' exceeds the maximum allowed size "
f"({MAX_POWER_RESULT_BITS} bits)"
)
elif operator == "%":
if isinstance(left, (str, bytes)):
format_string = (
left if isinstance(left, str) else left.decode("latin-1")
)
try:
_validate_percent_width_precision_tokens(
format_string,
MAX_OPERATION_RESULT_LENGTH,
)
except SecurityError as exc:
raise SecurityError(f"'%' operator rejected: {exc}") from exc
# Backstop for any `%` case that still slips past pre-checks, and for
# non-`%` operators after their own pre-checks.
return _reject_if_oversized(super().call_binop(context, operator, left, right))
def format_string(self, s, args, kwargs, format_func=None):
"""Pre-validate `str.format` / `str.format_map` specs before format.
Compatibility fallback for Jinja variants that route format calls
through `format_string` directly.
"""
if isinstance(s, str):
try:
_validate_newstyle_format_template(s, MAX_CALL_RESULT_LENGTH)
except SecurityError as exc:
raise SecurityError(f"str.format rejected: {exc}") from exc
return super().format_string(s, args, kwargs, format_func)
def call(__self, __context, __obj, *args, **kwargs):
"""
Generic backstop for any callable reached from sandboxed code
(string/bytes/list methods like `.rjust()`, `.replace()`, filters,
globals — anything routed through `environment.call`) whose result is
unexpectedly large.
Includes targeted pre-checks for known width-arg string methods before
invocation; `str.format`/`str.format_map` pre-checks are handled in
`format_string()` because jinja routes those through a separate path.
Double-underscore parameter names match SandboxedEnvironment.call's
own signature: they avoid colliding with a template kwarg literally
named `context`/`obj`, which `**kwargs` would otherwise pass through.
"""
_precheck_allocating_callable(__obj, args, kwargs, MAX_CALL_RESULT_LENGTH)
return _reject_if_oversized(super().call(__context, __obj, *args, **kwargs))
def render_with_output_limit(
template, context: dict, max_length: int = MAX_RENDERED_OUTPUT_LENGTH
) -> str:
"""
Render `template` while enforcing a cap on cumulative output length,
raising `SecurityError` as soon as the running total exceeds
`max_length` instead of after `template.render()` has already built the
full (potentially huge) string. Catches loop-based exhaustion — many
small chunks, none individually large enough to trip
`ResourceLimitedSandboxedEnvironment`'s per-operation cap — by checking
output size as the template streams rather than only at the end.
"""
chunks = []
total_length = 0
for chunk in template.generate(**context):
total_length += len(chunk)
if total_length > max_length:
raise SecurityError(
f"Rendered output exceeds the maximum allowed length ({max_length})"
)
chunks.append(chunk)
return "".join(chunks)

Xet Storage Details

Size:
25.7 kB
·
Xet hash:
71b580bb0de877b62923d70169ebb5671aac285f7f540bc749702b89dd6d9979

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.