Skip to content

Build your personal knowledge base with Trilium Notes

18.5 KB
Raw Blame
import { SHELL_OPEN_EXTERNAL_PROTOCOLS } from "@triliumnext/commons";
import { getBackup, getLog, utils as coreUtils } from "@triliumnext/core";
import dataDirs from "@triliumnext/server/src/services/data_dir.js";
import { execFile, spawn } from "child_process";
import electron from "electron";
import fs from "fs";
import { t } from "i18next";
import path from "path";
import url from "url";

/**
 * Handlers for `window.electronApi.shell.*` IPC channels.
 *
 * Each call is gated by an input validator that throws on any invariant
 * violation, so a hostile or buggy caller surfaces loudly in the main-process
 * log rather than silently triggering an OS-level action.
 */

//#region Shared helpers

/** Windows filesystems are case-insensitive, POSIX are case-sensitive. */
function normalizeForCompare(p: string): string {
    return process.platform === "win32" ? p.toLowerCase() : p;
}

/** True if `resolved` is a strict descendant of `root` (not `root` itself). */
function isStrictlyUnder(resolved: string, root: string): boolean {
    const prefix = path.resolve(root) + path.sep;
    return normalizeForCompare(resolved).startsWith(normalizeForCompare(prefix));
}

/** True if `resolved` equals `root` or is a descendant. */
function isUnderOrEquals(resolved: string, root: string): boolean {
    return normalizeForCompare(resolved) === normalizeForCompare(path.resolve(root))
        || isStrictlyUnder(resolved, root);
}

//#endregion

//#region open-custom — sandbox to Trilium's tmp dir + existence check

/**
 * Validates a path for the "open-custom" IPC channel (renderer asks the main
 * process to invoke Windows' "Open With…" dialog, the desktop portal's chooser on Linux, or an
 * application picker on macOS).
 * The legit caller always passes a path freshly written by saveToTmpDir, so
 * the path must live under that dir and the file must exist on disk.
 */
export function validateOpenCustomPath(filePath: unknown, tmpDir: string): string {
    if (typeof filePath !== "string" || filePath.length === 0 || filePath.includes("\0")) {
        throw new Error("open-custom: invalid filePath");
    }

    const resolved = path.resolve(filePath);
    if (!isStrictlyUnder(resolved, tmpDir)) {
        throw new Error(`open-custom: refusing path outside tmpdir: ${resolved}`);
    }

    if (!fs.existsSync(resolved)) {
        throw new Error(`open-custom: file does not exist: ${resolved}`);
    }

    return resolved;
}

//#endregion

//#region open-path — sandbox to Trilium's data dir ∪ tmp dir ∪ backup dir + existence check

/**
 * Validates a path for the "open-path" IPC channel (Open Note Externally,
 * Open Attachment Externally, and the "open data directory" / "open backup
 * directory" links in the About dialog and the backup settings), and for the
 * "show-item-in-folder" channel, which reveals a file rather than opening it.
 * The legit callers only ever pass server-generated paths either inside the tmp
 * dir or equal to one of the directories themselves.
 *
 * Beyond the data and tmp directories, each caller names the roots its own case
 * needs: the backup directory, which the user may have moved elsewhere, and the
 * database file, which `TRILIUM_DOCUMENT_PATH` may likewise put outside the
 * data directory. Those come from the app's own configuration rather than from
 * the renderer, so the sandbox still bounds the caller. A root may be a file, in
 * which case only that exact path passes.
 *
 * UNC paths are blocked implicitly — they cannot normalise to a descendant
 * of those roots, so the sandbox check rejects them. This closes the
 * NTLM-hash-leak vector that affects file:// and smb:// URLs.
 */
export function validateOpenPath(input: unknown, dataDir: string, tmpDir: string, ...extraRoots: (string | null | undefined)[]): string {
    if (typeof input !== "string" || input.length === 0 || input.includes("\0")) {
        throw new Error("open-path: invalid filePath");
    }

    const roots = [dataDir, tmpDir, ...extraRoots];
    const resolved = path.resolve(input);
    if (!roots.some((root) => root && isUnderOrEquals(resolved, root))) {
        throw new Error(`open-path: refusing path outside data dir: ${resolved}`);
    }

    if (!fs.existsSync(resolved)) {
        throw new Error(`open-path: file does not exist: ${resolved}`);
    }

    return resolved;
}

//#endregion

//#region open-external — scheme allowlist

