Skip to content

don't follow symlinks or trust another user's file in FS.open - #1628

Open
netliomax25-code wants to merge 7 commits into
lark-parser:masterfrom
netliomax25-code:cache-file-nofollow
Open

netliomax25-code wants to merge 7 commits into
lark-parser:masterfrom
netliomax25-code:cache-file-nofollow

Conversation

@netliomax25-code

Copy link
Copy Markdown
  1. With cache=True the cache path is derived only from the grammar, the options and the version strings, so <tmpdir>/.lark_cache_<user>_<sha256>_3_12.tmp is predictable to anyone else with access to the temp directory.
  2. A file another user leaves at that path reaches pickle.load in lark.py:377 before the sha256 line is compared on 378, and since that digest sits in the same file it is a cache key rather than an authenticity check, so the load is arbitrary code execution as whoever runs the parser.
  3. Saving the cache followed a symlink left at the same path and overwrote whatever it pointed at.

Sent the non-atomicwrites branch of FS.open through an O_NOFOLLOW open that also refuses a file it doesn't own and keeps the cache at 0600, which is roughly what the atomicwrites branch gets from mkstemp today. A refused cache just falls through to the existing handlers, so the grammar is parsed normally. Three tests in tests/test_cache.py cover the load path, the save path and the file mode; they fail on master and pass here, and the rest of the suite is green with and without atomicwrites installed.

@MegaIng

MegaIng commented Jul 26, 2026

Copy link
Copy Markdown
Member

Is this standard practice in other projects using cache files?

Would it be easier to put the cache files somewhere else?

@netliomax25-code

netliomax25-code commented Jul 28, 2026 •

Copy link
Copy Markdown
Author

Both fair questions.

  1. On prior art: it's what CPython does for its own temp files. tempfile.mkstemp opens with O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW at mode 0600 (tempfile.py, _text_openflags and _mkstemp_inner). Lark already inherits that on one path: with the atomic_cache extra installed, FS.open hands writes to atomicwrites.atomic_write, which creates the file through mkstemp and renames it into place, so that branch is already 0600 and already symlink-proof. This PR mostly gives the plain-open() fallback the same properties.

  2. The gap that made me file it is that reads never reach that branch. FS.open only routes to atomicwrites when "w" in mode, so 'rb' is a plain open() either way, and that's the call feeding pickle.load on lark.py:377 (the sha256 line is compared on 378, after that load). I re-checked on master just now: with atomicwrites installed, a pickle planted at the predictable cache path still runs on load; without the extra, the save path also follows a symlink and overwrites whatever it points at. On this branch both are refused and the grammar is parsed normally.

    The exposure is platform-dependent, which may be why it isn't obvious: on macOS gettempdir() is a per-user /var/folders/.../T at 0700, but on Linux and CI it's /tmp at 1777.

  3. On moving the files, yes, and I'd say that's the better fix if you want to go that way. A directory only the user can write to removes the cause instead of defending against it, and it's the norm: pip, black, pre-commit, Cython and huggingface_hub all default to a per-user cache dir, and matplotlib only falls back to the temp dir when that's unwritable, and even then uses mkdtemp at 0700 and warns. Two things to weigh: lark has no runtime dependencies, so it'd mean hand-rolling XDG_CACHE_HOME/~/.cache plus %LOCALAPPDATA% rather than taking platformdirs, and it changes the default cache location, so files already in the temp dir get orphaned and the new directory wants creating at 0700.

The two aren't exclusive, and they're not the same size of change. I'm happy to convert this PR to a per-user cache directory, or leave it as the narrow fix and do the relocation separately. Whichever you'd rather carry.

Validation on the branch: full suite green with and without atomicwrites installed (1315 tests), CI passing.

@netliomax25-code

Copy link
Copy Markdown
Author

any preference?

@MegaIng

MegaIng commented Aug 11, 2026

Copy link
Copy Markdown
Member

I think we should consider doing both. The change from this PR on it's own is a good idea already.

