sandlock icon indicating copy to clipboard operation
sandlock copied to clipboard

Python profile parser drops the `:ro` mount suffix, silently redirecting the mount

Open dzerik opened this issue 4 months ago • 1 comments

The Python SDK parses TOML mount specs itself instead of calling the core parser, and its version does not understand the :ro / :rw suffix. The suffix ends up glued to the host path, so the same profile behaves differently depending on whether it is loaded by the CLI or by the SDK.

Two outcomes, depending on whether a directory literally named <host>:ro happens to exist:

  • It does not exist (the ordinary case) — no mount is created and the guest gets Permission denied even for reads. Fail-closed, but the profile silently does nothing.
  • It does exist — the SDK mounts that directory instead, read-write, where the profile asked for read-only access to a different one.

Reproduction

Verified on main (0.8.5, x86-64). Full script, using the existing tests/rootfs-helper:

E=$(mktemp -d)
mkdir -p $E/rootfs/{usr/bin,usr/sbin,etc,proc,dev,tmp} $E/hostdata
cp tests/rootfs-helper $E/rootfs/usr/bin/
( cd $E/rootfs/usr/bin && for n in sh cat write; do ln -sf rootfs-helper $n; done )
( cd $E/rootfs && ln -sf usr/bin bin && ln -sf usr/sbin sbin && chmod 1777 tmp )

echo "original content" > $E/hostdata/file.txt

cat > $E/prof.toml <<EOF
[filesystem]
chroot = "$E/rootfs"
read = ["/usr", "/usr/bin", "/bin", "/sbin", "/etc", "/proc", "/dev"]
mount = ["/work:$E/hostdata:ro"]
EOF

The CLI honours the suffix

$ sandlock run --profile-file $E/prof.toml -- /bin/cat /work/file.txt
original content

$ sandlock run --profile-file $E/prof.toml -- /bin/write /work/file.txt HACKED
write: /work/file.txt: Permission denied

Read works, write is refused, the host file is untouched. Correct.

The SDK does not

from pathlib import Path
from sandlock._profile import load_profile_path

sb = load_profile_path(Path(f"{E}/prof.toml"))
print(sb.fs_mount)
# {'/work': '/tmp/.../hostdata:ro'}     <-- suffix is part of the host path

print(sb.run(["/bin/cat", "/work/file.txt"]).stderr)
# b'cat: /work/file.txt: Permission denied\n'

The host path does not exist, so nothing is mounted and even the read fails.

The same profile when <host>:ro exists

mkdir "$E/hostdata:ro"
echo "WRONG DIRECTORY - secrets" > "$E/hostdata:ro/file.txt"
sb = load_profile_path(Path(f"{E}/prof.toml"))

print(sb.run(["/bin/cat", "/work/file.txt"]).stdout)
# b'WRONG DIRECTORY - secrets\n'                    <-- the other directory

r = sb.run(["/bin/write", "/work/file.txt", "WRITTEN-THROUGH-RO-PROFILE"])
print(r.exit_code, r.stderr)
# 0 b''                                             <-- write succeeded

Side by side, same profile, same machine:

CLI Python SDK
directory mounted hostdata (as written) hostdata:ro (a different one)
read /work/file.txt original content WRONG DIRECTORY - secrets
write /work/file.txt Permission denied succeeds

A profile that asked for read-only access to one directory produced read-write access to another. Anyone able to create a directory next to the target — routine in shared trees like /srv or /var/lib — can redirect the mount by creating <path>:ro, and the operator reading the profile believes they tightened the policy.

Control: the identical profile with the suffix removed works correctly through the SDK — read and write both land in hostdata. The suffix is the whole difference.

Root cause

The core strips the suffix before splitting, crates/sandlock-core/src/profile.rs:319-324:

let (body, read_only) = if let Some(b) = s.strip_suffix(":ro") {
    (b, true)
} else if let Some(b) = s.strip_suffix(":rw") {
    (b, false)
} else {
    (s, false)
};
let (virt, host) = body.split_once(':')...

The Python SDK reimplemented the parser and splits on the first colon only, python/src/sandlock/_profile.py:237:

virt, host = spec.split(":", 1)

:ro and :rw appear nowhere under python/src/sandlock/. And since fs_mount_ro has no C ABI setter (crates/sandlock-core/src/sandbox/builder.rs:162 is the only mount field without one), the SDK could not apply the flag even if it parsed it — a missing export underneath a parser divergence.

Why the tests do not catch it

python/tests/test_fs_mount.py builds every mount through the dict form (fs_mount={"/work": str(work_dir)}, line 57), which bypasses the spec parser entirely. No Python test passes a VIRTUAL:HOST string, so the divergence from the core grammar is invisible to the suite.

Suggested fix

  1. Make the SDK reject a suffix it cannot honour. Recognising :ro and dropping it would be worse than today; erroring out fails loudly instead of mounting something else. Worth doing on its own, independently of (2).
  2. Export fs_mount_ro through the C ABI, then have the SDK parse and apply the suffix as the core does.

The deeper question is whether the SDKs should carry hand-written profile parsers at all rather than calling the core one across the ABI. This divergence is what a duplicated parser produces, and it will produce the next one.

Happy to implement either part.

dzerik avatar Jul 29 '26 13:07 dzerik

Excellent report, and the design question at the end deserves a direct answer: you are right, the SDK should not carry a hand-written profile parser. This is not a one-off slip; the duplication has already produced more divergences than the one you found. I went looking:

  • Byte sizes. The SDK's parse_memory_size accepts fractional values and a T suffix ("1.5G", "1T"); core's ByteSize::parse rejects both. The same profile runs through the SDK and errors in the CLI.
  • time_start. Core parses RFC 3339 (via jiff::Timestamp, offset required). The SDK's build path casts the raw value with int() (_sdk.py:1145), so a profile with time_start = "2026-01-01T00:00:00Z" works in the CLI and raises ValueError through the SDK. (The dataclass has an ISO-parsing helper, time_start_timestamp(), with its own third grammar, naive-means-UTC; nothing calls it.)

Three duplicated micro-grammars, three divergences. Port specs, net rules, and branch actions are the same shape, just not caught yet. So the answer to "will it produce the next one" is: it already has.

One design note on the fix, because "call the core parser over the ABI" has two shapes and they are not equal:

  1. Parse to an opaque built sandbox handle. Maximal parity, but it destroys the SDK's data model: Sandbox is a plain dataclass that users introspect, compose with presets, dataclasses.replace, and merge overrides into. An opaque handle kills all of that.
  2. Parse to canonical structured data. One export, roughly char *sandlock_profile_parse(const char *toml, int *err, char **err_msg), returning normalized JSON that the SDK materializes into its native Sandbox. Core resolves every micro-grammar: mounts come back as structured {virt, host, ro} objects, sizes as integer bytes, time_start as epoch seconds. The SDK's remaining job is structural field mapping, and with strict unknown-key checking on both sides, future drift fails loudly at load time instead of silently mis-parsing a string.

Shape 2 is the right one. Note that core's existing sandbox_to_json is not the canonical form as-is: it re-emits mounts as V:H:ro spec strings, which would put string parsing right back in the SDK. The new export must emit structured mounts.

Two objections that would normally apply, and do not here:

  • "The JSON becomes a new compatibility surface." No: the cdylib ships inside the wheel, so core and SDK are always version-locked and the JSON never crosses a version boundary.
  • "The SDK loses Pythonic error messages." It gains error messages identical to the CLI's, which is exactly what you want when the same profile is debugged in both.

Side benefit: the SDK drops tomli/tomllib, parse_memory_size, and the mount-spec code entirely.

Independent of the parser question, and worth doing first:

  • fs_mount_ro needs a C ABI export regardless. The SDK's native fs_mount dict cannot express a read-only mount at all today, profile or no profile.
  • Your fix (1), rejecting a suffix the SDK cannot honour, is correct as the immediate stopgap, and your instinct is right that recognising-and-dropping would be worse than the status quo.

Since you offered: PRs are very welcome. I would sequence it as (a) fs_mount_ro ABI export plus loud SDK rejection of :ro/:rw, which is small and closes the security hole, then (b) the sandlock_profile_parse export and SDK switchover, deleting the Python parser. We are pre-1.0, so if the SDK's fs_mount representation needs to change to carry the read-only flag, break it cleanly, no shims.

congwang-mk avatar Jul 30 '26 00:07 congwang-mk