示例工程 44-threat-model

44-threat-model/app/main/index.ts

typescript · 16 KB

import { app, BrowserWindow, ipcMain, session } from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
import {
  CH,
  type AttackReport,
  type Check,
  type EventRow,
  type RuntimeProbe,
  type Scenario,
  type Snapshot,
  type Verdict,
} from "../shared/ipc";
import {
  isAllowedNavigation,
  pluginAllowed,
  resolveInsideWorkspace,
  verifyUpdate,
} from "../shared/policy";

app.setName("Threat Model Lab");

const isSmoke =
  process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
const isShots = process.argv.includes("--shots");
const tempData =
  isSmoke || isShots
    ? path.join(
        os.tmpdir(),
        `threat-${isSmoke ? "smoke" : "shots"}-${process.pid}`,
      )
    : "";
if (tempData) app.setPath("userData", tempData);

const userData = app.getPath("userData");
const workspace = path.join(userData, "workspace");
const config = {
  contextIsolation: true,
  sandbox: true,
  nodeIntegration: false,
  webSecurity: true,
  allowRunningInsecureContent: false,
  experimentalFeatures: false,
  webviewTag: false,
};
const flags = {
  navigationGuard: false,
  windowOpenDenied: false,
  permissionDenied: false,
  webviewBlocked: false,
};

let win: BrowserWindow | null = null;
let runtime: RuntimeProbe = {
  csp: "",
  requireType: "unknown",
  processType: "unknown",
  probedAt: 0,
};
let events: EventRow[] = [];

function log(kind: string, detail: string): void {
  events = [{ at: Date.now(), kind, detail }, ...events].slice(0, 40);
  broadcast();
}

function broadcast(): void {
  if (win && !win.isDestroyed()) {
    win.webContents.send("threat:event", { at: Date.now() });
  }
}

function attacks(): AttackReport {
  const nav = [
    ["docs.xwrt.dev", "https://docs.xwrt.dev/security"],
    ["javascript:", "javascript:alert(1)"],
    ["file:", "file:///etc/passwd"],
    ["evil.example", "https://evil.example/"],
  ] as const;
  const paths = [
    ["inside", "notes/readme.md"],
    ["dot-dot", "../../etc/passwd"],
    ["absolute", "/etc/passwd"],
  ] as const;
  const updates = [
    [
      "good",
      {
        current: "1.0.0",
        next: "1.2.0",
        hash: "abc",
        expectedHash: "abc",
        signed: true,
      },
    ],
    [
      "bad-hash",
      {
        current: "1.0.0",
        next: "1.2.0",
        hash: "bad",
        expectedHash: "abc",
        signed: true,
      },
    ],
    [
      "unsigned",
      {
        current: "1.0.0",
        next: "1.2.0",
        hash: "abc",
        expectedHash: "abc",
        signed: false,
      },
    ],
    [
      "downgrade",
      {
        current: "1.0.0",
        next: "0.9.0",
        hash: "abc",
        expectedHash: "abc",
        signed: true,
      },
    ],
  ] as const;
  const plugins = [
    [
      "bundled-signed",
      { bundled: true, signed: true, path: "/app/plugins/a.node" },
    ],
    [
      "userData-unsigned",
      { bundled: false, signed: false, path: "/userData/plugins/a.node" },
    ],
    [
      "bundled-unsigned",
      { bundled: true, signed: false, path: "/app/plugins/a.node" },
    ],
  ] as const;

  const navigation: Verdict[] = nav.map(([label, url]) => {
    const result = isAllowedNavigation(url);
    return { label, allowed: result.allowed, reason: result.reason };
  });
  const pathVerdicts: Verdict[] = paths.map(([label, candidate]) => {
    const result = resolveInsideWorkspace(workspace, candidate);
    return { label, allowed: result.ok, reason: result.reason };
  });
  const updateVerdicts: Verdict[] = updates.map(([label, input]) => {
    const result = verifyUpdate(input);
    return { label, allowed: result.allowed, reason: result.reason };
  });
  const pluginVerdicts: Verdict[] = plugins.map(([label, input]) => {
    const result = pluginAllowed(input);
    return { label, allowed: result.allowed, reason: result.reason };
  });
  return {
    navigation,
    path: pathVerdicts,
    update: updateVerdicts,
    plugin: pluginVerdicts,
  };
}