/**
 * Validates a URL for the "open-external" IPC channel (electron.shell.openExternal,
 * which hands the URL to the OS protocol handler). Historically this is a
 * Follina-class RCE primitive on Windows (ms-msdt:, search-ms:, ms-officecmd:)
 * and a credential-leak primitive (smb:, ldap:). Allowlisting the scheme is
 * the only reliable defence — see SHELL_OPEN_EXTERNAL_PROTOCOLS in commons.
 */
export function validateOpenExternalUrl(input: unknown): URL {
    if (typeof input !== "string" || input.length === 0) {
        throw new Error("open-external: invalid URL");
    }

    let parsed: URL;
    try {
        parsed = new URL(input);
    } catch {
        throw new Error(`open-external: not a valid URL: ${input}`);
    }

    // URL.protocol returns "http:" — strip the trailing colon for comparison.
    const scheme = parsed.protocol.replace(/:$/, "").toLowerCase();
    if (!SHELL_OPEN_EXTERNAL_PROTOCOLS.includes(scheme)) {
        throw new Error(`open-external: blocked scheme '${scheme}'`);
    }

    return parsed;
}

//#endregion

//#region open-file-url — block UNC paths

/**
 * Validates a URL for the "open-file-url" IPC channel and returns the
 * resolved filesystem path. The specific threat blocked here is UNC paths:
 * a file: URL with a non-empty hostname (file://attacker.example/share/x)
 * resolves on Windows to \\attacker.example\share\x, which triggers SMB
 * authentication and leaks the user's NTLM hash to the attacker.
 */
export function validateOpenFileUrl(input: unknown): string {
    if (typeof input !== "string" || input.length === 0) {
        throw new Error("open-file-url: invalid URL");
    }

    // Some sources produce malformed file URLs that look like file://C:/path
    // (drive letter parsed as the host). Insert the missing slash so the URL
    // parser sees file:///C:/path with an empty host.
    const normalized = input.replace(/^file:\/\/(?=[a-zA-Z]:)/i, "file:///");

    let parsed: URL;
    try {
        parsed = new URL(normalized);
    } catch {
        throw new Error(`open-file-url: not a valid URL: ${input}`);
    }

    if (parsed.protocol !== "file:") {
        throw new Error(`open-file-url: not a file: URL: ${input}`);
    }

    if (parsed.hostname !== "") {
        throw new Error(`open-file-url: UNC path blocked: ${parsed.hostname}`);
    }

    return url.fileURLToPath(parsed);
}

//#endregion

//#region download-url — same-origin lock

/**
 * Validates a URL for the "download-url" IPC channel (WebContents.downloadURL,
 * which writes the response straight to the user's Downloads folder).
 * Locking it to the renderer's own origin closes the cross-origin abuse path
 * (a compromised renderer pre-positioning a malicious file disguised as a
 * legitimate download) while preserving the legitimate same-origin
 * attachment / revision / export downloads.
 */
export function validateDownloadUrl(input: unknown, allowedOrigin: string): URL {
    if (typeof input !== "string" || input.length === 0) {
        throw new Error("download-url: invalid URL");
    }

    let parsed: URL;
    try {
        parsed = new URL(input);
    } catch {
        throw new Error(`download-url: not a valid URL: ${input}`);
    }

    let allowed: URL;
    try {
        allowed = new URL(allowedOrigin);
    } catch {
        throw new Error(`download-url: invalid allowed origin: ${allowedOrigin}`);
    }

    // We can't use URL.origin for the comparison because Electron serves the
    // renderer via a custom protocol (trilium-app://app/) which the WHATWG URL
    // spec treats as opaque-origin (.origin === "null"). Two opaque-origin URLs
    // would always string-compare as equal even across different schemes/hosts.
    //
    // Instead, require both sides to have a non-empty hostname (rules out
    // data:, file:///, about:, blob:) and compare scheme + hostname + port
    // component-by-component.
    if (allowed.hostname === "" || parsed.hostname === "") {
        throw new Error("download-url: hostless URL not allowed");
    }

    const sameOrigin = parsed.protocol === allowed.protocol
        && parsed.hostname === allowed.hostname
        && parsed.port === allowed.port;
    if (!sameOrigin) {
        throw new Error(
            `download-url: cross-origin download blocked: ${parsed.protocol}//${parsed.host} (allowed: ${allowed.protocol}//${allowed.host})`
        );
    }

    return parsed;
}

//#endregion

//#region IPC wiring

/**
 * Registers the IPC handlers that back `window.electronApi.shell.*`.
 *
 * Every channel validates its input (see the per-region docstrings) before
 * calling into `electron.shell` / `WebContents` / `execFile`, so a compromised
 * renderer cannot trick the main process into launching arbitrary paths or
 * URLs.
 */
