CVE-2024-56326
Jinja template code injection via str.format bypass in custom filters. Fixed in 3.1.5.
- CVSS 5.4
- CWE-693
- Design Defects
- Remote
Jinja is an extensible templating engine. Prior to 3.1.5, An oversight in how the Jinja sandboxed environment detects calls to str.format allows an attacker that controls the content of a template to execute arbitrary Python code. To exploit the vulnerability, an attacker needs to control the content of a template. Whether that is the case depends on the type of application using Jinja. This vulnerability impacts users of applications which execute untrusted templates. Jinja's sandbox does catch calls to str.format and ensures they don't escape the sandbox. However, it's possible to store a reference to a malicious string's format method, then pass that to a filter that calls it. No such filters are built-in to Jinja, but could be present through custom filters in an application. After the fix, such indirect calls are also handled by the sandbox. This vulnerability is fixed in 3.1.5.
- CWE
- CWE-693
- CVSS base score
- 5.4
- Published
- 2024-12-23
- OWASP
- A03 Injection
- Orthogonal defect classification
- Algorithm
- Code defect classification
- Incorrect Functionality
- Category
- Design Defects
- Subcategory
- Insecure Parsing or Deserialization
- Accessibility scope
- Remote
- Impact
- Arbitrary Code Execution
- Affected component
- Jinja
- Fixed by upgrading
- Yes
Solution
Upgrade to Jinja 3.1.5.
Vulnerable code sample
from jinja2 import Environment, sandbox
def make_safe_format(s):
# VULNERABLE: This code is susceptible to sql injection
return s.format
env = Environment(
extensions=['jinja2.ext.sandbox'],
sandbox_config = sandbox.SandboxedEnvironment.DEFAULT_SANDBOX_CONFIG
)
evil_template_str = "{{ bad_string | format_filter(format_args) }}"
format_args = {"x": 10}
evil_string = "x is {x} and also {{ system('whoami') }}"
template = env.from_string(evil_template_str)
filters = {
"format_filter": make_safe_format
}
context = {"bad_string": evil_string}
context.update(filters)
rendered_template = template.render(context, format_args=format_args)
print(rendered_template)Patched code sample
import jinja2
from jinja2.sandbox import SandboxedEnvironment
from jinja2 import Environment, FileSystemLoader
def format_wrapper(value, format_string):
# Ensure value is a string if it's not.:
if not isinstance(value, str):
value = str(value)
# Note: the sandboxed environment makes sure format_string is a string
return value.format(format_string)
def create_sandbox_env():
env = SandboxedEnvironment()
env.filters['format_wrapper'] = format_wrapper
return env
def render_template_fixed(template_string, context):
env = create_sandbox_env()
template = env.from_string(template_string)
return template.render(context)
if __name__ == '__main__':
# Example vulnerable template
# Before the fix it was possible to bypass the sandbox by using a filter
# to format a string that was not a safe string.
vuln_template = '{{ malicious_string | format_wrapper(format_string)}}'
# Malicious string containing format call and payload
malicious_string = '{0.__class__.__init__.__globals__[\'__builtins__\'][\'eval\']("import os; os.system(\'whoami\')")}'
format_string = 'a' # Dummy format string
# Context for the template:
context = {
'malicious_string': malicious_string,
'format_string': format_string
}
# Show that the fix prevents the attack.
try:
print("Rendering template with exploit...")
result = render_template_fixed(vuln_template, context)
print(f"Rendered output: {result}") # The exploit should be prevented
except Exception as e:
print(f"Exception: {e}")
# Example non malicious template.
safe_template = '{{ safe_string | format_wrapper(format_string) }}'
safe_string = "Hello, {}!"
safe_context = {
'safe_string': safe_string,
'format_string': "World"
}
print("Rendering a safe template...")
result = render_template_fixed(safe_template, safe_contextPayload
{% set format_method = ''.__class__.__mro__[1].__subclasses__()[148].__init__.__globals__['__builtins__']['exec'] %}
{{ format_method('print("PWNED")') }}
Cite this entry
@misc{vaitp:cve202456326,
title = {{Jinja template code injection via str.format bypass in custom filters. Fixed in 3.1.5.
}},
author = {Bogaerts, Fr\'ed\'eric and Ivaki, Naghmeh and Fonseca, Jos\'e},
year = {2024},
note = {VAITP Python Vulnerability Dataset, entry CVE-2024-56326},
howpublished = {\url{https://netpack.pt/vaitp/vulnerability/CVE-2024-56326/}}
}
Introducing the "VAITP dataset": a specialized repository of Python vulnerabilities and patches, meticulously compiled for the use of the security research community. As Python's prominence grows, understanding and addressing potential security vulnerabilities become crucial. Crafted by and for the cybersecurity community, this dataset offers a valuable resource for researchers, analysts, and developers to analyze and mitigate the security risks associated with Python. Through the comprehensive exploration of vulnerabilities and corresponding patches, the VAITP dataset fosters a safer and more resilient Python ecosystem, encouraging collaborative advancements in programming security.
The supreme art of war is to subdue the enemy without fighting.
Sun Tzu – “The Art of War”
:: Shaping the future through research and ingenuity ::
