{"title":"Jinja2 Template Injection via render_template_string()","language":"Python","severity":"Critical","cwe":"CWE-94","source_lines":[8,9],"flow_lines":[8,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-policy')\ndef generate_bucket_policy():\n    bucket_name = request.args.get('bucket', 'default-bucket')\n    policy_template = request.args.get('policy_desc', 'Standard access policy')\n    policy_html = f\"<h2>S3 Bucket: {bucket_name}</h2><p>Policy: {policy_template}</p>\"\n    return render_template_string(policy_html)","explanation":"User-controlled input from request parameters (bucket_name and policy_template) is directly embedded into an HTML string via f-string formatting, then passed to render_template_string() without sanitization. This allows attackers to inject Jinja2 template expressions that will be evaluated server-side, leading to remote code execution.","remediation":"The fix replaces direct f-string interpolation of user input into the template string with Jinja2 template variables ({{ bucket_name }} and {{ policy_desc }}). By passing user-controlled values as context parameters to render_template_string(), Jinja2 automatically escapes them, preventing both template injection and XSS attacks since the template structure itself is now a static string that cannot be manipulated by user input.","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-policy')\ndef generate_bucket_policy():\n    bucket_name = request.args.get('bucket', 'default-bucket')\n    policy_template = request.args.get('policy_desc', 'Standard access policy')\n    policy_html = \"<h2>S3 Bucket: {{ bucket_name }}</h2><p>Policy: {{ policy_desc }}</p>\"\n    return render_template_string(policy_html, bucket_name=bucket_name, policy_desc=policy_template)"}