@MegaIng

MegaIng commented Aug 11, 2026

Copy link
Copy Markdown
Member

The current implementation does not refuse to open files that have incorrect permissions for reading, it just changes them. Is this intentional?

And don't worry about cache invalidation, a new lark version is going to invalidate all caches anyway.

@netliomax25-code

Copy link
Copy Markdown
Author
  1. On the read path it wasn't intentional, and you're right that it's the wrong default. Reads only checked ownership, so a file we own but that group or others can write could have been tampered with by another user and we'd still pickle.load it. Changing perms there doesn't help either, since the bad contents are already on disk.

  2. Fixed it to refuse instead: on read, _open_private now rejects a cache whose group/other bits are set (st_mode & 0o077) rather than trusting or rewriting it. A refused cache falls through to the existing handler and the grammar is rebuilt, and since 0600 is what we write, only stale or planted files get refused. Good point on invalidation too, so I didn't add any migration for older 0644 caches; they'll just be rebuilt.

The write path still tightens to 0600 rather than refusing, which seems right since it truncates and we own it.

Added test_load_refuses_group_or_world_accessible alongside the existing three. Full suite green with and without atomicwrites installed.

On the relocation: agreed, I'll keep this as the narrow fix and open the per-user cache directory as a separate PR.

@MegaIng

MegaIng commented Aug 12, 2026

Copy link
Copy Markdown
Member

@erezsh I can't approve workflows AFAICT.

@erezsh

erezsh commented Aug 13, 2026

Copy link
Copy Markdown
Member

@MegaIng I changed your role from “triage” to “write". Let me know if it still doesn't work.

@MegaIng

MegaIng commented Aug 13, 2026

Copy link
Copy Markdown
Member

@erezsh Works, thank you. I am going to leave merging to you, but I think this PR is ready.

@erezsh

erezsh commented Aug 13, 2026

Copy link
Copy Markdown
Member

Thanks, I haven't had time to look into it yet, but I'll do it soon.

@erezsh

erezsh commented Aug 25, 2026

Copy link
Copy Markdown
Member

Fable had some comments, and at a glance they seem right. I would appreciate if you could address them.

  1. O_TRUNC runs before the ownership check — _open_private, lark/utils.py:319 on the branch. In the non-atomicwrites write path the open truncates the target and only then fstats and refuses it. I reproduced it: a group-writable cache owned by nobody went from 16 bytes → 0 bytes, then PermissionError: ... belongs to another user. For a legitimately shared explicit cache="path" that means we destroy a colleague's cache and then don't replace it. Fix: drop O_TRUNC from the flags and call os.ftruncate(fd, 0) after the checks pass.

  2. Refusals surface as ERROR + full traceback. The new PermissionErrors land in except Exception: logger.exception(...) at lark/lark.py:393, so an intentional "won't read this" looks like a crash. Concretely, anyone with an explicit cache="path" file written by the current release (0644 under default umask) gets a traceback on first load after upgrading — before this PR the same situation (version mismatch) fell through silently. (cache=True is unaffected since the version is part of the filename.) Suggest catching PermissionError separately in lark.py and logging a one-line warning, or raising a dedicated exception lark.py can recognise.

  3. The read check is stricter than the threat. st.st_mode & 0o077 refuses group/world-readable files, but only write bits let another user tamper; 0o022 matches the stated rationale ("could have been tampered with"). More important: on filesystems that don't honour fchmod (vfat, WSL /mnt/c, some Docker bind mounts, NFS with squash) files report 0777/0755, so an explicit cache="path" there becomes permanently non-functional — reparsed on every Lark() with a traceback each time under the current logging. That's the scenario where point 2 turns from cosmetic to painful.

  4. No test coverage of _open_private on Windows.