export function setupShellHandlers() {
    electron.ipcMain.on("open-external", (_event, externalUrl: string) => {
        try {
            const validated = validateOpenExternalUrl(externalUrl);
            electron.shell.openExternal(validated.toString());
        } catch (e) {
            getLog().error(`open-external failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);
        }
    });

    electron.ipcMain.handle("open-path", (_event, filePath: string) => {
        try {
            const resolved = validateOpenPath(filePath, dataDirs.TRILIUM_DATA_DIR, dataDirs.TMP_DIR,
                ...getConfiguredOpenRoots());
            return electron.shell.openPath(resolved);
        } catch (e) {
            getLog().error(`open-path failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);
            return coreUtils.safeExtractMessageAndStackFromError(e);
        }
    });

    // Nothing is returned: `showItemInFolder` reports nothing back, and a refused path is a
    // main-process log line rather than an answer the renderer could act on.
    electron.ipcMain.on("show-item-in-folder", (_event, filePath: string) => {
        try {
            const resolved = validateOpenPath(filePath, dataDirs.TRILIUM_DATA_DIR, dataDirs.TMP_DIR,
                ...getConfiguredOpenRoots(), dataDirs.DOCUMENT_PATH);
            electron.shell.showItemInFolder(resolved);
        } catch (e) {
            getLog().error(`show-item-in-folder failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);
        }
    });

    electron.ipcMain.handle("open-file-url", (_event, fileUrl: string) => {
        try {
            const filePath = validateOpenFileUrl(fileUrl);

            if (shouldOpenViaProtocolHandler(filePath)) {
                return electron.shell.openExternal(url.pathToFileURL(filePath).href)
                    .then(() => "")
                    .catch((e) => coreUtils.safeExtractMessageAndStackFromError(e));
            }

            return electron.shell.openPath(filePath);
        } catch (e) {
            getLog().error(`open-file-url failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);
            return coreUtils.safeExtractMessageAndStackFromError(e);
        }
    });

    electron.ipcMain.on("download-url", (event, downloadUrl: string) => {
        try {
            const validated = validateDownloadUrl(downloadUrl, event.sender.getURL());
            event.sender.downloadURL(validated.toString());
        } catch (e) {
            getLog().error(`download-url failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);
        }
    });

    electron.ipcMain.handle("open-custom", async (event, filePath: string) => {
        // Defense in depth: validate the path is one the server itself wrote into
        // Trilium's tmp dir via /api/.../save-to-tmp-dir, and that it exists.
        // Without this, a compromised renderer (e.g. via XSS) could ask us to
        // launch arbitrary local files.
        try {
            const resolved = validateOpenCustomPath(filePath, dataDirs.TMP_DIR);

            switch (process.platform) {
                case "linux":
                    return await openWithPortalChooser(resolved);
                case "win32":
                    return await openWithWindowsDialog(resolved);
                case "darwin":
                    return await openWithApplicationPicker(resolved, electron.BrowserWindow.fromWebContents(event.sender));
                default:
                    getLog().error(`open-custom: no application chooser on ${process.platform}`);
                    return false;
            }
        } catch (e) {
            getLog().error(`open-custom failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);
            return false;
        }
    });
}

/**
 * Shows the application chooser of the desktop portal (`org.freedesktop.portal.OpenURI.OpenFile`),
 * which also works inside the Flatpak sandbox. The file travels as a descriptor on fd 3 of
 * `gdbus`, referenced by the `@h 3` handle. Resolves `false` if `gdbus` is missing or the call
 * fails (no portal on the session bus); a chooser the user cancels still resolves `true`.
 */
function openWithPortalChooser(resolved: string): Promise<boolean> {
    // The portal reads the access mode off the descriptor, so `writable` needs it opened read-write.
    const fd = fs.openSync(resolved, "r+");
    return new Promise((resolve) => {
        let stderr = "";
        let settled = false;
        // A failed spawn can emit both `error` and `close`; the first one settles.
        const finish = (opened: boolean) => {
            if (settled) {
                return;
            }
            settled = true;
            fs.closeSync(fd);
            resolve(opened);
        };

        const child = spawn("gdbus", [
            "call", "--session",
            "--dest", "org.freedesktop.portal.Desktop",
            "--object-path", "/org/freedesktop/portal/desktop",
            "--method", "org.freedesktop.portal.OpenURI.OpenFile",
            "", "@h 3", "{'ask': <true>, 'writable': <true>}"
        ], { stdio: [ "ignore", "ignore", "pipe", fd ] });

        child.stderr?.on("data", (chunk) => { stderr += chunk; });
        child.once("error", (err) => {
            getLog().error(`open-custom: gdbus failed: ${err.message}`);
            finish(false);
        });
        child.once("close", (code) => {
            if (code !== 0) {
                getLog().error(`open-custom: portal call failed (exit ${code}): ${stderr.trim()}`);
            }
            finish(code === 0);
        });
    });
}

