Skip to content

Commit 3fbf9a3

Browse files
committed
Tests and fix for CVE-2021-25283
1 parent ee4824d commit 3fbf9a3

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

salt/utils/templates.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
import jinja2
1313
import jinja2.ext
14+
import jinja2.sandbox
1415
import salt.utils.data
1516
import salt.utils.dateutils
1617
import salt.utils.files
@@ -453,9 +454,11 @@ def opt_jinja_env_helper(opts, optname):
453454
opt_jinja_env_helper(opt_jinja_env, "jinja_env")
454455

455456
if opts.get("allow_undefined", False):
456-
jinja_env = jinja2.Environment(**env_args)
457+
jinja_env = jinja2.sandbox.SandboxedEnvironment(**env_args)
457458
else:
458-
jinja_env = jinja2.Environment(undefined=jinja2.StrictUndefined, **env_args)
459+
jinja_env = jinja2.sandbox.SandboxedEnvironment(
460+
undefined=jinja2.StrictUndefined, **env_args
461+
)
459462

460463
tojson_filter = jinja_env.filters.get("tojson")
461464
indent_filter = jinja_env.filters.get("indent")
@@ -506,6 +509,7 @@ def opt_jinja_env_helper(opts, optname):
506509
except (
507510
jinja2.exceptions.TemplateRuntimeError,
508511
jinja2.exceptions.TemplateSyntaxError,
512+
jinja2.exceptions.SecurityError,
509513
) as exc:
510514
trace = traceback.extract_tb(sys.exc_info()[2])
511515
line, out = _get_jinja_error(trace, context=decoded_context)

tests/unit/utils/test_templates.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import sys
88
from pathlib import PurePath, PurePosixPath
99

10+
import pytest
1011
import salt.utils.files
1112
import salt.utils.templates
1213
from tests.support import mock
@@ -201,6 +202,13 @@ def test_render_cheetah_variable(self):
201202
res = salt.utils.templates.render_cheetah_tmpl(tmpl, ctx)
202203
self.assertEqual(res.strip(), "OK")
203204

205+
def test_render_jinja_cve_2021_25283(self):
206+
tmpl = """{{ [].__class__ }}"""
207+
ctx = dict(self.context)
208+
ctx["var"] = "OK"
209+
with pytest.raises(salt.exceptions.SaltRenderError):
210+
res = salt.utils.templates.render_jinja_tmpl(tmpl, ctx)
211+
204212

205213
class MockRender:
206214
def __call__(self, tplstr, context, tmplpath=None):

0 commit comments

Comments
 (0)