CVE-2023-1306
Jinja template code execution via resource.db method
- CVSS 8.8
- CWE-94 Improper Control of Generation of Code ('Code Injection')
- Input Validation and Sanitization
- Remote
An authenticated attacker can leverage an exposed resource.db() accessor method to smuggle Python method calls via a Jinja template, which can lead to code execution. This issue was resolved in the Managed and SaaS deployments on February 1, 2023, and in version 23.2.1 of the Self-Managed version of InsightCloudSec.
- CVSS base score
- 8.8
- Published
- 2023-03-21
- OWASP
- A03 Injection
- Orthogonal defect classification
- Function
- Code defect classification
- Incorrect Functionality
- Category
- Input Validation and Sanitization
- Subcategory
- Insecure Parsing or Deserialization
- Accessibility scope
- Remote
- Impact
- Arbitrary Code Execution
- Fixed by upgrading
- Yes
Solution
Update to version 23.2.1 of InsightCloudSec Self-Managed.
Vulnerable code sample
from jinja2 import Environment, FileSystemLoader
env = Environment(
loader=FileSystemLoader('templates')
)
def render(template_name, context):
template = env.get_template(template_name)
return template.render(context)
class Resource:
def db(self):
return "Database access"
if __name__ == "__main__":
resource = Resource()
user_context = {
'resource': resource,
'unsafe_variable': '{{ resource.db() }}'
}
output = render('example_template.html', user_context)
print(output)Patched code sample
import os
from typing import Dict, Any, Optional, Set
from jinja2 import (
Environment,
FileSystemLoader,
select_autoescape,
Template,
TemplateError,
Undefined
)
class RenderError(Exception):
pass
class Environment:
ALLOWED_EXTENSIONS = {'.html', '.xml', '.txt', '.j2'}
MAX_TEMPLATE_SIZE = 1024 * 1024
RESTRICTED = {
'__class__', '__dict__', '__bases__', '__globals__',
'__getattribute__', '__getattr__', '__setattr__',
'eval', 'exec', 'globals', 'locals', 'dir',
'open', 'file', 'read', 'write',
'os', 'sys', 'subprocess', 'popen'
}
def __init__(
self,
template_dir: str,
allowed_extensions: Optional[Set[str]] = None,
max_size: Optional[int] = None
):
try:
template_dir = os.path.abspath(template_dir)
if not os.path.isdir(template_dir):
raise RenderError("Invalid template directory")
self.allowed_extensions = allowed_extensions or self.ALLOWED_EXTENSIONS
self.max_size = max_size or self.MAX_TEMPLATE_SIZE
self.env = Environment(
loader=FileSystemLoader(template_dir),
autoescape=select_autoescape(['html', 'xml']),
auto_reload=False,
cache_size=400,
trim_blocks=True,
lstrip_blocks=True,
finalize=self._finalize_value
)
for name in self.RESTRICTED:
if name in self.env.globals:
del self.env.globals[name]
except Exception as e:
raise RenderError(f"Environment initialization failed: {str(e)}")
def _finalize_value(self, value: Any) -> Any:
if isinstance(value, Undefined):
return ''
return value
def _validate_template(self, template_name: str) -> None:
try:
_, ext = os.path.splitext(template_name)
if ext not in self.allowed_extensions:
raise RenderError("Invalid template extension")
template_path = os.path.join(
self.env.loader.searchpath[0],
template_name
)
if not os.path.isfile(template_path):
raise RenderError("Template not found")
if os.path.getsize(template_path) > self.max_size:
raise RenderError("Template too large")
except Exception as e:
if isinstance(e, RenderError):
raise
raise RenderError(f"Template validation failed: {str(e)}")
def _validate_context(self, context: Dict[str, Any]) -> None:
try:
for key in context:
if key in self.RESTRICTED:
raise RenderError(f"Restricted context key: {key}")
for value in context.values():
if callable(value):
raise RenderError("Callable values not allowed")
except Exception as e:
if isinstance(e, RenderError):
raise
raise RenderError(f"Context validation failed: {str(e)}")
def render(
self,
template_name: str,
context: Dict[str, Any]
) -> str:
try:
self._validate_template(template_name)
self._validate_context(context)
template = self.env.get_template(template_name)
return template.render(context)
except Exception as e:
if isinstance(e, RenderError):
raise
raise RenderError(f"Template rendering failed: {str(e)}")Cite this entry
@misc{vaitp:cve20231306,
title = {{Jinja template code execution via resource.db method}},
author = {Bogaerts, Fr\'ed\'eric and Ivaki, Naghmeh and Fonseca, Jos\'e},
year = {2023},
note = {VAITP Python Vulnerability Dataset, entry CVE-2023-1306},
howpublished = {\url{https://netpack.pt/vaitp/vulnerability/CVE-2023-1306/}}
}
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 ::
