RCE with Flask Jinja tempelate Injection
Published on medium.com
#### AkShAy KaTkAr
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
I received an invitation to a private program on Bugcrowd. The scope was not large: a single application with plenty of features to test. I like this kind of program because I am not that good at reconnaissance, so a single, feature-rich app suits me.
The application contained a utility called workflow builder, used to build a financial close process flow. It lets you automate daily activities such as sending approval emails and reminder emails. The email-sending functionality caught my attention, because email generator apps are often vulnerable to template injection. Since the site was built with Python, I was fairly confident it would be using Jinja2 templates.
Setup
My first step was to find out what technology the website was built with. I use wappalyzer for that. The site was using Angular Dart, Python Django and Flask. Having been a Python developer for the last few years, I know where developers commonly make mistakes.
No special account or role is described beyond access to the workflow builder and its send email function. The only tool mentioned is wappalyzer.
Finding it
The send email function has three fields: To, title and description. I set {{7*7}} as the title and as the description, then clicked the send email button. The email arrived with 49 as the subject and {{7*7}} as the description. The subject field was therefore vulnerable to template injection.
Payload:
What the payload does is evaluate Python code inside the curly brackets.
Exploitation
Step 1: Confirm evaluation and enumerate subclasses
I tried another payload to get the list of subclasses of the object class.
Payload:
{{ [].__class__.__base__.__subclasses__() }}
I received an email containing the list of subclasses of the object class.
The payload works as follows. In Python you can create a list with []. You can try these things in the Python interpreter.
- Access the class of list:
>>> [].__class__<type 'list'> #return class of list
- Access the base class of list:
>>> [].__class__.__base__<type 'object'> #return base class of list
List is a subclass of the object class.
- Access the subclasses of the object class:
>>> [].__class__.__base__.__subclasses__()[<type 'type'>, <type 'weakref'>, <type 'weakcallableproxy'>, <type 'weakproxy'>, <type 'int'>, <type 'basestring'>, <type 'bytearray'>, <type 'list'>.....
So the payload gives us a list of all subclasses of the object class.
Step 2: The triager asks for impact
I reported the issue as it was, hoping I would not have to go further to prove its significant impact. The Bugcrowd triager replied with the message shown below.
So I now had to provide a proof of concept to prove the impact of the issue, in order to have it marked as P1.
Step 3: Locate the file class
Most Django apps have a config file containing really sensitive information such as AWS keys, APIs and encryption keys. I had the path of that config file from my previous findings, so I decided to read that file.
To read a file in Python you have to create an object of file. We already have the list of all subclasses of the object class. Let us find the index of the file class:
>>> [].__class__.__base__.__subclasses__().index(file)40 #return index of "file" object
When you run [].__class__.__base__.__subclasses__().index(file) in the Python interpreter you get the index of the file object.
I tried the same payload, but it gave me nothing. Something was wrong. I tried to access other objects, but it gave a similar error and did not return any value.
Step 4: Indexing breaks the payload, so use pop
Next I decided to access the file object directly, since we know the index of the file object in the object subclasses list is 40. So I tried this payload:
{{[].__class__.__base__.__subclasses__()[40] }}
But I had no success: this payload also returned a similar result to the image above. The payload was breaking somewhere, but I could not find where.
After some research I concluded that the indexing might be blocked, or that it was breaking my payload.
If you know a little Python, you may know there are multiple methods to return a value from a list. One of them is the pop function:
>>> [1,2,3,4,5].pop(2)3
The code above returns the third value of the list and removes it from that list. So my new payload is:
{{[].__class__.__base__.__subclasses__().pop(40) }}
The payload above gives me the object of file.
Step 5: Read files from the server
Now that I had the file object, I could read any file on the server. I read the etc/passwd file.
Payload:
{{[].__class__.__base__.__subclasses__().pop(40)('etc/passwd').read() }}.
Finally, I was able to read files on the server. I was also able to read local files on the GCE instance responsible for sending notifications, including some source code and configuration files containing very sensitive values (for example API and encryption keys).
Root cause
The subject field of the send email function evaluates user input as template code rather than treating it as plain text. The site was built with Python, and the author expected Jinja2. The application is built on Python with Django and Flask, and the email generator is the kind of component where this mistake is common. The report does not show the template code itself, so the exact rendering call is not stated.
A second, incidental obstacle appeared during exploitation: the direct index form [40] did not return a value, while the pop(40) form did. The report only concludes that indexing may have been blocked or was breaking the payload; it does not identify the mechanism.
Impact
Through the vulnerable subject field, an attacker can evaluate Python expressions in the context of the server that sends the emails. In this case that allowed reading arbitrary files on the server, including etc/passwd, source code, and configuration files containing very sensitive values such as API and encryption keys, on the GCE instance responsible for sending notifications. The report does not describe what an attacker could do beyond file read, and does not state the final severity or reward assigned.
Fix
The general remedy for this class of issue is to stop rendering user-controlled input as a template: pass the subject and description as data into a template that is fixed in code, rather than concatenating or compiling them as template source.
Variants to test
- A positive result is arithmetic evaluated in the rendered message.
- Fields that accept a subject or title separately from a body: test each field independently, since in this case only the subject was vulnerable while the description was not.
- When
[index]access fails, try the same index throughpop(): a positive result is the object being returned and its methods becoming callable. - Once an object is reachable, try reading a known file such as
etc/passwdthrough thefileclass: a positive result is file contents appearing in the rendered output. - Look for configuration files referenced by earlier findings, such as Django settings, and attempt to read them the same way: a positive result is keys or credentials appearing in the output.
What happened, in plain words
A security researcher was invited to a private bug bounty program on Bugcrowd. The program had a single web application with many features. The researcher found that one feature, which sends emails, let him type special code into the email subject. The application ran that code on its server instead of treating it as plain text. By sending a few carefully crafted emails, he was able to read files on the server, and could read local files including configuration files that held sensitive keys. This kind of flaw is called server-side template injection (SSTI). In this case it allowed reading files on the server.
The write-up walks through how he confirmed the flaw, how he escalated it, and how he eventually read files. Below is the same story, explained from scratch for someone who has never done security testing.
Background: what is a template, and why does it matter?
Many websites build pages and emails by filling in a template: a piece of text with placeholders. For example, a template might say Hello {{ name }} and the server replaces {{ name }} with the actual name before sending. The template engine is the software that does the replacing. In Python web applications, a very common template engine is Jinja2. It uses double curly braces {{ ... }} to mark expressions that should be evaluated.
Normally the template is written by the developers and the user only supplies data (like a name). The danger starts when the application takes text typed by a user and treats it as part of the template itself. Then the user can write template code, and the server will run it. That is template injection.
A simple analogy: imagine a fill-in-the-blank letter. If the blank is filled with a name, that is data. But if the blank is filled with instructions like "multiply 7 by 7 and write the answer", and the letter-writing machine follows those instructions, then the person filling the blank controls the machine. Template injection is exactly that: the user's text is treated as instructions, not data.
The setup
The researcher received an invitation to a private program on Bugcrowd. The scope was not large: a single application with many features. He prefers this kind of program because he is not strong at reconnaissance (the phase of discovering what systems exist). A single, feature-rich app gives plenty to test without needing to map a large network.
The application had a utility called workflow builder, used to build a financial close process flow. It lets you automate daily activities such as sending approval emails and reminder emails. The email-sending functionality caught his attention because email generator apps are often vulnerable to template injection. Since the site was built with Python, he was fairly confident it would use Jinja2 templates.
His first step was to find out what technology the website was built with. He used a browser extension called wappalyzer, which inspects a site and reports the frameworks and languages it uses. The site was using Angular Dart, Python Django and Flask. Having been a Python developer for the last few years, he knows where developers commonly make mistakes.
No special account or role is described beyond access to the workflow builder and its send email function. The only tool mentioned is wappalyzer.
Finding the vulnerability
The send email function has three fields: To, title and description. He set {{7*7}} as the title and as the description, then clicked the send email button. The email arrived with 49 as the subject and {{7*7}} as the description. The subject field was therefore vulnerable to template injection.
Payload:
What the payload does is evaluate Python code inside the curly brackets.
Why this step: {{7*7}} is a harmless test. If the application treats it as plain text, the email subject will literally say {{7*7}}. If the application evaluates it as a template expression, the subject will say 49. Seeing 49 proves that the server is running the expression. The description field showed the literal text, so only the subject was vulnerable.
Exploitation
Step 1: Confirm evaluation and enumerate subclasses
He tried another payload to get the list of subclasses of the object class.
Payload:
{{ [].__class__.__base__.__subclasses__() }}
He received an email containing the list of subclasses of the object class.
The payload works as follows. In Python you can create a list with []. You can try these things in the Python interpreter.
- Access the class of list:
>>> [].__class__<type 'list'> #return class of list
- Access the base class of list:
>>> [].__class__.__base__<type 'object'> #return base class of list
List is a subclass of the object class.
- Access the subclasses of the object class:
>>> [].__class__.__base__.__subclasses__()[<type 'type'>, <type 'weakref'>, <type 'weakcallableproxy'>, <type 'weakproxy'>, <type 'int'>, <type 'basestring'>, <type 'bytearray'>, <type 'list'>.....
So the payload gives us a list of all subclasses of the object class.
Why this step: the first test only proved that arithmetic works. To do anything useful, the attacker needs to reach Python objects that can read files or run commands. In Python, every value (a list, a string, a number) is an object, and every object belongs to a class. The class object is the root of the class hierarchy. From any object you can walk up to object and then list all classes that inherit from it. That list includes powerful classes such as file, which can open files. The payload {{ [].__class__.__base__.__subclasses__() }} does exactly that walk: start with an empty list [], get its class (list), get its base class (object), and list all subclasses of object. The email returned that list, confirming the technique works.
The code blocks above are Python interpreter sessions. >>> is the prompt. The first line [].__class__ returns the class of an empty list, which is <type 'list'>. The second line [].__class__.__base__ returns the base class of that class, which is <type 'object'>. The third line calls __subclasses__() on object and prints a list of all classes that inherit from it. The comment after each line explains what is returned.
Step 2: The triager asks for impact
He reported the issue as it was, hoping he would not have to go further to prove its significant impact. The Bugcrowd triager replied with the message shown below.
So he now had to provide a proof of concept to prove the impact of the issue, in order to have it marked as P1.
Why this step: a bug report that only shows 49 might be dismissed as a low-impact information leak. The triager (the person who reviews reports on the bounty platform) asked for evidence that the flaw can cause real harm. A proof of concept (PoC) is a concrete demonstration, such as reading a sensitive file. P1 is the highest priority level on Bugcrowd, meaning critical.
Step 3: Locate the file class
Most Django apps have a config file containing really sensitive information such as AWS keys, APIs and encryption keys. He had the path of that config file from his previous findings, so he decided to read that file.
To read a file in Python you have to create an object of file. We already have the list of all subclasses of the object class. Let us find the index of the file class:
>>> [].__class__.__base__.__subclasses__().index(file)40 #return index of "file" object
When you run [].__class__.__base__.__subclasses__().index(file) in the Python interpreter you get the index of the file object.
He tried the same payload, but it gave him nothing. Something was wrong. He tried to access other objects, but it gave a similar error and did not return any value.
Why this step: to read a file, the attacker needs the file class. The list of subclasses is ordered, so each class has a position (index). The .index(file) method returns the position of the file class in that list. In the interpreter it returned 40. The attacker then tried to use that index in the payload, but the application returned nothing. The report does not explain why it failed at this point; the next step investigates.
Step 4: Indexing breaks the payload, so use pop
Next he decided to access the file object directly, since we know the index of the file object in the object subclasses list is 40. So he tried this payload:
{{[].__class__.__base__.__subclasses__()[40] }}
But he had no success: this payload also returned a similar result to the image above. The payload was breaking somewhere, but he could not find where.
After some research he concluded that the indexing might be blocked, or that it was breaking his payload.
If you know a little Python, you may know there are multiple methods to return a value from a list. One of them is the pop function:
>>> [1,2,3,4,5].pop(2)3
The code above returns the third value of the list and removes it from that list. So his new payload is:
{{[].__class__.__base__.__subclasses__().pop(40) }}
The payload above gives him the object of file.
Why this step: the direct index syntax [40] did not work. The researcher suspected that the application or a filter was blocking square brackets with a number, or that the syntax was breaking the template. He switched to .pop(40), which is a method call that returns the element at position 40 (and removes it from the list). The payload with .pop(40) succeeded and returned the file object. The report does not identify the exact reason [40] failed; it only notes the conclusion that indexing might be blocked.
The interpreter example [1,2,3,4,5].pop(2) returns 3 because positions start at 0: position 0 is 1, position 1 is 2, position 2 is 3. The pop method returns the value at that position and removes it from the list.
Step 5: Read files from the server
Now that he had the file object, he could read any file on the server. He read the etc/passwd file.
Payload:
{{[].__class__.__base__.__subclasses__().pop(40)('etc/passwd').read() }}.
The image shows the etc/passwd output in the email subject.
Why this step: etc/passwd is a standard file on Unix-like systems that lists user accounts. It is a safe, well-known file to read as proof that arbitrary file reading works. The payload calls the file object with the path 'etc/passwd' and then calls .read() to get the contents. The result appears in the email subject.
Finally, he was able to read files on the server. He was also able to read local files on the GCE instance responsible for sending notifications, including some source code and configuration files containing very sensitive values (for example API and encryption keys).
Why this matters: GCE stands for Google Compute Engine, a cloud service that runs virtual machines. The email-sending component ran on such a machine. Reading its configuration files could expose API keys and encryption keys, which could let an attacker access other services or decrypt data. The report does not describe what he did with those keys or what the final severity or reward was.
Root cause
The subject field of the send email function evaluates user input as template code rather than treating it as plain text. The site was built with Python, and the author expected Jinja2. The application is built on Python with Django and Flask, and the email generator is the kind of component where this mistake is common.
A second, incidental obstacle appeared during exploitation: the direct index form [40] did not return a value, while the pop(40) form did. The report only concludes that indexing may have been blocked or was breaking the payload; it does not identify the mechanism.
Impact
Through the vulnerable subject field, an attacker can evaluate Python expressions in the context of the server that sends the emails. In this case that allowed reading arbitrary files on the server, including etc/passwd, source code, and configuration files containing very sensitive values such as API and encryption keys, on the GCE instance responsible for sending notifications.
Fix
The general remedy for this class of issue is to stop rendering user-controlled input as a template: pass the subject and description as data into a template that is fixed in code, rather than concatenating or compiling them as template source.
Variants to test
- A positive result is arithmetic evaluated in the rendered message.
- Fields that accept a subject or title separately from a body: test each field independently, since in this case only the subject was vulnerable while the description was not.
- When
[index]access fails, try the same index throughpop(): a positive result is the object being returned and its methods becoming callable. - Once an object is reachable, try reading a known file such as
etc/passwdthrough thefileclass: a positive result is file contents appearing in the rendered output. - Look for configuration files referenced by earlier findings, such as Django settings, and attempt to read them the same way: a positive result is keys or credentials appearing in the output.
Glossary
- Bug bounty program: a scheme where organisations invite researchers to find and report security flaws in exchange for recognition or payment.
- Bugcrowd: a platform that hosts bug bounty programs and manages reports and triagers.
- Private program: a bounty program that is not open to the public; researchers are invited individually.
- Scope: the list of systems and features that a researcher is allowed to test.
- Reconnaissance (recon): the phase of discovering what systems, technologies and entry points exist.
- Wappalyzer: a browser extension that identifies the technologies used by a website.
- Angular Dart: a front-end web framework written in the Dart language.
- Django: a Python web framework for building server-side applications.
- Flask: a lightweight Python web framework.
- Jinja2: a template engine for Python that uses
{{ ... }}to mark expressions to be evaluated. - Template: a piece of text with placeholders that are filled in by a template engine.
- Template injection (SSTI): a vulnerability where user input is treated as template code and evaluated by the server.
- Remote code execution (RCE): a vulnerability that lets an attacker run their own code on a remote server.
- Payload: the specific input an attacker sends to trigger a vulnerability.
- Proof of concept (PoC): a concrete demonstration that a vulnerability can cause real harm.
- Triager: the person who reviews and classifies bug bounty reports on a platform.
- P1: the highest priority level on Bugcrowd, meaning critical severity.
- Python interpreter: the program that runs Python code interactively, showing a
>>>prompt. - Class: a blueprint in object-oriented programming that defines objects and their behaviour.
- Object: an instance of a class; in Python, every value is an object.
- Subclass: a class that inherits from another class.
__class__: a Python attribute that returns the class of an object.__base__: a Python attribute that returns the parent class of a class.__subclasses__(): a Python method that returns the list of classes that inherit from a given class.- Index: the position of an item in a list, starting at 0.
pop(): a Python list method that returns the item at a given index and removes it from the list.fileclass: a Python class used to open and read files.etc/passwd: a standard Unix file that lists user accounts, often used as a safe test file for file-read vulnerabilities.- GCE (Google Compute Engine): a cloud service that provides virtual machines.
- API key: a secret string that identifies an application when it calls another service.
- Encryption key: a secret value used to encrypt and decrypt data.
- Configuration file: a file that stores settings and secrets for an application.