# Jinja2 Server-Side Template Injection via render_template_string

Language: Python
Severity: Critical
CWE: CWE-1336

## Source
8-9

## Flow
8-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 Report')
    template_str = f"<html><body><h1>{report_title}</h1><p>Analyzing bucket: {bucket_name}</p></body></html>"
    return render_template_string(template_str)
```

## Explanation

User-controlled input from request.args.get('title') and request.args.get('bucket') is directly interpolated into an f-string template and passed to render_template_string() without sanitization. This allows attackers to inject arbitrary Jinja2 template expressions that execute server-side, leading to Remote Code Execution.

## Remediation

The fix eliminates the SSTI vulnerability by replacing the f-string interpolation with Jinja2's native template variable syntax ({{ variable }}). User-supplied values are passed as context parameters to render_template_string(), which automatically escapes them and prevents any injected Jinja2 expressions from being interpreted as 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_name = request.args.get('bucket', 'default-bucket')
    report_title = request.args.get('title', 'S3 Bucket Report')
    template_str = "<html><body><h1>{{ report_title }}</h1><p>Analyzing bucket: {{ bucket_name }}</p></body></html>"
    return render_template_string(template_str, report_title=report_title, bucket_name=bucket_name)
```
