# Jinja2 Server-Side 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 at {{{{ timestamp }}}}</p>"
    return render_template_string(report_template, timestamp='2024-01-15')
```

## Explanation

User-controlled input from request.args.get('filter') is directly embedded into a template string via f-string interpolation on line 10, then passed to render_template_string() on line 11. This allows attackers to inject Jinja2 template expressions that execute arbitrary Python code on the server.

## Remediation

The fix removes the f-string interpolation that directly embedded user input into the template string. Instead, the user-controlled `bucket_filter` value is passed as a template context variable using Jinja2's native variable substitution ({{ bucket_filter }}), which automatically escapes the value and prevents template injection attacks.

## 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 at {{ timestamp }}</p>"
    return render_template_string(report_template, timestamp='2024-01-15', bucket_filter=bucket_filter)
```
