Contents · Forum Home · StreamSec Tools 4.1.5.363 documentation

stFileJail

THE FILESYSTEM SECURITY BOUNDARY. A peer-supplied path plus an intended
  access in; an OPEN HANDLE on a confined object, or a refusal, out.

  TWO DIMENSIONS, ONE DECISION. Where a file may live (path confinement) and
  what kind of file may be touched (extension gating) are decided together and
  yield one verdict. They are not separable, because on Windows they share
  failure modes: 'logo.png::$DATA' and 'secrets.ini.' both defeat an extension
  allow-list through the PATH rules, not the extension rules.

  THE HANDLE IS THE RESULT, NOT THE PATH. This is the single most important
  thing about this unit's shape, and it was got wrong first time round. A jail
  whose output is a path STRING cannot be free of check-then-open races on any
  platform, however carefully the backend is written: the jail opens the object
  to inspect it, closes it, and hands back a name, and the caller then performs
  a second, independent open of that name at some later moment. Everything
  proved by the inspection has expired by then. So the verified handle IS the
  return value - see OpenVerified and OpenStream - and the physical path is
  demoted to a logging field on the handle. Resolve and ResolveUrl remain, but
  they are lexical only and deliberately emit the canonical VIRTUAL path: they
  cannot hand back anything openable, because the convenient method must not
  also be the unsafe one.

  THE ROOT IS PINNED. NewFileJail opens the root through the same OS-truth
  mechanism the backend uses for every later object, holds that handle for the
  jail's lifetime, and stores the canonical path the OS reported - never the
  answer from a lexical canonicaliser, which resolves '.' and '..' but not
  symbolic links on any platform. Without this, a document root that is itself
  a symlink (macOS /tmp and /var are; an admin-convenience symlinked docroot
  very often is) makes an honest backend refuse every request, and the usual
  repair - comparing lexically instead - makes verification decorative.

  VALIDATE WHAT YOU OPEN, NOT WHAT YOU WERE GIVEN. The lexical pass emits a
  RELATIVE path, and the backend walks it from the pinned root handle one
  segment at a time. Nothing concatenates the root with a relative path and
  re-canonicalises it, because Win32 canonicalisation MUTATES names - it strips
  trailing dots and spaces - so a jail built that way validates one name and
  opens another, which is precisely the attack this unit exists to stop.

  IMMUTABLE ONCE MINTED. NewFileJail snapshots the policy. Nothing on a live
  jail is settable and the policy object is not reachable through it. Two
  policies over one tree - a public read jail and an admin write jail over the
  same document root - are two jails. This is also what makes a jail safe to
  share across the reactor's I/O threads without locking.

  FAILS CLOSED EVERYWHERE. Every guard exits with the verdict already set to a
  refusal; an empty allow-list permits nothing; every call into a backend is
  guarded, and an unexpected exception is jvInternalError. A REFUSAL IS NEVER
  AN EXCEPTION - a Boolean gate that raises is a gate a swallowed exception
  opens - and that applies to NewFileJail itself, which always returns a usable
  interface even if construction failed.

  WHAT THIS DOES NOT CLOSE. Stated plainly, because an absolute claim here
  would be worth less than an accurate one:
    - HARD LINKS. A hard link inside the root to a file outside it is, on
      POSIX, indistinguishable from the file itself: there is no primary name
      to report. On Windows the final path of a hard link is the in-root name,
      so containment passes. jrRefuseHardLinks (link count > 1) is the only
      signal available and is blunt; it is off by default.
    - BIND MOUNTS and junction-free mount points, which are containment
      failures the filesystem itself endorses. jrSameDevice narrows this.
    - A LYING SERVER. Over SMB or NFS the answers come from the far end.
    - CASE-INSENSITIVE VOLUMES reached from a case-sensitive build, and the
      reverse. See tCaseMode; the default follows the platform, which is the
      right guess and not a guarantee.
    - ANYTHING AFTER THE HANDLE IS HANDED OVER. The jail guarantees what was
      opened. What the caller then does with it is the caller's business.

  WHAT THIS UNIT DOES NOT DECIDE. It does not map a verdict to an HTTP status.
  Distinguishing "not on the allow-list" from "not found" to the PEER is an
  information-disclosure oracle; distinguishing them in the LOG is what tells
  an operator whether they have a misconfiguration or an attacker. The jail
  reports the true cause; collapsing it for the wire is the caller's job.

