diff --git a/src/content/posts/en/static-malware-analysis-rea-codex.md b/src/content/posts/en/static-malware-analysis-rea-codex.md new file mode 100644 index 0000000..27f41e6 --- /dev/null +++ b/src/content/posts/en/static-malware-analysis-rea-codex.md @@ -0,0 +1,401 @@ +--- +title: "Static malware analysis with REA, Ghidra, and Codex" +description: "From a MalwareBazaar sample to useful defensive indicators: installing REA and statically analyzing a Windows loader, with evidence and limitations." +pubDate: 2026-10-18 +lang: en +translationKey: static-malware-analysis-rea-codex +urlSlug: static-malware-analysis-rea-codex +tags: [cybersecurity, malware-analysis, reverse-engineering, ai] +author: Fedele Mantuano +draft: false +--- + +In this article, I want to show how to use [REA](https://github.com/morluto/rea) and Codex to analyze malware statically. The goal is to understand how it works and extract information useful for defense: where it might write files, which processes it interacts with, which servers it contacts, and what traces to look for on a suspicious system. + +We start with a sample from [MalwareBazaar, the abuse.ch project](https://bazaar.abuse.ch/sample/5ecd3cbaa22a3298feebd051e9230103009dcd55eeaeeedc8f6473387eae0d55/), initially described as an infostealer. That label is the starting point of the investigation: as we will see, the available code supports some capabilities, while others depend on remote components we did not acquire. + +The case was analyzed on **October 17, 2026**, without executing the malware or contacting its endpoints. The findings below come from the case’s technical report; this article presents the parts most useful for understanding the method and its operational implications. + +For specific instructions on installing REA and Ghidra on macOS Apple Silicon and preparing the lab, see the [appendix at the end of this article](#appendix-installation-and-lab-setup). + +## The prompt that starts the investigation + +The sample is identified by this SHA-256: + +```text +5ecd3cbaa22a3298feebd051e9230103009dcd55eeaeeedc8f6473387eae0d55 +``` + +The initial request to Codex was simple: use REA to inspect the executable and produce a report covering installation directories, processes involved, hardcoded destinations, DGA, and update mechanisms. + +To reuse the method, it helps to make the constraints explicit too. This prompt is adapted from the original request, with a path to replace: + +```text +Use REA to statically analyze /path/to/case/sample.exe. +The sample is suspected to be an infostealer: check what evidence +in the available code supports that classification. + +Work in the prepared Docker lab, with no network access and the sample +mounted read-only. Verify isolation before opening the sample. +Do not execute the malware or extracted code, do not use Wine, and do +not contact any endpoints found in the sample. + +Produce a Markdown report covering: +- sample hashes and identification; +- directories and files created or merely referenced; +- processes started, enumerated, or modified; +- persistence, distinguishing configuration from demonstrated creation; +- domains, URLs, any DGA, and server-switching mechanisms; +- payload downloads and any updates; +- defensive indicators, with roles and code references; +- analysis limitations and unavailable components. + +Distinguish operations inferred from code from observed behavior. +Preserve the evidence and stop the container when finished. +``` + +During this work, the agent produced a chat summary and a more detailed report with artifacts, code references, and verification results. The summary provides an overview; the report lets us assess why a conclusion is supported. + +## What REA, Ghidra, and Codex do + +Reverse engineering an executable means reconstructing a program’s behavior from the available artifacts. A disassembler translates machine instructions into assembly; a decompiler attempts to produce a more readable representation resembling source code. That representation still requires interpretation and verification. + +[Ghidra](https://github.com/NationalSecurityAgency/ghidra), developed by the NSA’s Research Directorate, is a reverse engineering framework that includes disassembly, decompilation, graphing, and scripting, and can also run in automated mode. + +REA gives the agent tools to inspect binaries and other artifacts through **MCP**, the protocol Codex uses to communicate with external tools. It can use Ghidra as its native analysis engine and also provides tools for static JavaScript analysis. Agent integration and operating instructions are covered in [REA’s official installation guide](https://github.com/morluto/rea/blob/main/docs/installation.md). + +Codex organizes queries, follows clues, and produces an explanation. The value of the result depends on the evidence supporting that explanation: a string found in a file does not, by itself, prove that an operation is performed. + +In this case, for example, the Windows executable embeds a Bun runtime and a JavaScript bundle. After the initial PE inspection, the work focused on the extracted application code. We did not fully decompile the roughly 98 MB native executable. + +## What the sample actually contains + +The file is a **98,092,544-byte Windows x64 PE**, with an embedded Bun runtime and JavaScript. A **345,177-byte bundle spanning 4,059 lines** was extracted from it. + +The classification supported by the code is a **loader**: a component that prepares to load other programs. The bundle contains system information collection, screen capture, HTTPS communication, PE payload download and decryption, in-memory loading, and a branch dedicated to a component called a “miner.” + +The name “miner” appears in the configuration and program messages. Without that payload, we cannot confirm actual mining or identify a pool or wallet. Likewise, the initial suspicion of an infostealer does not allow us to attribute password, cookie, or cryptocurrency wallet theft to the missing payload. + +The reconstructed flow starts with environment checks, contacts the server to obtain a value needed for decryption, prepares telemetry and a screenshot, and then provides for component downloads. The PEs are decrypted with AES-256-GCM using a key derived from a remote seed and a local constant. The constant in the sample alone is not enough to recover the missing content. + +This chain depends on valid responses and completion of earlier stages. Reading the code does not demonstrate that the chain completed on a victim’s system. + +## Directories, files, and persistence + +The deployment branch provides for creating a directory and writing a component to: + +```text +%LOCALAPPDATA%\Microsoft\EdgeWebView\msedge_proxy.exe +``` + +The loader then attempts to start that file and searches for its process. This behavior is explicit in the code, conditional on payload availability and continued execution of the flow. It is not evidence of a file observed on a compromised machine, nor does it indicate that the sample copies itself to that location. + +Two other values are passed to a remote stage: + +```text +%LOCALAPPDATA%\Packages\Microsoft.MicrosoftEdge.Stable_8wekyb3d8bbwe\AC\Temp +EdgeUpdateService +``` + +The first is a directory designated for a watchdog, a component responsible for monitoring or restarting other processes. `EdgeUpdateService` is the configured task name. The available JavaScript does not demonstrate creation of that task, and the name does not prove installation of a Windows service. + +The code also references a sentinel file, `98765.txt`, and a log, `loader_debug.log`, in the loader’s directory. It checks for the sentinel and, if present, enables logging and skips an environment check. It does not create the sentinel itself. + +These details are useful in an investigation, but they mean different things: a write destination, a parameter passed to another component, and a file searched for by the program are not interchangeable evidence. + +## Which processes are involved + +The loader contains a manual PE loader: it allocates memory, copies sections, resolves imports, and starts code through a thread **inside its own process**. The examined bundle provides no evidence of injection into an external browser process. + +Process enumeration is also used to look for `msedge_proxy.exe` after the launch attempt. It does not demonstrate that the malware selects browsers or antivirus processes for termination. + +One significant detail concerns `ExitProcess` and `TerminateProcess`: the loader patches their behavior locally within its own process. In particular, the `TerminateProcess` patch returns success without performing termination. Finding the name of this API therefore does not justify concluding that the sample kills other processes. + +## Hardcoded servers, Telegram, and DGA + +The bundle contains a primary server and four fallback destinations. The addresses below are defanged: + +| Role | Indicator | +| --- | --- | +| Primary server | `nightly-sun[.]cc` | +| Fallback | `cold-signal[.]pw` | +| Fallback | `iron-pulse[.]cc` | +| Fallback | `amm-frosty[.]lol` | +| Fallback | `bears-speed[.]lol` | +| Alternative destination retrieval | `hxxps://t[.]me/s/spllcrash` | + +These values were extracted from the sample; they do not establish current reachability or ownership. We did not contact them during the analysis. + +If the initial attempts do not return a valid seed, the code provides for reading the Telegram channel’s public page, extracting HTML metadata, and decrypting its content to obtain a new address. If retrieval fails, it tries the fallback domains. + +This mechanism allows the server to be changed through remote content. **No DGA was identified in the analyzed bundle**: a Domain Generation Algorithm would generate domain names algorithmically, for example from a date or seed. Here, we see fixed destinations and retrieval of a remote address. This conclusion does not extend to the unavailable payloads. + +The HTTP paths include `/sys/pull/health`, `/cdn/sync/blob`, `/app/task/submit`, `/v2/info/pack`, and `/hub/init/gate`, serving roles related to the seed, payload, report submission, and additional components. The build identifier is `1d940c97b823`. + +The code also uses public services to determine the external IP address. Their use by the loader does not make them malicious infrastructure. Similarly, the Telegram channel can guide a targeted search, whereas blocking the entire platform would be a much broader decision. + +## What it collects and what it can update + +The first report prepared by the loader includes the public IP address, CPU, RAM, and operating system information, hostname, username, environment check data, a timestamp, and a screenshot. The image is reduced to a maximum width of 480 pixels, encoded, and included in the report: the code does not show the screenshot being saved to disk. + +The code provides for encrypted transmission of this data to the server. A second report contains the program’s declared operation results and file and process checks. These fields describe what the program intends to communicate; they are not measurements collected by running it in the lab. + +There are also checks on Chrome, Firefox, Edge, and Brave profiles, as well as the Desktop, recent files, and temporary directory. In the examined code, these assess how populated and plausible the environment is. They do not demonstrate access to browser password or cookie databases. + +As for updates, the server can supply different payloads and the Telegram channel can provide a new destination. However, there is no demonstrated mechanism for the loader executable to update itself. The URL parameter `v` contains a fixed build identifier: on its own, it is not a version comparison. + +## Verifying the agent’s conclusions + +The JavaScript obfuscation includes string tables, rotations, RC4, Base64, and XOR. Reconstruction used analyst-written decoders, without executing the malicious source through `eval`, imports, or a JavaScript VM. + +Checks covered hashes, the bundle extraction range, checksums for the four rotations, and 81 values from an RC4 table, also compared against an independent Python implementation. The decoded view preserves line and offset references so findings can be traced back to the original artifact. These checks support specific parts of the analysis; they do not prove complete equivalence of the entire deobfuscation. + +Verification itself revealed an anomaly: some decrypted names used in the anti-VM module’s FFI bindings are inconsistent with their points of use. This suggests that part of the initialization may not work in the examined build. The report preserves the anomaly and leaves dynamic verification of the overall effects open, without “correcting” values to match expected names. + +Static analysis establishes which operations are described by the code and under what conditions. Actual execution, established persistence, and remote stage capabilities remain separate questions. At the end of the work, the container was stopped and the report and evidence were preserved. + +## From analysis to threat intelligence + +One possible use for this approach is a collection and analysis pipeline. A spamtrap, for example, can collect suspicious messages and attachments; a mail parser such as [mailparser](https://github.com/SpamScope/mail-parser) can extract their artifacts. Arrival in a spamtrap is a selection criterion, not automatic confirmation of maliciousness. + +Selected files could be identified by hash and passed to isolated labs, where an agent produces reports and structured indicators. Before feeding an internal blocklist, each indicator should retain its provenance, role, analysis date, and confidence level. + +In our case, the hash identifies the exact file; domains and endpoints can guide network log checks; the full path to `msedge_proxy.exe` can guide endpoint searches. The process name alone, however, is not enough to declare an infection: it needs to be correlated with its path, hash, process origin, and communications. + +An operational workflow could therefore be: + +1. Collect and select suspicious artifacts. +2. Record their hashes, provenance, and dates. +3. Perform static analysis in an isolated lab. +4. Validate the evidence and assess the indicators. +5. Distribute approved indicators to detection or blocking systems. + +This is a proposed use of the method, not a pipeline implemented and measured in this case. The agent’s contribution is to make exploration faster and more organized while keeping conclusions verifiable. + +## Value in a forensic investigation + +During an incident, an initial analysis of this kind can provide concrete questions: does the file exist at the specified path? Which process created it? Do logs show contacts with the extracted domains or endpoints? Are there tasks matching the name passed to the remote stage? + +The report guides searches across disk, memory, endpoint telemetry, and network logs. The absence of an indicator does not rule out compromise, particularly when the sample can download different components; the presence of a common name requires correlation before drawing a conclusion. + +In this case, REA and Codex helped turn a large executable into a documented reconstruction of the loader, its destinations, and its limitations. Being able to trace a finding back to the code is what keeps the report useful beyond the first reading. + +**Further details about the technical report, artifacts, and code references can be provided privately.** + +## Appendix: installation and lab setup + +### Installing the tools on macOS Apple Silicon + +The following procedure reconstructs the configuration used on the Mac, with generic paths under the user’s home directory. It applies to **macOS Apple Silicon**: we are not presenting it as a procedure already tested on Windows or Linux. + +The reference versions are REA **6.5.0**, Ghidra **12.1.4**, Temurin JDK **25.0.4.1**, and Node.js **24.21.0**. These versions are pinned to reproduce the environment described. The variant including the skill was checked through a setup plan preview; the entire sequence was not repeated on a clean Mac. + +#### 1. Prepare the Mac + +You need Codex already installed and authenticated, Internet access to download the tools, and Apple’s build tools. Check the architecture and toolchain: + +```bash +uname -m +xcode-select -p +``` + +On Apple Silicon, the first command should return `arm64`. If Apple’s tools are not installed: + +```bash +xcode-select --install +``` + +Wait for installation to complete before continuing. Run the following steps in the same terminal session to preserve the environment variables: + +```bash +mkdir -p "$HOME/.local/bin" +mkdir -p "$HOME/.local/opt/jdks" +mkdir -p "$HOME/Downloads/rea-setup" +cd "$HOME/Downloads/rea-setup" +``` + +#### 2. Install Java + +Download the ARM64 JDK from the [official Eclipse Temurin release](https://github.com/adoptium/temurin25-binaries/releases/tag/jdk-25.0.4.1%2B1): + +```bash +curl -fL \ + 'https://github.com/adoptium/temurin25-binaries/releases/download/jdk-25.0.4.1%2B1/OpenJDK25U-jdk_aarch64_mac_hotspot_25.0.4.1_1.tar.gz' \ + -o temurin-jdk.tar.gz + +echo '61979887f7506a24a57439ff99adb8b3a7fc89977d9cfe3b8984f58a981b7b9d temurin-jdk.tar.gz' \ + | shasum -a 256 -c - +``` + +The digest is the one recorded for the archive used in our installation. If verification does not return `OK`, stop and check the download. Then: + +```bash +tar -xzf temurin-jdk.tar.gz +ditto "jdk-25.0.4.1+1/Contents/Home" \ + "$HOME/.local/opt/jdks/temurin-25.0.4.1-arm64" + +export JAVA_HOME="$HOME/.local/opt/jdks/temurin-25.0.4.1-arm64" +export PATH="$JAVA_HOME/bin:$PATH" +java -version +javac -version +``` + +#### 3. Install Ghidra and build the native components + +Download the public distribution from the [Ghidra 12.1.4 release](https://github.com/NationalSecurityAgency/ghidra/releases/tag/Ghidra_12.1.4_build). Archives named “Source code” are different from the ready-to-use distribution. + +```bash +curl -fL \ + 'https://github.com/NationalSecurityAgency/ghidra/releases/download/Ghidra_12.1.4_build/ghidra_12.1.4_PUBLIC_20260921.zip' \ + -o ghidra.zip + +echo 'ddac49f903da9d5bac833e5cc79395098b9c33cfd3279be5f31bd00387d2d4db ghidra.zip' \ + | shasum -a 256 -c - +``` + +Again, wait for `OK`. The destination must be a new directory: do not overlay different Ghidra versions. + +```bash +unzip -q ghidra.zip +ditto ghidra_12.1.4_PUBLIC "$HOME/.local/opt/ghidra_12.1.4_PUBLIC" +ln -s ghidra_12.1.4_PUBLIC "$HOME/.local/opt/ghidra_latest" +export GHIDRA_INSTALL_DIR="$HOME/.local/opt/ghidra_latest" + +( + cd "$GHIDRA_INSTALL_DIR/support/gradle" + ./gradlew --no-daemon buildNatives +) +``` + +The wrapper may download Gradle. Wait for `BUILD SUCCESSFUL`, then check the decompiler: + +```bash +file "$GHIDRA_INSTALL_DIR/Ghidra/Features/Decompiler/build/os/mac_arm_64/decompile" +``` + +The output should identify a Mach-O ARM64 executable. To try the graphical interface: + +```bash +"$GHIDRA_INSTALL_DIR/ghidraRun" +``` + +#### 4. Install Node.js and REA + +We use [NVM](https://github.com/nvm-sh/nvm/tree/v0.40.3) to manage Node. If it is already installed, skip downloading and running its installer: + +```bash +curl -fL \ + https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh \ + -o "$HOME/Downloads/rea-setup/install-nvm.sh" +bash "$HOME/Downloads/rea-setup/install-nvm.sh" +``` + +Load NVM and select the version used on the Mac: + +```bash +export NVM_DIR="$HOME/.nvm" +. "$NVM_DIR/nvm.sh" +nvm install 24.21.0 +nvm use 24.21.0 +node --version +npm --version + +npm install --global \ + --prefix "$HOME/.local/opt/rea" \ + --ignore-scripts \ + rea-agents@6.5.0 +``` + +The prefix belongs to the user, so `sudo` is not needed. Create a command that explicitly selects Node, Java, and Ghidra: + +```bash +cat > "$HOME/.local/bin/rea" <<'EOF' +#!/bin/sh +set -eu +export JAVA_HOME="$HOME/.local/opt/jdks/temurin-25.0.4.1-arm64" +export GHIDRA_INSTALL_DIR="$HOME/.local/opt/ghidra_latest" +export REA_ANALYSIS_PROVIDER=ghidra +export PATH="$HOME/.nvm/versions/node/v24.21.0/bin:$JAVA_HOME/bin:$PATH" +exec "$HOME/.nvm/versions/node/v24.21.0/bin/node" \ + "$HOME/.local/opt/rea/lib/node_modules/rea-agents/scripts/rea.mjs" \ + "$@" +EOF + +chmod +x "$HOME/.local/bin/rea" +export PATH="$HOME/.local/bin:$PATH" +rea --version +``` + +The expected version is `6.5.0`. If `~/.local/bin` is not already in `PATH`, add this line to `~/.zshrc` for future terminal sessions: + +```bash +export PATH="$HOME/.local/bin:$PATH" +``` + +#### 5. Connect REA to Codex + +Check Ghidra and preview the plan before applying it: + +```bash +rea doctor --provider ghidra --json +rea setup --client codex --skill=true --dry-run --json +``` + +The plan should include MCP registration and skill installation. To apply it: + +```bash +rea setup --client codex --skill=true --yes --json +``` + +The MCP server exposes the tools; the skill provides operating instructions to the agent. We use the explicit form `--skill=true`, verified in this version’s setup plan. + +When Node is managed by NVM, Codex launched from the graphical interface may have a different `PATH` from the terminal. If the generated registration does not select the intended runtime, adjust the REA sections in `~/.codex/config.toml`: + +```toml +[mcp_servers.rea] +command = "/Users/USERNAME/.nvm/versions/node/v24.21.0/bin/node" +args = [ + "/Users/USERNAME/.local/opt/rea/lib/node_modules/rea-agents/scripts/rea.mjs", + "mcp" +] +startup_timeout_sec = 30 +tool_timeout_sec = 450 + +[mcp_servers.rea.env] +GHIDRA_INSTALL_DIR = "/Users/USERNAME/.local/opt/ghidra_latest" +JAVA_HOME = "/Users/USERNAME/.local/opt/jdks/temurin-25.0.4.1-arm64" +REA_ANALYSIS_PROVIDER = "ghidra" +``` + +Replace `USERNAME` with your username and edit the existing sections without duplicating them or deleting other servers. Paths are absolute: do not assume `$HOME` will be expanded in TOML. + +The [official Codex MCP documentation](https://developers.openai.com/codex/mcp/) describes the command, arguments, environment, and timeouts. `startup_timeout_sec` applies to MCP server startup; `tool_timeout_sec` applies to individual calls. The 450 seconds allow time for analysis operations and for Ghidra to start when required by a call: this is a choice for our environment, not a universal requirement. + +Complete the checks: + +```bash +rea doctor --client codex --provider ghidra --json +rea doctor --skill --json +rea mcp doctor --json +``` + +Look for `healthy: true` in the selected checks, then close and reopen Codex. An initial prompt could be: + +```text +Use REA to check the server version and Ghidra availability, +without opening any files. +``` + +These checks verify tool availability. Analyzing a program is a separate verification step. + +### Preparing the analysis lab + +Installation on the Mac makes the tools available to the agent. The malware analysis was performed in a **separate Linux/amd64 lab in Docker Desktop**, with REA 6.5.0 and Node 24.22.0. The host and container configurations are two distinct environments. + +A Windows executable can be studied statically from Linux: reading its structure, strings, and code does not require launching it on Windows. In our case, Wine was not used, and neither the sample, the extracted JavaScript, nor any PEs were executed. + +The image and dependencies were prepared before analysis. During inspection, the container used network mode `none`, a read-only root filesystem, an unprivileged user, dropped capabilities, and `no-new-privileges`. The sample was mounted read-only; writes were limited to the case directory and the container’s temporary areas. + +**Starting Docker does not automatically apply these conditions.** The lab must be explicitly configured and checked. The container limits the tools’ access to the system and network; for this work, the central constraint remains static analysis only. + +The lab’s network and the connection used by Codex are also separate: the container can be offline while the agent communicates with the model service. “Offline” therefore does not mean the entire AI workflow has no external communications; this matters when handling confidential samples or evidence. diff --git a/src/content/posts/it/analisi-statica-malware-rea-codex.md b/src/content/posts/it/analisi-statica-malware-rea-codex.md new file mode 100644 index 0000000..958a2ad --- /dev/null +++ b/src/content/posts/it/analisi-statica-malware-rea-codex.md @@ -0,0 +1,401 @@ +--- +title: "Analisi statica di un malware con REA, Ghidra e Codex" +description: "Dal campione di MalwareBazaar agli indicatori utili alla difesa: installazione di REA e analisi statica di un loader Windows, con evidenze e limiti." +pubDate: 2026-10-18 +lang: it +translationKey: static-malware-analysis-rea-codex +urlSlug: analisi-statica-malware-rea-codex +tags: [cybersecurity, malware-analysis, reverse-engineering, ai] +author: Fedele Mantuano +draft: false +--- + +In questo articolo voglio mostrare come utilizzare [REA](https://github.com/morluto/rea) e Codex per analizzare staticamente un malware. L’obiettivo è comprenderne il funzionamento per ricavare informazioni utili alla difesa: dove potrebbe scrivere file, quali processi coinvolge, con quali server comunica e quali tracce cercare su un sistema sospetto. + +Partiamo da un campione proveniente da [MalwareBazaar, il progetto di abuse.ch](https://bazaar.abuse.ch/sample/5ecd3cbaa22a3298feebd051e9230103009dcd55eeaeeedc8f6473387eae0d55/), inizialmente indicato come infostealer. Questa etichetta è il punto di partenza dell’indagine: vedremo che il codice disponibile permette di confermare alcune capacità, mentre altre dipendono da componenti remoti che non abbiamo acquisito. + +Il caso è stato analizzato il **17 ottobre 2026**, senza eseguire il malware e senza contattare i suoi endpoint. I risultati descritti di seguito provengono dal report tecnico del caso; questo articolo ne riprende le parti più utili per capire il metodo e le implicazioni operative. + +Per le indicazioni specifiche sull’installazione di REA e Ghidra su macOS Apple Silicon e sulla preparazione del laboratorio, consulta l’[appendice in fondo all’articolo](#appendice-installazione-e-laboratorio). + +## Il prompt che avvia l’indagine + +Il campione è identificato da questo SHA-256: + +```text +5ecd3cbaa22a3298feebd051e9230103009dcd55eeaeeedc8f6473387eae0d55 +``` + +La richiesta iniziale a Codex era semplice: usare REA per ispezionare l’eseguibile e produrre un report su cartelle di installazione, processi coinvolti, destinazioni cablate, DGA e meccanismi di aggiornamento. + +Per riutilizzare il metodo conviene rendere espliciti anche i vincoli. Questo è un prompt riformulato a partire dalla richiesta originale, con un percorso da sostituire: + +```text +Usa REA per analizzare staticamente /percorso/del/caso/sample.exe. +Il campione è sospettato di essere un infostealer: verifica che cosa +supporta questa classificazione nel codice disponibile. + +Lavora nel laboratorio Docker predisposto, senza rete, con campione +in sola lettura. Verifica l’isolamento prima di aprire il campione. +Non eseguire il malware o il codice estratto, non usare Wine e non +contattare endpoint presenti nel campione. + +Produci un report Markdown con: +- hash e identificazione del campione; +- directory e file creati o soltanto referenziati; +- processi avviati, enumerati o modificati; +- persistenza, distinguendo configurazione e creazione dimostrata; +- domini, URL, eventuale DGA e meccanismi di cambio server; +- download di payload ed eventuali aggiornamenti; +- indicatori utili alla difesa, con ruolo e riferimenti al codice; +- limiti dell’analisi e componenti non disponibili. + +Distingui le operazioni ricavate dal codice dai comportamenti osservati. +Conserva le evidenze e arresta il container al termine. +``` + +Nel lavoro svolto, l’agente ha prodotto un riepilogo in chat e un report più esteso, con artefatti, riferimenti al codice e verifiche. Il riepilogo aiuta a orientarsi; il report permette di valutare perché una conclusione sia sostenibile. + +## Che cosa fanno REA, Ghidra e Codex + +Il reverse engineering di un eseguibile richiede di ricostruire il comportamento di un programma a partire dagli artefatti disponibili. Un disassemblatore traduce le istruzioni macchina in assembly; un decompilatore prova a ricavarne una rappresentazione più leggibile, simile al codice sorgente. Questa rappresentazione richiede comunque interpretazione e verifica. + +[Ghidra](https://github.com/NationalSecurityAgency/ghidra), sviluppato dalla Research Directorate della NSA, è un framework di reverse engineering che comprende disassemblaggio, decompilazione, grafi e scripting, utilizzabile anche in modalità automatizzata. + +REA mette a disposizione dell’agente strumenti per interrogare binari e altri artefatti attraverso **MCP**, il protocollo con cui Codex comunica con strumenti esterni. Può usare Ghidra come motore per l’analisi nativa e dispone anche di strumenti per l’analisi statica JavaScript. Il collegamento all’agente e le istruzioni operative sono descritti nella [guida ufficiale di installazione di REA](https://github.com/morluto/rea/blob/main/docs/installation.md). + +Codex organizza le interrogazioni, segue gli indizi e produce una spiegazione. Il valore del risultato dipende dalle evidenze che accompagnano quella spiegazione: una stringa trovata nel file, da sola, non dimostra che una certa operazione venga eseguita. + +In questo caso, per esempio, l’eseguibile Windows incorpora un runtime Bun e un bundle JavaScript. Dopo l’ispezione iniziale del PE, il lavoro si è concentrato sul codice applicativo estratto. Non abbiamo decompilato integralmente i circa 98 MB dell’eseguibile nativo. + +## Che cosa contiene davvero il campione + +Il file è un **PE Windows x64 di 98.092.544 byte**, con runtime Bun e JavaScript incorporato. Dal contenitore è stato estratto un bundle di **345.177 byte, su 4.059 righe**. + +La classificazione sostenuta dal codice è quella di un **loader**, cioè un componente che prepara il caricamento di altri programmi. Il bundle contiene raccolta di informazioni del sistema, acquisizione dello schermo, contatti HTTPS, download e decifratura di payload PE, caricamento in memoria e un ramo dedicato a un componente chiamato “miner”. + +Il nome “miner” compare nella configurazione e nei messaggi del programma. Senza il relativo payload non possiamo confermare il mining effettivo, né identificare pool o wallet. Allo stesso modo, il sospetto di infostealer non permette di attribuire al payload assente il furto di password, cookie o portafogli di criptovalute. + +Il flusso ricostruito parte da controlli ambientali, contatta il server per ottenere un valore necessario alla decifratura, prepara telemetria e screenshot, quindi prevede il download dei componenti. I PE vengono decifrati con AES-256-GCM usando una chiave derivata da un seed remoto e da una costante locale. La costante presente nel campione, da sola, non basta a recuperare i contenuti mancanti. + +È una catena condizionata da risposte valide e dal completamento delle fasi precedenti. La lettura del codice non dimostra che sia stata completata su una vittima. + +## Cartelle, file e persistenza + +Il ramo di distribuzione prevede la creazione della directory e la scrittura di un componente in: + +```text +%LOCALAPPDATA%\Microsoft\EdgeWebView\msedge_proxy.exe +``` + +Il loader tenta poi di avviare quel file e ne cerca il processo. Questo è un comportamento esplicito del codice, subordinato alla disponibilità dei payload e alla prosecuzione del flusso. Non è la prova di un file osservato su una macchina compromessa, né indica che il campione copi se stesso in quel percorso. + +Altri due valori vengono passati a uno stadio remoto: + +```text +%LOCALAPPDATA%\Packages\Microsoft.MicrosoftEdge.Stable_8wekyb3d8bbwe\AC\Temp +EdgeUpdateService +``` + +La prima è una directory designata per un watchdog, un componente incaricato di sorvegliare o rilanciare altri processi. `EdgeUpdateService` è il nome previsto per un task nella configurazione. Nel JavaScript disponibile non è dimostrata la creazione di quel task, e il nome non prova l’installazione di un servizio Windows. + +Esistono anche un file sentinella, `98765.txt`, e un log, `loader_debug.log`, nella directory del loader. Il codice controlla la presenza della sentinella e, se la trova, abilita il log e salta un controllo ambientale. Non crea direttamente la sentinella. + +Sono dettagli utili in un’indagine, ma hanno significati diversi: percorso di scrittura, parametro consegnato a un altro componente e file cercato dal programma non sono evidenze intercambiabili. + +## Quali processi coinvolge + +Il loader contiene un caricatore manuale di PE: alloca memoria, copia sezioni, risolve import e avvia codice attraverso un thread **nel proprio processo**. Nel bundle esaminato non emerge un’iniezione in un processo browser esterno. + +L’enumerazione dei processi serve anche a cercare `msedge_proxy.exe` dopo il tentativo di avvio. Non dimostra che il malware scelga browser o antivirus da terminare. + +Un dettaglio significativo riguarda `ExitProcess` e `TerminateProcess`: il loader ne modifica localmente il comportamento nel proprio processo. In particolare, la patch a `TerminateProcess` restituisce successo senza effettuare la terminazione. Trovare il nome di questa API non autorizza quindi a concludere che il campione uccida altri processi. + +## Server cablati, Telegram e DGA + +Il bundle contiene un server principale e quattro destinazioni di riserva. Gli indirizzi sono riportati in forma disattivata tipograficamente: + +| Ruolo | Indicatore | +| --- | --- | +| Server principale | `nightly-sun[.]cc` | +| Riserva | `cold-signal[.]pw` | +| Riserva | `iron-pulse[.]cc` | +| Riserva | `amm-frosty[.]lol` | +| Riserva | `bears-speed[.]lol` | +| Recupero di una destinazione alternativa | `hxxps://t[.]me/s/spllcrash` | + +Sono valori ricavati dal campione, non una verifica della loro attuale raggiungibilità o titolarità. Durante l’analisi non li abbiamo contattati. + +Se i tentativi iniziali non restituiscono un seed valido, il codice prevede di leggere la pagina pubblica del canale Telegram, estrarre un metadato HTML e decifrarne il contenuto per ricavare un nuovo indirizzo. Se il recupero fallisce, prova i domini di riserva. + +Questo meccanismo consente di cambiare server mediante contenuti remoti. **Non è stato individuato un DGA nel bundle analizzato**: un Domain Generation Algorithm produrrebbe nomi di dominio attraverso un algoritmo, per esempio a partire dalla data o da un seed. Qui vediamo destinazioni fisse e recupero di un indirizzo remoto. La conclusione non si estende ai payload non disponibili. + +Tra i percorsi HTTP figurano `/sys/pull/health`, `/cdn/sync/blob`, `/app/task/submit`, `/v2/info/pack` e `/hub/init/gate`, con ruoli rispettivamente legati a seed, payload, invio report e componenti aggiuntivi. L’identificativo di build è `1d940c97b823`. + +Il codice usa anche servizi pubblici per conoscere l’IP esterno. Il loro utilizzo da parte del loader non li rende infrastruttura malevola. Per la stessa ragione, la presenza del canale Telegram può orientare una ricerca mirata, mentre il blocco indiscriminato dell’intera piattaforma sarebbe una decisione molto più ampia. + +## Che cosa raccoglie e che cosa può aggiornare + +Il primo report preparato dal loader comprende IP pubblico, informazioni su CPU, RAM e sistema operativo, hostname, username, dati dei controlli ambientali, timestamp e screenshot. L’immagine viene ridotta a una larghezza massima di 480 pixel, codificata e inserita nel report: non compare un salvataggio dello screenshot su disco. + +Il codice prevede l’invio cifrato di questi dati al server. Un secondo report contiene l’esito dichiarato delle operazioni e verifiche su file e processo. Questi campi descrivono ciò che il programma intende comunicare; non sono misurazioni raccolte eseguendolo nel laboratorio. + +Compaiono anche controlli su profili Chrome, Firefox, Edge e Brave, oltre a Desktop, file recenti e directory temporanea. Nel codice esaminato servono a valutare quanto l’ambiente sia popolato e plausibile. Non dimostrano la lettura dei database di password o cookie dei browser. + +Quanto agli aggiornamenti, il server può fornire payload differenti e il canale Telegram può indicare una nuova destinazione. Non emerge invece un meccanismo dimostrato di aggiornamento autonomo dell’eseguibile del loader. Il parametro `v` degli URL contiene un identificativo fisso di build: da solo non costituisce un confronto fra versioni. + +## Verificare le conclusioni dell’agente + +L’offuscamento del JavaScript comprende tabelle di stringhe, rotazioni, RC4, Base64 e XOR. La ricostruzione è stata fatta con decoder dell’analista, senza eseguire il sorgente malevolo attraverso `eval`, import o una VM JavaScript. + +Sono stati controllati gli hash, l’intervallo di estrazione del bundle, i checksum delle quattro rotazioni e 81 valori di una tabella RC4, confrontati anche con un’implementazione Python indipendente. La vista decodificata mantiene riferimenti a righe e offset, così da poter risalire all’artefatto originale. Queste verifiche sostengono parti precise dell’analisi; non provano l’equivalenza completa di tutta la deoffuscazione. + +Proprio la verifica ha evidenziato un’anomalia: alcuni nomi decifrati usati nei binding FFI del modulo anti-VM risultano incoerenti con i rispettivi punti d’uso. Questo suggerisce che parte dell’inizializzazione possa non funzionare nella build esaminata. Il report conserva l’anomalia e lascia aperta la verifica dinamica degli effetti complessivi, senza “correggere” i valori per farli coincidere con quelli attesi. + +L’analisi statica stabilisce quali operazioni siano descritte dal codice e con quali condizioni. L’esecuzione effettiva, la persistenza realizzata e le capacità degli stadi remoti restano domande distinte. Al termine del lavoro il container è stato arrestato, conservando report e prove. + +## Dall’analisi alla threat intelligence + +Un possibile impiego di questo approccio è una pipeline di raccolta e analisi. Una spamtrap, per esempio, può raccogliere messaggi e allegati sospetti; un parser di posta come [mailparser](https://github.com/SpamScope/mail-parser) può estrarne gli artefatti. L’arrivo nella spamtrap è un criterio di selezione, non una conferma automatica di malevolenza. + +I file selezionati potrebbero essere identificati tramite hash e passati a laboratori isolati, dove un agente produce report e indicatori strutturati. Prima di alimentare un sistema di blacklist interno, ogni indicatore dovrebbe conservare provenienza, ruolo, data dell’analisi e livello di confidenza. + +Nel nostro caso l’hash identifica il file preciso; i domini e gli endpoint possono orientare controlli nei log di rete; il percorso completo di `msedge_proxy.exe` può guidare ricerche sugli endpoint. Il solo nome del processo, invece, non basta a dichiarare un’infezione: occorre correlarlo a percorso, hash, origine del processo e comunicazioni. + +Un flusso operativo potrebbe quindi essere: + +1. raccogliere e selezionare gli artefatti sospetti; +2. registrarne hash, provenienza e data; +3. eseguire l’analisi statica in un laboratorio isolato; +4. validare le evidenze e qualificare gli indicatori; +5. distribuire gli indicatori approvati ai sistemi di rilevamento o blocco. + +È una proposta di utilizzo del metodo, non una pipeline implementata e misurata in questo caso. Il contributo dell’agente è rendere più rapido e ordinato il lavoro di esplorazione, lasciando verificabili le conclusioni. + +## Utilità in un’analisi forense + +Durante un incidente, una prima analisi di questo tipo può fornire domande concrete: esiste il file nel percorso indicato? Quale processo lo ha creato? I log mostrano contatti con i domini o gli endpoint estratti? Sono presenti task compatibili con il nome passato allo stadio remoto? + +Il report orienta le ricerche su disco, memoria, telemetria endpoint e log di rete. L’assenza di un indicatore non esclude la compromissione, soprattutto quando il campione può scaricare componenti diversi; la presenza di un nome comune richiede correlazioni prima di formulare una conclusione. + +In questo caso REA e Codex hanno aiutato a passare da un eseguibile di grandi dimensioni a una ricostruzione documentata del loader, delle sue destinazioni e dei suoi limiti. La possibilità di tornare dal risultato al codice è ciò che rende il report utile anche dopo la prima lettura. + +**Maggiori dettagli sul report tecnico, sugli artefatti e sui riferimenti al codice possono essere forniti privatamente.** + +## Appendice: installazione e laboratorio + +### Installare gli strumenti su macOS Apple Silicon + +La procedura seguente ricostruisce la configurazione usata sul Mac, con percorsi generici nell’area utente. È riferita a **macOS Apple Silicon**: non la presentiamo come una procedura già collaudata su Windows o Linux. + +Le versioni di riferimento sono REA **6.5.0**, Ghidra **12.1.4**, Temurin JDK **25.0.4.1** e Node.js **24.21.0**. Sono versioni fissate per riprodurre l’ambiente descritto. La variante che include la skill è stata controllata in anteprima tramite il piano di setup; l’intera sequenza non è stata ripetuta su un Mac pulito. + +#### 1. Preparare il Mac + +Servono Codex già installato e autenticato, accesso a Internet per scaricare gli strumenti e gli strumenti di compilazione Apple. Verifichiamo architettura e toolchain: + +```bash +uname -m +xcode-select -p +``` + +Su Apple Silicon il primo comando deve restituire `arm64`. Se gli strumenti Apple non sono installati: + +```bash +xcode-select --install +``` + +Attendere il completamento prima di proseguire. I passaggi successivi vanno eseguiti nella stessa sessione del terminale, così da conservare le variabili d’ambiente: + +```bash +mkdir -p "$HOME/.local/bin" +mkdir -p "$HOME/.local/opt/jdks" +mkdir -p "$HOME/Downloads/rea-setup" +cd "$HOME/Downloads/rea-setup" +``` + +#### 2. Installare Java + +Scarichiamo il JDK ARM64 dalla [release ufficiale Eclipse Temurin](https://github.com/adoptium/temurin25-binaries/releases/tag/jdk-25.0.4.1%2B1): + +```bash +curl -fL \ + 'https://github.com/adoptium/temurin25-binaries/releases/download/jdk-25.0.4.1%2B1/OpenJDK25U-jdk_aarch64_mac_hotspot_25.0.4.1_1.tar.gz' \ + -o temurin-jdk.tar.gz + +echo '61979887f7506a24a57439ff99adb8b3a7fc89977d9cfe3b8984f58a981b7b9d temurin-jdk.tar.gz' \ + | shasum -a 256 -c - +``` + +Il digest è quello registrato per l’archivio della nostra installazione. Se la verifica non restituisce `OK`, fermarsi e controllare il download. Poi: + +```bash +tar -xzf temurin-jdk.tar.gz +ditto "jdk-25.0.4.1+1/Contents/Home" \ + "$HOME/.local/opt/jdks/temurin-25.0.4.1-arm64" + +export JAVA_HOME="$HOME/.local/opt/jdks/temurin-25.0.4.1-arm64" +export PATH="$JAVA_HOME/bin:$PATH" +java -version +javac -version +``` + +#### 3. Installare Ghidra e compilare i componenti nativi + +Scarichiamo la distribuzione pubblica dalla [release Ghidra 12.1.4](https://github.com/NationalSecurityAgency/ghidra/releases/tag/Ghidra_12.1.4_build). Gli archivi denominati “Source code” sono diversi dalla distribuzione pronta all’uso. + +```bash +curl -fL \ + 'https://github.com/NationalSecurityAgency/ghidra/releases/download/Ghidra_12.1.4_build/ghidra_12.1.4_PUBLIC_20260921.zip' \ + -o ghidra.zip + +echo 'ddac49f903da9d5bac833e5cc79395098b9c33cfd3279be5f31bd00387d2d4db ghidra.zip' \ + | shasum -a 256 -c - +``` + +Anche qui attendiamo `OK`. La destinazione deve essere una cartella nuova: non sovrapporre versioni differenti di Ghidra. + +```bash +unzip -q ghidra.zip +ditto ghidra_12.1.4_PUBLIC "$HOME/.local/opt/ghidra_12.1.4_PUBLIC" +ln -s ghidra_12.1.4_PUBLIC "$HOME/.local/opt/ghidra_latest" +export GHIDRA_INSTALL_DIR="$HOME/.local/opt/ghidra_latest" + +( + cd "$GHIDRA_INSTALL_DIR/support/gradle" + ./gradlew --no-daemon buildNatives +) +``` + +Il wrapper può scaricare Gradle. Attendere `BUILD SUCCESSFUL`, quindi verificare il decompilatore: + +```bash +file "$GHIDRA_INSTALL_DIR/Ghidra/Features/Decompiler/build/os/mac_arm_64/decompile" +``` + +Il risultato deve indicare un eseguibile Mach-O ARM64. Per provare l’interfaccia grafica: + +```bash +"$GHIDRA_INSTALL_DIR/ghidraRun" +``` + +#### 4. Installare Node.js e REA + +Per gestire Node usiamo [NVM](https://github.com/nvm-sh/nvm/tree/v0.40.3). Se è già installato, saltiamo il download e l’esecuzione del suo installer: + +```bash +curl -fL \ + https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh \ + -o "$HOME/Downloads/rea-setup/install-nvm.sh" +bash "$HOME/Downloads/rea-setup/install-nvm.sh" +``` + +Carichiamo NVM e selezioniamo la versione usata sul Mac: + +```bash +export NVM_DIR="$HOME/.nvm" +. "$NVM_DIR/nvm.sh" +nvm install 24.21.0 +nvm use 24.21.0 +node --version +npm --version + +npm install --global \ + --prefix "$HOME/.local/opt/rea" \ + --ignore-scripts \ + rea-agents@6.5.0 +``` + +Il prefisso appartiene all’utente, quindi non serve `sudo`. Creiamo un comando che selezioni esplicitamente Node, Java e Ghidra: + +```bash +cat > "$HOME/.local/bin/rea" <<'EOF' +#!/bin/sh +set -eu +export JAVA_HOME="$HOME/.local/opt/jdks/temurin-25.0.4.1-arm64" +export GHIDRA_INSTALL_DIR="$HOME/.local/opt/ghidra_latest" +export REA_ANALYSIS_PROVIDER=ghidra +export PATH="$HOME/.nvm/versions/node/v24.21.0/bin:$JAVA_HOME/bin:$PATH" +exec "$HOME/.nvm/versions/node/v24.21.0/bin/node" \ + "$HOME/.local/opt/rea/lib/node_modules/rea-agents/scripts/rea.mjs" \ + "$@" +EOF + +chmod +x "$HOME/.local/bin/rea" +export PATH="$HOME/.local/bin:$PATH" +rea --version +``` + +La versione attesa è `6.5.0`. Se `~/.local/bin` non è già nel `PATH`, aggiungere questa riga a `~/.zshrc` per i terminali futuri: + +```bash +export PATH="$HOME/.local/bin:$PATH" +``` + +#### 5. Collegare REA a Codex + +Controlliamo Ghidra e visualizziamo il piano prima di applicarlo: + +```bash +rea doctor --provider ghidra --json +rea setup --client codex --skill=true --dry-run --json +``` + +Il piano deve includere la registrazione MCP e l’installazione della skill. Per applicarlo: + +```bash +rea setup --client codex --skill=true --yes --json +``` + +Il server MCP espone gli strumenti; la skill fornisce le istruzioni operative all’agente. Usiamo la forma esplicita `--skill=true`, verificata nel piano di setup di questa versione. + +Quando Node è gestito da NVM, Codex avviato dall’interfaccia grafica può avere un `PATH` diverso da quello del terminale. Se la registrazione generata non seleziona il runtime desiderato, possiamo adattare le sezioni REA in `~/.codex/config.toml`: + +```toml +[mcp_servers.rea] +command = "/Users/NOME_UTENTE/.nvm/versions/node/v24.21.0/bin/node" +args = [ + "/Users/NOME_UTENTE/.local/opt/rea/lib/node_modules/rea-agents/scripts/rea.mjs", + "mcp" +] +startup_timeout_sec = 30 +tool_timeout_sec = 450 + +[mcp_servers.rea.env] +GHIDRA_INSTALL_DIR = "/Users/NOME_UTENTE/.local/opt/ghidra_latest" +JAVA_HOME = "/Users/NOME_UTENTE/.local/opt/jdks/temurin-25.0.4.1-arm64" +REA_ANALYSIS_PROVIDER = "ghidra" +``` + +Sostituire `NOME_UTENTE` con il proprio nome e modificare le sezioni esistenti, senza duplicarle o cancellare gli altri server. I percorsi sono assoluti: non presumere che `$HOME` venga espanso nel TOML. + +Nella [documentazione ufficiale MCP di Codex](https://developers.openai.com/codex/mcp/) sono descritti comando, argomenti, ambiente e timeout. `startup_timeout_sec` riguarda l’avvio del server MCP; `tool_timeout_sec` riguarda le singole chiamate. I 450 secondi lasciano margine alle operazioni di analisi e all’avvio di Ghidra richiesto da una chiamata: sono una scelta del nostro ambiente, non un requisito universale. + +Completiamo i controlli: + +```bash +rea doctor --client codex --provider ghidra --json +rea doctor --skill --json +rea mcp doctor --json +``` + +Cercare `healthy: true` nei controlli selezionati, quindi chiudere e riaprire Codex. Un primo prompt può essere: + +```text +Usa REA per verificare la versione del server e la disponibilità di Ghidra, +senza aprire alcun file. +``` + +Questi controlli verificano la disponibilità degli strumenti. L’analisi di un programma costituisce una verifica successiva. + +### Preparare il laboratorio di analisi + +L’installazione sul Mac serve a rendere disponibili gli strumenti all’agente. L’analisi del malware è stata svolta in un **laboratorio Linux/amd64 separato, in Docker Desktop**, con REA 6.5.0 e Node 24.22.0. La configurazione dell’host e quella del container sono due ambienti distinti. + +Un eseguibile Windows può essere studiato staticamente da Linux: per leggere struttura, stringhe e codice non occorre avviarlo su Windows. Nel nostro caso non è stato usato Wine e non sono stati eseguiti il campione, il JavaScript estratto o eventuali PE. + +Prima dell’analisi erano state preparate l’immagine e le dipendenze. Durante l’ispezione, il container aveva rete `none`, filesystem radice in sola lettura, utente non privilegiato, capability rimosse e `no-new-privileges`. Il campione era montato in sola lettura; le scritture erano limitate alla cartella del caso e alle aree temporanee del container. + +**Avviare Docker non applica automaticamente queste condizioni.** Il laboratorio va configurato e controllato esplicitamente. Il container limita l’accesso degli strumenti al sistema e alla rete; in questo lavoro il vincolo principale resta l’analisi esclusivamente statica. + +Anche la rete del laboratorio e la connessione usata da Codex sono piani diversi: il container può essere offline mentre l’agente comunica con il servizio del modello. “Offline” non significa quindi che l’intero flusso AI sia privo di comunicazioni esterne; occorre considerarlo quando si trattano campioni o evidenze riservati.