<?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 Amirmahdi Nozari on Medium]]></title>
        <description><![CDATA[Stories by Amirmahdi Nozari on Medium]]></description>
        <link>https://medium.com/@amirmahdinozari?source=rss-90e69642baaf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ghmQndrYxZNzMxMJwJma9Q.jpeg</url>
            <title>Stories by Amirmahdi Nozari on Medium</title>
            <link>https://medium.com/@amirmahdinozari?source=rss-90e69642baaf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:31:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amirmahdinozari/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[MirageOT: Building an Open-Source Deception Platform for ICS and OT Networks]]></title>
            <link>https://medium.com/@amirmahdinozari/mirageot-building-an-open-source-deception-platform-for-ics-and-ot-networks-10945df38247?source=rss-90e69642baaf------2</link>
            <guid isPermaLink="false">https://medium.com/p/10945df38247</guid>
            <category><![CDATA[honeypot]]></category>
            <category><![CDATA[ics-security]]></category>
            <category><![CDATA[deception]]></category>
            <category><![CDATA[ci]]></category>
            <dc:creator><![CDATA[Amirmahdi Nozari]]></dc:creator>
            <pubDate>Wed, 16 Sep 2026 22:08:21 GMT</pubDate>
            <atom:updated>2026-09-16T22:08:21.518Z</atom:updated>
            <content:encoded><![CDATA[<h3>From industrial protocol decoys to attacker correlation, MITRE ATT&amp;CK mapping, and OT-safe response</h3><p>Industrial networks are becoming increasingly connected.</p><p>SCADA systems, PLCs, engineering workstations, remote maintenance systems, and IT networks are no longer completely isolated environments. This connectivity improves operations, but it also creates new opportunities for attackers.</p><p>Traditional security monitoring can tell us that something suspicious happened.</p><p>Deception can tell us much more:</p><p><strong>Who interacted with the system? What were they looking for? Which industrial protocols did they touch? Did they move from reconnaissance to manipulation?</strong></p><p>That idea led me to build <strong>MirageOT</strong>, an open-source deception platform designed specifically for Industrial Control Systems and Operational Technology environments.</p><p><strong>GitHub:</strong><br><a href="https://github.com/Am1rX/MirageOT">https://github.com/Am1rX/MirageOT</a></p><h3>The Architecture</h3><p>MirageOT is designed as a grid of industrial decoys connected to a central event, correlation, and response layer.</p><p><em>MirageOT architecture — multiple OT/ICS protocol decoys feeding a centralized detection and monitoring layer.</em></p><h3>Why Build an OT-Specific Deception Platform?</h3><p>There are many traditional honeypots available for services such as SSH, HTTP, FTP, or Telnet.</p><p>Industrial environments are different.</p><p>An attacker targeting an OT network may search for:</p><ul><li>Modbus/TCP devices</li><li>Siemens S7 systems</li><li>DNP3 outstations</li><li>IEC 60870–5–104 endpoints</li><li>EtherNet/IP devices</li><li>BACnet systems</li><li>SNMP-enabled industrial equipment</li><li>PLC management interfaces</li><li>Industrial HMIs</li></ul><p>A normal Linux honeypot does not provide meaningful visibility into this behavior.</p><p>I wanted MirageOT to look at deception from an industrial perspective.</p><p>Instead of creating one fake service, the system creates a <strong>grid of industrial decoys</strong>.</p><h3>What MirageOT Does</h3><p>MirageOT can expose multiple simulated industrial services simultaneously.</p><p>The platform currently includes support for decoys around protocols and services such as:</p><ul><li>Modbus/TCP</li><li>S7comm</li><li>DNP3</li><li>IEC 60870–5–104</li><li>EtherNet/IP</li><li>BACnet</li><li>SNMP</li><li>FTP</li><li>Telnet</li><li>Web-based HMI interfaces</li></ul><p>The objective is not to reproduce an entire PLC firmware.</p><p>Instead, each decoy provides enough protocol behavior and device identity to observe reconnaissance and interaction attempts.</p><p>Different device profiles can represent industrial vendors and equipment families, allowing a deception environment to appear more realistic than a collection of generic open ports.</p><h3>Seeing an Attack as It Happens</h3><p>One of the most useful parts of a deception environment is visibility.</p><p>MirageOT records protocol interactions, source addresses, detected actions, threat scores, and session stages while the decoys are running.</p><p><em>Example MirageOT console output while the deception environment is receiving activity.</em></p><p>Instead of simply reporting that a port received a connection, the system attempts to preserve the <strong>context of the interaction</strong>.</p><p>That difference becomes important during investigation.</p><h3>From Individual Events to Attacker Sessions</h3><p>One of the problems with raw honeypot logs is that they quickly become noisy.</p><p>A connection to port 502 is interesting.</p><p>A connection to Modbus followed by S7 probing, HMI access, credential attempts, and register modification attempts is much more interesting.</p><p>MirageOT therefore correlates activity by source into <strong>attacker sessions</strong>.</p><p>Each session maintains information such as:</p><ul><li>First seen</li><li>Last seen</li><li>Number of events</li><li>Protocols touched</li><li>Actions performed</li><li>Threat score</li><li>Detected techniques</li></ul><p>Instead of looking at isolated packets, the analyst can observe an attacker’s behavior over time.</p><h3>A Simple Threat Scoring Model</h3><p>Different actions should not have the same meaning.</p><p>A connection attempt may only indicate reconnaissance.</p><p>A write operation against an industrial process is significantly more important.</p><p>MirageOT assigns different weights to different behaviors.</p><p>Activity can move through stages similar to:</p><p><strong>RECON → INTERACTION → MANIPULATION</strong></p><p>Low-impact activities increase the score slowly.</p><p>More serious actions such as parameter changes, writes, credential attempts, or interaction with planted tokens increase the score more aggressively.</p><p>The goal is not to claim that a single numeric score can perfectly represent attacker intent.</p><p>The score is designed as a <strong>triage mechanism</strong>.</p><p>It allows a defender to quickly identify sessions that deserve attention.</p><h3>Industrial Protocol Awareness</h3><p>The most important part of MirageOT is that it understands the context of the protocols it exposes.</p><p>Consider Modbus/TCP.</p><p>A simple scanner connecting to port 502 is different from a client attempting to read coils or holding registers.</p><p>A write operation is different again.</p><p>MirageOT can distinguish between different categories of interaction and record them accordingly.</p><p>This creates much more useful telemetry than simply logging:</p><blockquote><em>Connection received from 192.0.2.10</em></blockquote><p>Instead, an event can contain context about the protocol, action, affected address, severity, and session state.</p><h3>MITRE ATT&amp;CK for ICS Context</h3><p>Raw protocol events are useful for engineers.</p><p>SOC teams often need another level of abstraction.</p><p>MirageOT maps observed activity to relevant concepts from <strong>MITRE ATT&amp;CK for ICS</strong>.</p><p>This provides additional context for analysts who already use ATT&amp;CK-based workflows.</p><p>Rather than seeing only protocol-specific actions, defenders can connect activity to broader attacker behaviors such as:</p><ul><li>Discovery</li><li>Process state monitoring</li><li>Point and tag identification</li><li>Unauthorized command activity</li><li>Parameter modification</li><li>Credential-related behavior</li></ul><p>This becomes particularly useful when forwarding MirageOT telemetry into a SIEM.</p><h3>SIEM and SOC Integration</h3><p>A security tool becomes far more useful when it can integrate into existing workflows.</p><p>MirageOT can generate structured security events and forward them through mechanisms such as:</p><ul><li>CEF</li><li>Syslog</li><li>Webhooks</li><li>JSON-based threat intelligence output</li></ul><p>This means the deception platform does not need to operate as an isolated dashboard.</p><p>Events can be forwarded to SIEM or SOAR platforms for additional correlation.</p><p>For example:</p><p><strong>MirageOT interaction + firewall event + VPN authentication + IDS alert</strong></p><p>for the same source can provide a much richer investigation path than any individual alert.</p><h3>OT Safety Changes the Response Model</h3><p>One of the biggest differences between IT security and OT security is the cost of an incorrect response.</p><p>In an enterprise IT network, automatically blocking a suspicious IP may be acceptable.</p><p>In an industrial network, blocking the wrong system could interrupt communication with a production or safety-critical asset.</p><p>For this reason, MirageOT uses a conservative response philosophy.</p><p><strong>Alert first. Human review second. Blocking only when explicitly configured.</strong></p><p><em>MirageOT’s OT-aware response model prioritizes safety and availability over aggressive automated blocking.</em></p><p>The platform supports a never_block policy for protected systems and an alert-only mode intended to reduce the risk of an automated defensive action causing an operational outage.</p><p>For me, this was an important design decision.</p><p>Security controls in OT should consider <strong>availability and safety</strong>, not just detection accuracy.</p><h3>Honeytokens and High-Confidence Signals</h3><p>Another concept implemented in MirageOT is the use of planted lures.</p><p>An attacker who simply scans a network may generate many low-confidence signals.</p><p>But if someone accesses a resource that a legitimate user would have no reason to touch, the value of that event changes.</p><p>MirageOT can expose planted paths or tokens inside its deception environment.</p><p>Interaction with those resources can be treated as a higher-confidence signal and escalated accordingly.</p><p>This provides another way to separate generic scanning noise from more deliberate interaction.</p><h3>Where MirageOT Fits</h3><p>MirageOT is designed to run as a defensive sensor rather than as part of a real control process.</p><p>A practical architecture could place the deception layer inside an isolated industrial DMZ or monitored security segment.</p><p>In a mature environment, deception should complement — not replace — controls such as:</p><ul><li>Passive network monitoring</li><li>IDS</li><li>Asset inventory</li><li>Firewall segmentation</li><li>Authentication monitoring</li><li>Endpoint security</li><li>Log correlation</li></ul><p>A honeypot is particularly useful because legitimate production systems should generally have no reason to interact with it.</p><p>Unexpected interaction therefore becomes valuable telemetry.</p><h3>What MirageOT Is Not</h3><p>It is important to be clear about the project’s scope.</p><p>MirageOT is not intended to be a complete industrial process simulator.</p><p>It does not emulate every function of a real PLC or every corner case of every industrial protocol.</p><p>The objective is different:</p><p><strong>Provide believable industrial attack surfaces, observe interaction, correlate behavior, and generate useful defensive telemetry.</strong></p><h3>What I Want to Improve Next</h3><p>There are several areas I want to continue improving.</p><p>One major direction is deeper protocol realism.</p><p>Another is stronger automated testing using known protocol exchanges and PCAP-based validation.</p><p>I also want to continue separating the codebase into clearer components for:</p><ul><li>Protocol emulation</li><li>Session tracking</li><li>Detection</li><li>ATT&amp;CK mapping</li><li>Integrations</li><li>Dashboarding</li></ul><p>Longer term, a particularly interesting direction is combining MirageOT with passive OT network monitoring.</p><p>A future system could understand the surrounding industrial environment and deploy deception assets that resemble the real infrastructure without becoming part of the actual control process.</p><h3>Final Thoughts</h3><p>Deception changes the defender’s position.</p><p>Instead of trying to identify malicious activity inside millions of legitimate events, defenders can create systems that legitimate users should never need to access.</p><p>When someone interacts with them, the interaction itself becomes valuable intelligence.</p><p>In OT environments, this becomes particularly interesting because protocol behavior can help distinguish simple reconnaissance from attempts to manipulate industrial processes.</p><p><strong>MirageOT is my attempt to explore that idea as an open-source OT security project.</strong></p><p>If you work in network security, ICS/OT security, threat detection, or cyber deception, feedback and contributions are welcome.</p><h3>Project</h3><p><a href="https://github.com/Am1rX/MirageOT">https://github.com/Am1rX/MirageOT</a></p><h3>Suggested Medium Tags</h3><p>Cybersecurity ICS Security SCADA Honeypot Network Security</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10945df38247" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Smart Linux Firewall Manager & SOC Dashboard with Python (So You Don’t Have To)]]></title>
            <link>https://medium.com/@amirmahdinozari/i-built-a-smart-linux-firewall-manager-soc-dashboard-with-python-so-you-dont-have-to-bcd3e2d0ecf6?source=rss-90e69642baaf------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcd3e2d0ecf6</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Amirmahdi Nozari]]></dc:creator>
            <pubDate>Sun, 23 Nov 2025 10:49:44 GMT</pubDate>
            <atom:updated>2025-11-23T10:49:44.581Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hTJTEqsqaZsZ9eHJzgywvg.jpeg" /></figure><p>Goodbye iptables complexity. Hello, automated hardening and real-time threat monitoring.</p><p>If you manage Linux servers, you&#39;re familiar with the anxiety of configuring a firewall from scratch. You type a long iptables command, hit Enter, and for a split second, your heart stops—did you just lock yourself out of SSH?</p><p>iptables is powerful, but its syntax is archaic, and it lacks visibility. You set rules, but you rarely &quot;see&quot; the traffic unless you dig into dense system logs.</p><p>As a developer and security enthusiast, I wanted a tool that was simple enough to use on a fresh VPS but professional enough to offer real protection. I didn’t want to install heavy dependencies; I just wanted a Python script that understands my server.</p><p>So, I built one.</p><p>In this article, I’m open-sourcing my <strong>Linux Firewall Assistant &amp; SOC Dashboard</strong>. It’s a Python tool that automates server hardening, detects running services, and visualizes attacks in real-time.</p><h3>The Problem: Manual Configuration is Blind</h3><p>When we configure firewalls manually, we face three main issues:</p><ol><li><strong>Complexity:</strong> Remembering flags like -m conntrack --ctstate ESTABLISHED,RELATED is tedious.</li><li><strong>Lack of Context:</strong> Standard firewalls don’t tell you <em>what</em> is running on your server; you have to know the ports beforehand.</li><li><strong>Invisible Threats:</strong> You might be under a Brute-Force attack right now, but without tailing logs manually, you wouldn’t know.</li></ol><h3>The Solution: A Python-Powered SOC</h3><p>My tool solves these problems by acting as a wrapper around iptables and system logs. Here is what it does:</p><h4>1. The System Health Dashboard</h4><p>When you run the script, you aren’t greeted by a blank cursor. You get a full dashboard showing your CPU Load, RAM usage, Disk space, and Public IPs. This serves as a quick health check before you apply any security rules.</p><h4>2. Smart Auto-Discovery</h4><p>This is the feature I’m most proud of. Instead of asking you to type port numbers manually, the script uses system tools (like ss) to scan your server for listening ports.</p><p>It detects that you are running Nginx on port 80 or MySQL on 3306 and asks: <em>“I found these services. Do you want to secure them?”</em></p><h4>3. Anti-Brute Force Protection</h4><p>For sensitive services like SSH, simply “Allowing” traffic isn’t enough. My tool allows you to enable <strong>Rate Limiting</strong> logic with a single keystroke.</p><p>It configures iptables to track connection attempts. If an IP makes more than <strong>4 failed attempts in 60 seconds</strong>, it gets dropped automatically. No external tools like Fail2Ban are required; this is native kernel-level blocking.</p><h4>4. The SOC Dashboard (Live Monitoring)</h4><p>Once the firewall is up, the script transforms into a mini-SOC (Security Operations Center). It tails the system logs and uses Regex to color-code events:</p><ul><li><strong>Red:</strong> Failed SSH login attempts or Brute-force attacks.</li><li><strong>Green:</strong> Accepted traffic.</li><li><strong>Yellow:</strong> Firewall blocks.</li></ul><h3>A Look at the Code</h3><p>The tool is written in pure Python 3 with no external pip dependencies. One of the challenges was ensuring idempotency—making sure we don&#39;t add duplicate rules if the script is run multiple times.</p><p>I implemented a logic that checks for existing rules before applying new ones:</p><p><em>(Code Snippet logic)</em>: It scans the current iptables -S output. If it finds a rule matching the specific port and protocol you are trying to add, it removes the old rule first. This ensures your firewall configuration remains clean and efficient, no matter how many times you change your mind.</p><h3>How to Use It</h3><p>I made the installation as simple as possible.</p><p><strong>1. Clone the repository:</strong> git clone <a href="https://github.com/Am1rX/PRENFL.git">https://github.com/Am1rX/PRENFL.git</a></p><p><strong>2. Run with root:</strong> sudo python3 PRENFL.py</p><p>That’s it. Follow the interactive wizard, and your server will be hardened in under a minute.</p><h3>Conclusion</h3><p>Security shouldn’t be a black box. By wrapping complex networking commands in a user-friendly Python interface, we can make server hardening accessible to everyone.</p><p>This project is <strong>Open Source</strong>, and I am actively looking for feedback. If you find it useful, give it a try on your next VPS setup!</p><p><strong>🔗 Check out the code on GitHub:</strong> <a href="https://github.com/Am1rX/PRENFL.git">https://github.com/Am1rX/PRENFL.git</a></p><p><strong>🔗Check out my website: </strong><a href="https://amirmahdinozari.info/"><strong>https://AmirMahdiNozari.info</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcd3e2d0ecf6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenStreetMap Notes as a Data Source for Real-Time OSINT Analysis]]></title>
            <link>https://medium.com/@amirmahdinozari/openstreetmap-notes-as-a-data-source-for-real-time-osint-analysis-744b64f44dcd?source=rss-90e69642baaf------2</link>
            <guid isPermaLink="false">https://medium.com/p/744b64f44dcd</guid>
            <category><![CDATA[osint]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[openstreetmap]]></category>
            <category><![CDATA[search]]></category>
            <dc:creator><![CDATA[Amirmahdi Nozari]]></dc:creator>
            <pubDate>Sun, 19 Oct 2025 16:04:21 GMT</pubDate>
            <atom:updated>2025-10-19T16:04:21.450Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LWKp6VEO2M9NiPWt_ZBOzg.jpeg" /></figure><p><em>A simple tool to search OpenStreetMap Notes and uncover the intelligence hidden in plain sight.</em></p><p>The world of OSINT (Open-Source Intelligence) is filled with complex tools and sophisticated techniques. But sometimes, the most powerful insights are buried in the simplest, most accessible data sources. One such often-overlooked resource is <strong>OpenStreetMap (OSM)</strong>.</p><p>Most of us know OSM as an excellent open-source alternative to Google Maps. But OSM is more than just a map; it’s a massive, living database of geographic information, constantly updated by millions of contributors worldwide. One of its most fascinating features is “Notes.” Users create notes to report map errors, suggest changes, or log temporary observations. Anything from a “pothole on Main Street” to a “new cafe opening soon” or a “road closure for an event” can be found in these notes.</p><p>For an OSINT researcher, these notes are a goldmine of real-time, on-the-ground information. But how can we efficiently sift through thousands of them? With a simple Python script!</p><h3>Introducing the Tool: The OSM Note Searcher</h3><p>I wrote a small but effective Python script that allows you to search for any word or phrase within OpenStreetMap’s notes and retrieve the results along with their precise geographic locations. This tool helps you quickly tap into firsthand, crowdsourced intelligence.</p><h3>How is This Useful for OSINT?</h3><p>Imagine you’re investigating a specific event or location. With this script, you can:</p><ul><li><strong>Monitor Local Events:</strong> Search for terms like “protest,” “accident,” “fire,” or “construction” to find real-time, user-submitted reports from a specific area.</li><li><strong>Track Business Changes:</strong> By searching for phrases like “new shop,” “store closed,” or “now open,” you can get a feel for the commercial pulse of a neighborhood.</li><li><strong>Verify Information:</strong> If you see a claim on social media about an event at a certain location, you can search for related keywords around that geographic point on OSM to find corroborating reports from other users.</li><li><strong>Investigative Journalism:</strong> Reporters can find civic issues reported by citizens (like “broken streetlight,” “vandalism,” or “pothole”) and use them as leads for stories.</li></ul><h3>A Look at the Code: How It Works</h3><ul><li><strong>Get Input:</strong> The script prompts the user for a search term.</li><li><strong>Send Request:</strong> It URL-encodes the query and sends a GET request to the OSM Notes search API endpoint.</li><li><strong>Process Response:</strong> It parses the JSON response from the API, extracting key information like the note ID, status (open/closed), the full text of the note, and its geographic coordinates (latitude and longitude).</li><li><strong>Display Results:</strong> Finally, it prints the formatted results directly to your terminal.</li></ul><h3>How to Use the Script</h3><p>Getting started is incredibly simple.</p><p><strong>1. Prerequisites:</strong> Ensure you have Python 3 installed on your system.</p><p><strong>2. Install the Required Library:</strong> Open your terminal and install the requests library:</p><pre>pip install requests</pre><p><strong>3. Run the Script:</strong> Save the code as a Python file (e.g., osm_search.py) and run it from your terminal:</p><pre>python osm_search.py</pre><p><strong>4. Start Searching:</strong> The script will prompt you to enter your search term. For example, let’s look for “coffee shop”:</p><pre>Word &gt;&gt; coffee shop</pre><p>The script will then fetch and display the results in a clean, readable format:</p><pre>Searching for: &#39;coffee shop&#39;...</pre><pre>--- Found 25 results ---</pre><pre>Note ID: 3465890<br>Status: open<br>Description: There is a coffee shop here called &quot;The Daily Grind&quot;<br>Location (Lat, Lon): 40.7128, -74.0060<br>--------------------</pre><pre>Note ID: 3465891<br>Status: closed<br>Description: old coffee shop, now a bookstore<br>Location (Lat, Lon): 51.5074, -0.1278<br>--------------------<br>...</pre><h3>Final Thoughts</h3><p>The true power of OSINT lies in creativity and the ability to connect the dots. Simple tools like this script make valuable, public data sources more accessible. OpenStreetMap is a fantastic example of user-generated data that, with the right approach and a bit of curiosity, can become a boundless source of discovery.</p><p>Feel free to take this script, expand on it (perhaps by adding geographic area filters or saving results to a file), and use it in your own research.</p><p><strong>You can find the complete code for this project on my GitHub repository:</strong> <a href="https://github.com/Am1rX/OpenStreetMap-Note-Search-Scripts">https://github.com/Am1rX/OpenStreetMap-Note-Search-Scripts</a></p><p>And my personal website is: <a href="https://amirmahdinozari.info/">https://amirmahdinozari.info</a></p><p><strong>Happy hunting, and stay curious!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=744b64f44dcd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Block SQLmap with a Single PHP File?]]></title>
            <link>https://medium.com/@amirmahdinozari/how-to-block-sqlmap-with-a-single-php-file-a4e16c14e2c7?source=rss-90e69642baaf------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4e16c14e2c7</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[sql-injection-prevention]]></category>
            <category><![CDATA[web-application-firewall]]></category>
            <category><![CDATA[sqlmap]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Amirmahdi Nozari]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 11:52:35 GMT</pubDate>
            <atom:updated>2025-09-05T11:03:23.254Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*TcF9Rd0G26LDk3WwOU8iQQ.png" /></figure><p>For any web security professional, sqlmap It is a familiar name. For many developers, it’s a nightmare. This tool automatically and with surprising intelligence scans your website for <strong>SQL Injection</strong> vulnerabilities. But did you know that by understanding how SQLmap works? Can we build a simple and smart defensive shield with PHP to stop it in its tracks?</p><p>In this article, instead of focusing on complex code, we will first dissect the attack structure of SQLmap and then demonstrate how a simple PHP script can detect and block this behavior. I’m <a href="http://amirmahdinozari.info/">Amirmahdi, </a>and I will explain this method to you.</p><h3>The SQLmap Attack Structure: A Two-Phase Strategy</h3><p>SQLmap operates like a patient and intelligent attacker. Its assault is typically carried out in two main phases:</p><p><strong>Phase One:</strong> Reconnaissance and Probing (Sending Simple Requests)<br>sqlmap begins its work by sending very simple and seemingly harmless requests. The tool appends characters like a single quote (‘) or simple logical expressions such as AND 1=1 and OR 1=2 to URL parameters. The goal at this stage is not to extract information but to observe the server’s reaction. Does the server return an error? Does the page content change? The answers to these questions tell SQLmap whether it has found a vulnerable entry point.</p><p><strong>Phase Two:</strong> Exploitation (Sending Professional-Grade Payloads)<br>As soon as SQLmap identifies a weak point, it enters its aggressive phase. At this stage, it sends complex and dangerous payloads. These requests include keywords like UNION SELECT to extract data, information_schema to retrieve the database structure, and functions like SLEEP() or BENCHMARK() to execute Time-based Blind SQL Injection attacks.</p><h3>Our Defensive Algorithm: Intelligently Countering Both Attack Phases</h3><p>Now that we understand SQLmap’s behavior, our PHP script will counter it with a dual strategy:</p><p><strong>Countering Phase One (Behavioral Analysis):</strong> Our script doesn’t block the first suspicious request, as it could be a legitimate, albeit unusual, user input. Instead, it monitors the <strong>user’s behavior</strong>. When a large number of suspicious requests (even simple ones) are sent from a single IP within a short time frame, the script concludes that it is dealing with an automated tool like sqlmap and blocks that IP. This creates a behavioral trap for SQLmap’s reconnaissance phase.</p><p><strong>Countering Phase Two (Instant Blocking):</strong> If our script detects a request containing highly dangerous and obvious patterns (like information_schema), it doesn’t hesitate. These types of requests are so malicious that there’s no need for behavioral analysis; the attacker’s IP must be blocked <strong>immediately</strong>.</p><h3>How the Code Implements This Logic</h3><p>Our script uses a few key components to execute this algorithm:</p><ul><li><strong>Pattern Knowledge Base:</strong> An array of regular expressions (Regex) that contains patterns for SQLi attacks, ranging from simple to advanced.</li></ul><pre><br>$attack_patterns = [<br> // Extremely dangerous patterns (for instant blocking)<br> [‘pattern’ =&gt; ‘/(sqlite_master|information_schema)/i’, ‘score’ =&gt; 20, ‘type’ =&gt; ‘Metadata Access’],<br> // Suspicious patterns (for behavioral analysis)<br> [‘pattern’ =&gt; ‘/(union|select| — |#)/i’, ‘score’ =&gt; 8, ‘type’ =&gt; ‘SQLi Keyword’],<br> [‘pattern’ =&gt; ‘/\s(and|or)\s+[0–9a-z\s]+\s*(=|&lt;|&gt;)/i’, ‘score’ =&gt; 6, ‘type’ =&gt; ‘SQLi Logic’],<br> [‘pattern’ =&gt; ‘/(benchmark|sleep|load_file)/i’, ‘score’ =&gt; 9, ‘type’ =&gt; ‘SQLi Function’],<br>];</pre><ul><li><strong>Behavioral Analysis Engine:</strong> This part uses $_SESSION to track user behavior. Upon detecting any suspicious pattern, a counter (suspicion_counter) is incremented. If this count exceeds a certain limit (SUSPICION_THRESHOLD) within a specific time window (e.g., 60 seconds), the IP is blocked.</li></ul><pre><br>if ($is_suspicious) { // If even a simple pattern is found<br> // Increment the counter<br> $_SESSION[‘suspicion_counter’]++;<br> // If the counter exceeds the threshold, block the IP<br> if ($_SESSION[‘suspicion_counter’] &gt;= SUSPICION_THRESHOLD) {<br> // … block due to aggressive behavior<br> exit();<br> }<br>}</pre><ul><li><strong>Instant Blocking Engine:</strong> This component checks the request for highly dangerous patterns. If one of these patterns is found, the IP is blocked immediately, regardless of the behavioral counter.</li></ul><pre><br>if ($risk_score &gt;= RISK_THRESHOLD) { // If a highly dangerous pattern is found<br> // … instant block<br> exit();<br>}</pre><h3>Let’s Test It!</h3><p>Enough theory! Let’s put this defensive shield to the test in practice.</p><p><strong>Prepare the Test Environment:</strong> To see SQLmap in action, you need a vulnerable website. You can use this ready-made project from GitHub:</p><ul><li><strong>Vulnerable Website:</strong> <a href="https://github.com/Am1rX/Vulnerable-website">https://github.com/Am1rX/Vulnerable-website</a></li></ul><p><strong>Execute the Attack:</strong> After setting up the website, run sqlmap against it. You will see that the tool easily finds the vulnerability and accesses the data.</p><p><strong>Activate the Defensive Shield:</strong> Now, place our firewall file at the beginning of your project and run sqlmap again. This time, you’ll see that after a few initial requests, sqlmap gets blocked and is unable to proceed.</p><h3>Get the Full Source Code</h3><p>This script, named <strong>Dynamic Shield WAF</strong>, is available as an open-source project on GitHub. You can get the complete code from the link below and use it in your own projects:</p><ul><li><strong>Source Code Link:</strong> <a href="https://github.com/Am1rX/Dynamic-Shield-WAF-for-PHP">https://github.com/Am1rX/Dynamic-Shield-WAF-for-PHP</a></li></ul><h3>Final Conclusion</h3><p>The most important takeaway is this: <strong>This script is not a substitute for secure coding practices and the use of Prepared Statements.</strong> However, it is a very intelligent and efficient defense layer that, by understanding the behavior of hacking tools, can stop them and buy you time to secure your core application code.</p><h3>Future Improvements &amp; What’s Next?</h3><p>While our script is effective at stopping SQLmap scans, security is a constantly evolving field. Here are a few ideas for how you could expand this project into a more robust Web Application Firewall (WAF):</p><ul><li><strong>Expand the Rule Set:</strong> Add patterns to detect other common attacks like Cross-Site Scripting (XSS), Local File Inclusion (LFI), and Command Injection.</li><li><strong>Centralized Logging:</strong> Instead of simple file logs, send attack data to a centralized logging system (like the ELK Stack) for better analysis and visualization.</li><li><strong>IP Reputation System:</strong> Integrate with an IP blacklist service (like AbuseIPDB) to proactively block requests from known malicious actors.</li><li><strong>User-Friendly Dashboard:</strong> Build a simple front-end dashboard to view blocked requests, manage rules, and temporarily unblock IPs.</li></ul><h3>Get Involved</h3><p>This project is open-source, and contributions are always welcome! If you have ideas for new features, find a bug, or want to improve the detection patterns, feel free to open an issue or submit a pull request on the GitHub repository.</p><p>Security is a journey, not a destination. By adding simple, yet intelligent layers of defense like this one, you significantly complicate the attacker’s job. Happy coding, and stay secure!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4e16c14e2c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>