# Jinja2 Template Injection via render_template_string

Language: Python
Severity: Critical
CWE: CWE-1336

## Source
9

## Flow
9-10-11

## Sink
11

## Vulnerable Code
```python
from flask import Flask, request, render_template_string
import boto3

app = Flask(__name__)
s3_client = boto3.client('s3')

@app.route('/cloud/bucket-report')
def generate_bucket_report():
    bucket_filter = request.args.get('filter', 'all')
    report_template = f"<h2>AWS S3 Bucket Report</h2><p>Filter: {bucket_filter}</p><p>Generated for compliance audit</p>"
    return render_template_string(report_template)
```

## Explanation

User-controlled input from request.args.get('filter') is directly interpolated into an f-string to construct a Jinja2 template, which is then rendered using render_template_string(). This allows attackers to inject arbitrary Jinja2 template expressions that will be executed server-side, potentially leading to remote code execution.

## Remediation

The fix eliminates the template injection by passing user input as a context variable to render_template_string() instead of interpolating it directly into the template string via an f-string. Jinja2 automatically escapes context variables passed this way, preventing any injected template expressions from being interpreted as Jinja2 code. The template now uses the safe {{ bucket_filter }} placeholder syntax which treats the value as data, not executable template code.

## Secure Code
```python
from flask import Flask, request, render_template_string
import boto3
from markupsafe import escape

app = Flask(__name__)
s3_client = boto3.client('s3')

@app.route('/cloud/bucket-report')
def generate_bucket_report():
    bucket_filter = request.args.get('filter', 'all')
    report_template = "<h2>AWS S3 Bucket Report</h2><p>Filter: {{ bucket_filter }}</p><p>Generated for compliance audit</p>"
    return render_template_string(report_template, bucket_filter=bucket_filter)
```