function checks(): Check[] {
  const csp = runtime.csp;
  return [
    {
      id: "contextIsolation",
      label: "contextIsolation = true",
      pass: config.contextIsolation,
      detail: String(config.contextIsolation),
    },
    {
      id: "sandbox",
      label: "sandbox = true",
      pass: config.sandbox,
      detail: String(config.sandbox),
    },
    {
      id: "nodeIntegration",
      label: "nodeIntegration = false",
      pass: !config.nodeIntegration,
      detail: String(config.nodeIntegration),
    },
    {
      id: "webSecurity",
      label: "webSecurity = true",
      pass: config.webSecurity,
      detail: String(config.webSecurity),
    },
    {
      id: "webview",
      label: "webviewTag = false",
      pass: !config.webviewTag && flags.webviewBlocked,
      detail: String(config.webviewTag),
    },
    {
      id: "navigation",
      label: "导航白名单 + 新窗口拒绝",
      pass: flags.navigationGuard && flags.windowOpenDenied,
      detail: `${flags.navigationGuard}/${flags.windowOpenDenied}`,
    },
    {
      id: "permission",
      label: "权限请求默认拒绝",
      pass: flags.permissionDenied,
      detail: String(flags.permissionDenied),
    },
    {
      id: "csp",
      label: "CSP default-src 'self' 且无 unsafe-eval",
      pass:
        csp.includes("default-src 'self'") &&
        csp.includes("script-src 'self'") &&
        !csp.includes("unsafe-eval"),
      detail: csp.includes("default-src 'self'") ? "present" : "missing",
    },
    {
      id: "require",
      label: "渲染进程没有 require",
      pass: runtime.requireType === "undefined",
      detail: runtime.requireType,
    },
    {
      id: "process",
      label: "渲染进程没有 process",
      pass: runtime.processType === "undefined",
      detail: runtime.processType,
    },
  ];
}

function scenarios(): Scenario[] {
  const report = attacks();
  const webpageBlocked =
    report.navigation[0]?.allowed === true &&
    report.navigation.slice(1).every((item) => !item.allowed);
  const fileBlocked =
    report.path[0]?.allowed === true &&
    report.path.slice(1).every((item) => !item.allowed);
  const updateBlocked =
    report.update[0]?.allowed === true &&
    report.update.slice(1).every((item) => !item.allowed);
  const pluginBlocked =
    report.plugin[0]?.allowed === true &&
    report.plugin.slice(1).every((item) => !item.allowed);
  return [
    {
      id: "malicious-webpage",
      title: "恶意网页 / 导航",
      severity: "high",
      status: webpageBlocked ? "blocked" : "residual",
      controls: [
        "will-navigate 白名单",
        "setWindowOpenHandler deny",
        "CSP default-src 'self'",
      ],
    },
    {
      id: "malicious-file",
      title: "恶意文件 / 路径穿越",
      severity: "high",
      status: fileBlocked ? "blocked" : "residual",
      controls: [
        "resolveInsideWorkspace",
        "拒绝 .. 与绝对路径",
        "扩展名与大小限制",
      ],
    },
    {
      id: "malicious-update",
      title: "恶意更新包",
      severity: "high",
      status: updateBlocked ? "blocked" : "residual",
      controls: ["版本必须更新", "签名校验", "哈希匹配"],
    },
    {
      id: "malicious-plugin",
      title: "恶意插件 / 原生模块",
      severity: "high",
      status: pluginBlocked ? "blocked" : "residual",
      controls: ["只加载随包签名模块", "拒绝 userData 可写路径", "导出白名单"],
    },
    {
      id: "local-attacker",
      title: "本机同用户攻击",
      severity: "residual",
      status: "residual",
      controls: [
        "safeStorage 设备绑定",
        "最小权限",
        "无法完全防御同用户恶意软件",
      ],
    },
  ];
}

function snapshot(): Snapshot {
  const list = checks();
  const passed = list.filter((check) => check.pass).length;
  return {
    platform: process.platform,
    electronVersion: process.versions.electron,
    nodeVersion: process.versions.node,
    checks: list,
    score: Math.round((passed / list.length) * 100),
    scenarios: scenarios(),
    attacks: attacks(),
    runtime: { ...runtime },
    events: events.map((row) => ({ ...row })),
  };
}

