{"title":"Jinja2 Server-Side Template Injection via render_template_string","language":"Python","severity":"Critical","cwe":"CWE-94","source_lines":[12],"flow_lines":[12,13],"sink_lines":[13],"vulnerable_code":"from flask import Flask, request, render_template_string\nimport boto3\n\napp = Flask(__name__)\n\n@app.route('/cloud/provision')\ndef provision_aws_resource():\n    resource_type = request.args.get('type', 'ec2')\n    region_name = request.args.get('region', 'us-east-1')\n    status_msg = f\"Provisioning {resource_type} in {region_name}...\"\n    template_str = \"<h2>AWS Resource Manager</h2><p>Status: \" + request.args.get('custom_msg', status_msg) + \"</p>\"\n    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":"from flask import Flask, request, render_template_string\nimport boto3\nfrom markupsafe import escape\n\napp = Flask(__name__)\n\n@app.route('/cloud/provision')\ndef provision_aws_resource():\n    resource_type = request.args.get('type', 'ec2')\n    region_name = request.args.get('region', 'us-east-1')\n    status_msg = f\"Provisioning {resource_type} in {region_name}...\"\n    custom_msg = request.args.get('custom_msg', status_msg)\n    template_str = \"<h2>AWS Resource Manager</h2><p>Status: {{ status }}</p>\"\n    return render_template_string(template_str, status=custom_msg)"}