/** Shows the Windows "Open with" dialog; resolves `false` if `rundll32` fails. */
function openWithWindowsDialog(resolved: string): Promise<boolean> {
    const winPath = resolved.replace(/\//g, "\\");
    return new Promise((resolve) => {
        // OpenAs_RunDLL doesn't strip surrounding quotes from its arg, so we
        // must NOT let Node quote the path on our behalf. windowsVerbatimArguments
        // is safe here: CreateProcess passes the command line to rundll32 without
        // any shell interpretation (so `&` is inert), and the path is validated
        // to live inside dataDirs.TMP_DIR with a sanitize-filename'd basename
        // (so it cannot contain quotes or other rundll32-confusing characters).
        execFile("rundll32.exe", ["shell32.dll,OpenAs_RunDLL", winPath], { windowsVerbatimArguments: true }, (err) => {
            if (err) {
                getLog().error(`open-custom: rundll32 failed: ${err.message}`);
            }
            resolve(!err);
        });
    });
}

/**
 * Lets the user pick an application from `/Applications` and opens the file in it with `open -a`,
 * as Finder's "Open With > Other…" does: macOS has no chooser an app can show for a file. A canceled
 * picker resolves `true`, like a canceled chooser on Linux; a failed `open` resolves `false`.
 */
async function openWithApplicationPicker(resolved: string, window: Electron.BrowserWindow | null): Promise<boolean> {
    const options: Electron.OpenDialogOptions = {
        message: t("open_custom.choose_application"),
        defaultPath: "/Applications",
        properties: [ "openFile" ],
        filters: [ { name: t("open_custom.applications_filter"), extensions: [ "app" ] } ]
    };
    const { canceled, filePaths } = window
        ? await electron.dialog.showOpenDialog(window, options)
        : await electron.dialog.showOpenDialog(options);
    const appPath = canceled ? undefined : filePaths[0];
    if (!appPath) {
        return true;
    }

    return new Promise((resolve) => {
        execFile("open", [ "-a", appPath, resolved ], (err) => {
            if (err) {
                getLog().error(`open-custom: open -a failed: ${err.message}`);
            }
            resolve(!err);
        });
    });
}

/**
 * True when Windows must dispatch a directory through the `file:` protocol handler rather
 * than `shell.openPath`.
 *
 * `shell.openPath` sends a directory to Chromium's `OpenFolderViaShell`, which hardcodes the
 * `explore` verb — Explorer's own. A third-party file manager registers the default verb
 * instead, so `explore` never reaches it and the folder always opens in Explorer.
 * `shell.openExternal` invokes `open` on the URL, letting the shell resolve the handler the
 * user actually configured. Files already take the default verb, so they keep `openPath`.
 *
 * Non-ASCII paths keep `openPath` too: `openExternal` percent-encodes the URL as UTF-8 and
 * Windows decodes those escapes with the ANSI codepage, so the path arrives mangled. Such a
 * directory opens in Explorer, which is what it did before this branch existed.
 */
function shouldOpenViaProtocolHandler(filePath: string): boolean {
    if (process.platform !== "win32" || /[\u0080-\uffff]/.test(filePath)) {
        return false;
    }

    try {
        return fs.statSync(filePath).isDirectory();
    } catch {
        return false;
    }
}

/**
 * The roots `open-path` and `show-item-in-folder` accept besides the data and tmp directories:
 * directories the user can configure outside the data directory.
 */
export function getConfiguredOpenRoots() {
    return [ getConfiguredBackupDir(), dataDirs.RESOURCES_DIR ];
}

/**
 * The directory backups currently go to, which the user may have moved outside the data directory.
 * Read from the backup service rather than accepted from the renderer, so it stays the app's own
 * notion of where backups live. Null before core is initialized, leaving the other roots to apply.
 */
function getConfiguredBackupDir(): string | null {
    try {
        return getBackup().getBackupFolderPath();
    } catch {
        return null;
    }
}

//#endregion