Skip to content

Quickly sandbox your AI agent.

Python

Windows admin-free SMB mounts via host-side TCP SMB server

Jace Medlinfe1848bd472d
diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml
index e4e3f17..08dc9bd 100644
--- a/.github/workflows/check.yml
+++ b/.github/workflows/check.yml
@@ -10,11 +10,20 @@ permissions:
contents: read
jobs:
checks:
- runs-on: ubuntu-latest
+ runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
+ os: [ubuntu-latest]
task: [check, test:unit]
+ include:
+ # Windows runs the unit suite only. The `check` task is not run on
+ # Windows because `ty` resolves os/asyncio against win32 and reports
+ # platform-API diagnostics (e.g. os.sysconf, os.pread, the existing
+ # `ty: ignore` directives) that are clean under the Linux resolution
+ # the `check` job already enforces.
+ - os: windows-latest
+ task: test:unit
steps:
- uses: actions/checkout@v6
with:
diff --git a/packages/quicksand-core/quicksand_core/host/smb.py b/packages/quicksand-core/quicksand_core/host/smb.py
index b00ab82..5fe05a8 100644
--- a/packages/quicksand-core/quicksand_core/host/smb.py
+++ b/packages/quicksand-core/quicksand_core/host/smb.py
@@ -2,19 +2,25 @@
Provides a base class and platform-specific implementations:
- QuicksandSMBServer: Pure-Python SMB3 server via QEMU guestfwd (macOS/Linux)
-- WindowsSMBServer: Uses Windows native SMB via PowerShell
+- QuicksandSMBTCPServer: Pure-Python SMB3 server as a loopback TCP listener
+ (Windows default; no Administrator required)
+- WindowsSMBServer: Windows native SMB via PowerShell (opt-in via
+ QUICKSAND_WINDOWS_NATIVE_SMB=1)
All mounts (boot-time and dynamic) use CIFS over QEMU slirp networking.
"""
from __future__ import annotations
+import contextlib
import logging
import os
import secrets
+import socket
import subprocess
import sys
import tempfile
+import threading
from abc import ABC, abstractmethod
from pathlib import Path
from typing import TYPE_CHECKING
@@ -91,6 +97,78 @@ class SMBServer(ABC):
return None
+class _ConfigBackedSMBServer(SMBServer):
+ """Shared base for the pure-Python SMB servers.
+
+ Holds the share state and the JSON config file that ``quicksand_smb`` reads
+ (re-read on every TREE_CONNECT, so shares can be added/removed on a running
+ server). Subclasses add the transport: ``QuicksandSMBServer`` is spawned per
+ connection by QEMU guestfwd; ``QuicksandSMBTCPServer`` runs a persistent
+ loopback TCP listener.
+ """
+
+ def __init__(self) -> None:
+ self._shares: dict[str, dict] = {}
+ self._config_path: Path | None = None
+ self._temp_dir: Path | None = None
+
+ @property
+ def credentials(self) -> tuple[str, str]:
+ return ("guest", "")
+
+ def start(self) -> None:
+ self._temp_dir = Path(tempfile.mkdtemp(prefix="quicksand-smb-"))
+ self._config_path = self._temp_dir / "smb_config.json"
+ self._write_config()
+
+ def stop(self) -> None:
+ if self._temp_dir is not None and self._temp_dir.exists():
+ import shutil
+
+ shutil.rmtree(self._temp_dir, ignore_errors=True)
+ self._temp_dir = None
+ self._config_path = None
+ self._shares.clear()
+
+ def add_share(self, host_path: str, readonly: bool = False) -> str:
+ share_name = f"QUICKSAND_{secrets.token_hex(8)}"
+ Path(host_path).mkdir(parents=True, exist_ok=True)
+ self._shares[share_name] = {"host_path": host_path, "readonly": readonly}
+ self._write_config()
+ logger.info("Added share %s -> %s (readonly=%s)", share_name, host_path, readonly)
+ return share_name
+
+ def remove_share(self, share_name: str) -> None:
+ self._shares.pop(share_name, None)
+ self._write_config()
+ logger.info("Removed share %s", share_name)
+
+ def list_shares(self) -> list[dict]:
+ return [
+ {"share_name": name, "host_path": info["host_path"], "readonly": info["readonly"]}
+ for name, info in self._shares.items()
+ ]
+
+ def _write_config(self) -> None:
+ """Atomically write the shares config JSON file."""
+ if self._config_path is None:
+ return
+
+ import json
+
+ data = {
+ "shares": {
+ name: {"host_path": info["host_path"], "readonly": info["readonly"]}
+ for name, info in self._shares.items()
+ }
+ }
+
+ # Atomic write: write to temp file then rename
+ tmp_path = self._config_path.with_suffix(".tmp")
+ tmp_path.write_text(json.dumps(data))
+ os.replace(str(tmp_path), str(self._config_path))
+
+
class WindowsSMBServer(SMBServer):
"""Windows native SMB sharing via PowerShell.
@@ -173,7 +251,7 @@ class WindowsSMBServer(SMBServer):
]
-class QuicksandSMBServer(SMBServer):
+class QuicksandSMBServer(_ConfigBackedSMBServer):
"""Pure-Python SMB3 server spawned by QEMU guestfwd (macOS/Linux).
Does NOT start a background process or open a TCP port. Shares are
@@ -181,95 +259,140 @@ class QuicksandSMBServer(SMBServer):
process per guest TCP connection via guestfwd.
"""
- def __init__(self) -> None:
- self._shares: dict[str, dict] = {}
- self._config_path: Path | None = None
- self._temp_dir: Path | None = None
-
@property
def port(self) -> int:
# No real TCP port — guestfwd uses the virtual IP
return 445
- @property
- def credentials(self) -> tuple[str, str]:
- return ("guest", "")
-
def start(self) -> None:
- self._temp_dir = Path(tempfile.mkdtemp(prefix="quicksand-smb-"))
- self._config_path = self._temp_dir / "smb_config.json"
- self._write_config()
+ super().start()
logger.info("QuicksandSMBServer ready (config=%s)", self._config_path)
- def stop(self) -> None:
- if self._temp_dir is not None and self._temp_dir.exists():
- import shutil
+ def get_guestfwd_cmd(self) -> str:
+ """Return the command string for QEMU guestfwd to spawn the SMB server."""
+ assert self._config_path is not None
+ return f"{sys.executable} -m quicksand_smb --config {self._config_path}"
- shutil.rmtree(self._temp_dir, ignore_errors=True)
- self._temp_dir = None
- self._config_path = None
- self._shares.clear()
- def add_share(self, host_path: str, readonly: bool = False) -> str:
- share_name = f"QUICKSAND_{secrets.token_hex(8)}"
- Path(host_path).mkdir(parents=True, exist_ok=True)
- self._shares[share_name] = {"host_path": host_path, "readonly": readonly}
- self._write_config()
- logger.info("Added share %s -> %s (readonly=%s)", share_name, host_path, readonly)
- return share_name
+class QuicksandSMBTCPServer(_ConfigBackedSMBServer):
+ """Pure-Python SMB3 server running as a persistent loopback TCP listener.
- def remove_share(self, share_name: str) -> None:
- self._shares.pop(share_name, None)
- self._write_config()
- logger.info("Removed share %s", share_name)
+ Used on Windows, where QEMU's guestfwd ``cmd:`` does not reliably spawn a
+ per-connection helper and the native ``New-SmbShare`` path requires
+ Administrator. Binds ``127.0.0.1:<random>`` and serves each accepted
+ connection on its own daemon thread via ``quicksand_smb.serve_socket``. The
+ guest reaches it through QEMU's slirp gateway (``10.0.2.2:<port>``) in FULL
+ network mode, so no host port is exposed beyond loopback and no privileges
+ are required.
- def list_shares(self) -> list[dict]:
- return [
- {"share_name": name, "host_path": info["host_path"], "readonly": info["readonly"]}
- for name, info in self._shares.items()
- ]
+ ``get_guestfwd_cmd`` returns ``None`` so the mount path uses the slirp
+ gateway + this server's ``port`` rather than a guestfwd tunnel.
+ """
- def get_guestfwd_cmd(self) -> str:
- """Return the command string for QEMU guestfwd to spawn the SMB server."""
- assert self._config_path is not None
- return f"{sys.executable} -m quicksand_smb --config {self._config_path}"
+ def __init__(self) -> None:
+ super().__init__()
+ self._port_value = 0
+ self._server_sock: socket.socket | None = None
+ self._accept_thread: threading.Thread | None = None
+ self._stopping = threading.Event()
+ self._conn_threads: list[threading.Thread] = []
- def _write_config(self) -> None:
- """Atomically write the shares config JSON file."""
- if self._config_path is None:
- return
+ @property
+ def port(self) -> int:
+ return self._port_value
- import json
+ def start(self) -> None:
+ super().start()
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ sock.bind(("127.0.0.1", 0))
+ sock.listen(8)
+ self._port_value = sock.getsockname()[1]
+ self._server_sock = sock
+ self._stopping.clear()
+ self._accept_thread = threading.Thread(
+ target=self._accept_loop, args=(sock,), name="quicksand-smb-accept", daemon=True
+ )
+ self._accept_thread.start()
+ logger.info(
+ "QuicksandSMBTCPServer listening on 127.0.0.1:%d (config=%s)",
+ self._port_value,
+ self._config_path,
+ )
- data = {
- "shares": {
- name: {"host_path": info["host_path"], "readonly": info["readonly"]}
- for name, info in self._shares.items()
- }
- }
+ def stop(self) -> None:
+ self._stopping.set()
+ if self._server_sock is not None:
+ # Closing the listening socket unblocks accept().
+ with contextlib.suppress(OSError):
+ self._server_sock.close()
+ self._server_sock = None
+ if self._accept_thread is not None:
+ self._accept_thread.join(timeout=5)
+ self._accept_thread = None
+ self._port_value = 0
+ super().stop()
+
+ def get_guestfwd_cmd(self) -> None:
+ # Reached directly via the slirp gateway; no guestfwd tunnel.
+ return None
- # Atomic write: write to temp file then rename
- tmp_path = self._config_path.with_suffix(".tmp")
- tmp_path.write_text(json.dumps(data))
- os.replace(str(tmp_path), str(self._config_path))
+ def _accept_loop(self, sock: socket.socket) -> None:
+ from quicksand_smb import SMBConfig, serve_socket
+
+ while not self._stopping.is_set():
+ try:
+ conn, _addr = sock.accept()
+ except OSError:
+ break # listener closed during stop()
+
+ # SMB is request/response with small frames; disable Nagle so the
+ # guest does not stall waiting on a delayed response (e.g. a WRITE
+ # ack), which otherwise shows up as a CIFS request timeout.
+ with contextlib.suppress(OSError):
+ conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
+
+ def _serve(conn: socket.socket = conn) -> None:
+ try:
+ assert self._config_path is not None
+ config = SMBConfig.from_json_file(str(self._config_path))
+ serve_socket(conn, config, config_path=str(self._config_path))
+ except Exception as e:
+ logger.debug("SMB connection handler ended: %s", e)
+ finally:
+ with contextlib.suppress(OSError):
+ conn.close()
+
+ t = threading.Thread(target=_serve, name="quicksand-smb-conn", daemon=True)
+ t.start()
+ self._conn_threads.append(t)
+ # Drop references to finished handler threads.
+ self._conn_threads = [t for t in self._conn_threads if t.is_alive()]
def create_smb_server() -> SMBServer:
"""Factory: returns the appropriate SMBServer for the current platform.
- Windows uses native SMB via PowerShell. All other platforms use the
- pure-Python QuicksandSMBServer (spawned by QEMU guestfwd, no TCP port).
+ - Windows: the pure-Python ``QuicksandSMBTCPServer`` (loopback TCP listener),
+ which needs no Administrator rights. The native ``WindowsSMBServer``
+ (PowerShell ``New-SmbShare``) is available as an opt-in via
+ ``QUICKSAND_WINDOWS_NATIVE_SMB=1`` for callers who want OS-native shares
+ and have the privileges to create them.
+ - macOS/Linux: the pure-Python ``QuicksandSMBServer`` spawned per connection
+ by QEMU guestfwd (no TCP port).
"""
if sys.platform == "win32":
- username = os.environ.get("QUICKSAND_SMB_USERNAME", "")
- password = os.environ.get("QUICKSAND_SMB_PASSWORD", "")
- if not username:
- try:
- username = os.getlogin()
- except OSError:
- import getpass as _getpass
-
- username = _getpass.getuser()
- return WindowsSMBServer(username, password)
+ if os.environ.get("QUICKSAND_WINDOWS_NATIVE_SMB") == "1":
+ username = os.environ.get("QUICKSAND_SMB_USERNAME", "")
+ password = os.environ.get("QUICKSAND_SMB_PASSWORD", "")
+ if not username:
+ try:
+ username = os.getlogin()
+ except OSError:
+ import getpass as _getpass
+
+ username = _getpass.getuser()
+ return WindowsSMBServer(username, password)
+ return QuicksandSMBTCPServer()
return QuicksandSMBServer()
diff --git a/packages/quicksand-core/quicksand_core/sandbox/_mounts.py b/packages/quicksand-core/quicksand_core/sandbox/_mounts.py
index 988c37b..297e5b5 100644
--- a/packages/quicksand-core/quicksand_core/sandbox/_mounts.py
+++ b/packages/quicksand-core/quicksand_core/sandbox/_mounts.py
@@ -65,8 +65,11 @@ class _MountMixin(_SandboxProtocol):
ro_opt = ",ro" if readonly else ""
- # QuicksandSMBServer uses guestfwd in ALL modes (no TCP port).
- # SambaSMBServer uses guestfwd in MOUNTS_ONLY, direct TCP in FULL.
+ # Servers that return a guestfwd command (QuicksandSMBServer) are reached
+ # through the guestfwd virtual IP. Servers without one
+ # (QuicksandSMBTCPServer / WindowsSMBServer) are reached directly through
+ # the slirp gateway (10.0.2.2) at the server's own port in FULL mode, or
+ # via the guestfwd relay in MOUNTS_ONLY mode.
uses_guestfwd = self._smb_server.get_guestfwd_cmd() is not None
if uses_guestfwd or self.config.network_mode is NetworkMode.MOUNTS_ONLY:
diff --git a/packages/quicksand-smb/quicksand_smb/__init__.py b/packages/quicksand-smb/quicksand_smb/__init__.py
index f91b9c8..8ef2363 100644
--- a/packages/quicksand-smb/quicksand_smb/__init__.py
+++ b/packages/quicksand-smb/quicksand_smb/__init__.py
@@ -1,21 +1,30 @@
"""quicksand-smb: Pure-Python SMB3 server for host-guest directory mounts.
-This server runs in inetd mode (stdin/stdout) and is spawned per-connection
-by QEMU's guestfwd mechanism. No TCP listener, no auth, no external deps.
+The dispatch loop serves a single connection over either transport:
+
+- stdin/stdout (inetd-style), spawned per-connection by QEMU's guestfwd
+ mechanism (macOS/Linux), via :func:`serve_stdio`; or
+- a connected socket, used by a persistent loopback TCP listener (Windows),
+ via :func:`serve_socket`.
+
+No auth, no external deps.
Usage:
python -m quicksand_smb --config /path/to/config.json
Public API:
SMBConfig — share configuration
- serve_stdio — main server loop (reads stdin, writes stdout)
+ serve_stdio — serve one connection over stdin/stdout
+ serve_socket — serve one connection over a connected socket
"""
from __future__ import annotations
import json
import logging
+import socket
import struct
+from collections.abc import Callable
from dataclasses import dataclass, field
from pathlib import Path
@@ -36,8 +45,10 @@ from ._protocol import (
build_error_response,
parse_request,
read_frame,
+ read_frame_from_sock,
split_compound,
write_frame,
+ write_frame_to_sock,
)
from ._query import handle_query_directory, handle_query_info, handle_set_info
from ._status import STATUS_NOT_IMPLEMENTED, STATUS_SUCCESS
@@ -213,95 +224,125 @@ def _dispatch(session: SMBSession, req: SMBRequest) -> bytes:
return build_error_response(req.header, STATUS_NOT_IMPLEMENTED)
-def serve_stdio(config: SMBConfig, config_path: str | None = None) -> None:
- """Main server loop: read SMB frames from stdin, dispatch, write responses to stdout.
+def _serve_loop(
+ read_frame_fn: Callable[[], bytes],
+ write_frame_fn: Callable[[bytes], None],
+ config: SMBConfig,
+ config_path: str | None = None,
+) -> None:
+ """Dispatch SMB frames until the transport closes.
- Runs until stdin is closed (QEMU terminates the connection).
+ Reads framed requests via ``read_frame_fn`` and writes framed responses via
+ ``write_frame_fn``, so the same logic serves both the stdin/stdout (inetd)
+ transport and a connected socket.
"""
- _init_io()
session = SMBSession(config=config, config_path=config_path)
- while True:
- try:
- raw = read_frame()
- except EOFError:
- break
-
- logger.debug("Frame: %d bytes, hex=%s", len(raw), raw.hex())
-
- # SMB1 negotiate: some clients send \xFFSMB first to discover SMB2.
- # Respond with SMB2 negotiate error to force protocol upgrade.
- if raw[:4] == b"\xffSMB":
- logger.debug("Received SMB1 negotiate, sending SMB2 upgrade response")
- # SMB2 negotiate response with dialect 0x02FF (wildcard) tells
- # the client to retry with SMB2. But the simplest approach is
- # to just send back a minimal SMB2 negotiate response.
- # The Linux CIFS client with vers=3.0 should NOT send SMB1,
- # but vers=default might. Log and continue.
- continue
-
- # Handle compound requests
- messages = split_compound(raw)
-
- responses: list[bytes] = []
- last_file_id: bytes = b"\x00" * 16
- last_tree_id: int = 0
- for msg_data in messages:
+ try:
+ while True:
try:
- req = parse_request(msg_data)
-
- # Compound related operations: inherit FileId/TreeId from
- # the previous response in the chain
- if req.header.flags & 0x04: # SMB2_FLAGS_RELATED_OPERATIONS
- if req.header.tree_id == 0:
- req.header.tree_id = last_tree_id
- # Replace sentinel FileId (0xFFFF...) in payload
- sentinel = b"\xff" * 16
- if sentinel in req.payload:
- req = SMBRequest(
- header=req.header,
- payload=req.payload.replace(sentinel, last_file_id, 1),
- raw=req.raw,
- )
-
- resp = _dispatch(session, req)
- responses.append(resp)
-
- # Track FileId from CREATE responses for compound chains
- if req.header.command == Command.CREATE and len(resp) >= 64 + 82:
- status = struct.unpack_from("<I", resp, 8)[0]
- if status == 0:
- last_file_id = resp[64 + 64 : 64 + 80]
- last_tree_id = struct.unpack_from("<I", resp, 36)[0]
- except Exception as e:
- logger.error("Error processing SMB request: %s", e, exc_info=True)
+ raw = read_frame_fn()
+ except EOFError:
+ break
+
+ logger.debug("Frame: %d bytes, hex=%s", len(raw), raw.hex())
+
+ # SMB1 negotiate: some clients send \xFFSMB first to discover SMB2.
+ # Respond with SMB2 negotiate error to force protocol upgrade.
+ if raw[:4] == b"\xffSMB":
+ logger.debug("Received SMB1 negotiate, sending SMB2 upgrade response")
+ # SMB2 negotiate response with dialect 0x02FF (wildcard) tells
+ # the client to retry with SMB2. But the simplest approach is
+ # to just send back a minimal SMB2 negotiate response.
+ # The Linux CIFS client with vers=3.0 should NOT send SMB1,
+ # but vers=default might. Log and continue.
+ continue
+
+ # Handle compound requests
+ messages = split_compound(raw)
+
+ responses: list[bytes] = []
+ last_file_id: bytes = b"\x00" * 16
+ last_tree_id: int = 0
+ for msg_data in messages:
try:
- from ._protocol import parse_header
-
- hdr = parse_header(msg_data)
- from ._status import STATUS_UNSUCCESSFUL
-
- responses.append(build_error_response(hdr, STATUS_UNSUCCESSFUL))
- except Exception:
- break
-
- # Write compound response
- if len(responses) == 1:
- write_frame(responses[0])
- elif responses:
- # Chain responses: set NextCommand in headers
- parts = []
- for i, resp in enumerate(responses):
- if i < len(responses) - 1:
- # Pad to 8-byte alignment and set NextCommand
- padded_len = (len(resp) + 7) & ~7
- resp = resp.ljust(padded_len, b"\x00")
- # NextCommand is at offset 20 in SMB2 header
- ba = bytearray(resp)
- struct.pack_into("<I", ba, 20, padded_len)
- resp = bytes(ba)
- parts.append(resp)
- write_frame(b"".join(parts))
-
- # Cleanup
- session.handles.close_all()
+ req = parse_request(msg_data)
+
+ # Compound related operations: inherit FileId/TreeId from
+ # the previous response in the chain
+ if req.header.flags & 0x04: # SMB2_FLAGS_RELATED_OPERATIONS
+ if req.header.tree_id == 0:
+ req.header.tree_id = last_tree_id
+ # Replace sentinel FileId (0xFFFF...) in payload
+ sentinel = b"\xff" * 16
+ if sentinel in req.payload:
+ req = SMBRequest(
+ header=req.header,
+ payload=req.payload.replace(sentinel, last_file_id, 1),
+ raw=req.raw,
+ )
+
+ resp = _dispatch(session, req)
+ responses.append(resp)
+
+ # Track FileId from CREATE responses for compound chains
+ if req.header.command == Command.CREATE and len(resp) >= 64 + 82:
+ status = struct.unpack_from("<I", resp, 8)[0]
+ if status == 0:
+ last_file_id = resp[64 + 64 : 64 + 80]
+ last_tree_id = struct.unpack_from("<I", resp, 36)[0]
+ except Exception as e:
+ logger.error("Error processing SMB request: %s", e, exc_info=True)
+ try:
+ from ._protocol import parse_header
+
+ hdr = parse_header(msg_data)
+ from ._status import STATUS_UNSUCCESSFUL
+
+ responses.append(build_error_response(hdr, STATUS_UNSUCCESSFUL))
+ except Exception:
+ break
+
+ # Write compound response
+ if len(responses) == 1:
+ write_frame_fn(responses[0])
+ elif responses:
+ # Chain responses: set NextCommand in headers
+ parts = []
+ for i, resp in enumerate(responses):
+ if i < len(responses) - 1:
+ # Pad to 8-byte alignment and set NextCommand
+ padded_len = (len(resp) + 7) & ~7
+ resp = resp.ljust(padded_len, b"\x00")
+ # NextCommand is at offset 20 in SMB2 header
+ ba = bytearray(resp)
+ struct.pack_into("<I", ba, 20, padded_len)
+ resp = bytes(ba)
+ parts.append(resp)
+ write_frame_fn(b"".join(parts))
+ finally:
+ # Cleanup
+ session.handles.close_all()
+
+
+def serve_stdio(config: SMBConfig, config_path: str | None = None) -> None:
+ """Serve one connection over stdin/stdout (inetd-style).
+
+ Runs until stdin is closed (QEMU terminates the connection).
+ """
+ _init_io()
+ _serve_loop(read_frame, write_frame, config, config_path)
+
+
+def serve_socket(sock: socket.socket, config: SMBConfig, config_path: str | None = None) -> None:
+ """Serve one connection over a connected socket.
+
+ Runs until the peer closes the socket. Used by the persistent TCP listener
+ on Windows, where ``os.read``/``os.write`` on a socket fd is unavailable.
+ """
+ _serve_loop(
+ lambda: read_frame_from_sock(sock),
+ lambda data: write_frame_to_sock(sock, data),
+ config,
+ config_path,
+ )
diff --git a/packages/quicksand-smb/quicksand_smb/_files.py b/packages/quicksand-smb/quicksand_smb/_files.py
index 6a4038d..0b649c1 100644
--- a/packages/quicksand-smb/quicksand_smb/_files.py
+++ b/packages/quicksand-smb/quicksand_smb/_files.py
@@ -30,6 +30,34 @@ from ._status import (
STATUS_SUCCESS,
)
+# Positional file I/O. ``os.pread``/``os.pwrite`` are atomic (no seek) but
+# POSIX-only; Windows has neither, so fall back to ``lseek`` + ``read``/``write``.
+# Each open handle is only touched by its own connection thread, so the
+# non-atomic fallback is safe here.
+if hasattr(os, "pread"):
+
+ def _pread(fd: int, length: int, offset: int) -> bytes:
+ return os.pread(fd, length, offset)
+
+ def _pwrite(fd: int, data: bytes, offset: int) -> int:
+ return os.pwrite(fd, data, offset)
+
+else:
+
+ def _pread(fd: int, length: int, offset: int) -> bytes:
+ os.lseek(fd, offset, os.SEEK_SET)
+ return os.read(fd, length)
+
+ def _pwrite(fd: int, data: bytes, offset: int) -> int:
+ os.lseek(fd, offset, os.SEEK_SET)
+ return os.write(fd, data)
+
+
+# Open in binary mode on Windows so the OS does no CRLF/EOF translation;
+# os.O_BINARY does not exist on POSIX (where all I/O is already binary).
+_O_BINARY = getattr(os, "O_BINARY", 0)
+
+
# CreateDisposition values
FILE_SUPERSEDE = 0x00000000
FILE_OPEN = 0x00000001
@@ -283,7 +311,7 @@ def handle_create(
if not share_readonly and wants_write:
flags = os.O_RDWR
try:
- fd = os.open(str(target), flags)
+ fd = os.open(str(target), flags | _O_BINARY)
except PermissionError:
return build_error_response(req.header, STATUS_ACCESS_DENIED)
except FileNotFoundError:
@@ -449,7 +477,7 @@ def handle_read(req: SMBRequest, handles: HandleManager) -> bytes:
return build_error_response(req.header, STATUS_FILE_IS_A_DIRECTORY)
try:
- data = os.pread(info.fd, length, offset)
+ data = _pread(info.fd, length, offset)
except OSError:
return build_error_response(req.header, STATUS_END_OF_FILE)
@@ -508,7 +536,7 @@ def handle_write(req: SMBRequest, handles: HandleManager) -> bytes:
write_data = payload[data_start : data_start + length]
try:
- written = os.pwrite(info.fd, write_data, offset)
+ written = _pwrite(info.fd, write_data, offset)
except OSError:
return build_error_response(req.header, STATUS_ACCESS_DENIED)
diff --git a/packages/quicksand-smb/quicksand_smb/_protocol.py b/packages/quicksand-smb/quicksand_smb/_protocol.py
index 796d6bb..b00bc6d 100644
--- a/packages/quicksand-smb/quicksand_smb/_protocol.py
+++ b/packages/quicksand-smb/quicksand_smb/_protocol.py
@@ -9,6 +9,7 @@ Reference: [MS-SMB2] Sections 2.2.1 (header) and 2.2.3 (negotiate).
from __future__ import annotations
import os
+import socket
import struct
import sys
from dataclasses import dataclass
@@ -112,6 +113,40 @@ def write_frame(data: bytes) -> None:
os.write(_stdout_fd, header + data)
+# ---------------------------------------------------------------------------
+# I/O: read/write over a connected socket
+#
+# Used when the server runs as a persistent TCP listener (Windows) rather than
+# inetd-style over stdin/stdout. ``os.read``/``os.write`` cannot be used on a
+# socket fd on Windows ("Bad file descriptor"), so these go through the socket's
+# own ``recv``/``sendall``.
+# ---------------------------------------------------------------------------
+
+
+def _read_exactly_sock(sock: socket.socket, n: int) -> bytes:
+ """Read exactly n bytes from *sock*, or raise EOFError on close."""
+ buf = bytearray()
+ while len(buf) < n:
+ chunk = sock.recv(n - len(buf))
+ if not chunk:
+ raise EOFError("socket closed")
+ buf.extend(chunk)
+ return bytes(buf)
+
+
+def read_frame_from_sock(sock: socket.socket) -> bytes:
+ """Read one NetBIOS-framed SMB message from *sock*."""
+ length_bytes = _read_exactly_sock(sock, 4)
+ length = struct.unpack(">I", length_bytes)[0]
+ return _read_exactly_sock(sock, length)
+
+
+def write_frame_to_sock(sock: socket.socket, data: bytes) -> None:
+ """Write one NetBIOS-framed SMB message to *sock*."""
+ header = struct.pack(">I", len(data))
+ sock.sendall(header + data)
+
+
# ---------------------------------------------------------------------------
# Header parsing / building
# ---------------------------------------------------------------------------
diff --git a/packages/quicksand-smb/quicksand_smb/_query.py b/packages/quicksand-smb/quicksand_smb/_query.py
index 50d6899..a26bc7d 100644
--- a/packages/quicksand-smb/quicksand_smb/_query.py
+++ b/packages/quicksand-smb/quicksand_smb/_query.py
@@ -35,6 +35,47 @@ from ._status import (
logger = logging.getLogger("quicksand.smb.query")
+
+class _FsStats:
+ """Filesystem capacity in the subset of ``os.statvfs`` fields used below.
+
+ ``os.statvfs`` is POSIX-only; on Windows we derive the same values from
+ ``shutil.disk_usage`` (bytes) using a fixed allocation-unit size.
+ """
+
+ __slots__ = ("f_bavail", "f_bfree", "f_blocks", "f_frsize")
+
+ def __init__(self, f_blocks: int, f_bavail: int, f_bfree: int, f_frsize: int) -> None:
+ self.f_blocks = f_blocks
+ self.f_bavail = f_bavail
+ self.f_bfree = f_bfree
+ self.f_frsize = f_frsize
+
+
+def _fs_stats(path: Path) -> _FsStats | None:
+ """Return filesystem capacity stats for *path*, cross-platform."""
+ if hasattr(os, "statvfs"):
+ try:
+ svfs = os.statvfs(str(path))
+ except OSError:
+ return None
+ return _FsStats(svfs.f_blocks, svfs.f_bavail, svfs.f_bfree, svfs.f_frsize)
+
+ import shutil
+
+ try:
+ usage = shutil.disk_usage(str(path))
+ except OSError:
+ return None
+ frsize = 4096
+ return _FsStats(
+ usage.total // frsize,
+ usage.free // frsize,
+ usage.free // frsize,
+ frsize,
+ )
+
+
# InfoType values
SMB2_0_INFO_FILE = 0x01
SMB2_0_INFO_FILESYSTEM = 0x02
@@ -313,10 +354,7 @@ def _handle_file_info(
def _handle_fs_info(info_class: int, path: Path) -> bytes | None:
"""Build response data for SMB2_0_INFO_FILESYSTEM queries."""
- try:
- svfs = os.statvfs(str(path))
- except OSError:
- svfs = None
+ svfs = _fs_stats(path)
if info_class == FS_VOLUME_INFORMATION:
label = "quicksand".encode("utf-16-le")
diff --git a/tests/unit/smb/test_smb_server.py b/tests/unit/smb/test_smb_server.py
index ae5f514..31343be 100644
--- a/tests/unit/smb/test_smb_server.py
+++ b/tests/unit/smb/test_smb_server.py
@@ -496,7 +496,11 @@ class TestPathTraversal:
# Create symlink inside share pointing outside
link = share_dir / "escape"
- link.symlink_to(secret)
+ try:
+ link.symlink_to(secret)
+ except (OSError, NotImplementedError) as e:
+ # Windows needs Administrator or Developer Mode to create symlinks.
+ pytest.skip(f"cannot create symlink on this platform: {e}")
session = self._setup_session(share_dir)
status = self._try_create(session, "escape")
diff --git a/tests/unit/test_dev_build.py b/tests/unit/test_dev_build.py
index 6247b96..bb5fae8 100644
--- a/tests/unit/test_dev_build.py
+++ b/tests/unit/test_dev_build.py
@@ -4,6 +4,7 @@ from __future__ import annotations
from unittest.mock import patch
+import pytest
from quicksand_image_tools.build import (
_find_initrd,
_find_kernel,
@@ -114,7 +115,11 @@ class TestGetDirSize:
def test_ignores_symlinks(self, tmp_dir):
"""Test that symlinks are not counted."""
(tmp_dir / "file").write_bytes(b"a" * 100)
- (tmp_dir / "link").symlink_to(tmp_dir / "file")
+ try:
+ (tmp_dir / "link").symlink_to(tmp_dir / "file")
+ except (OSError, NotImplementedError) as e:
+ # Windows needs Administrator or Developer Mode to create symlinks.
+ pytest.skip(f"cannot create symlink on this platform: {e}")
size = _get_dir_size(tmp_dir)
assert size == 100
diff --git a/tests/unit/test_smb_tcp_server.py b/tests/unit/test_smb_tcp_server.py
new file mode 100644
index 0000000..ee6e8c1
--- /dev/null
+++ b/tests/unit/test_smb_tcp_server.py
@@ -0,0 +1,177 @@
+"""Unit tests for QuicksandSMBTCPServer (the Windows loopback TCP SMB server).
+
+These run on every platform — the server binds 127.0.0.1 and serves the
+pure-Python SMB3 implementation over a socket, independent of any VM.
+"""
+
+from __future__ import annotations
+
+import os
+import socket
+import struct
+from unittest.mock import patch
+
+import pytest
+from quicksand_core.host.smb import (
+ QuicksandSMBServer,
+ QuicksandSMBTCPServer,
+ WindowsSMBServer,
+ create_smb_server,
+)
+from quicksand_smb._protocol import SMB2_MAGIC, Command
+
+
+def _frame(data: bytes) -> bytes:
+ """Add NetBIOS framing (4-byte big-endian length prefix)."""
+ return struct.pack(">I", len(data)) + data
+
+
+def _smb_header(command: int) -> bytes:
+ """Build a minimal SMB2 sync request header."""
+ return struct.pack(
+ "<4sHHIHHIIQIIQ16s",
+ SMB2_MAGIC,
+ 64, # StructureSize
+ 0, # CreditCharge
+ 0, # Status
+ command,
+ 1, # CreditRequest
+ 0, # Flags
+ 0, # NextCommand
+ 0, # MessageId
+ 0, # Reserved/ProcessId
+ 0, # TreeId
+ 0, # SessionId
+ b"\x00" * 16, # Signature
+ )
+
+
+def _negotiate_frame() -> bytes:
+ """A framed SMB2 NEGOTIATE request advertising dialect 3.0."""
+ dialects = struct.pack("<H", 0x0300)
+ body = struct.pack("<HHHHI16sIHH", 36, 1, 0, 0, 0, os.urandom(16), 0, 0, 0)
+ body = body[:36] + dialects
+ return _frame(_smb_header(Command.NEGOTIATE) + body)
+
+
+def _read_status(data: bytes) -> int:
+ """Extract NTSTATUS from a framed SMB2 response buffer."""
+ length = struct.unpack_from(">I", data, 0)[0]
+ payload = data[4 : 4 + length]
+ return struct.unpack_from("<I", payload, 8)[0]
+
+
+def tcp_server():
+ srv = QuicksandSMBTCPServer()
+ srv.start()
+ try:
+ yield srv
+ finally:
+ srv.stop()
+
+
+class TestLifecycle:
+ def test_start_binds_loopback_port(self, tcp_server):
+ assert tcp_server.port > 0
+ # The port accepts connections while running.
+ c = socket.create_connection(("127.0.0.1", tcp_server.port), timeout=3)
+ c.close()
+
+ def test_credentials_are_guest(self, tcp_server):
+ assert tcp_server.credentials == ("guest", "")
+
+ def test_get_guestfwd_cmd_is_none(self, tcp_server):
+ # None routes mounts through the slirp gateway, not a guestfwd tunnel.
+ assert tcp_server.get_guestfwd_cmd() is None
+
+ def test_stop_closes_listener(self):
+ srv = QuicksandSMBTCPServer()
+ srv.start()
+ port = srv.port
+ srv.stop()
+ assert srv.port == 0
+ with pytest.raises(OSError):
+ socket.create_connection(("127.0.0.1", port), timeout=1)
+
+
+class TestShareConfig:
+ def test_add_and_remove_share(self, tcp_server, tmp_path):
+ name = tcp_server.add_share(str(tmp_path), readonly=True)
+ assert name.startswith("QUICKSAND_")
+ shares = tcp_server.list_shares()
+ assert len(shares) == 1
+ assert shares[0]["host_path"] == str(tmp_path)
+ assert shares[0]["readonly"] is True
+
+ tcp_server.remove_share(name)
+ assert tcp_server.list_shares() == []
+
+ def test_add_share_creates_missing_dir(self, tcp_server, tmp_path):
+ target = tmp_path / "made" / "bythserver"
+ tcp_server.add_share(str(target), readonly=False)
+ assert target.is_dir()
+
+
+class TestServeSocket:
+ def test_negotiate_round_trip(self, tcp_server, tmp_path):
+ """A real client connection gets a successful NEGOTIATE response."""
+ tcp_server.add_share(str(tmp_path), readonly=False)
+
+ c = socket.create_connection(("127.0.0.1", tcp_server.port), timeout=5)
+ try:
+ c.sendall(_negotiate_frame())
+ # Read the 4-byte length prefix, then the payload.
+ header = b""
+ while len(header) < 4:
+ chunk = c.recv(4 - len(header))
+ assert chunk, "server closed before responding"
+ header += chunk
+ length = struct.unpack(">I", header)[0]
+ payload = b""
+ while len(payload) < length:
+ chunk = c.recv(length - len(payload))
+ assert chunk, "truncated response"
+ payload += chunk
+ finally:
+ c.close()
+
+ assert payload[:4] == SMB2_MAGIC
+ assert struct.unpack_from("<I", payload, 8)[0] == 0 # STATUS_SUCCESS
+
+ def test_multiple_sequential_connections(self, tcp_server, tmp_path):
+ """The listener keeps serving after a connection closes."""
+ tcp_server.add_share(str(tmp_path), readonly=False)
+ for _ in range(3):
+ c = socket.create_connection(("127.0.0.1", tcp_server.port), timeout=5)
+ try:
+ c.sendall(_negotiate_frame())
+ resp = c.recv(4096)
+ assert resp[4:8] == SMB2_MAGIC
+ finally:
+ c.close()
+
+
+class TestFactory:
+ def test_non_windows_returns_guestfwd_server(self):
+ with patch("quicksand_core.host.smb.sys.platform", "linux"):
+ srv = create_smb_server()
+ assert isinstance(srv, QuicksandSMBServer)
+ assert not isinstance(srv, QuicksandSMBTCPServer)
+
+ def test_windows_default_returns_tcp_server(self):
+ with (
+ patch("quicksand_core.host.smb.sys.platform", "win32"),
+ patch.dict(os.environ, {}, clear=False),
+ ):
+ os.environ.pop("QUICKSAND_WINDOWS_NATIVE_SMB", None)
+ srv = create_smb_server()
+ assert isinstance(srv, QuicksandSMBTCPServer)
+
+ def test_windows_native_opt_in(self):
+ with (
+ patch("quicksand_core.host.smb.sys.platform", "win32"),
+ patch.dict(os.environ, {"QUICKSAND_WINDOWS_NATIVE_SMB": "1"}, clear=False),
+ ):
+ srv = create_smb_server()
+ assert isinstance(srv, WindowsSMBServer)