# 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_name = request.args.get('bucket', 'default-bucket')
    report_title = request.args.get('title', 'S3 Bucket Analysis')
    template_markup = f"<html><head><title>{report_title}</title></head><body><h1>Report for: {bucket_name}</h1></body></html>"
    return render_template_string(template_markup)
```

## Explanation

The application accepts user-controlled input through the 'title' parameter (line 9) and directly embeds it into a template string using an f-string (line 10), which is then passed to render_template_string() (line 11). This allows attackers to inject Jinja2 template expressions that will be executed server-side, potentially leading to remote code execution.

## Remediation

The fix replaces the dangerous f-string interpolation of user input directly into the template string with Jinja2's native variable placeholders ({{ title }} and {{ bucket }}). By passing user inputs as context variables to render_template_string(), Jinja2 automatically escapes them, preventing any template expressions in user input from being interpreted as 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_name = request.args.get('bucket', 'default-bucket')
    report_title = request.args.get('title', 'S3 Bucket Analysis')
    template_markup = "<html><head><title>{{ title }}</title></head><body><h1>Report for: {{ bucket }}</h1></body></html>"
    return render_template_string(template_markup, title=report_title, bucket=bucket_name)
```
