{"title":"Jinja2 Server-Side Template Injection via Untrusted render_template_string()","language":"Python","severity":"Critical","cwe":"CWE-1336","source_lines":[9,10],"flow_lines":[9,10,11],"sink_lines":[11],"vulnerable_code":"from flask import Flask, request, render_template_string\nimport boto3\n\napp = Flask(__name__)\ns3_client = boto3.client('s3')\n\n@app.route('/cloud/bucket-status')\ndef check_bucket_health():\n    bucket_name = request.args.get('bucket', 'default-bucket')\n    status_msg = request.args.get('custom_message', 'Bucket operational')\n    template_output = render_template_string(f\"<h2>AWS S3 Status for {bucket_name}</h2><p>Status: {status_msg}</p>\")\n    return template_output","explanation":"User-controlled input from request.args.get() for both 'bucket' and 'custom_message' parameters is directly embedded into an f-string template and passed to render_template_string() without sanitization. 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 with Jinja2's native template variable syntax ({{ variable }}), passing user inputs as context variables to render_template_string(). This ensures Jinja2 automatically escapes the user-provided values and treats them as data rather than template code, preventing any injected template expressions from being evaluated.","secure_code":"from flask import Flask, request, render_template_string\nimport boto3\nfrom markupsafe import escape\n\napp = Flask(__name__)\ns3_client = boto3.client('s3')\n\n@app.route('/cloud/bucket-status')\ndef check_bucket_health():\n    bucket_name = request.args.get('bucket', 'default-bucket')\n    status_msg = request.args.get('custom_message', 'Bucket operational')\n    template = \"<h2>AWS S3 Status for {{ bucket_name }}</h2><p>Status: {{ status_msg }}</p>\"\n    template_output = render_template_string(template, bucket_name=bucket_name, status_msg=status_msg)\n    return template_output"}