async function probe(window: BrowserWindow): Promise<void> {
  try {
    const result = await window.webContents.executeJavaScript(`(() => {
      const meta = document.querySelector('meta[http-equiv="Content-Security-Policy"]');
      return {
        csp: meta ? meta.getAttribute('content') || '' : '',
        requireType: typeof window.require,
        processType: typeof window.process
      };
    })()`);
    runtime = {
      csp: String((result as { csp?: string }).csp ?? ""),
      requireType: String(
        (result as { requireType?: string }).requireType ?? "unknown",
      ),
      processType: String(
        (result as { processType?: string }).processType ?? "unknown",
      ),
      probedAt: Date.now(),
    };
    log(
      "probe",
      `CSP ${runtime.csp ? "present" : "missing"} · require ${runtime.requireType}`,
    );
  } catch (error) {
    log("probe-error", error instanceof Error ? error.message : String(error));
  }
  broadcast();
}

function resolvePreload(): string {
  const candidates = [
    path.join(__dirname, "preload.cjs"),
    path.join(__dirname, "../preload/index.cjs"),
    path.join(__dirname, "preload.js"),
  ];
  return (
    candidates.find((candidate) => fsSync.existsSync(candidate)) ??
    candidates[0] ??
    ""
  );
}

function createWindow(): BrowserWindow {
  const window = new BrowserWindow({
    width: 1100,
    height: 860,
    show: false,
    title: "威胁模型实验室",
    backgroundColor: "#ffffff",
    webPreferences: {
      preload: resolvePreload(),
      contextIsolation: true,
      sandbox: true,
      nodeIntegration: false,
      webSecurity: true,
      allowRunningInsecureContent: false,
      experimentalFeatures: false,
      webviewTag: false,
      spellcheck: false,
      backgroundThrottling: true,
    },
  });
  const contents = window.webContents;
  contents.setWindowOpenHandler(({ url }) => {
    log("window-open", `拒绝 ${url}`);
    return { action: "deny" };
  });
  flags.windowOpenDenied = true;
  contents.on("will-navigate", (event, url) => {
    const appFile = pathToFileURL(app.getAppPath()).href;
    if (url.startsWith(appFile)) return;
    if (
      MAIN_WINDOW_VITE_DEV_SERVER_URL &&
      url.startsWith(MAIN_WINDOW_VITE_DEV_SERVER_URL)
    )
      return;
    const result = isAllowedNavigation(url);
    if (!result.allowed) {
      event.preventDefault();
      log("navigation", `拦截 ${url} · ${result.reason}`);
    }
  });
  flags.navigationGuard = true;
  contents.on("will-attach-webview", (event) => {
    event.preventDefault();
    log("webview", "拒绝 attach webview");
  });
  flags.webviewBlocked = true;
  session.defaultSession.setPermissionRequestHandler(
    (_webContents, permission, callback) => {
      log("permission", `拒绝 ${permission}`);
      callback(false);
    },
  );
  flags.permissionDenied = true;
  window.once("ready-to-show", () => window.show());
  contents.once("did-finish-load", () => {
    if (!window.isDestroyed() && !window.isVisible()) window.show();
    log("ready", "威胁模型界面已加载");
    void probe(window);
  });
  if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
    void window.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
  } else {
    void window.loadFile(
      path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`),
    );
  }
  win = window;
  return window;
}

function delay(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function evalRenderer<T>(
  window: BrowserWindow,
  code: string,
): Promise<T> {
  let lastError: unknown = null;
  for (let attempt = 0; attempt < 3; attempt += 1) {
    try {
      return (await window.webContents.executeJavaScript(code)) as T;
    } catch (caught) {
      lastError = caught;
      await delay(200);
    }
  }
  throw lastError instanceof Error ? lastError : new Error(String(lastError));
}

async function waitForRenderer(window: BrowserWindow): Promise<void> {
  for (let attempt = 0; attempt < 160; attempt += 1) {
    if (window.isDestroyed()) return;
    try {
      const ready = await evalRenderer<boolean>(
        window,
        "typeof window.__smoke === 'function'",
      );
      if (ready) return;
    } catch {
      // 页面仍在加载。
    }
    await delay(100);
  }
  throw new Error("renderer did not become ready");
}

type SmokeResult = {
  score: number;
  checks: number;
  passed: number;
  scenarios: number;
  blocked: number;
  residual: number;
  navAllowed: number;
  navBlocked: number;
  pathAllowed: number;
  pathBlocked: number;
  updateAllowed: number;
  updateBlocked: number;
  pluginAllowed: number;
  pluginBlocked: number;
  requireType: string;
  processType: string;
  requireError: string;
  csp: string;
  events: number;
};

async function runSmoke(window: BrowserWindow): Promise<void> {
  try {
    await waitForRenderer(window);
    await delay(900);
    await waitForRenderer(window);
    const result = await evalRenderer<SmokeResult>(window, "window.__smoke()");
    process.stdout.write(
      `${JSON.stringify({
        evt: "smoke",
        ok:
          result.score === 100 &&
          result.checks === 10 &&
          result.passed === 10 &&
          result.scenarios === 5 &&
          result.blocked === 4 &&
          result.residual === 1 &&
          result.navAllowed === 1 &&
          result.navBlocked === 3 &&
          result.pathAllowed === 1 &&
          result.pathBlocked === 2 &&
          result.updateAllowed === 1 &&
          result.updateBlocked === 3 &&
          result.pluginAllowed === 1 &&
          result.pluginBlocked === 2 &&
          result.requireType === "undefined" &&
          result.processType === "undefined" &&
          result.requireError.includes("not a function") &&
          result.csp.includes("default-src 'self'") &&
          !result.csp.includes("unsafe-eval") &&
          result.events >= 3,
        ...result,
      })}\n`,
    );
    app.quit();
  } catch (caught) {
    process.stdout.write(
      `${JSON.stringify({ evt: "smoke", ok: false, message: String(caught) })}\n`,
    );
    app.exit(1);
  }
}

async function capture(
  window: BrowserWindow,
  dir: string,
  file: string,
): Promise<void> {
  const image = await window.webContents.capturePage();
  if (image.isEmpty()) throw new Error(`empty capture: ${file}`);
  const png = image.toPNG();
  fsSync.writeFileSync(path.join(dir, file), png);
  fsSync.writeFileSync(path.join(dir, "raw", file), png);
}

async function runShots(window: BrowserWindow): Promise<void> {
  try {
    const dir = path.resolve(
      process.cwd(),
      "../../../docs/assets/images/44-threat-model",
    );
    fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
    await waitForRenderer(window);
    await delay(900);
    await waitForRenderer(window);
    await evalRenderer(window, `window.__prepareShots("boundaries")`);
    await delay(300);
    await capture(window, dir, "44-01-boundaries.png");
    await evalRenderer(window, `window.__prepareShots("attacks")`);
    await delay(300);
    await capture(window, dir, "44-02-attacks.png");
    await evalRenderer(window, `window.__prepareShots("checklist")`);
    await delay(500);
    await capture(window, dir, "44-03-checklist.png");
    app.quit();
  } catch (caught) {
    process.stdout.write(
      `${JSON.stringify({ evt: "shots-error", message: String(caught) })}\n`,
    );
    app.exit(1);
  }
}

ipcMain.handle(CH.snapshot, () => snapshot());

ipcMain.handle(CH.probe, async () => {
  if (win) await probe(win);
  return snapshot();
});

ipcMain.handle(CH.refresh, async () => {
  if (win) await probe(win);
  log("refresh", "重新检查安全配置");
  return snapshot();
});

app.whenReady().then(() => {
  fsSync.mkdirSync(workspace, { recursive: true });
  const window = createWindow();
  if (isSmoke) {
    void runSmoke(window);
  } else if (isShots) {
    void runShots(window);
  }
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    } else {
      win?.show();
      win?.focus();
    }
  });
});

app.on("will-quit", () => {
  if (tempData) {
    try {
      fsSync.rmSync(tempData, { recursive: true, force: true });
    } catch {
      // 清理失败不影响退出。
    }
  }
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") app.quit();
});