{"title":"Jinja2 Template Injection via render_template_string()","language":"Python","severity":"Critical","cwe":"CWE-1336","source_lines":[9],"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-report')\ndef generate_bucket_report():\n    bucket_name = request.args.get('bucket', 'default-bucket')\n    report_format = request.args.get('format', 'html')\n    user_header = request.args.get('header', 'S3 Bucket Report')\n    template_str = f\"<html><head><title>{user_header}</title></head><body><h1>{user_header}</h1><p>Bucket: {bucket_name}</p><p>Format: {report_format}</p></body></html>\"\n    return render_template_string(template_str)","explanation":"The application accepts user-controlled input from the 'header' parameter and directly interpolates it into a template string that is then passed to render_template_string(). This allows attackers to inject Jinja2 template expressions that will be executed on the server, leading to remote code execution.","remediation":"Instead of using Python f-string interpolation to embed user input directly into the template string, the fix uses Jinja2's native variable substitution with {{ }} placeholders and passes user inputs as context variables to render_template_string(). Jinja2 automatically escapes these context variables when rendering, preventing both template injection and XSS attacks.","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-report')\ndef generate_bucket_report():\n    bucket_name = request.args.get('bucket', 'default-bucket')\n    report_format = request.args.get('format', 'html')\n    user_header = request.args.get('header', 'S3 Bucket Report')\n    template_str = \"<html><head><title>{{ header }}</title></head><body><h1>{{ header }}</h1><p>Bucket: {{ bucket }}</p><p>Format: {{ fmt }}</p></body></html>\"\n    return render_template_string(template_str, header=user_header, bucket=bucket_name, fmt=report_format)"}