# Jinja2 Server-Side Template Injection via render_template_string

Language: Python
Severity: Critical
CWE: CWE-94

## Source
12

## Flow
12-13

## Sink
13

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

app = Flask(__name__)

@app.route('/cloud/provision')
def provision_aws_resource():
    resource_type = request.args.get('type', 'ec2')
    region_name = request.args.get('region', 'us-east-1')
    status_msg = f"Provisioning {resource_type} in {region_name}..."
    template_str = "<h2>AWS Resource Manager</h2><p>Status: " + request.args.get('custom_msg', status_msg) + "</p>"
    return render_template_string(template_str)
```

## Explanation

The application takes untrusted user input from request.args.get('custom_msg') and directly concatenates it into a template string that is passed to render_template_string() without sanitization. This allows attackers to inject Jinja2 template expressions that will be executed on the server, leading to Remote Code Execution.

## Remediation

The fix passes user input as a context variable to render_template_string() instead of concatenating it directly into the template string. By using {{ status }} as a placeholder and passing the user-controlled value as a template variable, Jinja2 automatically escapes the content and treats it as data rather than executable template code, preventing SSTI attacks.

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

app = Flask(__name__)

@app.route('/cloud/provision')
def provision_aws_resource():
    resource_type = request.args.get('type', 'ec2')
    region_name = request.args.get('region', 'us-east-1')
    status_msg = f"Provisioning {resource_type} in {region_name}..."
    custom_msg = request.args.get('custom_msg', status_msg)
    template_str = "<h2>AWS Resource Manager</h2><p>Status: {{ status }}</p>"
    return render_template_string(template_str, status=custom_msg)
```
