CVE-2023-25657: Insufficient Information (NVD-CWE-noinfo)
value: Nautobot is a Network Source of Truth and Network Automation Platform. All users of Nautobot versions earlier than 1.5.7 are impacted by a remote code execution vulnerability. Nautobot did not properly sandbox Jinja2 template rendering. In Nautobot 1.5.7 has enabled sandboxed environments for the Jinja2 template engine used internally for template rendering for the following objects: `extras.ComputedField`, `extras.CustomLink`, `extras.ExportTemplate`, `extras.Secret`, `extras.Webhook`. While no active exploits of this vulnerability are known this change has been made as a preventative measure to protect against any potential remote code execution attacks utilizing maliciously crafted template code. This change forces the Jinja2 template engine to use a `SandboxedEnvironment` on all new installations of Nautobot. This addresses any potential unsafe code execution everywhere the helper function `nautobot.utilities.utils.render_jinja2` is called. Additionally, the documentation that had previously suggesting the direct use of `jinja2.Template` has been revised to suggest `render_jinja2`. Users are advised to upgrade to Nautobot 1.5.7 or newer. For users that are unable to upgrade to the latest release of Nautobot, you may add the following setting to your `nautobot_config.py` to apply the sandbox environment enforcement: `TEMPLATES[1]["OPTIONS"]["environment"] = "jinja2.sandbox.SandboxedEnvironment"` After applying this change, you must restart all Nautobot services, including any Celery worker processes. **Note:** *Nautobot specifies two template engines by default, the first being “django” for the Django built-in template engine, and the second being “jinja” for the Jinja2 template engine. This recommended setting will update the second item in the list of template engines, which is the Jinja2 engine.* For users that are unable to immediately update their configuration such as if a Nautobot service restart is too disruptive to operations, access to provide custom Jinja2 template values may be mitigated using permissions to restrict “change” (write) actions to the affected object types listed in the first section. **Note:** *This solution is intended to be stopgap until you can successfully update your `nautobot_config.py` or upgrade your Nautobot instance to apply the sandboxed environment enforcement.*
CWE description: There is insufficient information about the issue to classify it; details are unkown or unspecified.
CVSS v3 base score: 9.8
Published: 2023-02-21T21:15Z
Repository: https://github.com/nautobot/nautobot
Language: Python
Files changed: nautobot/core/settings.py, nautobot/docs/models/dcim/deviceredundancygroup.md, nautobot/utilities/tests/test_jinja_filters.py
Commit date: 2023-01-04 09:59:49 -0800
Commit message: Enforce sandboxed rendering for Jinja2 templates.

- This forces the Jinja2 template renderer to use a `SandboxedEnvironment`
- This addresses any unsafe code execution everywhere `render_jinja2` is called.
- Test added to assert that unsafe attributes cannot be accessed and will result in a `SecurityError`.
- Documentation referencing direct use of `jinja2.Template` replaced with `render_jinja2`

Diff: diff --git a/nautobot/core/settings.py b/nautobot/core/settings.py
index 944e11172..a5b84fdcb 100644
--- a/nautobot/core/settings.py
+++ b/nautobot/core/settings.py
@@ -466,10 +466,11 @@ TEMPLATES = [
                 "social_django.context_processors.backends",
                 "social_django.context_processors.login_redirect",
                 "nautobot.core.context_processors.settings",
                 "nautobot.core.context_processors.sso_auth",
             ],
+            "environment": "jinja2.sandbox.SandboxedEnvironment",
         },
     },
 ]
 
 # Set up authentication backends
