feat(ghidra): enable Windows x64 read-only analysis (#699)
* feat(ghidra): enable Windows x64 read-only analysis * test(ghidra): exercise native Windows runtime boundaries * test(ghidra): verify current Windows inventory and isolate ACL observer * fix(ghidra): align Windows admission and address P0 review
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createDoctorHostFixture } from "../../../src/application/Doctor.fixture.js";
|
||||
import { systemSetupHost } from "../../../src/application/SetupHost.js";
|
||||
import { runSetup } from "../../../src/application/Setup.js";
|
||||
import { options } from "../../../src/application/Setup.fixture.js";
|
||||
import { supportedClients } from "../../../src/application/SupportedClients.js";
|
||||
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("setup with configured but unavailable providers", () => {
|
||||
it("preserves Hopper settings and makes the second setup perform no writes", async () => {
|
||||
const root = await createTestTempDirectory("rea-setup-unavailable-");
|
||||
roots.push(root);
|
||||
const client = supportedClients(root, "darwin", {}).find(
|
||||
(candidate) => candidate.name === "cursor",
|
||||
);
|
||||
if (client === undefined) throw new Error("Cursor registration is missing");
|
||||
const original = '{"theme":"dark"}\n';
|
||||
await mkdir(dirname(client.configPath), { recursive: true });
|
||||
await writeFile(client.configPath, original);
|
||||
const environment = { HOPPER_LAUNCHER_PATH: "/custom/Hopper" };
|
||||
const doctor = createDoctorHostFixture({
|
||||
validTarget: () => Promise.resolve(false),
|
||||
executable: () => Promise.resolve(false),
|
||||
clientRegistrations: () =>
|
||||
readClientRegistrationStatuses(root, undefined, {
|
||||
platform: "darwin",
|
||||
environment: {},
|
||||
}),
|
||||
providerInspections: () =>
|
||||
Promise.resolve([
|
||||
{
|
||||
id: "hopper",
|
||||
configured: true,
|
||||
available: false,
|
||||
providerVersion: "6",
|
||||
registrationEnvironment: environment,
|
||||
checks: [
|
||||
{
|
||||
name: "hopper-license",
|
||||
ok: false,
|
||||
code: "unavailable",
|
||||
detail: "Runtime license is unavailable",
|
||||
classification: "missing_analysis_engine",
|
||||
remediation: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
]),
|
||||
});
|
||||
const host = {
|
||||
...systemSetupHost(doctor),
|
||||
detectedClients: () => Promise.resolve([client]),
|
||||
supportedClients: () => Promise.resolve([client]),
|
||||
};
|
||||
const selected = {
|
||||
...options(true),
|
||||
clientIds: ["cursor"],
|
||||
installSkill: false,
|
||||
proposeHopper: false,
|
||||
// This lane checks registration effects; no deep provider is required.
|
||||
readinessScope: { clients: [], providers: [], skill: false },
|
||||
};
|
||||
const first = await runSetup(selected, host);
|
||||
expect(first.status).toBe("ready");
|
||||
expect(first.clients.cursor).toMatchObject({ status: "configured" });
|
||||
const configured = await readFile(client.configPath, "utf8");
|
||||
expect(JSON.parse(configured)).toMatchObject({
|
||||
theme: "dark",
|
||||
mcpServers: { rea: { env: environment } },
|
||||
});
|
||||
await expect(
|
||||
readFile(`${client.configPath}.rea.backup`, "utf8"),
|
||||
).resolves.toBe(original);
|
||||
|
||||
const second = await runSetup(selected, host);
|
||||
expect(second.status).toBe("ready");
|
||||
expect(second.plannedActions).toEqual([]);
|
||||
expect(second.appliedActions).toEqual([]);
|
||||
await expect(readFile(client.configPath, "utf8")).resolves.toBe(configured);
|
||||
await expect(
|
||||
readFile(`${client.configPath}.rea.backup`, "utf8"),
|
||||
).resolves.toBe(original);
|
||||
});
|
||||
});
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
spawnOwnedProviderProcess,
|
||||
type ProviderProcessDiagnostic,
|
||||
} from "../../../src/process/ProviderProcess.js";
|
||||
import { WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON } from "../../../src/process/WindowsAuthority.js";
|
||||
import {
|
||||
spawnProviderProcessFixture,
|
||||
stopProviderProcessFixture,
|
||||
@@ -69,7 +70,7 @@ describe("provider process runtime and wait primitives", () => {
|
||||
PrivateRuntimeRoot.create({ platform: "win32" }),
|
||||
).rejects.toMatchObject({
|
||||
code: "private-runtime-root-authority-unavailable",
|
||||
message: expect.stringContaining("chmod(0700)"),
|
||||
message: WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ import { fileURLToPath } from "node:url";
|
||||
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
import { createGhidraTestRuntime } from "../../../fixtures/ghidraRuntime.js";
|
||||
import type { PrivateRuntimeRoot } from "../../../../src/process/PrivateRuntimeRoot.js";
|
||||
|
||||
import {
|
||||
ghidraHeadlessArguments,
|
||||
@@ -21,6 +23,7 @@ const fixturePath = fileURLToPath(
|
||||
),
|
||||
);
|
||||
const roots: string[] = [];
|
||||
const runtimes: PrivateRuntimeRoot[] = [];
|
||||
|
||||
const expectIsolatedEnvironment = (
|
||||
environment: Record<string, string>,
|
||||
@@ -32,6 +35,8 @@ const expectIsolatedEnvironment = (
|
||||
...(process.platform === "win32"
|
||||
? {
|
||||
USERPROFILE: join(runtimeRoot, "home"),
|
||||
APPDATA: join(runtimeRoot, "config"),
|
||||
LOCALAPPDATA: join(runtimeRoot, "cache"),
|
||||
TEMP: join(runtimeRoot, "tmp"),
|
||||
TMP: join(runtimeRoot, "tmp"),
|
||||
}
|
||||
@@ -42,7 +47,10 @@ const expectIsolatedEnvironment = (
|
||||
XDG_DATA_HOME: join(runtimeRoot, "data"),
|
||||
GHIDRA_JAVA_OPTIONS: "",
|
||||
JAVA_TOOL_OPTIONS: "",
|
||||
JDK_JAVA_OPTIONS: "",
|
||||
JDK_JAVA_OPTIONS:
|
||||
process.platform === "win32"
|
||||
? `"-Duser.home=${join(runtimeRoot, "home")}" "-Djava.io.tmpdir=${join(runtimeRoot, "tmp")}" "-XX:-UsePerfData"`
|
||||
: "",
|
||||
_JAVA_OPTIONS: "",
|
||||
JAVA_HOME: javaHome,
|
||||
REA_PROCESS_RUN_ID: "d6fcbb66-e829-4ff6-a535-0035aec63139",
|
||||
@@ -59,6 +67,7 @@ beforeAll(async () => {
|
||||
});
|
||||
afterEach(async () => {
|
||||
vi.unstubAllEnvs();
|
||||
await Promise.all(runtimes.splice(0).map((runtime) => runtime.close()));
|
||||
await Promise.all(
|
||||
roots.splice(0).map((path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
@@ -191,8 +200,11 @@ describe("Ghidra headless launcher", () => {
|
||||
vi.stubEnv("JAVA_TOOL_OPTIONS", "-Duser.home=/unapproved/home");
|
||||
vi.stubEnv("JDK_JAVA_OPTIONS", "-XX:MaxRAMPercentage=99");
|
||||
vi.stubEnv("_JAVA_OPTIONS", "-Xmx99G");
|
||||
const runtimeRoot = await createTestTempDirectory("rea-launcher-test-");
|
||||
roots.push(runtimeRoot);
|
||||
const parent = await createTestTempDirectory("rea-launcher-test-");
|
||||
roots.push(parent);
|
||||
const runtime = await createGhidraTestRuntime(parent);
|
||||
runtimes.push(runtime);
|
||||
const runtimeRoot = runtime.path;
|
||||
const token = "secret-token-that-must-not-leak";
|
||||
const javaHome =
|
||||
process.platform === "win32" ? "C:\\Java\\jdk-21" : "/opt/jdk-21";
|
||||
@@ -226,16 +238,11 @@ describe("Ghidra headless launcher", () => {
|
||||
descriptor_has_token: true,
|
||||
});
|
||||
expectIsolatedEnvironment(capture.environment, runtimeRoot, javaHome);
|
||||
expect(capture.environment.GHIDRA_HEADLESS_JAVA_OPTIONS).toContain(
|
||||
`-Duser.home=${join(runtimeRoot, "home")}`,
|
||||
);
|
||||
expect(capture.environment.GHIDRA_HEADLESS_JAVA_OPTIONS).toBe(
|
||||
`-Duser.home=${join(runtimeRoot, "home")} -Djava.io.tmpdir=${join(runtimeRoot, "tmp")}`,
|
||||
process.platform === "win32"
|
||||
? ""
|
||||
: `-Duser.home=${join(runtimeRoot, "home")} -Djava.io.tmpdir=${join(runtimeRoot, "tmp")}`,
|
||||
);
|
||||
if (process.platform === "win32")
|
||||
expect(capture.environment.GHIDRA_HEADLESS_JAVA_OPTIONS).not.toContain(
|
||||
'"',
|
||||
);
|
||||
if (process.platform !== "win32")
|
||||
expect(
|
||||
(await stat(join(runtimeRoot, "ownership.json"))).mode & 0o777,
|
||||
|
||||
@@ -5,18 +5,38 @@ import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
import { createGhidraTestRuntime } from "../../../fixtures/ghidraRuntime.js";
|
||||
import type { PrivateRuntimeRoot } from "../../../../src/process/PrivateRuntimeRoot.js";
|
||||
|
||||
import { createGhidraTargetSnapshot } from "../../../../src/ghidra/GhidraTargetSnapshot.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
const runtimes: PrivateRuntimeRoot[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(runtimes.splice(0).map((runtime) => runtime.close()));
|
||||
await Promise.all(
|
||||
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("Ghidra target snapshot", () => {
|
||||
it("uses the selected installation platform instead of the ambient host", async () => {
|
||||
const root = await createTestTempDirectory("rea-ghidra-platform-");
|
||||
roots.push(root);
|
||||
const source = join(root, "source.exe");
|
||||
const bytes = Buffer.from("platform fixture");
|
||||
const sha256 = createHash("sha256").update(bytes).digest("hex");
|
||||
await writeFile(source, bytes);
|
||||
const snapshot = await createGhidraTargetSnapshot(source, root, sha256, {
|
||||
platform: "linux",
|
||||
});
|
||||
expect(snapshot.admission).toBeUndefined();
|
||||
await expect(readFile(snapshot.path)).resolves.toEqual(bytes);
|
||||
await expect(
|
||||
createGhidraTargetSnapshot(source, root, sha256, { platform: "win32" }),
|
||||
).rejects.toThrow(/No native private runtime owns/u);
|
||||
});
|
||||
it("copies an exact digest-bound target into the private runtime", async () => {
|
||||
const root = await createTestTempDirectory("rea-ghidra-snapshot-");
|
||||
roots.push(root);
|
||||
@@ -24,27 +44,39 @@ describe("Ghidra target snapshot", () => {
|
||||
const bytes = Buffer.from("native PE fixture");
|
||||
const sha256 = createHash("sha256").update(bytes).digest("hex");
|
||||
await writeFile(source, bytes);
|
||||
const runtime = await createGhidraTestRuntime(root);
|
||||
runtimes.push(runtime);
|
||||
|
||||
const snapshot = await createGhidraTargetSnapshot(source, root, sha256);
|
||||
const snapshot = await createGhidraTargetSnapshot(
|
||||
source,
|
||||
runtime.path,
|
||||
sha256,
|
||||
);
|
||||
|
||||
expect(snapshot).toEqual({
|
||||
path: join(root, `target-${sha256.slice(0, 12)}.exe`),
|
||||
expect(snapshot).toMatchObject({
|
||||
path: join(runtime.path, `target-${sha256.slice(0, 12)}.exe`),
|
||||
sha256,
|
||||
});
|
||||
await expect(readFile(snapshot.path)).resolves.toEqual(bytes);
|
||||
});
|
||||
|
||||
it("removes a snapshot whose digest differs from admission", async () => {
|
||||
it("rejects a mismatched digest and removes the failed runtime snapshot", async () => {
|
||||
const root = await createTestTempDirectory("rea-ghidra-snapshot-");
|
||||
roots.push(root);
|
||||
const source = join(root, "source with unsafe extension.%PATH%");
|
||||
await writeFile(source, "changed target");
|
||||
const runtime = await createGhidraTestRuntime(root);
|
||||
runtimes.push(runtime);
|
||||
const expected = "a".repeat(64);
|
||||
const snapshotPath = join(root, `target-${expected.slice(0, 12)}.bin`);
|
||||
const snapshotPath = join(
|
||||
runtime.path,
|
||||
`target-${expected.slice(0, 12)}.bin`,
|
||||
);
|
||||
|
||||
await expect(
|
||||
createGhidraTargetSnapshot(source, root, expected),
|
||||
createGhidraTargetSnapshot(source, runtime.path, expected),
|
||||
).rejects.toThrow(/digest mismatch/u);
|
||||
await runtime.close();
|
||||
await expect(access(snapshotPath)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
|
||||
@@ -4,12 +4,19 @@ import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
import {
|
||||
createGhidraTestRuntime,
|
||||
publishGhidraTestEndpoint,
|
||||
} from "../../../fixtures/ghidraRuntime.js";
|
||||
import type { PrivateRuntimeRoot } from "../../../../src/process/PrivateRuntimeRoot.js";
|
||||
|
||||
import { observeGhidraEndpoint } from "../../../../src/ghidra/GhidraTransport.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
const runtimes: PrivateRuntimeRoot[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(runtimes.splice(0).map((runtime) => runtime.close()));
|
||||
await Promise.all(
|
||||
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
|
||||
);
|
||||
@@ -33,9 +40,10 @@ describe("Ghidra local transport", () => {
|
||||
it("accepts only an exact IPv4 loopback endpoint record", async () => {
|
||||
const root = await createTestTempDirectory("rea-ghidra-transport-");
|
||||
roots.push(root);
|
||||
const path = join(root, "bridge-endpoint.json");
|
||||
await writeFile(
|
||||
path,
|
||||
const runtime = await createGhidraTestRuntime(root);
|
||||
runtimes.push(runtime);
|
||||
const path = await publishGhidraTestEndpoint(
|
||||
runtime,
|
||||
`${JSON.stringify({ host: "127.0.0.1", port: 49152 })}\n`,
|
||||
);
|
||||
|
||||
@@ -59,8 +67,12 @@ describe("Ghidra local transport", () => {
|
||||
async (value) => {
|
||||
const root = await createTestTempDirectory("rea-ghidra-transport-");
|
||||
roots.push(root);
|
||||
const path = join(root, "bridge-endpoint.json");
|
||||
await writeFile(path, JSON.stringify(value));
|
||||
const runtime = await createGhidraTestRuntime(root);
|
||||
runtimes.push(runtime);
|
||||
const path = await publishGhidraTestEndpoint(
|
||||
runtime,
|
||||
JSON.stringify(value),
|
||||
);
|
||||
|
||||
await expect(
|
||||
observeGhidraEndpoint({
|
||||
|
||||
@@ -35,7 +35,7 @@ describe("real Windows Ghidra workflow trust boundary", () => {
|
||||
expect.objectContaining({
|
||||
uses: "actions/upload-artifact@v4",
|
||||
with: expect.objectContaining({
|
||||
path: "windows-ghidra-proof.log",
|
||||
path: expect.stringContaining("windows-ghidra-proof.log"),
|
||||
}),
|
||||
}),
|
||||
]),
|
||||
|
||||
@@ -12,6 +12,23 @@ const dependencies = (
|
||||
): WindowsCapabilityDependencies => ({
|
||||
platform: "win32",
|
||||
architecture: "x64",
|
||||
nativeCapabilities: () => ({
|
||||
job_object_process_ownership: {
|
||||
available: false,
|
||||
reason: WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
|
||||
proof: "not-proven",
|
||||
},
|
||||
private_runtime_dacl: {
|
||||
available: false,
|
||||
reason: WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
|
||||
proof: "not-proven",
|
||||
},
|
||||
reparse_safe_path_admission: {
|
||||
available: false,
|
||||
reason: WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
|
||||
proof: "not-proven",
|
||||
},
|
||||
}),
|
||||
probeSymlinkCreation: () =>
|
||||
Promise.resolve({ available: false, reason: "EPERM" }),
|
||||
probeNoFollowOpen: () => ({
|
||||
@@ -39,7 +56,8 @@ describe("Windows host capability report", () => {
|
||||
it("never treats a numeric POSIX flag as Windows reparse authority", () => {
|
||||
expect(systemNoFollowOpenCapability("win32", 0x20_000)).toEqual({
|
||||
available: false,
|
||||
reason: "Windows reparse-safe handle admission is not implemented",
|
||||
reason:
|
||||
"Node pathname O_NOFOLLOW is not Windows handle authority; native admission is reported separately in security.",
|
||||
});
|
||||
expect(systemNoFollowOpenCapability("linux", 0x20_000)).toEqual({
|
||||
available: true,
|
||||
|
||||
+2
@@ -15,6 +15,8 @@ await writeFile(
|
||||
environment: {
|
||||
HOME: process.env.HOME,
|
||||
USERPROFILE: process.env.USERPROFILE,
|
||||
APPDATA: process.env.APPDATA,
|
||||
LOCALAPPDATA: process.env.LOCALAPPDATA,
|
||||
TMPDIR: process.env.TMPDIR,
|
||||
TEMP: process.env.TEMP,
|
||||
TMP: process.env.TMP,
|
||||
|
||||
Vendored
+50
@@ -0,0 +1,50 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { PrivateRuntimeRoot } from "../../src/process/PrivateRuntimeRoot.js";
|
||||
import type { ProcessCleanupResult } from "../../src/process/ProcessOwnership.js";
|
||||
import { spawnOwnedProviderProcess } from "../../src/process/ProviderProcess.js";
|
||||
|
||||
/** Allocate the same private runtime boundary used by the real Ghidra client. */
|
||||
export const createGhidraTestRuntime = (
|
||||
parent: string,
|
||||
): Promise<PrivateRuntimeRoot> =>
|
||||
PrivateRuntimeRoot.create({ parent, prefix: "rea-ghidra-test-" });
|
||||
|
||||
/** Publish a closed endpoint file with the provider child's actual file owner. */
|
||||
export const publishGhidraTestEndpoint = async (
|
||||
runtime: PrivateRuntimeRoot,
|
||||
content: string,
|
||||
): Promise<string> => {
|
||||
const path = join(runtime.path, "bridge-endpoint.json");
|
||||
if (process.platform !== "win32") {
|
||||
await writeFile(path, content, { flag: "wx" });
|
||||
return path;
|
||||
}
|
||||
const launched = await spawnOwnedProviderProcess({
|
||||
command: process.execPath,
|
||||
arguments: [
|
||||
"-e",
|
||||
"require('node:fs').writeFileSync(process.argv[1],process.argv[2],{flag:'wx'})",
|
||||
path,
|
||||
content,
|
||||
],
|
||||
runId: randomUUID(),
|
||||
});
|
||||
let cleanup: ProcessCleanupResult | undefined;
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
launched.process.once("error", reject);
|
||||
launched.process.once("close", (code: number | null) => {
|
||||
if (code === 0) resolve();
|
||||
else reject(new Error(`Endpoint fixture exited with code ${code}`));
|
||||
});
|
||||
});
|
||||
} finally {
|
||||
cleanup = await launched.cleanup?.();
|
||||
}
|
||||
if (cleanup?.cleaned !== true)
|
||||
throw new Error("Endpoint fixture process cleanup was not verified");
|
||||
return path;
|
||||
};
|
||||
Vendored
+4
-3
@@ -1,5 +1,6 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { ProviderProcessHandle } from "../../src/process/ProviderProcess.js";
|
||||
|
||||
const fixturePath = fileURLToPath(
|
||||
new URL("./providerProcess.mjs", import.meta.url),
|
||||
@@ -18,7 +19,7 @@ export const spawnProviderProcessFixture = (
|
||||
|
||||
/** Wait until a long-lived fixture has installed its signal behavior. */
|
||||
export const waitForProviderProcessReady = (
|
||||
child: ChildProcess,
|
||||
child: ProviderProcessHandle,
|
||||
timeoutMs = 2_000,
|
||||
): Promise<void> =>
|
||||
new Promise((resolve, reject) => {
|
||||
@@ -54,7 +55,7 @@ export const waitForProviderProcessReady = (
|
||||
|
||||
/** Read the distinct process-group leader created by the detached-child mode. */
|
||||
export const waitForDetachedProviderChild = (
|
||||
child: ChildProcess,
|
||||
child: ProviderProcessHandle,
|
||||
timeoutMs = 2_000,
|
||||
): Promise<number> =>
|
||||
new Promise((resolve, reject) => {
|
||||
@@ -90,7 +91,7 @@ export const waitForDetachedProviderChild = (
|
||||
|
||||
/** Kill a fixture if necessary and wait for its process handle to settle. */
|
||||
export const stopProviderProcessFixture = async (
|
||||
child: ChildProcess,
|
||||
child: ProviderProcessHandle,
|
||||
): Promise<void> => {
|
||||
if (child.exitCode !== null || child.signalCode !== null) return;
|
||||
const exited = new Promise<void>((resolve) => {
|
||||
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
// Test-only launcher: reuse a non-elevated shell token belonging to the current user.
|
||||
// No accounts, host policies, profiles, or caller privileges are changed.
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#include <sddl.h>
|
||||
#include <tlhelp32.h>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
static std::wstring quote(const std::wstring& value) {
|
||||
std::wstring result = L"\"";
|
||||
size_t slashes = 0;
|
||||
for (const auto character : value) {
|
||||
if (character == L'\\') { ++slashes; continue; }
|
||||
result.append(slashes * (character == L'\"' ? 2 : 1), L'\\');
|
||||
slashes = 0;
|
||||
if (character == L'\"') result += L'\\';
|
||||
result += character;
|
||||
}
|
||||
result.append(slashes * 2, L'\\');
|
||||
return result + L"\"";
|
||||
}
|
||||
|
||||
int wmain(int count, wchar_t** args) {
|
||||
if (count < 3) return 64;
|
||||
HANDLE current = nullptr;
|
||||
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ADJUST_DEFAULT | TOKEN_ASSIGN_PRIMARY, ¤t)) return 65;
|
||||
std::vector<unsigned char> callerUser(4096); DWORD callerUserSize;
|
||||
if (!GetTokenInformation(current, TokenUser, callerUser.data(), callerUser.size(), &callerUserSize)) return 66;
|
||||
HANDLE primary = nullptr;
|
||||
const auto snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
|
||||
PROCESSENTRY32W entry{}; entry.dwSize = sizeof(entry);
|
||||
if (snapshot != INVALID_HANDLE_VALUE && Process32FirstW(snapshot, &entry)) do {
|
||||
if (_wcsicmp(entry.szExeFile, L"explorer.exe") != 0) continue;
|
||||
HANDLE candidate = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, entry.th32ProcessID);
|
||||
HANDLE token = nullptr;
|
||||
if (candidate && OpenProcessToken(candidate, TOKEN_QUERY | TOKEN_DUPLICATE, &token)) {
|
||||
TOKEN_ELEVATION elevation{}; DWORD size;
|
||||
std::vector<unsigned char> user(4096);
|
||||
if (GetTokenInformation(token, TokenElevation, &elevation, sizeof(elevation), &size) && !elevation.TokenIsElevated &&
|
||||
GetTokenInformation(token, TokenUser, user.data(), user.size(), &size) &&
|
||||
EqualSid(reinterpret_cast<TOKEN_USER*>(user.data())->User.Sid,
|
||||
reinterpret_cast<TOKEN_USER*>(callerUser.data())->User.Sid))
|
||||
DuplicateTokenEx(token, MAXIMUM_ALLOWED, nullptr, SecurityImpersonation, TokenPrimary, &primary);
|
||||
CloseHandle(token);
|
||||
}
|
||||
if (candidate) CloseHandle(candidate);
|
||||
if (primary) break;
|
||||
} while (Process32NextW(snapshot, &entry));
|
||||
if (snapshot != INVALID_HANDLE_VALUE) CloseHandle(snapshot);
|
||||
CloseHandle(current);
|
||||
if (!primary) { std::fprintf(stderr, "No non-elevated shell token belonging to the current user.\n"); return 67; }
|
||||
unsigned char medium[SECURITY_MAX_SID_SIZE]; DWORD mediumSize = sizeof(medium);
|
||||
if (!CreateWellKnownSid(WinMediumLabelSid, nullptr, medium, &mediumSize)) return 71;
|
||||
TOKEN_MANDATORY_LABEL label{{medium, SE_GROUP_INTEGRITY}};
|
||||
if (!SetTokenInformation(primary, TokenIntegrityLevel, &label, sizeof(label) + GetLengthSid(medium))) {
|
||||
std::fprintf(stderr, "Medium-integrity fixture token failed: %lu\n", GetLastError()); CloseHandle(primary); return 72;
|
||||
}
|
||||
std::wstring line;
|
||||
for (int index = 1; index < count; ++index) { if (index > 1) line += L' '; line += quote(args[index]); }
|
||||
std::vector<wchar_t> buffer(line.begin(), line.end()); buffer.push_back(0);
|
||||
std::vector<unsigned char> user(4096); DWORD userSize;
|
||||
if (!GetTokenInformation(primary, TokenUser, user.data(), user.size(), &userSize)) return 73;
|
||||
wchar_t* userSid = nullptr;
|
||||
if (!ConvertSidToStringSidW(reinterpret_cast<TOKEN_USER*>(user.data())->User.Sid, &userSid)) return 74;
|
||||
const std::wstring sddl = L"O:" + std::wstring(userSid) + L"D:P(A;;GA;;;" + userSid + L")(A;;GA;;;SY)S:(ML;;NW;;;ME)";
|
||||
LocalFree(userSid);
|
||||
PSECURITY_DESCRIPTOR descriptor = nullptr;
|
||||
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.c_str(), SDDL_REVISION_1, &descriptor, nullptr)) return 75;
|
||||
PACL acl = nullptr; BOOL present, defaulted;
|
||||
if (!GetSecurityDescriptorDacl(descriptor, &present, &acl, &defaulted) || !present) return 78;
|
||||
TOKEN_DEFAULT_DACL defaultDacl{acl};
|
||||
TOKEN_OWNER owner{reinterpret_cast<TOKEN_USER*>(user.data())->User.Sid};
|
||||
if (!SetTokenInformation(primary, TokenDefaultDacl, &defaultDacl, sizeof(defaultDacl)) ||
|
||||
!SetTokenInformation(primary, TokenOwner, &owner, sizeof(owner))) return 79;
|
||||
SECURITY_ATTRIBUTES security{sizeof(SECURITY_ATTRIBUTES), descriptor, FALSE};
|
||||
const auto stationName = L"rea-fixture-" + std::to_wstring(GetCurrentProcessId());
|
||||
const auto originalStation = GetProcessWindowStation();
|
||||
const auto station = CreateWindowStationW(stationName.c_str(), 0, WINSTA_ALL_ACCESS, &security);
|
||||
if (!station || !SetProcessWindowStation(station)) return 76;
|
||||
const auto desktop = CreateDesktopW(L"fixture", nullptr, nullptr, 0, GENERIC_ALL, &security);
|
||||
SetProcessWindowStation(originalStation); LocalFree(descriptor);
|
||||
if (!desktop) return 77;
|
||||
auto desktopName = stationName + L"\\fixture";
|
||||
STARTUPINFOW startup{}; startup.cb = sizeof(startup);
|
||||
startup.lpDesktop = desktopName.data();
|
||||
PROCESS_INFORMATION process{};
|
||||
auto environment = GetEnvironmentStringsW();
|
||||
wchar_t workingDirectory[32768]; GetCurrentDirectoryW(32768, workingDirectory);
|
||||
const BOOL started = CreateProcessWithTokenW(primary, 0, args[1], buffer.data(),
|
||||
CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW | BELOW_NORMAL_PRIORITY_CLASS,
|
||||
environment, workingDirectory, &startup, &process);
|
||||
const DWORD failure = GetLastError();
|
||||
FreeEnvironmentStringsW(environment); CloseHandle(primary);
|
||||
if (!started) { std::fprintf(stderr, "Non-admin fixture launch failed: %lu\n", failure); return 68; }
|
||||
HANDLE job = CreateJobObjectW(nullptr, nullptr);
|
||||
JOBOBJECT_EXTENDED_LIMIT_INFORMATION policy{};
|
||||
policy.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
||||
if (!job || !SetInformationJobObject(job, JobObjectExtendedLimitInformation, &policy, sizeof(policy)) ||
|
||||
!AssignProcessToJobObject(job, process.hProcess) || !SetProcessAffinityMask(process.hProcess, 3)) {
|
||||
TerminateProcess(process.hProcess, 69); CloseHandle(process.hThread); CloseHandle(process.hProcess);
|
||||
if (job) CloseHandle(job); return 69;
|
||||
}
|
||||
ResumeThread(process.hThread); CloseHandle(process.hThread);
|
||||
const DWORD waited = WaitForSingleObject(process.hProcess, 900000);
|
||||
DWORD code = 70;
|
||||
if (waited == WAIT_OBJECT_0) GetExitCodeProcess(process.hProcess, &code);
|
||||
CloseHandle(job); CloseHandle(process.hProcess);
|
||||
CloseDesktop(desktop); CloseWindowStation(station);
|
||||
return static_cast<int>(code);
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
// Independent Windows observations for the real native conformance lane.
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#include <windows.h>
|
||||
#include <winioctl.h>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
int wmain(int count, wchar_t** args) {
|
||||
if (count == 2 && std::wstring(args[1]) == L"environment") {
|
||||
wchar_t* block = GetEnvironmentStringsW();
|
||||
if (!block) return 7;
|
||||
std::wstring previous;
|
||||
bool sorted = true;
|
||||
for (const wchar_t* entry = block; *entry; entry += std::wcslen(entry) + 1) {
|
||||
const auto value = std::wstring(entry);
|
||||
const auto end = value.find(L'=', value.front() == L'=' ? 1 : 0);
|
||||
const auto name = value.substr(0, end);
|
||||
if (!previous.empty() && CompareStringOrdinal(previous.data(), previous.size(),
|
||||
name.data(), name.size(), TRUE) != CSTR_LESS_THAN)
|
||||
sorted = false;
|
||||
previous = name;
|
||||
}
|
||||
FreeEnvironmentStringsW(block);
|
||||
auto value = [](const wchar_t* name) {
|
||||
wchar_t text[128]{}; GetEnvironmentVariableW(name, text, 128); return std::wstring(text);
|
||||
};
|
||||
const auto sameUnicodeName = CompareStringOrdinal(L"REA_\u00df", -1, L"REA_SS", -1, TRUE) == CSTR_EQUAL;
|
||||
const auto expectedSharp = sameUnicodeName ? L"double" : L"sharp";
|
||||
std::printf("{\"ordinallySorted\":%s,\"lastDuplicateSelected\":%s,\"unicodeNamesPreserved\":%s}\n",
|
||||
sorted ? "true" : "false", value(L"REA_CASE") == L"last" ? "true" : "false",
|
||||
value(L"REA_\u00df") == expectedSharp && value(L"REA_SS") == L"double" ? "true" : "false");
|
||||
return 0;
|
||||
}
|
||||
if (count == 4 && std::wstring(args[1]) == L"reparse-directory") {
|
||||
// Only the conformance lane's disposable, nonempty source directory is used.
|
||||
const auto substitute = L"\\??\\" + std::wstring(args[3]);
|
||||
const auto substituteBytes = static_cast<WORD>(substitute.size() * sizeof(wchar_t));
|
||||
struct MountPoint {
|
||||
DWORD tag; WORD dataLength, reserved;
|
||||
WORD substituteOffset, substituteLength, printOffset, printLength;
|
||||
} header{IO_REPARSE_TAG_MOUNT_POINT, static_cast<WORD>(8 + substituteBytes + 4), 0,
|
||||
0, substituteBytes, static_cast<WORD>(substituteBytes + 2), 0};
|
||||
std::vector<unsigned char> buffer(sizeof(header) + substituteBytes + 4, 0);
|
||||
std::memcpy(buffer.data(), &header, sizeof(header));
|
||||
std::memcpy(buffer.data() + sizeof(header), substitute.data(), substituteBytes);
|
||||
HANDLE directory = CreateFileW(args[2], GENERIC_WRITE,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING,
|
||||
FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, nullptr);
|
||||
DWORD observed = directory == INVALID_HANDLE_VALUE ? GetLastError() : ERROR_SUCCESS;
|
||||
if (directory != INVALID_HANDLE_VALUE) {
|
||||
DWORD bytes;
|
||||
if (!DeviceIoControl(directory, FSCTL_SET_REPARSE_POINT, buffer.data(),
|
||||
static_cast<DWORD>(buffer.size()), nullptr, 0, &bytes, nullptr))
|
||||
observed = GetLastError();
|
||||
CloseHandle(directory);
|
||||
}
|
||||
std::printf("{\"reparseConversionDenied\":%s,\"win32Code\":%lu}\n",
|
||||
observed == ERROR_DIR_NOT_EMPTY || observed == ERROR_SHARING_VIOLATION || observed == ERROR_ACCESS_DENIED
|
||||
? "true" : "false", observed);
|
||||
return 0;
|
||||
}
|
||||
if (count > 1 && std::wstring(args[1]) == L"breakaway") {
|
||||
wchar_t executable[32768]; GetModuleFileNameW(nullptr, executable, 32768);
|
||||
std::wstring line = L"\"" + std::wstring(executable) + L"\" exit";
|
||||
STARTUPINFOW startup{}; startup.cb = sizeof(startup); PROCESS_INFORMATION child{};
|
||||
if (CreateProcessW(executable, line.data(), nullptr, nullptr, FALSE,
|
||||
CREATE_BREAKAWAY_FROM_JOB | CREATE_NO_WINDOW, nullptr, nullptr, &startup, &child)) {
|
||||
TerminateProcess(child.hProcess, 1); CloseHandle(child.hThread); CloseHandle(child.hProcess);
|
||||
std::puts("{\"breakawayDenied\":false}"); return 1;
|
||||
}
|
||||
std::printf("{\"breakawayDenied\":%s,\"win32Code\":%lu}\n",
|
||||
GetLastError() == ERROR_ACCESS_DENIED ? "true" : "false", GetLastError()); return 0;
|
||||
}
|
||||
HANDLE token = nullptr; DWORD size;
|
||||
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_DUPLICATE, &token)) return 2;
|
||||
TOKEN_ELEVATION elevation{};
|
||||
if (!GetTokenInformation(token, TokenElevation, &elevation, sizeof(elevation), &size)) return 3;
|
||||
std::vector<unsigned char> user(4096), owner(4096), integrity(4096);
|
||||
if (!GetTokenInformation(token, TokenUser, user.data(), user.size(), &size) ||
|
||||
!GetTokenInformation(token, TokenOwner, owner.data(), owner.size(), &size) ||
|
||||
!GetTokenInformation(token, TokenIntegrityLevel, integrity.data(), integrity.size(), &size)) return 4;
|
||||
HANDLE impersonation = nullptr;
|
||||
if (!DuplicateToken(token, SecurityIdentification, &impersonation)) return 5;
|
||||
unsigned char administrator[SECURITY_MAX_SID_SIZE]; DWORD administratorSize = sizeof(administrator);
|
||||
CreateWellKnownSid(WinBuiltinAdministratorsSid, nullptr, administrator, &administratorSize);
|
||||
BOOL member = TRUE;
|
||||
if (!CheckTokenMembership(impersonation, administrator, &member)) return 6;
|
||||
auto sid = reinterpret_cast<TOKEN_MANDATORY_LABEL*>(integrity.data())->Label.Sid;
|
||||
const auto level = *GetSidSubAuthority(sid, *GetSidSubAuthorityCount(sid) - 1);
|
||||
const bool ownerIsUser = EqualSid(reinterpret_cast<TOKEN_USER*>(user.data())->User.Sid,
|
||||
reinterpret_cast<TOKEN_OWNER*>(owner.data())->Owner);
|
||||
std::printf("{\"elevated\":%s,\"administrator\":%s,\"integrityLevel\":%lu,\"defaultOwnerIsUser\":%s}\n",
|
||||
elevation.TokenIsElevated ? "true" : "false", member ? "true" : "false", level,
|
||||
ownerIsUser ? "true" : "false");
|
||||
CloseHandle(impersonation); CloseHandle(token); return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user