Feature notes: File jail (filesystem confinement) notes

Classes, interfaces and records

recordtJailHandle

An open, verified object. The jail's actual output.

Native is the platform descriptor - a THandle on Windows, a file descriptor on POSIX - and is cJailHandleNone when nothing is open. Physical is OS TRUTH, reported by the operating system for the object that was actually opened, and is for LOGGING ONLY: re-opening it re-introduces exactly the race the handle exists to avoid.

Native: NativeInt;
The object itself.
Parent: NativeInt;
The object's PARENT DIRECTORY, or cJailHandleNone. On POSIX this is what makes a race-free mutation possible at all: unlinkat / renameat / fdopendir take a directory descriptor plus a leaf name, so nothing is ever re-resolved through a path again. Full description »
Leaf: string;
The final segment, for use with Parent.
IsDirectory: Boolean; Physical: string;
OS truth for the object that was opened. LOGGING ONLY - re-opening it re-introduces exactly the race the descriptor exists to avoid.
function IsOpen: Boolean;
Returns True if Native does not equal cJailHandleNone; otherwise False.

classtFileJailPolicy

inherits from TPersistent

Configuration for one jail. A TPersistent sub-object: configuration, not identity, so it may be copied.

NOTE ON THE OWNER TYPE. The house template (tCustomHTTPLimits) takes aOwner: TComponent. This one widens to TPersistent, a strict superset - every TComponent is a TPersistent, and GetOwner returns TPersistent regardless - because a policy must be ownable by a TCollectionItem as well as by a component: an HTTP static-file mount is a collection item, and N mounts over one tree each need their own policy without cloning a component.

constructor Create(aOwner: TPersistent); virtual; destructor Destroy; override; procedure AssignTo(Dest: TPersistent); override; procedure AllowFromMimeTypes(const aMap: iMimeTypeMap);
Fills Allowed from a media-type map, so a deployment that already configured its content types does not enumerate the same extensions twice. Only the map's explicitly present extensions are taken - which is exactly stMimeTypes.HasExtension's contract.
property Access: tJailAccessSet read fAccess write fAccess default [jaRead];
What this jail carries. Empty means the jail refuses everything.
property Options: tJailOptions read fOptions write fOptions;
See tJailOption. Defaults to cJailRulesStrict.
property ExtensionMode: tExtensionMode read fExtensionMode write fExtensionMode default emAllowListed; property CaseMode: tCaseMode read fCaseMode write fCaseMode default cmPlatform; property ShareMode: tJailShareMode read fShareMode write fShareMode default jsmShareAll;
What other processes may do to an object while a handle from this jail is open. See tJailShareMode - MANDATORY on Windows, IGNORED on POSIX, which has no equivalent.
property Allowed: TStringList read fAllowed write SetAllowed;
Permitted extensions, one per line, in either spelling. Consulted only in emAllowListed.
property Refused: TStringList read fRefused write SetRefused;
Never-permitted extensions, one per line. Consulted in BOTH modes and always wins. Applied as an extension AND as a whole-segment suffix, so a name contrived to hide its extension from ExtractFileExt still meets it. Seed it with the material that must never leave the box: .pfx .p12 .key .pem .ini .log .dat .data .bak
property MaxPathLength: Integer read fMaxPathLength write SetMaxPathLength default cMaxJailPath;

classtJailVerifier

The verification backend. Declared here so the core carries no platform API; stFileJail.Windows and stFileJail.Posix each provide a descendant and NewJailVerifier branches, following the stSocket / stSocket.Posix precedent.

EVERY METHOD MUST ASSIGN EVERY out PARAMETER ON EVERY PATH, INCLUDING REFUSALS. Delphi does not zero an out parameter of an unmanaged type on entry, so a backend that Exits early without assigning leaves the caller reading a stale value - and the stale value here decides whether something is treated as a directory.