diff --git a/nautobot/docs/models/dcim/deviceredundancygroup.md b/nautobot/docs/models/dcim/deviceredundancygroup.md
index 240bb3ffd..a90e68108 100644
--- a/nautobot/docs/models/dcim/deviceredundancygroup.md
+++ b/nautobot/docs/models/dcim/deviceredundancygroup.md
@@ -140,11 +140,11 @@ We will demonstrate how to execute the command for Primary Unit only, however yo
 
 The following snippet represents an example Cisco ASA failover configuration template:
 
 ```python
 # Configuration Template for Cisco ASA
-template_body="""
+template_code = """
 {% set redundancy_members = gql_data['data']['devices'][0]['device_redundancy_group']['members'] %}
 {% set failover_device_local = redundancy_members[0] if redundancy_members[0].name == device else redundancy_members[1] %}
 {% set failover_device_peer = redundancy_members[0] if redundancy_members[0].name != device else redundancy_members[1] %}
 {% set failover_local_vif = failover_device_local.interfaces | first %}
 {% set failover_peer_vif = failover_device_peer.interfaces | first %}
@@ -170,19 +170,19 @@ failover
 ### Rendering Cisco ASA Configuration Template with the data retrieved from GraphQL
 
 Following snippet represents an example Cisco ASA Failover rendered configuration:
 
 ```python
-from jinja2 import Template
+from nautobot.utilities.utils import render_jinja2
 
-tm=Template(template_body)
 
-nyc_fw_primary_config = tm.render(
+context = dict(
     device=hostname,
     gql_data=gql_data,
     priority_mapping={50: 'secondary', 100: 'primary'}
 )
+nyc_fw_primary_config = render_jinja2(template_code=template_code, context=context)
 
 print(nyc_fw_primary_config)
 ```
 
 ```text
diff --git a/nautobot/utilities/tests/test_jinja_filters.py b/nautobot/utilities/tests/test_jinja_filters.py
index cdb1a89f3..1d6218b4b 100644
--- a/nautobot/utilities/tests/test_jinja_filters.py
+++ b/nautobot/utilities/tests/test_jinja_filters.py
@@ -1,11 +1,11 @@
 from django.test import TestCase
-from jinja2.exceptions import TemplateAssertionError
-
+from jinja2.exceptions import SecurityError, TemplateAssertionError
 from netutils.utils import jinja2_convenience_function
 
 from nautobot.utilities.utils import render_jinja2
+from nautobot.dcim.models import Site
 
 
 class NautobotJinjaFilterTest(TestCase):
     def test_invalid_templatetags_raise_exception(self):
         """Validate that executing render_jinja2 with an invalid filter will raise TemplateAssertionError."""
@@ -62,5 +62,22 @@ class NautobotJinjaFilterTest(TestCase):
                 render_jinja2("{{ data | " + filter_ + " }}", {"data": None})
             except TemplateAssertionError:
                 raise
             except Exception:
                 pass
+
+    def test_sandboxed_render(self):
+        """Assert that Jinja template rendering is sandboxed."""
+        template_code = "{{ ''.__class__.__name__ }}"
+        with self.assertRaises(SecurityError):
+            render_jinja2(template_code=template_code, context={})
+
+    def test_safe_render(self):
+        """Assert that safe Jinja rendering still works."""
+        site = Site.objects.filter(region__isnull=False).first()
+        template_code = "{{ obj.region.name }}"
+        try:
+            value = render_jinja2(template_code=template_code, context={"obj": site})
+        except SecurityError:
+            self.fail("SecurityError raised on safe Jinja template render")
+        else:
+            self.assertEqual(value, site.region.name)

Vulnerable code: template_body="""
from jinja2 import Template
tm=Template(template_body)
nyc_fw_primary_config = tm.render(
from jinja2.exceptions import TemplateAssertionError

Fixed code:             "environment": "jinja2.sandbox.SandboxedEnvironment",
template_code = """
from nautobot.utilities.utils import render_jinja2
context = dict(
nyc_fw_primary_config = render_jinja2(template_code=template_code, context=context)
from jinja2.exceptions import SecurityError, TemplateAssertionError
from nautobot.dcim.models import Site

    def test_sandboxed_render(self):
        """Assert that Jinja template rendering is sandboxed."""
        template_code = "{{ ''.__class__.__name__ }}"
        with self.assertRaises(SecurityError):
            render_jinja2(template_code=template_code, context={})

    def test_safe_render(self):
        """Assert that safe Jinja rendering still works."""
        site = Site.objects.filter(region__isnull=False).first()
        template_code = "{{ obj.region.name }}"
        try:
            value = render_jinja2(template_code=template_code, context={"obj": site})
        except SecurityError:
            self.fail("SecurityError raised on safe Jinja template render")
        else:
            self.assertEqual(value, site.region.name)