# Server-Side Template Injection via Jinja2 render_template_string()

Language: Python
Severity: Critical
CWE: CWE-1336

## Source
8

## Flow
8-9-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 Analytics')
    template_markup = f"<h1>{{{{ '{report_title}' }}}}</h1><p>Bucket: {bucket_name}</p><div>{{{{ user_content }}}}</div>"
    user_content = request.args.get('content', 'No additional data')
    return render_template_string(template_markup, user_content=user_content)
```

## Explanation

The report_title parameter from user input (line 8) is directly embedded into the Jinja2 template string via f-string formatting (line 9), then rendered by render_template_string() (line 11). This allows attackers to inject arbitrary Jinja2 template code that gets executed server-side, potentially leading to remote code execution.

## Remediation

The fix eliminates the SSTI vulnerability by using a static Jinja2 template string with placeholder variables instead of embedding user input directly into the template via f-string formatting. All user-provided values (report_title, bucket_name, user_content) are now passed as context variables to render_template_string(), which automatically escapes them during rendering, preventing any template injection.

## Secure Code
```python
from flask import Flask, request, render_template_string
from markupsafe import escape
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 Analytics')
    user_content = request.args.get('content', 'No additional data')
    template_markup = "<h1>{{ report_title }}</h1><p>Bucket: {{ bucket_name }}</p><div>{{ user_content }}</div>"
    return render_template_string(template_markup, report_title=report_title, bucket_name=bucket_name, user_content=user_content)
```