function OpenRoot(const aRoot: string; out aHandle: tJailHandle; out aVerdict: tJailVerdict): Boolean; virtual; abstract;
Opens aRoot and pins it. On success aHandle carries the held descriptor and, in Physical, the canonical root AS THE OPERATING SYSTEM REPORTS IT. That string - not a lexical canonicaliser's answer - is what every later containment decision is measured against.
function OpenAt(const aRoot: tJailHandle; const aRelative: string; aAccess: tJailAccessSet; aOptions: tJailOptions; aCaseMode: tCaseMode; aShareMode: tJailShareMode; out aHandle: tJailHandle; out aVerdict: tJailVerdict): Boolean; virtual; abstract;
Opens aRelative beneath the pinned aRoot. aRelative is already validated and contains no '.' or '..' segment; an empty aRelative means the root itself. The backend walks it from the root descriptor - it must NOT concatenate and re-canonicalise - and confirms the opened object lies beneath the root before returning it. aAccess is the access ACTUALLY requested, never the jail's whole capability set.
function NewStream(var aHandle: tJailHandle; aAccess: tJailAccessSet; out aStream: TStream; out aVerdict: tJailVerdict): Boolean; virtual; abstract;
Wraps an open handle in a stream. OWNERSHIP OF THE HANDLE PASSES TO THE STREAM: on success aHandle is cleared and freeing the stream closes the descriptor. On failure the handle is untouched and remains the caller's to Close.
procedure Close(var aHandle: tJailHandle); virtual; abstract;
Closes and clears. Safe on an already-closed handle.

interfaceiFileJail

A minted jail. Immutable; safe to share across threads.

function Status: tJailStatus;
Why this jail is or is not usable. jsReady is the only status under which any method below can return True.
function Root: string;
The pinned canonical root, as the operating system reported it.
function Resolve(const aVirtualPath: string; aAccess: tJailAccess; out aCanonical: string; out aVerdict: tJailVerdict): Boolean;
LEXICAL ONLY - no filesystem I/O. Emits the CANONICAL VIRTUAL path (a slash-rooted string), deliberately never a physical one: these methods exist for logging, for building a redirect, and for pre-filtering, and an unsafe method that handed back something openable would be the most convenient method in the interface.
function ResolveUrl(const aUrlPath: string; aAccess: tJailAccess; out aCanonical: string; out aVerdict: tJailVerdict): Boolean;
As Resolve, percent-decoding per policy first. For URL paths.
function OpenVerified(const aVirtualPath: string; aAccess: tJailAccess; out aHandle: tJailHandle; out aVerdict: tJailVerdict): Boolean;
THE SAFE ENTRY POINTS. Resolve lexically, then walk the validated relative path from the pinned root and return the OPEN OBJECT. The caller must Close the handle.
function OpenUrlVerified(const aUrlPath: string; aAccess: tJailAccess; out aHandle: tJailHandle; out aVerdict: tJailVerdict): Boolean; function OpenStream(const aVirtualPath: string; aAccess: tJailAccess; out aStream: TStream; out aVerdict: tJailVerdict): Boolean;
As above, wrapping the verified handle in a stream the caller owns. Fails with jvAccessNotPermitted on a directory - use OpenVerified and read the handle's IsDirectory for that.
function OpenUrlStream(const aUrlPath: string; aAccess: tJailAccess; out aStream: TStream; out aVerdict: tJailVerdict): Boolean; procedure Close(var aHandle: tJailHandle);
Closes a handle obtained above. Safe on a handle THIS JAIL PRODUCED, whether the call that produced it succeeded or failed. Full description »
function ToVirtual(const aPhysical: string; out aVirtual: string): Boolean;
The reverse mapping: an ABSOLUTE physical path back to the slash-rooted virtual path a peer sees. Refuses a relative path rather than anchoring it on the process current directory. Full description »
function PermitsSegment(const aSegment: string; out aVerdict: tJailVerdict): Boolean;
Whether a whole final SEGMENT would pass this jail's name and extension rules. Takes the segment, not just the extension, so a caller building a directory listing does not advertise names the jail will then refuse.

Types (enumerations, sets, aliases)

enumtJailVerdict

