Feature notes
File jail (filesystem confinement) notes
================================================================================
FILESYSTEM CONFINEMENT (FILE JAIL)
Analysis of stFileJail and stMimeTypes (path and file-extension confinement)
(StreamSec Security Library for Embarcadero Delphi)
================================================================================
Generated: 2026-07-31
The library's single filesystem security boundary. Any component that turns a
peer-supplied name into a file - an SFTP server, an HTTP document root, an
administrative file endpoint, a challenge-token writer - goes through this unit
rather than carrying its own copy of the rules.
Companion to SFTP.txt (section 10 describes the SFTP server's use of it) and to
HTTP.txt (static content serving). Neither is required reading first.
--------------------------------------------------------------------------------
0. SUMMARY
--------------------------------------------------------------------------------
Four units in the StrSecIV runtime packages (170 through 370, i.e. XE3 through
Delphi 13). No design-time registration: nothing here is a component.
stFileJail The primitive. iFileJail, tFileJailPolicy, the verdict
enum, and the platform-neutral half of the algorithm.
stFileJail.Windows Win32 verification backend.
stFileJail.Posix POSIX verification backend (Linux, macOS, iOS,
Android).
stMimeTypes Extension to media-type registry, used both as a
content-type LABEL and as a permit predicate.
Both backend units are wrapped entirely in a platform conditional, so each is a
legal empty unit on the other platform and both sit unconditionally in every
package.
WHAT PROBLEM IT SOLVES. Given a root directory and a name that arrived from a
network peer, answer two questions together:
- may this name resolve to a file BENEATH the root, and
- may a file of this KIND be touched at all?
and, on success, hand back the OPEN OBJECT rather than a string.
WHY BOTH QUESTIONS AT ONCE. On Windows the two dimensions share failure modes.
'logo.png::$DATA' and 'secrets.ini.' both defeat an extension allow-list through
the PATH rules, not the extension rules - the first names an alternate data
stream, the second is silently rewritten to 'secrets.ini' by Win32 at open time.
An implementation that checks the path, hands back a name, and lets somebody
else check the extension has already lost.
--------------------------------------------------------------------------------
1. THE HANDLE IS THE RESULT, NOT THE PATH
--------------------------------------------------------------------------------
This is the single most important thing about the shape of the API.
A confinement primitive whose output is a path STRING cannot be free of
check-then-open races on any platform, however carefully it checks. The
sequence is always:
t0 caller asks the jail about "/uploads/report.html"
t1 jail validates, and returns C:\root\uploads\report.html
t2 somebody replaces C:\root\uploads with a link to C:\deploy
t3 caller opens the returned path, and reads C:\deploy\report.html
The string produced at t1 was correct when it was produced. It stopped being
correct before it was used, and no amount of checking at t1 can prevent that,
because t1 and t3 are separated by a window whose timing an attacker chooses.
Opening the object during validation NARROWS the window without closing it: it
moves from (check, caller's open) to (jail's open, caller's open).
So the jail keeps the object. iFileJail.OpenVerified returns a tJailHandle
carrying the platform descriptor, and OpenStream wraps THAT descriptor rather
than re-opening by name. A descriptor refers to the opened object itself: once
it is held, renaming the path, substituting a link for a directory, or
unmounting the volume does not change what it refers to. The thing that was
verified IS the thing that is read.
Resolve / ResolveUrl LEXICAL ONLY. No filesystem access. They emit the
canonical VIRTUAL path and deliberately cannot
return anything openable - for logging, for
building a redirect, and for pre-filtering.
OpenVerified / OpenUrl... The safe entry points. Return the open object.
OpenStream / OpenUrlStream As above, wrapped in a TStream the caller owns.
Close Releases a handle.
The unsafe method is not also the convenient one. That is deliberate: an API
whose most obvious call is its least safe one will be misused, and a comment is
not a mitigation.
--------------------------------------------------------------------------------
2. THE PINNED ROOT
--------------------------------------------------------------------------------
NewFileJail opens the root through the same operating-system mechanism every
later object goes through, holds that descriptor for the jail's lifetime, and
records the canonical path the OS reported.
It does NOT use a lexical canonicaliser. Those resolve '.' and '..' and prepend
the current directory, but resolve symbolic links on NO platform. A document
root that is itself a symbolic link - /tmp and /var are on macOS, and an
administrator-convenience document root very often is - would then never match
the path the OS reports for anything inside it, so an honest implementation
would refuse every request, and the usual repair (compare lexically instead)
makes the verification decorative.
Consequences worth knowing:
- The root directory cannot be deleted while a jail over it is alive. For a
document root that is a feature.
- On Windows the reported root is an extended-length '\\?\' form. Every path
the jail composes and every path it accepts back is in that same domain, so
the two halves agree. The prefix additionally DISABLES Win32 path
normalisation, which is what stops a validated name and an opened name
diverging.
- A jail is immutable once minted. Two policies over one tree - a public read
jail and an administrative write jail over the same document root - are two
jails, not one jail reconfigured. This is also what makes a jail safe to
share across threads without locking.
--------------------------------------------------------------------------------
3. MINTING A JAIL
--------------------------------------------------------------------------------
tFileJailPolicy is a TPersistent configuration object. It is SNAPSHOTTED by
NewFileJail: the caller may free or re-use it immediately, and later mutation
cannot affect the jail.
var
lPolicy: tFileJailPolicy;
lJail: iFileJail;
begin
lPolicy := tFileJailPolicy.Create(nil);
try
lPolicy.Options := cJailRulesUrl;
lPolicy.Access := [jaRead,jaList];
lPolicy.ExtensionMode := emAllowListed;
lPolicy.ShareMode := jsmShareAll; { see section 6 }
lPolicy.Allowed.Add('.html');
lPolicy.Allowed.Add('.css');
lPolicy.Refused.Add('.pfx');
lPolicy.Refused.Add('.key');
lPolicy.Refused.Add('.ini');
lJail := NewFileJail('D:\sites\example\www',lPolicy);
finally
lPolicy.Free;
end;
if lJail.Status <> jsReady then
...report and refuse to serve...
NewFileJail ALWAYS returns a usable interface, even when construction failed -
it simply refuses everything. A caller that ignores Status therefore gets a
server that serves nothing, never a server that serves anything. Status values:
jsReady Usable.
jsBadRoot The root does not exist, cannot be opened, or is not a
directory.
jsEmptyPolicy An allow-list nobody filled in (which permits nothing), or
emAny with an empty veto list (which would fail open). Both
are refused loudly at mint time rather than silently at
request time.
jsNoVerifier No verification backend for this platform.
Filling Allowed from a media-type table avoids enumerating the same extensions
twice:
lPolicy.AllowFromMimeTypes(DefaultMimeTypeMap);
--------------------------------------------------------------------------------
4. SERVING A FILE
--------------------------------------------------------------------------------
var
lStream: TStream;
lVerdict: tJailVerdict;
begin
if lJail.OpenUrlStream(lRequestPath,jaRead,lStream,lVerdict) then
try
...send lStream...
finally
lStream.Free; { closes the underlying descriptor }
end
else
...map lVerdict to a status code, and log the true cause...
For a directory, or when the descriptor itself is wanted:
var
lHandle: tJailHandle;
begin
if lJail.OpenUrlVerified(lPath,jaList,lHandle,lVerdict) then
try
if lHandle.IsDirectory then
...
finally
lJail.Close(lHandle);
end;
Close is safe on a handle this jail produced whether the call succeeded or
failed. It is NOT safe on a tJailHandle that has never been through
OpenVerified or OpenStream: only its managed fields are zeroed by the compiler,
so the descriptor fields hold whatever was on the stack. Pass such a record to
ClearJailHandle first. (The POSIX backend additionally refuses to close
anything at or below descriptor 2, because a stale small value there is
somebody else's file.)
--------------------------------------------------------------------------------
5. VERDICTS
--------------------------------------------------------------------------------
Every refusal carries a reason. The enum is fine-grained for ONE purpose: an
operator reading a log must be able to tell a misconfiguration from an attack.
A refusal for the wrong stated reason is a defect even when the refusal itself
is correct.
jvAllow Resolved and opened.
jvOutsideRoot A '..' below the root, or an opened object outside
it. The classic traversal.
jvMalformedPath Octets that 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, a residual escape, or
an over-length path.
jvReservedName A name the OS would reinterpret: a reserved device
name with or without an extension, a trailing dot or
space, an 8.3 short-name alias, a wildcard or
redirection character - or, from the backend, an
object that is neither a regular file nor a
directory.
jvExtensionNotPermitted Not on the allow-list. A CHAINED handler may
legitimately read this as "not mine" and pass the
request on.
jvExtensionRefused On the veto list. Always worth a loud log line:
somebody asked for a .pfx.
jvNoExtension No extension, and extensionless files are not
permitted. Distinct from the above so the log names
the switch.
jvDotFile A leading-dot file or directory.
jvAccessNotPermitted The requested access is not carried by this jail, or
the object cannot be opened for it.
jvLinkEscape The opened object is not beneath the pinned root: a
link, junction or mount redirected it, or its link
count or device says it is reachable from outside.
jvNotVerifiable No verification backend on this platform.
jvNotFound Permitted, but nothing is there.
jvInternalError An unexpected local failure. Never leaks an
exception to the caller.
jvJailNotReady The jail was never usable - see Status.
JailVerdictText renders these for a log. Do NOT put them on the wire.
Distinguishing "not on the allow-list" from "not found" to a PEER is an
information-disclosure oracle; distinguishing them in the LOG is the entire
point. Collapsing them for the response is the caller's decision, and a
document root should generally answer 404 for everything except a genuine
server fault.
A REFUSAL IS NEVER AN EXCEPTION. Every entry point is a fail-closed Boolean
with out parameters, every call into a backend is guarded, and NewFileJail
itself cannot raise. A Boolean gate that raises is a gate that a swallowed
exception opens.
--------------------------------------------------------------------------------
6. RULE SETS
--------------------------------------------------------------------------------
tJailOptions selects the lexical and structural rules. Three ready-made sets:
cJailRulesStrict Device names, 8.3 shapes, dot files, dot directories and
portable-name rules. What a new consumer should use.
cJailRulesUrl Strict, plus percent-decoding and rejection of a residual
escape after one decode pass. What an HTTP document root
should use.
cJailRulesLegacy The historical SFTP rule set, for migrating a shipped
protocol without tightening it silently. Portable names
only: wildcards and redirection characters are refused,
device names and 8.3 shapes are NOT.
Individually settable:
jrRejectDeviceNames CON, PRN, AUX, NUL, COM1-9, LPT1-9, CONIN$,
CONOUT$, and their extensioned forms (NUL.txt),
on every platform.
jrRejectShortNames The 8.3 shape. A lexical pre-filter only; the
backend's identity check is what actually catches
aliases.
jrRejectDotFiles A final segment beginning with a dot.
jrRejectDotDirectories An intermediate segment beginning with a dot.
jrAllowExtensionless Permit a file with no extension. OFF by default.
Note that ACME http-01 challenge tokens have no
extension, so a jail serving that path needs it.
jrPercentDecode Percent-decode each segment. URL entry points
only.
jrRefusePercentAfterDecode Refuse a segment that still contains an escape
after exactly one decode pass - the
double-encoding case.
jrPortableNames 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.
jrSameDevice Refuse an object on a different device from the
root, checked at EVERY step of the walk. Catches
a mount point inside the root, which the walk
cannot otherwise see. It does NOT catch a bind
mount within one filesystem - that leaves the
device unchanged and only a kernel-side resolver
sees it. OFF by default.
jrRefuseHardLinks 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.
OFF by default; worth setting for a
hostile-tenant deployment.
Trailing dots and spaces are refused UNCONDITIONALLY on Windows, in every rule
set including the legacy one, because Win32 strips them at open time: a name
validated with one and opened without it is a name nobody approved.
SHARE MODE. Separate from the rule set, because it governs what OTHER processes
may do while this jail holds an object open rather than which names are
acceptable:
jsmShareAll Readers, writers and deleters all permitted. The DEFAULT: a
static content server has no reason to lock anything, and a
file server that blocks its own operators is worse than one
that does not.
jsmDenyWrite Other readers permitted, writers and deleters refused. What a
classic file-transfer read open does - it stops the file
changing under a transfer in progress. Combined with a write
open this yields single-writer / multi-reader.
jsmDenyAll Nobody else, for as long as the handle is held.
WINDOWS ONLY, and that is not a caveat worth burying. Windows share modes are
MANDATORY - the kernel refuses a conflicting open. POSIX has no equivalent:
flock and fcntl locks are ADVISORY, so a process that never asks is never
stopped. The POSIX backend therefore IGNORES this setting rather than honouring
it with a lock that guarantees nothing, because a guarantee that is not one is
worse than a documented gap. Code that depends on a deny mode is depending on
Windows behaviour.
The jail's own VERIFICATION opens are unaffected and always share fully. The
pinned root is held for the jail's entire lifetime, and a brief interrogating
open must never be able to make an unrelated operation fail.
--------------------------------------------------------------------------------
7. THE EXTENSION DIMENSION
--------------------------------------------------------------------------------
emAllowListed Deny by default: only extensions on the allow-list are
permitted. The only defensible posture for a public document
root.
emAny Permit anything not on the veto list. For an administrative
tree whose contents cannot be enumerated in advance. REQUIRES
a non-empty veto list.
emUngated 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 whose root IS the authenticated user's own home. A veto
list is still honoured if supplied. Do NOT use for a document
root.
The veto list wins in both gated modes, and is applied as an extension AND as a
whole-segment suffix, so a name contrived to hide its extension still meets it.
The GOVERNING extension is the LAST one: 'shell.php.txt' is a .txt. That is
what the filesystem and every content handler will agree on.
A raw extension that NORMALISES AWAY is treated as a hostile name, not as an
extensionless one. 'secrets.ini.' yields a raw '.', and an implementation that
called that "no extension" would let a veto be bypassed by appending a dot -
after which Win32 opens the un-suffixed file.
--------------------------------------------------------------------------------
8. THE MEDIA-TYPE TABLE
--------------------------------------------------------------------------------
stMimeTypes exists because one table is read for two different purposes, and
confusing them is a security bug:
HasExtension THE PERMIT PREDICATE. True only for an extension
explicitly present. Never infers, never falls back.
MediaTypeOf / ...OfExtension
THE LABEL. Takes the fallback FROM THE CALLER, who is
the only one who knows whether a fallback is safe in
its context.
A label lookup wants a fallback: an unrecognised extension is still a file, and
application/octet-stream is a fine answer. A permit lookup must never fall
back, because an extension nobody enumerated is exactly the case a
deny-by-default server has to refuse - and a table that answers
application/octet-stream for .pfx has just permitted the private key. There is
deliberately no single method that does both.
The seeded table is small on purpose: the extensions a static site cannot run
without. A deployment's real table is CONFIGURATION, in the same syntax an ini
file already uses:
Map.AddMapping('jpeg,jpg,jpe','image/jpeg');
Growing the seeded list instead is how a library ships one deployment's policy
to every other deployment.
A map is not internally locked. DefaultMimeTypeMap is built during unit
initialisation, so there is no first-call race, but it is a mutable shared
object: configure it at startup, before anything is listening, and treat it as
read-only thereafter. Clone takes an independent snapshot; that is what a jail
does so its permit set cannot change under it.
--------------------------------------------------------------------------------
9. PLATFORM BEHAVIOUR
--------------------------------------------------------------------------------
The two backends reach the same verdicts by different routes, because the
platforms differ in what they can prove.
WINDOWS. The object is opened following every reparse point, then the operating
system is asked what was actually opened, and that answer is compared against
the root resolved through the IDENTICAL call. Both sides are then OS-produced
strings in the same extended-length domain, which disposes of the '\\?\'
prefix, 8.3 aliasing, on-disk casing, and subst / mount-point rewriting in one
step. A junction that stays INSIDE the root is therefore permitted. This is also
the only backend that honours ShareMode, Windows share modes being mandatory
where POSIX has nothing equivalent (section 6).
POSIX. Containment is STRUCTURAL rather than textual. The validated relative
path is walked one segment at a time from the pinned root descriptor, refusing
to follow a link at any step, so no name is ever re-resolved and no string
comparison participates in the security decision. The walk is then proved to
have stayed beneath the root by walking upward and comparing device and inode
numbers - because a descriptor-based walk is immune to a link being
substituted, but NOT to a directory it is holding being renamed out of the tree
while the walk is in progress.
A DELIBERATE DIFFERENCE: on POSIX, ANY symbolic link on the path is refused,
including one whose target is inside the root. This is a DEFAULT, not a
platform limitation - containment for a link target is provable - but
refusing is the safe default and is what ships. Both halves of that statement
are asserted by the Linux run of the SFTP self-test (section 12).
POSIX additionally hands back the final segment's PARENT DIRECTORY descriptor,
so a later delete or rename can go through the *at family and never re-resolve
a name. Windows has no such family, so a delete there is by name: a residual
race, stated rather than papered over.
--------------------------------------------------------------------------------
10. WHAT THIS DOES NOT CLOSE
--------------------------------------------------------------------------------
Stated plainly, because an accurate limit is worth more than an absolute claim.
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 reported path of a
hard link is the in-root name, so containment passes.
jrRefuseHardLinks is the only signal available and is
blunt.
BIND MOUNTS A bind mount within one filesystem is a containment
failure the filesystem itself endorses, and leaves the
device number unchanged. jrSameDevice narrows the
cross-device case only.
A LYING SERVER Over SMB or NFS the answers come from the far end.
CASE-INSENSITIVE A case-insensitive volume reached from a case-sensitive
VOLUMES build, and the reverse. tCaseMode defaults to the platform,
which is the right guess and not a guarantee. Note that
macOS volumes are usually case-insensitive while the
platform is case-sensitive, and that Windows supports
per-directory case sensitivity.
AFTER THE HANDOVER The jail guarantees what was opened. What the caller then
does with the descriptor is the caller's business.
It also does not decide policy. It does not map a verdict to an HTTP status, it
does not choose your allow-list, and it does not know which of your directories
are sensitive.
--------------------------------------------------------------------------------
11. CONSUMERS
--------------------------------------------------------------------------------
SFTP SERVER. TstSFTPServerSubSystem confines every client-supplied path through
this unit, with cJailRulesLegacy, emUngated and jsmDenyWrite - the root is the
authenticated user's own home, so the kind of a file carries no meaning, and the
deny mode reproduces the single-writer / multi-reader behaviour the subsystem
had before. See SFTP.txt section 5.
Its FILE DATA path is race-free: SSH_FXP_OPEN of an existing file takes its
stream from OpenStream, so the descriptor the jail verified is the descriptor
every subsequent SSH_FXP_READ and SSH_FXP_WRITE uses. Every other request -
creation and truncation, and the one-shot operations: stat, remove, rename,
mkdir, rmdir and directory enumeration - acts on a path by name. That path is
checked on disk first, by the rules the verifying open applies, so a link
already in the tree cannot take it out of the root; what remains is a race
with something that puts one in between the check and the operation. Losing
that race leaks metadata, misdirects a delete, or creates or truncates a file
outside the root - and a created or truncated file is checked again once it is
open, so nothing is written to it. It does not disclose file contents. Closing
the race needs the POSIX *at family, for which tJailHandle already carries
Parent and Leaf, and has no Windows equivalent.
STATIC CONTENT. An HTTP document root should use cJailRulesUrl with
emAllowListed and an allow-list drawn from its media-type table.
ACME. A challenge-token writer needs jrAllowExtensionless, because http-01
tokens have no extension.
--------------------------------------------------------------------------------
12. TESTS
--------------------------------------------------------------------------------
A test corpus is the executable form of the hazard table: the traversal
encodings, overlong and truncated UTF-8, encoded separators and surrogates,
alternate data streams, NUL and control bytes, trailing dots and spaces, 8.3
shapes, device names, wildcards, the extension gate in all three modes, the
access gate, the policy failures, a planted link that redirects out of the
root, and a set of cases that call the backend directly to exercise the
defence-in-depth layer the core never reaches.
Every case asserts BOTH the outcome and the verdict, for the reason given in
section 5.
PLATFORM STATUS. The corpus builds and runs on Win32 and Win64. It also
compiles for Linux64, OSX64 and OSXARM64.
The POSIX backend is exercised at runtime by the SFTP self-test, which builds
for Linux64 and runs the whole request matrix - including the jail - against a
real SSH connection on loopback. It carries three POSIX-only cases that no
other test reaches:
- a symbolic link pointing OUT of the jail, refused;
- a symbolic link pointing at an ordinary file INSIDE the jail, ALSO refused,
which is the documented default described in section 9 rather than an
accident;
- that same target opened by its real name and served normally, which is what
makes the previous case mean "the link was refused" rather than "the file
was unreachable".
Not yet covered at runtime: OSX64 and OSXARM64, which differ from Linux in the
constants and in using F_GETPATH where Linux reads /proc/self/fd. Those two
compile but have not been run.
================================================================================
END
================================================================================