Skip to content

FLT-359 Fix Round 5 / 5b / 5c / 5d: Full Unix Ledger Path Guard + Display Sanitization

Decision by Andrew (2026-10-31): "Fix Unix properly" rather than restricting the executor ledger to Windows-only.

1. Linux/Unix POSIX (fcntl) Lock Preservation and Coordinated Per-Inode Pinning (src/Forge.Approvals.Cli/LedgerPathGuard.cs, src/Forge.Approvals.Cli/SqliteApprovalLedger.cs)

  • Problem (Cedric P1, LedgerPathGuard.cs:97-101; Round 5b/5c Findings): On Linux/POSIX, fcntl record locks (F_SETLK/F_SETLKW) are associated with (process, inode). Closing any file descriptor referring to that inode in the process immediately releases all POSIX record locks held by the process on that file—including active BEGIN IMMEDIATE transaction locks held by SQLite on another descriptor. Conversely, pinning descriptors into a static table before .identity and schema validation succeed would retain file descriptors for failed/probed files, while allowing two concurrent cold opens to open separate provisional descriptors could close a duplicate descriptor mid-transaction or on GC finalization.
  • Fix:
  • LedgerPathGuard coordinates both provisional and committed descriptors per (Device, Inode) under UnixPinLock via UnixInodePin(Handle, Identity, ActiveGuards, Committed) in PinnedUnixFiles.
  • When OpenUnixLeaf runs on Linux, at most one file descriptor is opened per (Device, Inode) across the process. Concurrent guards opening the same (Device, Inode) before or after CommitPin() increment ActiveGuards and share the same SafeFileHandle rather than opening a second descriptor that could later be closed or finalized.
  • SqliteApprovalLedger calls guard.CommitPin() (unixPin.Committed = true) only after CheckIdentity(), VerifyConnectionHandle(), VerifyUnchanged(), and PRAGMA user_version == 1 succeed. If validation fails before CommitPin(), LedgerPathGuard.Dispose() decrements ActiveGuards and disposes/evicts the provisional descriptor when ActiveGuards == 0 && !Committed, so failed opens never leak file descriptors and never close a descriptor while another guard is active.
  • SqliteApprovalLedger serializes in-process ledger operations via ProcessGate and wraps every BEGIN IMMEDIATE block in TryObserveAsync, TryRecordAsync, and TryCommitEffectAsync with try/finally that explicitly executes ROLLBACK whenever committed is false before closing the connection.
  • VerifyUnchanged() on Linux never opens or closes a file descriptor to the database inode: it re-stats held directory descriptors and unixPin.Handle with fstat, re-walks ancestor directories from / via openat(O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC), verifies the leaf directory entry via fstatat(leafDirFd, fileName, AT_SYMLINK_NOFOLLOW), and verifies/hardens any -journal, -wal, and -shm side files in leafDirFd via VerifyUnixSideFiles.
  • Problem (Gronktayvius General & Red Team High, Jenny K1/K2, CedricFocus Round 5b/5c Findings):
  • open(path, O_NOFOLLOW) only checks the final component of each call and does not prevent ancestor directory rename swaps on Unix between the guard check and sqlite3_open_v2(path).
  • Passing /proc/self/fd/<fileFd> directly to sqlite3_open_v2 causes SQLite's unixFullPathname (lstat + readlink on the final path component) to either resolve the /proc/self/fd/<fileFd> symlink back to the mutable filesystem path or fail when attempting to create /proc/self/fd/<fileFd>-journal inside procfs.
  • Scanning /proc/self/fd for "any matching descriptor" does not prove which descriptor belongs to the specific sqlite3* connection when another descriptor to the ledger is open in the process.
  • Upstream SQLite creates -journal, -wal, and -shm with mode 0644 masked by process umask; enforcing mode 0600 (384u) in the custom VFS open syscall wrapper and hardening any existing side files to 0600 via fchmod closes any group/world-readable window without mutating process-global umask.
  • Loading bare libsqlite3.so.0 on Linux allows LD_LIBRARY_PATH / app-directory search order hijacking, and following a soname symlink with fstatat(..., 0) without validating the resolved target's directory chain or pinning the opened .so descriptor leaves a path-reopen window.
  • Fix:
  • Anchored openat directory walk with strict ancestor ownership/mode checks: Every directory component from / is walked step-by-step via openat(parentFd, segment, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) (and created during PrepareDirectory / SavePrivateRecord via mkdirat(parentFd, segment, 0700) + openat + fchmod(fd, 0700) to clear any inherited S_ISGID bit). Every directory descriptor is verified via fstat to be S_ISDIR ((mode & 0xF000) == 0x4000) with nlink >= 1, owned by root or the effective UID (uid == 0 || uid == geteuid()), and free of group/other write bits (0x012) unless the sticky bit (0x200) is set; the leaf directory (for both the ledger and FileRequestStore) additionally requires RequirePrivate (uid == geteuid() and mode 0700 on Unix; protected owner-only DACL on Windows).
  • Non-blocking single-link regular-file leaf open: The leaf database file is checked via fstatat(leafDirFd, fileName, AT_SYMLINK_NOFOLLOW) and opened relative to leafDirFd with openat(leafDirFd, fileName, O_RDWR | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC, 0600) (plus O_CREAT | O_EXCL and fchmod(fd, 0600) on creation). Both fstatat and fstat enforce (mode & 0xF000) == 0x8000 (S_ISREG), nlink == 1, uid == geteuid(), and mode 0600, rejecting FIFOs, sockets, device nodes, symlinks, hard-linked files (nlink > 1), and directories.
  • SQLite opened via /proc/self/fd/<leafDirFd>/<leafName> and verified directly before any PRAGMA runs:
    • LedgerPathGuard.ResolveOpenPath requires a live file guard matching Path.GetFullPath(filePath) and on Linux returns /proc/self/fd/<leafDirFd>/<leafName>.
    • Immediately across sqlite3_open_v2—before PRAGMA trusted_schema=OFF, PRAGMA foreign_keys=ON, or PRAGMA synchronous=FULL executes—SqliteApprovalLedger.Database retrieves SQLite's own connection handle/descriptor for "main": on Windows via SQLITE_FCNTL_WIN32_GET_HANDLE (29), and on Linux x64 via a registered sqlite3_vfs ("forge_unix", cloned from sqlite3_vfs_find(NULL)) whose xOpen wrapper intercepts the sqlite3_vfs "open" system call (xGetSystemCall/xSetSystemCall on sqlite3_vfs v3) under VfsSync + UnixPinLock using a [ThreadStatic] recorder (activeSysOpenRecorder), enforces mode 0600 (384u) on any created file without mutating process-global umask, preserves/restores native errno (SetLastError = true on UnixSysOpenDelegate + Marshal.GetLastPInvokeError() / Marshal.SetLastSystemError), and binds the exact fd returned by SQLite's open syscall (openCallCount == 1, ordinal expectedOpenPath match) directly to that sqlite3_file* (pFile) via LedgerPathGuard.CaptureVfsMainDbOpen(pFile, expectedOpenPath, ..., CleanupRejectedVfsOpen). If baseOpen succeeds (rc == 0) but the VFS binding is invalid (pathMismatch, openCallCount != 1, or openedFd < 0), CleanupRejectedVfsOpen invokes pFile->pMethods->xClose(pFile), clears pFile->pMethods = IntPtr.Zero (NULL) per SQLite's xOpen error contract, and returns 14 (SQLITE_CANTOPEN). Database then queries SQLITE_FCNTL_FILE_POINTER (7) and claims the descriptor via guard.ClaimVfsConnectionDescriptor(sqliteFilePtr), and guard.VerifyConnectionHandle(borrowed, dbFilename) verifies sqliteDbFilename, RequirePrivate(borrowed, path, false), and ReadIdentity(borrowed, false) == guard.FileIdentity directly on SQLite's descriptor.
    • SqliteApprovalLedger rejects embedded NUL (\0) characters in bound parameters (PersonId, ChallengeId, and Database.Execute values) and passes explicit UTF-8 byte lengths (Encoding.UTF8.GetByteCount) to sqlite3_bind_text.
    • VerifyUnixSideFiles checks -journal, -wal, and -shm in leafDirFd via fstatat(..., AT_SYMLINK_NOFOLLOW) before BEGIN/COMMIT/ROLLBACK statements step (and after BEGIN steps, never after COMMIT has already stepped), requiring S_ISREG, nlink == 1, and uid == geteuid(), and tightening any SQLite-created side file whose mode is not yet 0600 via openat(O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) + fstat inode match + fchmod(0600).
  • Root-owned system libsqlite3.so.0 resolution and fd pinning on Linux: LedgerPathGuard.ResolveTrustedUnixSqlite() resolves any soname symlink hop via readlinkat (up to 4 hops), walks every ancestor directory of the resolved target from / with O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC requiring uid == 0 and (mode & 0x012) == 0, opens the final regular .so file with O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC, verifies fstat (S_ISREG, nlink == 1, uid == 0, (mode & 0x012) == 0), pins the handle in PinnedUnixSqliteLibrary, and returns /proc/self/fd/<libFd> to NativeLibrary.Load.
  • Ancestor- and path-bound .identity record with atomic renameat2(RENAME_NOREPLACE) publication: SqliteApprovalLedger.Initialize() calls fileGuard.SaveIdentity() inside the initialization transaction prior to COMMIT (rolling back the transaction and cleaning up unconditionally via no-follow RemoveIdentityIfPresent() if any step before CommitPin() fails), publishing .identity via renameat2(..., RENAME_NOREPLACE) on Linux (File.Move(..., overwrite: false) on Windows), and CheckIdentity verifies canonical Path, FileIdentity, and the full Ancestors chain.
  • Anchored FileRequestStore.Save, fail-closed FileRequestStore.Load, and hardened FileNotificationOutbox:
    • LedgerPathGuard.SavePrivateRecord and OpenPrivateRead enforce ValidateSingleFileName(fileName) (rejecting empty, ., .., path separators, :, trailing . or ' ', NUL, and Windows reserved device names CON, PRN, AUX, NUL, CONIN$, CONOUT$, COM1..COM9, LPT1..LPT9), enforce RequirePrivate on the leaf store directory (0700 on Unix, protected owner-only DACL on Windows), and publish <jti>.json atomically without overwrite via renameat2(..., RENAME_NOREPLACE) on Unix (File.Move(..., overwrite: false) on Windows).
    • FileRequestStore.Load opens request files via LedgerPathGuard.OpenPrivateRead(directory, fileName), enforces a byte-length cap before JSON deserialization, rejects null/whitespace ChallengeId, and catches only FileNotFoundException/DirectoryNotFoundException as null while allowing tamper, permission, symlink, oversized-payload, and malformed-JSON exceptions to propagate.
    • FileNotificationOutbox walks and pins the outbox directory without following symlinks or reparse points (O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC + 0700 + uid == geteuid() on Unix; single-component CreateDirectoryW + CreateFileW(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT) without FILE_SHARE_DELETE + handle-bound SetKernelObjectSecurity/GetKernelObjectSecurity owner-only DACL on Windows), writes a private 0600 temporary marker relative to the pinned directory that omits Jti (.pending-{guid}.tmp), publishes without overwrite (renameat2(..., RENAME_NOREPLACE) on Unix; File.Move(..., overwrite: false) on Windows), separates atomic publication (TryPublishMarkerNoReplace) from post-publish verification and durability (VerifyAndFlushPublishedMarker + FlushPinnedDirectoryHandle(outboxDirHandle)), verifies directory chain identity (VerifyOutboxChainUnchanged) across reservation and synchronization, and durably flushes the pinned directory handle before dispatch.