Why a path was refused. One member per distinguishable cause, because the log line and the operator's next action differ for each. MEMBERS ARE ONLY EVER APPENDED - the ordinal is compiled into every consumer of a given package generation.

  tJailVerdict = (
    { Resolved and opened. }
    jvAllow,
    { Confinement failed: a '..' below the root, or an opened object outside
      it. The classic traversal. }
    jvOutsideRoot,
    { The octets could not be trusted: NUL, a control character, a separator
      or ':' surviving percent-decoding of a segment, malformed or overlong
      UTF-8, an unpaired surrogate, or a residual escape when
      jrRefusePercentAfterDecode is set. }
    jvMalformedPath,
    { A segment the OS would reinterpret: a reserved device name with or
      without an extension, a trailing dot or space, an 8.3 short-name alias,
      or a wildcard / redirection character. }
    jvReservedName,
    { Simply not on the allow-list. A CHAINED caller may legitimately read
      this as "not mine" and pass the request on. }
    jvExtensionNotPermitted,
    { On the veto list. Never anything but terminal, and always worth a loud
      log line: somebody asked for a .pfx. Overrides emAny. }
    jvExtensionRefused,
    { No extension at all, and jrAllowExtensionless is clear. Distinct from
      jvExtensionNotPermitted so the log names the switch. }
    jvNoExtension,
    { A leading-dot final segment with jrAllowDotFiles clear, or a leading-dot
      intermediate segment with jrAllowDotDirectories clear. }
    jvDotFile,
    { The requested access is not carried by this jail - a read jail asked to
      write. Decided before the path is parsed: the caller asked the wrong
      jail, not for the wrong file. }
    jvAccessNotPermitted,
    { The opened object is not beneath the pinned root: a junction, symlink or
      mount redirected it, or its link count / device says it is reachable
      from outside. }
    jvLinkEscape,
    { No verification backend is linked in for this platform, so the jail
      cannot honour its own contract and refuses everything. }
    jvNotVerifiable,
    { The path resolved and was permitted, but nothing is there. }
    jvNotFound,
    { An unexpected exception. Never leaks the exception to the caller. }
    jvInternalError,
    { The jail was never usable - see Status for which of jsBadRoot /
      jsEmptyPolicy applies. Appended rather than inserted: the ordinals above
      are compiled into consumers. }
    jvJailNotReady);

enumtExtensionMode

Whether an unlisted extension is permitted. The veto list applies in BOTH modes and always wins.

  tExtensionMode = (
    { Deny by default: only extensions in the allow-list are permitted. The
      only defensible posture for a public document root. }
    emAllowListed,
    { Permit any extension not on the veto list. For an administrative tree
      whose contents are not enumerable in advance. Requires a non-empty veto
      list - NewFileJail refuses this mode without one, because a deny-list
      that nobody filled in fails open. }
    emAny,
    { NO EXTENSION DIMENSION AT ALL. Not "an empty deny-list" - the caller is
      stating that the kind of a file carries no meaning in this tree, which
      is true of a jailed single-identity file server (SFTP) whose root IS the
      authenticated user's own home: every file in it is already theirs, and
      refusing one by its suffix would be theatre.
      It exists as an explicit mode rather than as a side effect of leaving a
      list empty, because those are different statements and only one of them
      is ever intended. A veto list is still honoured if the caller supplies
      one, and the hostile-NAME rules (a raw extension that normalises away,
      device names, trailing dots) are unaffected - those are not extension
      policy. Do NOT use this for a document root. }
    emUngated);

enumtCaseMode

How containment comparisons fold case. Both halves of every comparison use ONE fold - an earlier draft folded the equality test with ASCII SameText and the prefix test with locale-aware AnsiStartsText, so the two halves of a single containment decision disagreed about which names are the same.

  tCaseMode = (
    { Follow the platform: insensitive on Windows, sensitive on POSIX. Note
      that macOS volumes are usually case-INSENSITIVE while the platform is
      case-sensitive; set cmInsensitive explicitly for a tree on one. }
    cmPlatform,
    { Always case-sensitive (ordinal). }
    cmSensitive,
    { Always case-insensitive, ASCII fold only. Deliberately not a locale
      fold: under a Turkish locale a locale fold equates U+0130 with 'i', so
      a name could match a veto row that ASCII normalisation left alone. }
    cmInsensitive);

