Contents · Forum Home · StreamSec Tools 4.1.5.365 documentation

Confine file access to a root directory with FileJail

Let a caller read a text report by its virtual path. For example, a request for /daily.txt should read the copy held in your configured reports directory. FileJail verifies the requested file and gives the application an open stream from which to read it.

Set up a read-only reports directory

uses
  System.Classes, stFileJail;
function SetUpReportJail(const aRoot: string; out aJail: iFileJail): tJailStatus;
var
  lPolicy: tFileJailPolicy;
begin
  lPolicy := tFileJailPolicy.Create(nil);
  try
    lPolicy.Access := [jaRead];
    lPolicy.Options := cJailRulesStrict + [jrRefuseHardLinks, jrSameDevice];
    lPolicy.ExtensionMode := emAllowListed;
    lPolicy.Allowed.Add('.txt');
    aJail := NewFileJail(aRoot, lPolicy);
    Result := aJail.Status;
  finally
    lPolicy.Free;
  end;
end;

Pass the absolute path of an existing directory from your application configuration to SetUpReportJail. Start accepting requests when it returns jsReady. A missing directory produces jsBadRoot. NewFileJail pins the root and copies the policy, so you can free the policy and keep the iFileJail interface for subsequent requests.

The allow-list admits files ending in .txt, and the jail grants read access only. The two additional options require the file to be on the same device as the root and reject files with multiple hard links.

Copy a report from the verified stream

function CopyReport(const aJail: iFileJail; const aVirtualPath: string;
  aDestination: TStream; out aVerdict: tJailVerdict): Boolean;
var
  lInput: TStream;
begin
  Result := aJail.OpenStream(aVirtualPath, jaRead, lInput, aVerdict);
  if Result then
    try
      aDestination.CopyFrom(lInput, 0);
    finally
      lInput.Free;
    end;
end;

Call CopyReport(Jail, '/daily.txt', Output, Verdict) with a writable destination stream. OpenStream accepts a virtual file path and opens the file under the pinned root. The returned stream owns the verified file handle. Read from that stream and free it when finished. The caller owns the destination.

On a refused open, CopyReport returns False and leaves the destination untouched. For example, an existing /inventory.csv produces jvExtensionNotPermitted. A missing /daily.txt produces jvNotFound. For a remote caller, use the same unavailable response for either refusal and record JailVerdictText(Verdict) in your application log. A stream I/O exception during copying can leave a partial report in the destination.

For URL paths that need percent decoding, see the filesystem confinement notes for cJailRulesUrl and OpenUrlStream.

Reference

stFileJail