(I'm not sure 2 is a bad thing, but worth keeping in mind.)

@netliomax25-code

Copy link
Copy Markdown
Author

Thanks, all four look right. Addressed them:

  1. O_TRUNC before the ownership check. Dropped O_TRUNC from the write flags and moved to os.ftruncate(fd, 0) after the checks pass, so a file we end up refusing is left intact instead of emptied first. Confirmed on the plain-open path: a 0600 cache faked as owned by another uid now raises before any truncation and its contents are untouched.

  2. Refusals surfacing as ERROR + traceback. lark.py now catches PermissionError separately from the load and logs a one-line warning, then rebuilds as normal. I also translated the O_NOFOLLOW symlink error (ELOOP, EMLINK on some BSDs) into a PermissionError inside _open_private, so a planted symlink takes the same quiet path rather than a traceback. The version-mismatch-on-upgrade case you described now logs 'Not loading Lark from cache: ... We will rebuild it.' and parses fine.

  3. Read check stricter than the threat. Narrowed the mask from 0o077 to 0o022, so only group/other write bits are refused and a file we own that is merely group/world readable loads normally. On the fchmod-less filesystems (vfat, WSL /mnt/c, some bind mounts) an explicit cache path is still refused, but with point 2 that is now a one-line warning and a rebuild each time rather than a traceback, so it stays functional just uncached. Added a test that a 0644 file we own is accepted and one that a 0666 file is refused.

  4. Windows coverage. Added TestCacheFilePortable (not gated on posix) that round-trips a write/read through FS.open and checks truncate-on-write, so _open_private is exercised on Windows where the ownership and symlink checks are no-ops.

Validation: full suite green with and without atomicwrites installed (1320 tests), mypy clean on the changed files.

@erezsh
erezsh force-pushed the cache-file-nofollow branch from 2360cd3 to 7ad4b28 Compare August 27, 2026 12:29
@erezsh

erezsh commented Aug 27, 2026

Copy link
Copy Markdown
Member

I made small changes. Let me know if you agree @MegaIng & @netliomax25-code

@netliomax25-code

Copy link
Copy Markdown
Author

Looks good to me. The save-path PermissionError branch is the half I'd only done on the load side, so catching it there is the right symmetry, and the reworded warnings are clearer. I pulled the branch and ran the full suite green (1321 tests, with and without atomicwrites), and the new test passes both ways. Happy for it to go in.

@netliomax25-code

Copy link
Copy Markdown
Author

any update?

@erezsh

erezsh commented Sep 8, 2026

Copy link
Copy Markdown
Member

A question that just occurred to me, should we make it possible to disable this protection?

Because some users might not care about it, and might not need it, while it could break some legitimate workflows. (at least, legitimate in the context of personal use)

@netliomax25-code

Copy link
Copy Markdown
Author

I think yes, as long as it stays on by default and the opt-out is explicit.

  1. Where it can bite: only an explicit cache="path". With cache=True lark creates the file itself at 0600 under a name that includes the username, so the checks shouldn't fire on a file it wrote and there's nothing to opt out of. The cases I can see breaking are all explicit paths: a cache baked into a Docker image as root and loaded by a non-root user, a cache file shared between accounts, and a path on a filesystem that reports 0777 for everything (vfat, WSL /mnt/c, some bind mounts).

  2. What happens there today: I checked the first and third on this branch (faking the uid and the mode bits). The parser still builds and parses fine, but the cache is refused on every construction, so it reparses each time. Since lark's logger defaults to CRITICAL the warning isn't visible either, so from the user's side the cache just quietly stops helping. That seems like a good enough reason to give them a switch.

  3. Shape I'd suggest: a boolean Lark option, default on (something like cache_strict=True, naming is yours), that makes FS.open fall back to a plain open() when turned off, with a line in the option docs saying what it skips. I'd keep the checks unconditional for cache=True, since that's the predictable path in a shared temp dir and nothing legitimate gets refused there. There's precedent for the pattern: sshd's StrictModes and git's safe.directory are both ownership/mode checks that default to on and can be turned off explicitly.

I can add that to this PR with a test for both settings, or it could go in separately so this one isn't held up further. The default-on behavior here doesn't change either way.

@erezsh

erezsh commented Sep 18, 2026

Copy link
Copy Markdown
Member

I think unsafe_cache = False is a good name. WDYT?

@MegaIng

MegaIng commented Sep 18, 2026

Copy link
Copy Markdown
Member

I don't quite like using "safe" as a term for a functionality that still loads arbitrary data. This doesn't fix the attack vector, it just makes it harder to use.

@erezsh

erezsh commented Sep 18, 2026

Copy link
Copy Markdown
Member

Maybe unguarded_cache is a better term? Anyway, I'm open to suggestions.

@netliomax25-code

Copy link
Copy Markdown
Author

unguarded_cache works for me.

  1. On the name: I agree with MegaIng that "safe"/"unsafe" would oversell it, since the cache is still a pickle and the checks only narrow who can plant one. "Unguarded" says what gets switched off without claiming the default is safe, and False reads naturally as the default. I don't have a better candidate.

  2. I pushed it under that name so there's something concrete to look at; it's a single rename if you settle on something else. unguarded_cache=False keeps everything in this PR as it is. With True, FS.open falls back to the plain open() it used before (writes still go through atomicwrites when that's installed). The option doc lists what gets skipped and says the cache is a pickle, so it should only be set when everyone who can write to the path is trusted.

  3. Two things differ from what I sketched earlier:

    • It's left out of the cache key, since it only changes how the file is opened and not what's in it. Otherwise turning it on to get an existing cache accepted (say one baked into an image as root) would miss on the hash and rebuild anyway.
    • I'd suggested keeping the checks unconditional for cache=True. I dropped that: a temp dir on a filesystem that reports 0777 would have no way out, and a switch that only half applies seemed more surprising than useful. Easy to restrict to explicit paths if you'd rather.

Validation: the new tests cover both settings (a 0666 cache is refused and rebuilt by default, and loaded with unguarded_cache=True), plus a round trip that also runs on Windows. I also checked the other-owner case by faking the uid: the default rebuilds, unguarded loads from the cache. Full suite green with and without atomicwrites (1324 tests), mypy clean.

@netliomax25-code

Copy link
Copy Markdown
Author

gentle ping

@erezsh

erezsh commented Oct 29, 2026

Copy link
Copy Markdown
Member

Thanks, this is close. However, I did another pass with Fable, and here's what it had to say:

  1. A hard link at the cache path still lets an attacker overwrite the victim's files. A hard link to one of the victim's own files has the victim's uid, so it passes the ownership check. Without atomicwrites, the save then truncates it, writes the cache into it and chmods it to 0600. This needs fs.protected_hardlinks=0 (the kernel default, though most systemd distros set it to 1) and the target on the same filesystem as the temp dir. Still, it's the same attack as the symlink one. Fix: refuse st.st_nlink != 1 next to the uid check.

  2. A FIFO planted at the cache path makes Lark() hang forever, because the read-only open blocks waiting for a writer. Please add O_NONBLOCK to the open flags (via getattr, since Windows doesn't have it). After the fstat, refuse anything that isn't stat.S_ISREG(st.st_mode).

  3. Other non-regular files still log ERROR with a traceback, because the os.open itself fails before any check runs:

    • EISDIR when saving to a directory;
    • ENXIO for a socket, on both load and save;
    • ENXIO for a FIFO opened non-blocking for writing.

    Please turn ENXIO and EISDIR into PermissionError next to the existing ELOOP handling.

  4. The tests should expect PermissionError instead of OSError. That's tests/test_cache.py:254, :275 and :303, plus the except OSError in test_save_does_not_follow_symlink. The quiet fallback in lark.py only catches PermissionError, so the tests should pin that. Please also add tests for items 1–3. Putting an os.link, os.mkfifo or os.mkdir at the cache path is enough, and no second user is needed.

  5. Please add an end-to-end test for cache=True (a miss, then a hit) with tempfile.gettempdir patched to a temp dir. Right now every test uses MockFS or an explicit path, so the default path is never exercised, including on Windows CI.

Optional nit: NetBSD reports O_NOFOLLOW on a symlink as EFTYPE, so getattr(errno, "EFTYPE", -1) could join the ELOOP/EMLINK check.

Please address these points! (if you think some of them are wrong or irrelevant, include your reasoning)

A hard link to one of the user's own files passes the ownership check, so
refuse st_nlink != 1. Open with O_NONBLOCK so a FIFO can't hang Lark(),
refuse anything that isn't S_ISREG after the fstat, and turn EISDIR,
ENXIO and EOPNOTSUPP (socket on macOS) from os.open into PermissionError,
along with EFTYPE for a symlink on NetBSD.

Tests now expect PermissionError, cover hard links, FIFOs and directories,
and run cache=True end to end against a patched temp dir.
@netliomax25-code

Copy link
Copy Markdown
Author

Pushed b28bc87. It covers all five points and the nit.

  1. Hard links: _open_private now refuses st_nlink != 1 next to the uid check. Without atomicwrites, a hard link to one of the user's own files is refused on both load and save, and the linked file keeps its contents. With atomicwrites the save already went through a rename, which replaces the link instead of writing through it.

  2. FIFOs: the open now adds O_NONBLOCK (via getattr), and anything that isn't S_ISREG after the fstat is refused. A FIFO at the cache path no longer hangs Lark(). The read open returns immediately and is then refused, and the write open fails with ENXIO.

  3. Errors from os.open: EISDIR and ENXIO now become PermissionError next to the ELOOP handling. One addition: on macOS a socket gives EOPNOTSUPP rather than ENXIO, so I mapped that as well. I planted a hard link, a FIFO, a directory and a socket at an explicit cache=path. Without atomicwrites, each case logs two warnings (load and save), no ERROR, and the parse works. With atomicwrites, one case still logs ERROR: saving over a directory, because atomicwrites' own os.rename raises IsADirectoryError outside _open_private. Master behaves the same and nothing gets overwritten, so I left it out. If you want it handled here, it's a small except in lark.py.

  4. Tests: the three assertRaises(OSError) calls and the except OSError now use PermissionError. New tests put an os.link, an os.mkfifo and an os.mkdir at the cache path and check that load and save both raise PermissionError, and that the hard-linked file is left intact. Against the previous _open_private, the hard-link and directory tests fail and the FIFO test hangs.

  5. End to end: test_cache_true_miss_then_hit is in TestCacheFilePortable, so it isn't posix-gated. It patches tempfile.gettempdir and builds twice with cache=True. It checks that the first call builds the grammar and leaves one .lark_cache_* file, and that the second loads from that file without calling load_grammar again.

Nit: getattr(errno, "EFTYPE", -1) is now part of the symlink check. I also updated the unguarded_cache option doc so it lists hard links and non-regular files among what gets skipped.

Validation: full suite passes with and without atomicwrites (1329 tests on 3.12, 1323 on 3.9), and mypy is clean. I've only run this on macOS. The Linux ENXIO case for sockets is going by open(2), and the Windows job still needs a CI run.

@erezsh

erezsh commented Nov 10, 2026

Copy link
Copy Markdown
Member

Thanks, the follow-up looks good. I think we're getting really close.

One more issue from a reviewer: on save, _open_private accepts a cache we own that others can write (the 0o022 check only applies on read), then fchmods it to 0600 and rewrites it in place. A writer who already has that file open keeps their descriptor and can overwrite the pickle after we write it, and the next load will trust it. Rather than refusing such files on write, which would leave a legacy cache unusable forever, please write to a tempfile.mkstemp file in the same directory and os.replace it onto the cache path, which is what atomicwrites does. That lets the atomicwrites branch in FS.open go away too. The read path and its checks stay as they are. A test that a self-owned 0666 cache ends up as a new 0600 inode after save would cover it.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants