sandlock icon indicating copy to clipboard operation
sandlock copied to clipboard

Python SDK: NUL byte path truncation + Checkpoint path traversal

Open dzerik opened this issue 7 months ago • 1 comments

Part 1: _encode() passes NUL bytes through — policy path truncation

File: python/src/sandlock/_sdk.py:429-430

The _encode helper converts strings to bytes for FFI. When the input is already bytes, it's passed through unchanged — including any embedded NUL bytes:

# _sdk.py:429-430
def _encode(s: str) -> bytes:
    return s.encode("utf-8") if isinstance(s, str) else s

On the Rust side, CStr::from_ptr() reads until the first NUL byte, silently truncating the string.

Reproduction

from sandlock import Policy, Sandbox

# User intends to deny a specific path with unusual name
policy = Policy(
    fs_readable=["/"],
    fs_denied=[b"/tmp\x00this-part-is-lost"],  # bytes with NUL
)

# Python sees: fs_denied = [b"/tmp\x00this-part-is-lost"]
# Rust sees:   fs_denied = ["/tmp"]  ← truncated at NUL

# Result: entire /tmp is denied, not just the specific path
# The policy is MORE restrictive than intended (safe direction in this case)

The more concerning direction — fs_readable or fs_writable with NUL:

policy = Policy(
    fs_readable=[b"/safe/path\x00ignored"],
    fs_writable=[b"/workspace\x00ignored"],
)
# Rust sees: fs_readable = ["/safe/path"], fs_writable = ["/workspace"]
# In this case it happens to be the same effective paths,
# but the Python and Rust sides see different values.

The real risk is inconsistency: Python-side validation or logging sees the full bytes, Rust-side enforcement sees the truncated string. This makes security reasoning unreliable.

_encode is called from 20+ locations including fs_read, fs_write, fs_deny, chroot, net_allow_host, http_allow, workdir, cwd, fs_mount.

Suggested fix

def _encode(s: str) -> bytes:
    if isinstance(s, str):
        result = s.encode("utf-8")
    elif isinstance(s, bytes):
        result = s
    else:
        result = str(s).encode("utf-8")
    if b'\x00' in result:
        raise ValueError(f"NUL byte in path or string argument: {result!r}")
    return result

Part 2: Checkpoint.save/load/delete — path traversal via name

File: python/src/sandlock/_sdk.py:548, 570, 645

The checkpoint name parameter is used directly in path construction without sanitization:

# _sdk.py:548 (save)
cp_dir = root / name      # name is user-controlled
root.mkdir(parents=True, exist_ok=True)

# _sdk.py:645-648 (delete)
cp_dir = root / name      # name is user-controlled
if not cp_dir.is_dir():
    raise FileNotFoundError(...)
shutil.rmtree(cp_dir)     # deletes whatever cp_dir resolves to

Reproduction

from sandlock import Checkpoint

# Delete arbitrary directory
Checkpoint.delete("../../.ssh")
# root = ~/.sandlock/checkpoints
# cp_dir = ~/.sandlock/checkpoints/../../.ssh = ~/.ssh
# shutil.rmtree(~/.ssh) 💀

# Save to arbitrary location
cp = some_checkpoint
cp.save("../../../tmp/evil")
# Creates directory at ~/.sandlock/checkpoints/../../../tmp/evil
# = /tmp/evil

# Load from arbitrary location
Checkpoint.load("../../.config/sensitive")
# Reads from ~/.sandlock/checkpoints/../../.config/sensitive

Suggested fix

@staticmethod
def _validate_name(name: str) -> None:
    """Reject checkpoint names that could escape the storage directory."""
    if not name or os.sep in name or name.startswith('.') or '/' in name:
        raise ValueError(
            f"Invalid checkpoint name: {name!r}. "
            "Use a simple name without path separators."
        )

def save(self, name: str, store: str | Path | None = None) -> Path:
    self._validate_name(name)
    # ... rest of save

@staticmethod
def delete(name: str, store: str | Path | None = None) -> None:
    Checkpoint._validate_name(name)
    # ... rest of delete

@staticmethod
def load(name: str, store: str | Path | None = None) -> "Checkpoint":
    Checkpoint._validate_name(name)
    # ... rest of load

Or use resolve() with prefix check:

cp_dir = (root / name).resolve()
if not str(cp_dir).startswith(str(root.resolve())):
    raise ValueError(f"Path traversal in checkpoint name: {name!r}")

Summary

Part What Severity Exploitable Fix
1 NUL byte truncation Medium Only if caller passes bytes (API accepts str) Reject NUL in _encode()
2 Checkpoint path traversal High Direct — Checkpoint.delete("../../target") Validate name parameter

dzerik avatar Apr 06 '26 08:04 dzerik

Thanks for the report! Fixed in commit 5d0fab4dd02c4fbbaea70699602cef38cd7233d0

congwang-mk avatar Apr 06 '26 22:04 congwang-mk