3. Complete Display Sanitization Across Push and Email Sinks (src/Forge.Approvals.Twilio/TwilioProvider.cs, src/Forge.Approvals.Notify/Notifications.cs)

  • Problem (Jenny K3 High, TwilioProvider.cs:45-50, TwilioProvider.cs:171-173):
  • BuildDeviceMessage sanitized EffectBinding and HumanSummary but interpolated target and request.Action.Ticket without calling SanitizeDisplayText.
  • SanitizeDisplayText iterated UTF-16 char code units, where char.GetUnicodeCategory returns UnicodeCategory.Surrogate for surrogate pairs, allowing supplementary-plane UnicodeCategory.Format characters (such as Unicode Tag characters U+E0001, U+E0020..U+E007F and musical format controls U+1D173..U+1D17A) and unpaired surrogates through.
  • Fix:
  • BuildDeviceMessage and EmailNotifier now pass kind, target, ticket, commandSha256, effect, summary, and serializedAction through SanitizeDisplayText.
  • SanitizeDisplayText in both TwilioProvider and EmailNotifier enforces ArgumentNullException.ThrowIfNull and decodes Unicode scalar values with Rune.TryGetRuneAt: unpaired surrogates (TryGetRuneAt == false), C0/C1 controls (Rune.IsControl), UnicodeCategory.Format (BMP and non-BMP), UnicodeCategory.LineSeparator (U+2028), UnicodeCategory.ParagraphSeparator (U+2029), and non-' ' UnicodeCategory.SpaceSeparator scalar values are all replaced with ' '.
  • CI TRX gate cleanup (ci/Assert-TestResults.ps1, ci/Test-AssertTestResults.ps1):
  • Assert-TestResults.ps1 enforces executed == discovered and passed == discovered and includes pending, inProgress, and warning in the counter denylist.
  • Test-AssertTestResults.ps1 writes its synthetic TRX fixtures under a unique temp directory and removes it in finally.