Compare commits

2 Commits
1.1 ... main

7 changed files with 78 additions and 336 deletions

View File

@@ -1,64 +0,0 @@
From 56a724644b1ad9cb03745c10cca732715cdc79e9 Mon Sep 17 00:00:00 2001
From: Sigurd Spieckermann <sigurd.spieckermann@gmail.com>
Date: Fri, 26 May 2023 14:32:36 +0200
Subject: [PATCH] fix f-string syntax error in code generation
---
src/jinja2/compiler.py | 7 ++++++-
tests/test_compile.py | 19 +++++++++++++++++++
2 files changed, 25 insertions(+), 1 deletion(-)
Index: jinja2-3.1.4/src/jinja2/compiler.py
===================================================================
--- jinja2-3.1.4.orig/src/jinja2/compiler.py
+++ jinja2-3.1.4/src/jinja2/compiler.py
@@ -1125,9 +1125,14 @@ class CodeGenerator(NodeVisitor):
)
self.writeline(f"if {frame.symbols.ref(alias)} is missing:")
self.indent()
+ # The position will contain the template name, and will be formatted
+ # into a string that will be compiled into an f-string. Curly braces
+ # in the name must be replaced with escapes so that they will not be
+ # executed as part of the f-string.
+ position = self.position(node).replace("{", "{{").replace("}", "}}")
message = (
"the template {included_template.__name__!r}"
- f" (imported on {self.position(node)})"
+ f" (imported on {position})"
f" does not export the requested name {name!r}"
)
self.writeline(
Index: jinja2-3.1.4/tests/test_compile.py
===================================================================
--- jinja2-3.1.4.orig/tests/test_compile.py
+++ jinja2-3.1.4/tests/test_compile.py
@@ -1,6 +1,9 @@
import os
import re
+import pytest
+
+from jinja2 import UndefinedError
from jinja2.environment import Environment
from jinja2.loaders import DictLoader
@@ -26,3 +29,19 @@ def test_import_as_with_context_determin
expect = [f"'bar{i}': " for i in range(10)]
found = re.findall(r"'bar\d': ", content)[:10]
assert found == expect
+
+
+def test_undefined_import_curly_name():
+ env = Environment(
+ loader=DictLoader(
+ {
+ "{bad}": "{% from 'macro' import m %}{{ m() }}",
+ "macro": "",
+ }
+ )
+ )
+
+ # Must not raise `NameError: 'bad' is not defined`, as that would indicate
+ # that `{bad}` is being interpreted as an f-string. It must be escaped.
+ with pytest.raises(UndefinedError):
+ env.get_template("{bad}").render()

View File

@@ -1,169 +0,0 @@
From 91a972f5808973cd441f4dc06873b2f8378f30c7 Mon Sep 17 00:00:00 2001
From: Lydxn <hlyndon20@gmail.com>
Date: Mon, 23 Sep 2024 15:09:10 -0700
Subject: [PATCH] sandbox indirect calls to str.format
---
src/jinja2/sandbox.py | 81 ++++++++++++++++++++++--------------------
tests/test_security.py | 17 +++++++++
2 files changed, 60 insertions(+), 38 deletions(-)
Index: jinja2-3.1.4/src/jinja2/sandbox.py
===================================================================
--- jinja2-3.1.4.orig/src/jinja2/sandbox.py
+++ jinja2-3.1.4/src/jinja2/sandbox.py
@@ -7,6 +7,7 @@ import types
import typing as t
from collections import abc
from collections import deque
+from functools import update_wrapper
from string import Formatter
from _string import formatter_field_name_split # type: ignore
@@ -81,20 +82,6 @@ _mutable_spec: t.Tuple[t.Tuple[t.Type[t.
)
-def inspect_format_method(callable: t.Callable[..., t.Any]) -> t.Optional[str]:
- if not isinstance(
- callable, (types.MethodType, types.BuiltinMethodType)
- ) or callable.__name__ not in ("format", "format_map"):
- return None
-
- obj = callable.__self__
-
- if isinstance(obj, str):
- return obj
-
- return None
-
-
def safe_range(*args: int) -> range:
"""A range that can't generate ranges with a length of more than
MAX_RANGE items.
@@ -314,6 +301,9 @@ class SandboxedEnvironment(Environment):
except AttributeError:
pass
else:
+ fmt = self.wrap_str_format(value)
+ if fmt is not None:
+ return fmt
if self.is_safe_attribute(obj, argument, value):
return value
return self.unsafe_undefined(obj, argument)
@@ -331,6 +321,9 @@ class SandboxedEnvironment(Environment):
except (TypeError, LookupError):
pass
else:
+ fmt = self.wrap_str_format(value)
+ if fmt is not None:
+ return fmt
if self.is_safe_attribute(obj, attribute, value):
return value
return self.unsafe_undefined(obj, attribute)
@@ -346,34 +339,49 @@ class SandboxedEnvironment(Environment):
exc=SecurityError,
)
- def format_string(
- self,
- s: str,
- args: t.Tuple[t.Any, ...],
- kwargs: t.Dict[str, t.Any],
- format_func: t.Optional[t.Callable[..., t.Any]] = None,
- ) -> str:
- """If a format call is detected, then this is routed through this
- method so that our safety sandbox can be used for it.
+ def wrap_str_format(self, value: t.Any) -> t.Optional[t.Callable[..., str]]:
+ """If the given value is a ``str.format`` or ``str.format_map`` method,
+ return a new function than handles sandboxing. This is done at access
+ rather than in :meth:`call`, so that calls made without ``call`` are
+ also sandboxed.
"""
+ if not isinstance(
+ value, (types.MethodType, types.BuiltinMethodType)
+ ) or value.__name__ not in ("format", "format_map"):
+ return None
+
+ f_self: t.Any = value.__self__
+
+ if not isinstance(f_self, str):
+ return None
+
+ str_type: t.Type[str] = type(f_self)
+ is_format_map = value.__name__ == "format_map"
formatter: SandboxedFormatter
- if isinstance(s, Markup):
- formatter = SandboxedEscapeFormatter(self, escape=s.escape)
+
+ if isinstance(f_self, Markup):
+ formatter = SandboxedEscapeFormatter(self, escape=f_self.escape)
else:
formatter = SandboxedFormatter(self)
- if format_func is not None and format_func.__name__ == "format_map":
- if len(args) != 1 or kwargs:
- raise TypeError(
- "format_map() takes exactly one argument"
- f" {len(args) + (kwargs is not None)} given"
- )
+ vformat = formatter.vformat
+
+ def wrapper(*args: t.Any, **kwargs: t.Any) -> str:
+ if is_format_map:
+ if kwargs:
+ raise TypeError("format_map() takes no keyword arguments")
+
+ if len(args) != 1:
+ raise TypeError(
+ f"format_map() takes exactly one argument ({len(args)} given)"
+ )
+
+ kwargs = args[0]
+ args = ()
- kwargs = args[0]
- args = ()
+ return str_type(vformat(f_self, args, kwargs))
- rv = formatter.vformat(s, args, kwargs)
- return type(s)(rv)
+ return update_wrapper(wrapper, value)
def call(
__self, # noqa: B902
@@ -383,9 +391,6 @@ class SandboxedEnvironment(Environment):
**kwargs: t.Any,
) -> t.Any:
"""Call an object from sandboxed code."""
- fmt = inspect_format_method(__obj)
- if fmt is not None:
- return __self.format_string(fmt, args, kwargs, __obj)
# the double prefixes are to avoid double keyword argument
# errors when proxying the call.
Index: jinja2-3.1.4/tests/test_security.py
===================================================================
--- jinja2-3.1.4.orig/tests/test_security.py
+++ jinja2-3.1.4/tests/test_security.py
@@ -171,3 +171,20 @@ class TestStringFormatMap:
'{{ ("a{x.foo}b{y}"|safe).format_map({"x":{"foo": 42}, "y":"<foo>"}) }}'
)
assert t.render() == "a42b&lt;foo&gt;"
+
+ def test_indirect_call(self):
+ def run(value, arg):
+ return value.run(arg)
+
+ env = SandboxedEnvironment()
+ env.filters["run"] = run
+ t = env.from_string(
+ """{% set
+ ns = namespace(run="{0.__call__.__builtins__[__import__]}".format)
+ %}
+ {{ ns | run(not_here) }}
+ """
+ )
+
+ with pytest.raises(SecurityError):
+ t.render()

View File

@@ -1,87 +0,0 @@
From 065334d1ee5b7210e1a0a93c37238c86858f2af7 Mon Sep 17 00:00:00 2001
From: David Lord <davidism@gmail.com>
Date: Wed, 5 Mar 2025 10:08:48 -0800
Subject: [PATCH] attr filter uses env.getattr
---
src/jinja2/filters.py | 37 ++++++++++++++++---------------------
tests/test_security.py | 10 ++++++++++
2 files changed, 26 insertions(+), 21 deletions(-)
diff --git a/src/jinja2/filters.py b/src/jinja2/filters.py
index e5b5a00c5..2bcba4fbd 100644
--- a/src/jinja2/filters.py
+++ b/src/jinja2/filters.py
@@ -6,6 +6,7 @@
import typing
import typing as t
from collections import abc
+from inspect import getattr_static
from itertools import chain
from itertools import groupby
@@ -1411,31 +1412,25 @@ def do_reverse(value: t.Union[str, t.Iterable[V]]) -> t.Union[str, t.Iterable[V]
def do_attr(
environment: "Environment", obj: t.Any, name: str
) -> t.Union[Undefined, t.Any]:
- """Get an attribute of an object. ``foo|attr("bar")`` works like
- ``foo.bar`` just that always an attribute is returned and items are not
- looked up.
+ """Get an attribute of an object. ``foo|attr("bar")`` works like
+ ``foo.bar``, but returns undefined instead of falling back to ``foo["bar"]``
+ if the attribute doesn't exist.
See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.
"""
+ # Environment.getattr will fall back to obj[name] if obj.name doesn't exist.
+ # But we want to call env.getattr to get behavior such as sandboxing.
+ # Determine if the attr exists first, so we know the fallback won't trigger.
try:
- name = str(name)
- except UnicodeError:
- pass
- else:
- try:
- value = getattr(obj, name)
- except AttributeError:
- pass
- else:
- if environment.sandboxed:
- environment = t.cast("SandboxedEnvironment", environment)
-
- if not environment.is_safe_attribute(obj, name, value):
- return environment.unsafe_undefined(obj, name)
-
- return value
-
- return environment.undefined(obj=obj, name=name)
+ # This avoids executing properties/descriptors, but misses __getattr__
+ # and __getattribute__ dynamic attrs.
+ getattr_static(obj, name)
+ except AttributeError:
+ # This finds dynamic attrs, and we know it's not a descriptor at this point.
+ if not hasattr(obj, name):
+ return environment.undefined(obj=obj, name=name)
+
+ return environment.getattr(obj, name)
@typing.overload
diff --git a/tests/test_security.py b/tests/test_security.py
index 864d5f7f9..3a1378192 100644
--- a/tests/test_security.py
+++ b/tests/test_security.py
@@ -190,3 +190,13 @@ def run(value, arg):
with pytest.raises(SecurityError):
t.render()
+
+ def test_attr_filter(self) -> None:
+ env = SandboxedEnvironment()
+ t = env.from_string(
+ """{{ "{0.__call__.__builtins__[__import__]}"
+ | attr("format")(not_here) }}"""
+ )
+
+ with pytest.raises(SecurityError):
+ t.render()

BIN
jinja2-3.1.4.tar.gz (Stored with Git LFS)

Binary file not shown.

BIN
jinja2-3.1.6.tar.gz (Stored with Git LFS) Normal file

Binary file not shown.

View File

@@ -1,13 +1,71 @@
-------------------------------------------------------------------
Wed Mar 12 13:00:14 UTC 2025 - Nico Krapp <nico.krapp@suse.com>
Mon Mar 17 11:59:32 UTC 2025 - Daniel Garcia <daniel.garcia@suse.com>
- Add security patch CVE-2025-27516.patch (bsc#1238879)
- Skip test_elif_deep on s390x arch
-------------------------------------------------------------------
Fri Dec 27 15:07:20 UTC 2024 - Nico Krapp <nico.krapp@suse.com>
Mon Mar 10 08:46:26 UTC 2025 - John Paul Adrian Glaubitz <adrian.glaubitz@suse.com>
- Add security patch CVE-2024-56201.patch (bsc#1234808)
- Add security patch CVE-2024-56326.patch (bsc#1234809)
- Update to 3.1.6
* The ``|attr`` filter does not bypass the environment's attribute lookup,
allowing the sandbox to apply its checks.
-------------------------------------------------------------------
Fri Dec 27 09:16:40 UTC 2024 - Nico Krapp <nico.krapp@suse.com>
- Update to 3.1.5:
* The sandboxed environment handles indirect calls to str.format,
such as by passing a stored reference to a filter that calls
its argument. GHSA-q2x7-8rv6-6q7h
* Escape template name before formatting it into error messages,
to avoid issues with names that contain f-string syntax. #1792,
GHSA-gmj6-6f8f-6699
* Sandbox does not allow clear and pop on known mutable sequence
types. #2032
* Calling sync render for an async template uses asyncio.run. #1952
* Avoid unclosed auto_aiter warnings. #1960
* Return an aclose-able AsyncGenerator from
Template.generate_async. #1960
* Avoid leaving root_render_func() unclosed in
Template.generate_async. #1960
* Avoid leaving async generators unclosed in blocks, includes and
extends. #1960
* The runtime uses the correct concat function for the current
environment when calling block references. #1701
* Make |unique async-aware, allowing it to be used after another
async-aware filter. #1781
* |int filter handles OverflowError from scientific notation. #1921
* Make compiling deterministic for tuple unpacking in a {% set ... %}
call. #2021
* Fix dunder protocol (copy/pickle/etc) interaction with Undefined
objects. #2025
* Fix copy/pickle support for the internal missing object. #2027
* Environment.overlay(enable_async) is applied correctly. #2061
* The error message from FileSystemLoader includes the paths that
were searched. #1661
* PackageLoader shows a clearer error message when the package does
not contain the templates directory. #1705
* Improve annotations for methods returning copies. #1880
* urlize does not add mailto: to values like @a@b. #1870
* Tests decorated with @pass_context can be used with the
|select filter. #1624
* Using set for multiple assignment (a, b = 1, 2) does not fail when
the target is a namespace attribute. #1413
* Using set in all branches of {% if %}{% elif %}{% else %} blocks does
not cause the variable to be considered initially undefined. #1253
- drop fix-ftbfs-with-python313.patch, merged upstream
-------------------------------------------------------------------
Tue Sep 24 12:48:03 UTC 2024 - ecsos <ecsos@opensuse.org>
- Fix build error under Leap.
-------------------------------------------------------------------
Tue Jul 30 10:44:01 UTC 2024 - John Paul Adrian Glaubitz <adrian.glaubitz@suse.com>
- Cherry-pick patch from Fedora to fix FTBFS with Python 3.13
* fix-ftbfs-with-python313.patch
- Add new build dependency python-trio to BuildRequires
-------------------------------------------------------------------
Mon May 6 18:10:40 UTC 2024 - Dirk Müller <dmueller@suse.com>

View File

@@ -1,7 +1,7 @@
#
# spec file for package python-Jinja2
#
# Copyright (c) 2024 SUSE LLC
# Copyright (c) 2025 SUSE LLC
#
# All modifications and additions to the file contributed by third parties
# remain the property of their copyright owners, unless otherwise agreed
@@ -23,23 +23,18 @@
%endif
%{?sle15_python_module_pythons}
Name: python-Jinja2
Version: 3.1.4
Version: 3.1.6
Release: 0
Summary: A template engine written in pure Python
License: BSD-3-Clause
URL: https://jinja.palletsprojects.com
Source: https://files.pythonhosted.org/packages/source/J/Jinja2/jinja2-%{version}.tar.gz
# PATCH-FIX-UPSTREAM CVE-2024-56201.patch
Patch0: CVE-2024-56201.patch
# PATCH-FIX-UPSTREAM CVE-2024-56326.patch
Patch1: CVE-2024-56326.patch
# PATCH-FIX-UPSTREAM CVE-2025-27516.patch
Patch2: CVE-2025-27516.patch
BuildRequires: %{python_module MarkupSafe >= 0.23}
BuildRequires: %{python_module base >= 3.7}
BuildRequires: %{python_module flit-core}
BuildRequires: %{python_module pip}
BuildRequires: %{python_module pytest}
BuildRequires: %{python_module trio}
BuildRequires: %{python_module wheel}
BuildRequires: dos2unix
BuildRequires: fdupes
@@ -65,6 +60,11 @@ sandboxed environment.
%install
%pyproject_install
# Fix python-bytecode-inconsistent-mtime
pushd %{buildroot}%{python_sitelib}
find . -name '*.pyc' -exec rm -f '{}' ';'
python%python_bin_suffix -m compileall *.py ';'
popd
%python_expand %fdupes %{buildroot}%{$python_sitelib}
%check
@@ -72,6 +72,10 @@ sandboxed environment.
# Test broken with latest version of MarkupSafe (2.1.4)
# gh#pallets/jinja#1930, gh#pallets/markupsafe#417
donttest="test_striptags"
# Test fails in s390x with maximum recursion depth exceeded during compilation
%if "%{_arch}" == "s390x"
donttest+=" or test_elif_deep"
%endif
%pytest -W ignore:'Support for nose tests is deprecated' -k "not ($donttest)"
%endif