Once Again I Am Being Attacked Template
Executive Summary
Template injection is a class of vulnerabilities that are unremarkably plant in spider web applications. These vulnerabilities consist of any vulnerability that results from parsing unvalidated input that is mistakenly evaluated every bit lawmaking by a templating engine. Attackers abuse these vulnerabilities to execute code on either the web browser (customer-side) or directly on the web server itself (server-side).
Prisma Cloud Web Application and API Security (WAAS) module is a Web Awarding and API protection (WAAP) solution designed to protect web applications on any compages. One of the many features of WAAS is the ability to secure applications via virtual patches, better known as "Custom Rules". WAAS Custom Rules allow setting upward custom signatures to detect and forbid exploitations of vulnerabilities that are recently published, environment-specific or discovered by security teams. In the following blog, we will cover Template Injection vulnerabilities and include an case of how Custom Rules tin be configured and used to forbid such web application attacks.
What is a Template Engine?
Template engines are normally used in web applications to parse dynamic content into a preconfigured template, for example, usernames, items chosen by the user, item prices, and then on.
For example, we receive letters with the aforementioned template message while only some parts relevant to our identity are inverse (due east.thousand., name, address, fees, dates, subscription ID).
Even some formal messages are written in the aforementioned way:
"Dear ______,
Nosotros regret to inform you that your application is denied."
The benefits of using a template engine are articulate, they allow a more efficient manner to build spider web applications and reduce the complexity of user personalization's.
Template engines can be instructed with placeholders within the preset templates and in one case the awarding renders the template to be presented to the user, the placeholders will be replaced with the relevant information, for example, John will authenticate to a portal that uses the following template:
"Hello {{username}}!"
Seeing every bit John'south username is John Doe the template engine will render the template and replace the placeholder with John's username that way he will be greeted by the post-obit message:
"Hello John Doe!"
We shall divide template engines into two groups to understand the impact of exploitation on each group.
Client-Side Template Engine
The get-go group will be the Client-Side template engines group, for example, AngularJS and Vue.js.
Client-Side Template Engines, as their name suggests, will render the data on the client-side. These engines can simply admission data that is attainable and presented to the client and will process the data locally. Their impact volition be express mostly to the user, for example, XSS attacks, which may lead to account hijacking, presenting simulated information, or committing deportment on behalf of the user.
Additionally, Customer-Side Template Injection (CSTI), if found, tin can exist a great way for attackers to bypass weak defenses against XSS attacks such as input sanitization techniques where HTML entities encode the presented data.
The client-side template injection has a similar attack surface as XSS attacks. In the more powerful "persistent" template injection, information technology is possible to inject a payload to a message that volition be saved persistently within the server and presented to all the users. While past itself will cause the payload to be executed on every customer that exposes to it (particular name for example). Alternatively, in a less powerful variant, the payload is exposed to the user as a malicious link that the user will have to interact with for the exploit to execute. For example, the payload is hyperlinked to the username or personal setting and might require some social engineering, and then the user interacts with the hyperlink.
Server-Side Template Engine
Server-Side Template Engines (SSTI) volition return the data remotely at the server and present the already processed data to the user, these engines can access any data available to the server allowing the malicious player to access and betrayal data that is typically not in their privileges.
Some known server-side template engines include Twig (PHP), Jinja2 (Python), Freemarker (Coffee) and EJS (JavaScript).
Server-Side Template Injection can become a deadly exploitation vector for an organization. Successful exploitation leads to impact limited just by the creativity of the attacker, it is possible to disembalm sensitive information, upload malicious files, corrupt server files or functions while ultimately leading to consummate remote code execution over the vulnerable server.
Vulnerable Demo Applications
No description beats a live sit-in. For this blog, we have created a vulnerable application that will be vulnerable to both vulnerabilities discussed. Our demo app volition have ii vulnerable routes. Our code volition be a Python-based, Flask web application that will be using the Jinja2 template engine for the SSTI instance and a second Vue.js iii road for the CSTI example.
CSTI Road
CSTI Vulnerable route code snippet:
This route (/csti) is vulnerable to Customer-Side Template Injection, in line l you lot can see that the "username" parameter is being concatenated to the "app" container. Information technology should likewise exist noted that the html.escape() function is used to introduce output encoding sanitations, in this case, HTMLEntityEncode the input value before presenting to the user, this style protecting the application from XSS attacks.
SSTI Route
SSTI Vulnerable route code snippet:
This road (/ssti) is vulnerable to Server-Side Template Injection, on line 24, the parameter "username" is concatenated to the cord that is nearly to be rendered and presented to the user.
The Vulnerable Application
One time we fire the Docker container up and navigate to the application'due south page, we will be greeted with the following home page:
Effigy three. Vulnerable application home page.
Client-Side Template Injection
Finding the vulnerability
Starting with the CSTI road, in one case we open up it, nosotros will be redirected to "/csti?username=TemplateInjection" with the following greeting:
Figure 4. CSTI vulnerable road.
We can see that the username is beingness reflected on the folio. Let's try to sympathise if the username parameter is vulnerable to CSTI. Nosotros can offset by sending the following payload:
"{{8*eight}}"
Ordinarily, if the page is not vulnerable to CSTI, the page will greet us with "Hello {{8*eight}}". If the folio is vulnerable to template injection and parses the input we transport as a Get parameter, we volition be greeted with "Hullo 64".
Upon sending the payload we are greeted with "Hullo 64" thus verifying that the parameter "username" is vulnerable to CSTI.
Effigy 5. Sit-in of a CSTI with simple arithmetics expression.
Now, if we refer to line l with the html.escape() method, we remember that this parameter shouldn't exist vulnerable to XSS. Thus, trying to input some simple payloads nosotros might see that this is the case, simply by exploiting the CSTI we can pop an alert on this folio.
Exploiting the vulnerability
When attempting to popular an warning box using the template injection with "{{alert(one)}}" an fault was introduced stating that "Uncaught TypeError: warning is not a function", it appears that the error was introduced from Vue.js on line 15479.
Looking at line 15479 a new function was synthetic using the parameter "lawmaking" as its content. To better understand the flow a breakpoint was set on this line.
Using the browser'southward debugger, it appeared that the "code" parameter contains the following code:
It seems that the input from the injected template is concatenated into the "_toDisplayString" office which is referred to in the previous line along with other interesting functions such as "_openBlock" and "_createElementBlock". The post-obit payload "{{_createElementBlock}}" disclosed the "_createElementBlock" function'due south code.
Seeing as JavaScript functions are objects nosotros can utilize the "constructor" property which volition allow us to refer to the constructor function that created this example object using this payload: "{{_createElementBlock.constructor}}"
Figure 10. XSS vulnerability introduced through CSTI.
Now we can use the office'south constructor to create our own role which for the given case will be used to pop an alarm box using this payload: {{_createElementBlock.constructor("alert(i)")}}
Effigy xi. Using the function's constructor to create our own function.
The just thing that is left to execute this office and exploit the XSS vulnerability is to phone call information technology using parentheses with a payload that should look similar this: {{_createElementBlock.constructor("warning(1)")()}}
Server-Side Template Injection
Finding the vulnerability
Navigating to the SSTI link we are redirected to "/ssti?username=TemplateInjection" and the following message is presented to united states of america:
Over again, nosotros tin can run across that the username is being reflected within the page, we should check if the username parameter is vulnerable to SSTI in the aforementioned manner as previously with the CSTI by injecting "{{8*8}}".
It appears that the username parameter is indeed vulnerable to some kind of template injection. We can verify that this is an SSTI and indeed Jinja2 behind the scenes by sending the post-obit payload: "{{eight*'8'}}", if it is a CSTI we will receive "Hi 64!" once more but if it is a Jinja2 SSTI we will receive "Hello 88888888!", this behavior can be explained seeing as JavaScript'southward multiplication operator "*" will only multiply numbers, if a string is introduced Javascript will attempt to convert the string to an integer to multiply it otherwise the effect will be "NaN". While Python'south multiplication operator allows multiplying strings with integers and will return the given string times the integer.
Nifty! We have verified this is indeed the example of an SSTI vulnerability. We can try another tricks likewise such as Python's .upper() or .split() functions or any cadre function to ostend that Python is being used behind the scenes:
Now that nosotros take verified the vulnerability, let's understand how nosotros tin further escalate this exploit into a full-blown remote code execution assail.
Exploiting the vulnerability
Our code execution is at the Python's context judging by previous behavior.
We are non able to import dependencies inside our SSTI code because Jinja's "import" statement is used to admission macros from other templates. Achieving code execution might be tricky.
Judging by the behavior of previous requests information technology appeared that information technology is possible to call Python built-in methods like in the previous examples ".separate() or .upper()", combining this with the fact that Python is an object-oriented language we can inspect objects and their inheritances while looking for references to any module that might allow usa to accomplish OS-level code execution.
Our goal is to notice a way to read a flag.txt file within the container using the SSTI vulnerability.
Seeing as everything is an object in Python, a payload such as "{{''.__class__}}" will present the grade of '' which should be "str".
Now nosotros can utilize the Method Resolution Guild attribute (__mro__), this aspect should return a tuple of inheritances and types that the current grade is derived from.
We tin can meet that the response mentions "str" and "object". The latter seems interesting because if nosotros can try and get to classes that inherit the "object" form through it, we can achieve such a listing using the "__subclasses__" method.
The "__subclasses__" method has disclosed a big list of classes that can exist used to find the module nosotros are looking for. We can apply the "__init__" method to refer to the class constructor and further use the "__globals__" method to go the function's global variables while looking for a module that will let us to execute commands on the OS, we can look for the "sys" module and use it to refer to other modules imported past the Python interpreter for example the module OS.
Seeing as there are and so many subclasses disclosed in the list that going over it manually might take quite some fourth dimension.
We are going to utilise the following Python script to notice the outset subclass that tin can lead us to the "sys" module using the fact that if the module does not be an exception will be raised and when the module exists the page will present the "Hi" greeting page.
After executing the script, we constitute out that the subclass on index 80 is the offset course that has the "sys" module within its global variables.
Now the simply affair that is left is to employ the sys module's method called "modules" which can point usa to many Python built-in modules such as "os" for example which by itself will allow executing OS commands.
This payload tin can be used: "{{"".__class__.__mro__[ane].__subclasses__()[eighty].__init__.__globals__['sys'].modules['os'].popen("ls").read()}}"
Finally, we have achieved remote code execution.
How can Prisma Cloud WAAS protect against Template Injections?
What is a Custom Rule?
WAAS Custom Rule is the name of a feature that allows creating custom rules to your liking. These rules consist of various modes (alert, prevent, and ban) that volition check a request or response header names or values, parameter names or values, methods and more for item strings or regular expressions. One time a rule detects the pattern that is instructed WAAS will behave accordingly to the mode that was set, for example, "preclude" will block the request, "ban" will blacklist the asking issuer'southward IP address and then on.
Once you have Prisma Cloud's WAAS solution deployed we then start creating custom rules. Nosotros will create a custom rule based on a elementary regular expression to block the aforementioned template injections.
Setting up an app policy
Kickoff, we must set up an app policy for WAAS to protect the web application.
In this case, our web awarding is container-based so nosotros will navigate to Defend/WAAS tab and create a new container WAAS policy.
Giving it a general name such as TemplateInjectionApp.
Adjacent, nosotros need to select a scope for the WAAS policy.
Seeing every bit the scope of our container is non defined, we will use the "Add together drove" to define it.
We will select our container prototype as the scope of the collection and name it accordingly.
At present that we have set the scope and name, we tin can add the app and continue setting up its policy.
We will utilise the "Add endpoint" button to specify the awarding's endpoint details.
In one case everything is set up, nosotros tin can continue and create the endpoint and follow up on the custom rule creation.
Creating and deploying a Custom Dominion
Nosotros will navigate to the Custom Rules tab within the app policy.
Now we tin can finally create the custom rule, nosotros will use an example regex to take hold of the blueprint being used both with the CSTI and SSTI examples "{{}}", nosotros will check the query parameters, body parameters and header values for the following regex:
(?i){{(?:\due north|\r\n?|.)*?[^\due west\d\s-,:_]+(?:\n|\r\n?|.)*?}}
We will specify the dominion'south proper name, description and a forensic message that will be shown if the rule is triggered by whatsoever request.
In one case the rule is created, we will set the rule to "prevent" mode which will cake whatsoever requests that match the rule.
Preventing Exploitations with WAAS
In one case the custom rule is created our vulnerable application is protected from exploitations and nosotros tin can examination this out by trying the same payloads used earlier and see what will happen.
Client-Side Template Injection
The CSTI payload was successfully blocked.
The "{{8*8}}" payload we used to discover the vulnerability was blocked.
Server-Side Template Injection
The SSTI payload was successfully blocked as well forth with the vulnerability discovery payloads.
Conclusion
Both types of Template Injection attacks tin can result in severe consequences. The possible bear upon from a unmarried CSTI or SSTI vulnerability ranges from user hijacking to complete remote takeover, all the same many common spider web awarding protection platforms do not mitigate this attack vector.
Like most web application vulnerabilities template injection can exist prevented by properly validating inputs before processing them, while this sounds elementary enough it might crave an extensive amount of endeavor and development resource which is why it is often disregarded.
Prisma Cloud WAAS will mitigate such threats via functionality such as the App Firewall or Bot Protection. In addition, WAAS is able to enforce Custom Rules which allow detecting and preventing unique attacks based on custom signatures or regular expressions every bit demonstrated earlier.
To test out all the great functionality and more with Prisma Cloud, request a hands on demo.
Source: https://www.paloaltonetworks.com/blog/prisma-cloud/template-injection-vulnerabilities/
0 Response to "Once Again I Am Being Attacked Template"
Post a Comment