enumtJailAccess

What a jail carries. A jail refuses any access outside this set before it parses the path at all.

  tJailAccess = (jaRead, jaWrite, jaList, jaDelete);

settJailAccessSet

  tJailAccessSet = set of tJailAccess;

enumtJailShareMode

What OTHER processes may do to an object while this jail holds it open. WINDOWS ONLY, and that is not a caveat to bury. Windows share modes are MANDATORY - the kernel enforces them - whereas POSIX has no equivalent: flock and fcntl locks are ADVISORY, so a process that does not ask is not stopped. The POSIX backend therefore ignores this setting rather than pretending to honour it with a lock that guarantees nothing. Code that relies on a deny mode is relying on Windows behaviour. The jail's own VERIFICATION opens are unaffected and always share fully: the pinned root is held for the jail's lifetime, and a brief interrogating open must never be able to make somebody else's operation fail.

  tJailShareMode = (
    { Readers, writers and deleters all permitted. The default, because a file
      server that blocks its own operators is worse than one that does not, and
      because a static content server has no reason to lock anything. }
    jsmShareAll,
    { Other readers permitted; writers and deleters refused. This is what a
      classic file-transfer read open does - it stops the file changing under a
      transfer in progress. }
    jsmDenyWrite,
    { Nobody else at all, for as long as the handle is held. }
    jsmDenyAll);

enumtJailOption

Lexical and structural rules.

  tJailOption = (
    { Reject CON, PRN, AUX, NUL, COM1-9, LPT1-9, CONIN$, CONOUT$ and their
      extensioned forms (NUL.txt), on every platform. }
    jrRejectDeviceNames,
    { Reject the 8.3 short-name shape (<=6 chars, tilde, digits). A lexical
      pre-filter only; the backend's identity check is what actually catches
      aliases. }
    jrRejectShortNames,
    { Reject a final segment beginning with a dot (.env, .htaccess). }
    jrRejectDotFiles,
    { Reject an intermediate segment beginning with a dot (.git/). }
    jrRejectDotDirectories,
    { Permit a file with no extension at all. Off by default; note that ACME
      http-01 challenge tokens have no extension, so a jail serving
      /.well-known/acme-challenge/ needs this on. }
    jrAllowExtensionless,
    { Percent-decode each segment. URL entry points only. }
    jrPercentDecode,
    { After exactly one decode pass, refuse a segment that still contains a
      '%' followed by two hex digits - the double-encoding case. }
    jrRefusePercentAfterDecode,
    { Apply the Windows name rules on POSIX too, so a POSIX server cannot be
      used to plant a name that is a weapon on a Windows client. }
    jrPortableNames,
    { Refuse an object on a different device / volume from the pinned root,
      checked at EVERY step of the walk rather than only on the final object.
      Catches a mount point inside the root, which the walk itself cannot see -
      a mount point is not a link, so it is traversed silently.
      IT DOES NOT CATCH A BIND MOUNT WITHIN ONE FILESYSTEM. `mount --bind` of a
      directory onto another directory on the same device leaves st_dev
      unchanged, so the commonest bind-mount escape on Linux is invisible to
      this option; only a kernel-side resolver (openat2 RESOLVE_NO_XDEV) sees
      it. Off by default: a legitimate deployment may well mount content inside
      its own document root. }
    jrSameDevice,
    { Refuse an object whose link count exceeds one. The ONLY available signal
      against a hard link that reaches outside the root, and a blunt one -
      plenty of innocent trees contain hard links. Off by default; worth
      turning on for a hostile-tenant deployment. }
    jrRefuseHardLinks);

settJailOptions

  tJailOptions = set of tJailOption;

enumtJailStatus

Why NewFileJail did not produce a usable jail. A jail is always returned - it simply refuses everything - so a caller that ignores the status gets a server that serves nothing, never a server that serves anything.

  tJailStatus = (
    jsReady,
    { The root does not exist, cannot be opened, or is not a directory. }
    jsBadRoot,
    { emAllowListed with nothing allowed, or emAny with nothing vetoed. }
    jsEmptyPolicy,
    { No verification backend for this platform. }
    jsNoVerifier);

Routines