fix(server): refuse planted Windows data, guard new archives, trust only loopback proxies

- Windows data folder: the folder and everything in it must belong to SYSTEM,
  Administrators or the server's account and hold no link, checked before the
  ACL is rewritten; otherwise the server stops and names the entry. server.json
  is read only after its owner is checked on the open handle. Secrets are
  deleted and created anew with the private ACL, so a planted file's owner
  loses its rights.
- Windows archive: a folder the server creates is changeable only by those
  accounts (users may read it) and a .titano folder it creates is private; an
  existing archive others can change is logged as a warning at start.
- Proxy mode: only loopback is trusted by default, since LAN clients reach the
  HTTP port from private addresses; a cookie sign-in that did not come through
  a trusted proxy over HTTPS answers proxy_untrusted, naming
  TITANO_TRUSTED_PROXIES.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-12 11:08:12 +00:00
1 parent 650a82a8f7
commit df2d4b4316
11 files changed
+497 -64

No files matched your search

+1
View File
@@ -67,6 +67,7 @@
<data name="Server.Error.NotFound" xml:space="preserve"><value>Not found.</value><comment>long</comment></data>
<data name="Server.Error.NotTitano" xml:space="preserve"><value>That address is not a Titano Server.</value><comment>long</comment></data>
<data name="Server.Error.PasswordChangeRequired" xml:space="preserve"><value>Change your password first.</value><comment>long</comment></data>
<data name="Server.Error.ProxyUntrusted" xml:space="preserve"><value>This page did not come through a trusted proxy over HTTPS. Open it through your proxy, or add the proxy's address to TITANO_TRUSTED_PROXIES.</value><comment>long</comment></data>
<data name="Server.Error.QuotaExceeded" xml:space="preserve"><value>This upload would exceed your quota.</value><comment>long</comment></data>
<data name="Server.Error.RateLimited" xml:space="preserve"><value>Too many attempts; wait a minute and try again.</value><comment>long</comment></data>
<data name="Server.Error.SamePassword" xml:space="preserve"><value>Choose a password different from the current one.</value><comment>long</comment></data>
+1
View File
@@ -65,6 +65,7 @@
<data name="Server.Error.NotFound" xml:space="preserve"><value>Non trovato.</value></data>
<data name="Server.Error.NotTitano" xml:space="preserve"><value>Questo indirizzo non è un Titano Server.</value></data>
<data name="Server.Error.PasswordChangeRequired" xml:space="preserve"><value>Cambia prima la password.</value></data>
<data name="Server.Error.ProxyUntrusted" xml:space="preserve"><value>Questa pagina non è arrivata da un proxy attendibile in HTTPS. Aprila tramite il proxy o aggiungi l'indirizzo del proxy a TITANO_TRUSTED_PROXIES.</value></data>
<data name="Server.Error.QuotaExceeded" xml:space="preserve"><value>Questo caricamento supererebbe la tua quota.</value></data>
<data name="Server.Error.RateLimited" xml:space="preserve"><value>Troppi tentativi; attendi un minuto e riprova.</value></data>
<data name="Server.Error.SamePassword" xml:space="preserve"><value>Scegli una password diversa da quella attuale.</value></data>
+12 -2
View File
@@ -18,8 +18,18 @@ public static class AuthEndpoints
api.MapGet("/auth/me", (Caller caller) => Results.Json(Dto.User(caller.User), ProtocolJson.Default.UserDto)).AllowDuringPasswordChange();
}
/// <summary>
/// Why the <c>Secure</c> session cookie cannot be set for this request, or null when it can (HTTPS, or the machine
/// itself). In TLS mode proxy only a trusted proxy makes a request HTTPS, so the refusal names that setting.
/// </summary>
internal static string? CookieRefusal(HttpContext context, ServerOptions options)
{
if (SessionCookies.IsSecureTransport(context)) return null;
return options.TlsMode == TlsMode.Proxy ? "proxy_untrusted" : "https_required";
}
private static async Task<IResult> LoginAsync(HttpContext context, LoginRequest request, TitanoDatabase db, TokenService tokens, LoginGuard guard,
AuditLog audit, TimeProvider time)
AuditLog audit, TimeProvider time, ServerOptions options)
{
var ct = context.RequestAborted;
if (!guard.TryAttempt(context.Connection.RemoteIpAddress?.ToString() ?? "unknown", out var wait)) return TooMany(context, "rate_limited", wait);
@@ -27,7 +37,7 @@ public static class AuthEndpoints
if (!Accounts.IsValidUsername(account) || string.IsNullOrEmpty(request.Password))
return ApiErrors.Result(context, StatusCodes.Status401Unauthorized, "invalid_credentials");
if (guard.IsLocked(account, out wait)) return TooMany(context, "account_locked", wait);
if (request.Cookie && !SessionCookies.IsSecureTransport(context)) return ApiErrors.BadRequest(context, "https_required");
if (request.Cookie && CookieRefusal(context, options) is { } refusal) return ApiErrors.BadRequest(context, refusal);
var user = await db.Users.GetByUsernameAsync(account, ct);
bool valid;
@@ -3,6 +3,7 @@ using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
using Titano.Data;
using Titano.Server.Hosting;
namespace Titano.Server.Configuration;
@@ -59,10 +60,12 @@ public sealed class ServerOptions
];
/// <summary>
/// Reverse proxies whose <c>X-Forwarded-*</c> headers count in TLS mode proxy: loopback and the private networks a
/// compose or Unraid proxy container connects from (RFC 1918, IPv6 unique local).
/// Reverse proxies whose <c>X-Forwarded-*</c> headers count in TLS mode proxy when none are configured: loopback only.
/// A home network's machines reach the HTTP port directly from private addresses (also through Docker's port
/// publishing, which keeps the client's address), so trusting a private network would let them pick their own
/// address again; a proxy in another container or on another machine is listed by its address or network.
/// </summary>
public const string DefaultTrustedProxies = "127.0.0.0/8, ::1/128, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7";
public const string DefaultTrustedProxies = "127.0.0.0/8, ::1/128";
/// <summary>The environment variables the server reads (<c>--help</c> lists them all).</summary>
public static IEnumerable<string> EnvironmentVariables => Variables.Select(v => v.Variable).Prepend("TITANO_DATA_PATH");
@@ -170,7 +173,8 @@ public sealed class ServerOptions
{
try
{
options = JsonSerializer.Deserialize(File.ReadAllText(file), ServerOptionsJson.Default.ServerOptions) ?? options;
// Its owner is checked first: a file another user planted would choose the archive, database and TLS key.
options = JsonSerializer.Deserialize(DataFolderAccess.ReadTrustedText(file), ServerOptionsJson.Default.ServerOptions) ?? options;
}
catch (JsonException ex)
{
+211 -24
View File
@@ -1,6 +1,7 @@
using System.Runtime.Versioning;
using System.Security.AccessControl;
using System.Security.Principal;
using Titano.Core.Archiving;
namespace Titano.Server.Hosting;
@@ -8,15 +9,32 @@ namespace Titano.Server.Hosting;
/// Keeps the data folder and its secrets private (BRIEF §14.2): it holds the database, the TLS private key, the
/// temporary admin password and <c>server.json</c>. On Windows the folder sits in <c>%ProgramData%</c>, whose ACL lets
/// every local user read it and create files in it, so it gets a protected DACL (nothing inherited) that allows only
/// SYSTEM, Administrators and the account the server runs as; everything inside inherits that. Elsewhere the container
/// entrypoint owns <c>/data</c>, and secrets are written with mode 0600.
/// SYSTEM, Administrators and the account the server runs as; everything inside inherits that. Those accounts must also
/// own the folder and everything in it, and nothing in it may be a link: an owner can always change the ACL back, and
/// whoever planted a file chose what it says. Elsewhere the container entrypoint owns <c>/data</c>, and secrets are
/// written with mode 0600. An archive folder the server creates on Windows gets the same accounts (see
/// <see cref="PrepareArchive"/>).
/// </summary>
public static class DataFolderAccess
{
private const UnixFileMode OwnerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite;
private const int GenericAll = 0x10000000;
private const int GenericWrite = 0x40000000;
/// <summary>Creates the folder if needed and, on Windows, replaces an ACL that grants anyone else access.</summary>
/// <exception cref="InvalidOperationException">The ACL cannot be changed (the account neither owns the folder nor is an administrator).</exception>
/// <summary>Rights that let an account replace or alter a file or folder (including the generic forms).</summary>
[SupportedOSPlatform("windows")]
private const FileSystemRights ChangeRights = FileSystemRights.WriteData | FileSystemRights.AppendData | FileSystemRights.WriteExtendedAttributes
| FileSystemRights.DeleteSubdirectoriesAndFiles | FileSystemRights.Delete | FileSystemRights.ChangePermissions | FileSystemRights.TakeOwnership
| (FileSystemRights)GenericWrite | (FileSystemRights)GenericAll;
/// <summary>
/// Creates the folder if needed and, on Windows, refuses a folder that holds a link or an entry owned by anyone
/// else, then replaces an ACL that grants anyone else access.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Something in the folder is a link or belongs to another account, or the ACL cannot be read or changed (the account
/// is not an administrator).
/// </exception>
public static void Restrict(string folder)
{
if (!OperatingSystem.IsWindows())
@@ -31,10 +49,22 @@ public static class DataFolderAccess
catch (UnauthorizedAccessException ex)
{
throw new InvalidOperationException(
$"Titano Server cannot restrict access to {folder}: {ex.Message} Run it once as an administrator, or as the account that created the folder.", ex);
$"Titano Server cannot check or restrict access to {folder}: {ex.Message} Run it once as an administrator; if someone else changed the folder's access, delete the folder.", ex);
}
}
/// <summary>
/// Reads a file the server acts on (<c>server.json</c>). On Windows its owner must be SYSTEM, Administrators or the
/// server's account, checked on the handle that is read, so a file another user planted (or swapped in) is refused
/// before any of its settings is used.
/// </summary>
/// <exception cref="InvalidOperationException">The file belongs to another account.</exception>
public static string ReadTrustedText(string path)
{
if (!OperatingSystem.IsWindows()) return File.ReadAllText(path);
return ReadTrustedText(path, AllowedAccounts());
}
/// <summary>Writes a secret that only the server's account (and, on Windows, SYSTEM and Administrators) may read.</summary>
public static void WritePrivateFile(string path, ReadOnlySpan<byte> contents)
{
@@ -49,12 +79,44 @@ public static class DataFolderAccess
File.SetUnixFileMode(path, OwnerOnly);
}
/// <summary>True when the ACL is protected and names no account besides SYSTEM, Administrators and this process's account.</summary>
/// <summary>
/// Creates the archive folder when it is missing, and says whether accounts other than SYSTEM, Administrators and the
/// server's own can change it (always false off Windows, where the container entrypoint checks the archive). On
/// Windows a folder created here gets a protected ACL: those accounts change it, other local users may only read it;
/// a <c>.titano</c> folder (staging, trash) created here is private. Whoever can write where the server moves files
/// can put a link in place of a folder and send the server's writes elsewhere; an existing archive is only reported,
/// because its ACL is its owner's choice.
/// </summary>
public static bool PrepareArchive(string root)
{
if (!OperatingSystem.IsWindows())
{
Directory.CreateDirectory(root);
return false;
}
var folder = new DirectoryInfo(root);
if (!folder.Exists)
{
if (folder.Parent is { } parent) parent.Create();
folder.Create(ArchiveFolderSecurity());
folder.Refresh();
}
// Created before the archive engine would create it with the archive's ACL; an existing one is left as it is.
var meta = new DirectoryInfo(new ArchivePaths(root).MetaDirectory);
if (!meta.Exists) meta.Create(PrivateFolderSecurity());
return OthersCanChange(folder);
}
/// <summary>
/// True when the ACL is protected, its owner is SYSTEM, Administrators or this process's account, and it names no
/// other account.
/// </summary>
[SupportedOSPlatform("windows")]
public static bool IsPrivate(FileSystemSecurity security)
{
if (!security.AreAccessRulesProtected) return false;
var allowed = AllowedAccounts();
if (security.GetOwner(typeof(SecurityIdentifier)) is not SecurityIdentifier owner || !allowed.Contains(owner)) return false;
foreach (FileSystemAccessRule rule in security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier)))
{
if (rule.AccessControlType == AccessControlType.Allow && !allowed.Contains((SecurityIdentifier)rule.IdentityReference)) return false;
@@ -62,6 +124,73 @@ public static class DataFolderAccess
return true;
}
/// <summary>
/// The first problem with <paramref name="folder"/> or anything inside it, as a sentence for the operator, or null:
/// a link (it would carry what the server reads, writes and secures elsewhere) or an owner outside
/// <paramref name="owners"/> (who may have written the contents and can always change the ACL back). Links are
/// reported, never followed.
/// </summary>
[SupportedOSPlatform("windows")]
internal static string? FindUntrusted(DirectoryInfo folder, IReadOnlySet<SecurityIdentifier> owners)
{
var everything = new EnumerationOptions { AttributesToSkip = 0, IgnoreInaccessible = false };
var pending = new Stack<DirectoryInfo>();
pending.Push(folder);
while (pending.TryPop(out var directory))
{
if (Untrusted(directory, owners) is { } problem) return problem;
foreach (var entry in directory.EnumerateFileSystemInfos("*", everything))
{
if (entry is DirectoryInfo child && !IsLink(child)) pending.Push(child);
else if (Untrusted(entry, owners) is { } entryProblem) return entryProblem;
}
}
return null;
}
/// <inheritdoc cref="ReadTrustedText(string)"/>
[SupportedOSPlatform("windows")]
internal static string ReadTrustedText(string path, IReadOnlySet<SecurityIdentifier> owners)
{
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
if (UntrustedOwner(path, stream.GetAccessControl(), owners) is { } problem) throw new InvalidOperationException(problem);
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
/// <summary>
/// True when the owner is outside <paramref name="trusted"/> or an allow entry gives change rights to such an
/// account. Entries that only pass to children count too, since new files would inherit them; CREATOR OWNER and
/// CREATOR GROUP stand for whoever creates a child, which already takes change rights on the folder.
/// </summary>
[SupportedOSPlatform("windows")]
internal static bool IsChangeableByOthers(FileSystemSecurity security, IReadOnlySet<SecurityIdentifier> trusted, bool checkOwner)
{
if (checkOwner && (security.GetOwner(typeof(SecurityIdentifier)) is not SecurityIdentifier owner || !trusted.Contains(owner))) return true;
foreach (FileSystemAccessRule rule in security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier)))
{
if (rule.AccessControlType != AccessControlType.Allow || (rule.FileSystemRights & ChangeRights) == 0) continue;
var account = (SecurityIdentifier)rule.IdentityReference;
if (trusted.Contains(account) || account.IsWellKnown(WellKnownSidType.CreatorOwnerSid) || account.IsWellKnown(WellKnownSidType.CreatorGroupSid)) continue;
return true;
}
return false;
}
/// <summary>SYSTEM, Administrators and the account this process runs as (SYSTEM again for the Windows service).</summary>
[SupportedOSPlatform("windows")]
internal static HashSet<SecurityIdentifier> AllowedAccounts()
{
using var identity = WindowsIdentity.GetCurrent();
var accounts = new HashSet<SecurityIdentifier>
{
new(WellKnownSidType.LocalSystemSid, null),
new(WellKnownSidType.BuiltinAdministratorsSid, null),
};
if (identity.User is { } user) accounts.Add(user);
return accounts;
}
[SupportedOSPlatform("windows")]
private static void RestrictOnWindows(DirectoryInfo folder)
{
@@ -71,18 +200,80 @@ public static class DataFolderAccess
folder.Create(PrivateFolderSecurity());
folder.Refresh();
}
// Before the ACL is touched: a folder another user created in advance, or a file planted in an older version's
// folder, stays theirs whatever the ACL says, and a link would carry the new ACL elsewhere.
if (FindUntrusted(folder, AllowedAccounts()) is { } problem) throw new InvalidOperationException(problem);
// An older version, or Windows' default inheritance from %ProgramData%, left the folder readable by every user.
// Setting the DACL by name also replaces what the files inside inherited.
if (!IsPrivate(folder.GetAccessControl())) folder.SetAccessControl(PrivateFolderSecurity());
}
[SupportedOSPlatform("windows")]
private static string? Untrusted(FileSystemInfo entry, IReadOnlySet<SecurityIdentifier> owners)
{
if (IsLink(entry))
{
return $"{entry.FullName} is a link to {entry.LinkTarget}, and Titano Server follows no links in its data folder. "
+ "Delete the link (TITANO_DATA_PATH moves the data folder) and start the server again.";
}
FileSystemSecurity security = entry is DirectoryInfo directory
? directory.GetAccessControl(AccessControlSections.Owner)
: ((FileInfo)entry).GetAccessControl(AccessControlSections.Owner);
return UntrustedOwner(entry.FullName, security, owners);
}
[SupportedOSPlatform("windows")]
private static string? UntrustedOwner(string path, FileSystemSecurity security, IReadOnlySet<SecurityIdentifier> owners)
{
var owner = security.GetOwner(typeof(SecurityIdentifier)) as SecurityIdentifier;
if (owner is not null && owners.Contains(owner)) return null;
return $"{path} belongs to {(owner is null ? "no account" : AccountName(owner))}, not to SYSTEM, Administrators or the account Titano Server "
+ "runs as, so it cannot be trusted. Check it, then delete it or make Administrators its owner, and start the server again.";
}
/// <summary>A symbolic link or junction (other reparse points, such as deduplicated files, are ordinary files).</summary>
private static bool IsLink(FileSystemInfo entry) => (entry.Attributes & FileAttributes.ReparsePoint) != 0 && entry.LinkTarget is not null;
[SupportedOSPlatform("windows")]
private static string AccountName(SecurityIdentifier account)
{
try
{
return account.Translate(typeof(NTAccount)).Value;
}
catch (IdentityNotMappedException)
{
return account.Value;
}
}
[SupportedOSPlatform("windows")]
private static bool OthersCanChange(DirectoryInfo folder)
{
try
{
return IsChangeableByOthers(folder.GetAccessControl(), AllowedAccounts(), checkOwner: true);
}
catch (NotSupportedException)
{
// A volume without ACLs (FAT, exFAT): everyone can change everything.
return true;
}
catch (Exception ex) when (ex is UnauthorizedAccessException or IOException or InvalidOperationException)
{
// The ACL cannot be read (some network shares); the warning would be a guess.
return false;
}
}
[SupportedOSPlatform("windows")]
private static void WritePrivateFileOnWindows(FileInfo file, ReadOnlySpan<byte> contents)
{
// The security descriptor applies when the file is created; one that already existed gets it afterwards.
using (var stream = file.Create(FileMode.Create, FileSystemRights.Write, FileShare.None, 4096, FileOptions.None, PrivateFileSecurity()))
stream.Write(contents);
if (!IsPrivate(file.GetAccessControl())) file.SetAccessControl(PrivateFileSecurity());
// A file that already exists is replaced, never rewritten in place: it would keep its owner, who could change its
// ACL back at any time, and a link would carry the secret elsewhere. The new file is owned by this account.
file.Delete();
using var stream = file.Create(FileMode.CreateNew, FileSystemRights.Write, FileShare.None, 4096, FileOptions.None, PrivateFileSecurity());
stream.Write(contents);
}
/// <summary>A protected DACL that gives the allowed accounts full control, passed on to everything inside.</summary>
@@ -99,6 +290,16 @@ public static class DataFolderAccess
return security;
}
/// <summary>The private DACL, plus read access for every local user (photos and renders, never <c>.titano</c>).</summary>
[SupportedOSPlatform("windows")]
private static DirectorySecurity ArchiveFolderSecurity()
{
var security = PrivateFolderSecurity();
security.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.ReadAndExecute,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
return security;
}
[SupportedOSPlatform("windows")]
private static FileSecurity PrivateFileSecurity()
{
@@ -108,18 +309,4 @@ public static class DataFolderAccess
security.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.FullControl, AccessControlType.Allow));
return security;
}
/// <summary>SYSTEM, Administrators and the account this process runs as (SYSTEM again for the Windows service).</summary>
[SupportedOSPlatform("windows")]
private static HashSet<SecurityIdentifier> AllowedAccounts()
{
using var identity = WindowsIdentity.GetCurrent();
var accounts = new HashSet<SecurityIdentifier>
{
new(WellKnownSidType.LocalSystemSid, null),
new(WellKnownSidType.BuiltinAdministratorsSid, null),
};
if (identity.User is { } user) accounts.Add(user);
return accounts;
}
}
@@ -43,7 +43,7 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<stri
ports clients reach when the container's ports are published as other host ports
(admin redirect to HTTPS, LAN beacon)
TITANO_TRUSTED_PROXIES proxy mode: addresses or networks (CIDR) whose X-Forwarded-* headers count
(default: loopback, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7)
(default: loopback only; list a proxy in another container or on another machine)
Container image only: PUID, PGID (user and group the server runs as, owners of /data), TZ (local time zone)
""";
+7 -1
View File
@@ -33,7 +33,7 @@ public static class ServerHost
DataFolderAccess.Restrict(options.DataPath);
Directory.CreateDirectory(options.LogPath);
Directory.CreateDirectory(options.UploadsPath);
Directory.CreateDirectory(options.ArchivePath);
var archiveOpenToOthers = DataFolderAccess.PrepareArchive(options.ArchivePath);
var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions { Args = args, ContentRootPath = AppContext.BaseDirectory });
builder.Logging.ClearProviders();
@@ -82,6 +82,12 @@ public static class ServerHost
app.Logger.LogInformation("Titano Server {Version} · archive {Archive} · data {Data} · {Database} · TLS {Tls}{Fingerprint}",
SystemEndpoints.Version, options.ArchivePath, options.DataPath, state.Database, options.TlsMode,
state.TlsFingerprint is null ? string.Empty : " · SHA-256 " + state.TlsFingerprint);
if (archiveOpenToOthers)
{
app.Logger.LogWarning("Accounts other than SYSTEM, Administrators and the one Titano Server runs as can change the archive {Archive}: "
+ "they could put a link in place of a folder and redirect the files the server moves. Let only those accounts change it (others may read it).",
options.ArchivePath);
}
app.Lifetime.ApplicationStopping.Register(() => app.Logger.LogInformation("Titano Server stopping"));
app.Lifetime.ApplicationStopped.Register(() => database.DisposeAsync().AsTask().GetAwaiter().GetResult());
return app;
@@ -1,7 +1,6 @@
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.AccessControl;
using System.Security.Principal;
using Titano.Core.Localization;
using static Titano.Server.Hosting.Windows.ServiceNative;
@@ -20,13 +19,6 @@ namespace Titano.Server.Hosting.Windows;
public static unsafe class ServiceInstaller
{
private const string DisplayName = "Titano Server";
private const int GenericAll = 0x10000000;
private const int GenericWrite = 0x40000000;
/// <summary>Rights that let an account replace or alter a file or folder (including the generic forms).</summary>
private const FileSystemRights ChangeRights = FileSystemRights.WriteData | FileSystemRights.AppendData | FileSystemRights.WriteExtendedAttributes
| FileSystemRights.DeleteSubdirectoriesAndFiles | FileSystemRights.Delete | FileSystemRights.ChangePermissions | FileSystemRights.TakeOwnership
| (FileSystemRights)GenericWrite | (FileSystemRights)GenericAll;
/// <summary>TrustedInstaller, the owner of Windows' own files under Program Files.</summary>
private static readonly SecurityIdentifier TrustedInstaller = new("S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464");
@@ -128,10 +120,10 @@ public static unsafe class ServiceInstaller
private static string? FindChangeable(DirectoryInfo folder, bool recursive, HashSet<SecurityIdentifier> trusted)
{
if (IsChangeableByOthers(folder.GetAccessControl(), trusted)) return folder.FullName;
if (DataFolderAccess.IsChangeableByOthers(folder.GetAccessControl(), trusted, checkOwner: false)) return folder.FullName;
foreach (var file in folder.EnumerateFiles())
{
if (IsChangeableByOthers(file.GetAccessControl(), trusted)) return file.FullName;
if (DataFolderAccess.IsChangeableByOthers(file.GetAccessControl(), trusted, checkOwner: false)) return file.FullName;
}
if (!recursive) return null;
foreach (var child in folder.EnumerateDirectories())
@@ -141,23 +133,6 @@ public static unsafe class ServiceInstaller
return null;
}
/// <summary>
/// True when an allow entry gives change rights to an account outside <paramref name="trusted"/>. Entries that only
/// pass to children count too, since new files would inherit them; CREATOR OWNER and CREATOR GROUP stand for whoever
/// creates a child, which already takes change rights on the folder.
/// </summary>
private static bool IsChangeableByOthers(FileSystemSecurity security, HashSet<SecurityIdentifier> trusted)
{
foreach (FileSystemAccessRule rule in security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier)))
{
if (rule.AccessControlType != AccessControlType.Allow || (rule.FileSystemRights & ChangeRights) == 0) continue;
var account = (SecurityIdentifier)rule.IdentityReference;
if (trusted.Contains(account) || account.IsWellKnown(WellKnownSidType.CreatorOwnerSid) || account.IsWellKnown(WellKnownSidType.CreatorGroupSid)) continue;
return true;
}
return false;
}
private static HashSet<SecurityIdentifier> TrustedAccounts()
{
var trusted = new HashSet<SecurityIdentifier>
@@ -8,7 +8,8 @@ namespace Titano.Server.Tests.Hosting;
/// <summary>
/// The data folder and its secrets are private (BRIEF §14.2): mode 0600 off Windows; on Windows a protected ACL that no
/// ordinary user appears in, where %ProgramData% would otherwise let every local user read the folder.
/// ordinary user appears in, where %ProgramData% would otherwise let every local user read the folder, with owners the
/// server trusts and no links. On Windows a new archive folder lets other users only read it.
/// </summary>
[Category("server")]
public sealed class DataFolderAccessTests(TestContext context)
@@ -81,9 +82,186 @@ public sealed class DataFolderAccessTests(TestContext context)
Assert.False(NamesUsers(settings.GetAccessControl()));
}
[Test]
[WindowsOnly]
public void ASecretAnotherAccountOwnedIsReplacedByOneTheServerOwns()
{
if (!OperatingSystem.IsWindows()) return;
var folder = context.CreateTempDirectory("planted");
var own = OwnerOf(NewFile(Path.Combine(folder, "probe.txt")));
// Planted before the first start: whoever owns it keeps the right to change its ACL, whatever the server sets.
var secret = NewFile(Path.Combine(folder, "initial-admin-password.txt"));
if (!TrySetOwner(secret, OtherOwner(own))) Assert.Inconclusive("giving a file to another owner needs an elevated administrator");
GrantUsersRead(secret);
DataFolderAccess.WritePrivateFile(secret.FullName, [1, 2, 3]);
secret.Refresh();
Assert.Equal(own, OwnerOf(secret));
Assert.True(DataFolderAccess.IsPrivate(secret.GetAccessControl()));
Assert.False(NamesUsers(secret.GetAccessControl()));
Assert.BytesEqual([1, 2, 3], File.ReadAllBytes(secret.FullName));
}
[Test]
[WindowsOnly]
public void AnythingAnotherAccountOwnsIsFound()
{
if (!OperatingSystem.IsWindows()) return;
var folder = new DirectoryInfo(context.CreateTempDirectory("squatted"));
var key = NewFile(Path.Combine(folder.CreateSubdirectory("tls").FullName, "server.pfx"));
var own = OwnerOf(key);
Assert.Null(DataFolderAccess.FindUntrusted(folder, new HashSet<SecurityIdentifier> { own }));
// A folder someone else created before the first start is reported before anything inside it.
Assert.Contains(folder.FullName, Assert.NotNull(DataFolderAccess.FindUntrusted(folder, new HashSet<SecurityIdentifier> { LocalSystem })));
if (!TrySetOwner(key, OtherOwner(own))) Assert.Inconclusive("giving a file to another owner needs an elevated administrator");
Assert.Contains(key.FullName, Assert.NotNull(DataFolderAccess.FindUntrusted(folder, new HashSet<SecurityIdentifier> { own })));
}
[Test]
[WindowsOnly]
public void ALinkInTheDataFolderStopsTheServerBeforeTheAclChanges()
{
if (!OperatingSystem.IsWindows()) return;
var folder = new DirectoryInfo(context.CreateTempDirectory("linked"));
var link = Path.Combine(folder.FullName, "logs");
try
{
Directory.CreateSymbolicLink(link, context.CreateTempDirectory("elsewhere"));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Assert.Inconclusive("creating a symbolic link needs an elevated administrator or developer mode");
}
var refused = Assert.Throws<InvalidOperationException>(() => DataFolderAccess.Restrict(folder.FullName));
Assert.Contains(link, refused.Message);
// The ACL change would have followed the link; it never started.
Assert.False(folder.GetAccessControl().AreAccessRulesProtected);
}
[Test]
[WindowsOnly]
public void SettingsAnotherAccountOwnsAreNotRead()
{
if (!OperatingSystem.IsWindows()) return;
var settings = NewFile(Path.Combine(context.CreateTempDirectory("settings"), "server.json"), """{ "ArchivePath": "D:\\Elsewhere" }""");
Assert.Contains("Elsewhere", DataFolderAccess.ReadTrustedText(settings.FullName));
// As if another account had planted it: the owner is not among those the server trusts.
InvalidOperationException? refused = null;
try
{
DataFolderAccess.ReadTrustedText(settings.FullName, new HashSet<SecurityIdentifier> { LocalSystem });
}
catch (InvalidOperationException ex)
{
refused = ex;
}
Assert.Contains(settings.FullName, Assert.NotNull(refused).Message);
}
[Test]
public void AMissingArchiveFolderIsCreated()
{
var root = Path.Combine(context.CreateTempDirectory("archive"), "TitanoArchive");
Assert.False(DataFolderAccess.PrepareArchive(root));
Assert.True(Directory.Exists(root));
// An existing folder is left as it is.
Assert.False(DataFolderAccess.PrepareArchive(root));
}
[Test]
[WindowsOnly]
public void ANewArchiveIsReadableByUsersButOnlyTheServerChangesIt()
{
if (!OperatingSystem.IsWindows()) return;
// Under C:\ a new folder would inherit "Authenticated Users: modify" and every local user could plant links
// where the service moves uploads.
var root = new DirectoryInfo(Path.Combine(context.CreateTempDirectory("archive"), "TitanoArchive"));
Assert.False(DataFolderAccess.PrepareArchive(root.FullName));
var security = root.GetAccessControl();
Assert.True(security.AreAccessRulesProtected);
Assert.Equal(FileSystemRights.ReadAndExecute, RightsOf(security, Users) & FileSystemRights.ReadAndExecute);
Assert.Equal((FileSystemRights)0, RightsOf(security, Users) & (FileSystemRights.Write | FileSystemRights.Delete | FileSystemRights.ChangePermissions));
// Staging and trash are the server's alone.
var meta = new DirectoryInfo(Path.Combine(root.FullName, ".titano"));
Assert.True(DataFolderAccess.IsPrivate(meta.GetAccessControl()));
Assert.False(NamesUsers(meta.CreateSubdirectory("staging").GetAccessControl()));
}
[Test]
[WindowsOnly]
public void AnArchiveOtherUsersCanChangeIsReportedButLeftAsItIs()
{
if (!OperatingSystem.IsWindows()) return;
var root = new DirectoryInfo(context.CreateTempDirectory("shared"));
DataFolderAccess.PrepareArchive(root.FullName);
var open = root.GetAccessControl();
open.AddAccessRule(new FileSystemAccessRule(Users, FileSystemRights.Modify,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
root.SetAccessControl(open);
Assert.True(DataFolderAccess.PrepareArchive(root.FullName));
Assert.Equal(FileSystemRights.Modify, RightsOf(root.GetAccessControl(), Users) & FileSystemRights.Modify);
// The .titano folder the server added at the first start stays its own.
Assert.True(DataFolderAccess.IsPrivate(new DirectoryInfo(Path.Combine(root.FullName, ".titano")).GetAccessControl()));
}
[SupportedOSPlatform("windows")]
private static SecurityIdentifier Users => new(WellKnownSidType.BuiltinUsersSid, null);
[SupportedOSPlatform("windows")]
private static SecurityIdentifier LocalSystem => new(WellKnownSidType.LocalSystemSid, null);
[SupportedOSPlatform("windows")]
private static SecurityIdentifier Administrators => new(WellKnownSidType.BuiltinAdministratorsSid, null);
private static FileInfo NewFile(string path, string contents = "x")
{
File.WriteAllText(path, contents);
return new FileInfo(path);
}
[SupportedOSPlatform("windows")]
private static SecurityIdentifier OwnerOf(FileInfo file) => (SecurityIdentifier)file.GetAccessControl().GetOwner(typeof(SecurityIdentifier))!;
/// <summary>An owner this process may give a file that its new files do not get: its own account or Administrators.</summary>
[SupportedOSPlatform("windows")]
private static SecurityIdentifier OtherOwner(SecurityIdentifier own)
{
using var identity = WindowsIdentity.GetCurrent();
return own == Administrators ? identity.User! : Administrators;
}
[SupportedOSPlatform("windows")]
private static bool TrySetOwner(FileInfo file, SecurityIdentifier owner)
{
var security = new FileSecurity();
security.SetOwner(owner);
try
{
file.SetAccessControl(security);
return true;
}
catch (Exception ex) when (ex is InvalidOperationException or UnauthorizedAccessException)
{
return false;
}
}
/// <summary>The rights allow entries give <paramref name="account"/>.</summary>
[SupportedOSPlatform("windows")]
private static FileSystemRights RightsOf(FileSystemSecurity security, SecurityIdentifier account)
{
FileSystemRights rights = 0;
foreach (FileSystemAccessRule rule in security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier)))
{
if (rule.AccessControlType == AccessControlType.Allow && rule.IdentityReference.Equals(account)) rights |= rule.FileSystemRights;
}
return rights;
}
/// <summary>True when Users, Authenticated Users or Everyone have any allow entry.</summary>
[SupportedOSPlatform("windows")]
private static bool NamesUsers(FileSystemSecurity security)
@@ -1,6 +1,14 @@
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Titano.Core.Localization;
using Titano.Protocol;
using Titano.Server.Api;
using Titano.Server.Configuration;
using Titano.Testing;
@@ -39,7 +47,7 @@ public sealed class ProxyModeTests(TestContext context)
[Test]
public async Task ATrustedProxyReportsTheClientAddress()
{
// The default trusts loopback and the private networks a compose or Unraid proxy container connects from.
// The default trusts loopback, where a proxy on the same machine (and this test) connects from.
await using var server = await TestServer.StartAsync(context, o =>
{
o.TlsMode = TlsMode.Proxy;
@@ -54,6 +62,49 @@ public sealed class ProxyModeTests(TestContext context)
Assert.Contains("203.0.113.8", audit.Items.Select(e => e.RemoteAddress));
}
[Test]
public async Task ByDefaultAMachineOfTheHomeNetworkIsNoProxy()
{
// The machines of a home network reach the HTTP port directly from private addresses, also through Docker's
// port publishing (which keeps the client's address): none of them may choose its own address.
await using var server = await TestServer.StartAsync(context, o => o.TlsMode = TlsMode.Proxy);
foreach (var peer in new[] { "192.168.1.50", "10.0.0.7", "172.17.0.1", "fd00::7" })
Assert.Equal((peer, false), await ForwardAsync(server, peer));
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "127.0.0.1"));
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "::ffff:127.0.0.1"));
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "::1"));
}
[Test]
public async Task AProxyNetworkCountsOnceListed()
{
await using var server = await TestServer.StartAsync(context, o =>
{
o.TlsMode = TlsMode.Proxy;
o.TrustedProxies = "172.18.0.0/16";
});
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "172.18.0.5"));
Assert.Equal(("192.168.1.50", false), await ForwardAsync(server, "192.168.1.50"));
}
[Test]
public void AnAdminSignInThroughAnUntrustedProxyNamesTheSetting()
{
// The warning chip needs a session first: the sign-in refusal itself points at TITANO_TRUSTED_PROXIES.
var request = new DefaultHttpContext();
request.Connection.RemoteIpAddress = IPAddress.Parse("172.18.0.5");
request.Request.Scheme = "http";
Assert.Equal("proxy_untrusted", AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Proxy }));
Assert.Equal("https_required", AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Auto }));
Assert.Contains("TITANO_TRUSTED_PROXIES", Loc.L("Server.Error.ProxyUntrusted"));
request.Request.Scheme = "https";
Assert.Null(AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Proxy }));
request.Request.Scheme = "http";
request.Connection.RemoteIpAddress = IPAddress.Loopback;
Assert.Null(AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Proxy }));
}
[Test]
public async Task TheAdminWarnsWhenAPageDidNotComeThroughATrustedProxyOverHttps()
{
@@ -83,6 +134,24 @@ public sealed class ProxyModeTests(TestContext context)
Assert.False((await SettingsAsync(admin, forwardedProto: null)).ProxyWarning);
}
/// <summary>
/// Runs the server's own forwarded-headers step on a request from <paramref name="peer"/> that claims to forward a
/// client at 203.0.113.7 over HTTPS: the address and scheme the rest of the server then sees.
/// </summary>
private static async Task<(string? Address, bool Https)> ForwardAsync(TestServer server, string peer)
{
var request = new DefaultHttpContext();
request.Connection.RemoteIpAddress = IPAddress.Parse(peer);
request.Request.Scheme = "http";
request.Request.Headers["X-Forwarded-For"] = "203.0.113.7";
request.Request.Headers["X-Forwarded-Proto"] = "https";
var forwarded = new ForwardedHeadersMiddleware(_ => Task.CompletedTask, NullLoggerFactory.Instance,
server.Services.GetRequiredService<IOptions<ForwardedHeadersOptions>>());
await forwarded.Invoke(request);
var address = request.Connection.RemoteIpAddress;
return ((address is { IsIPv4MappedToIPv6: true } ? address.MapToIPv4() : address)?.ToString(), request.Request.IsHttps);
}
private static bool IsLoopback(string? address) =>
IPAddress.TryParse(address, out var ip) && IPAddress.IsLoopback(ip.IsIPv4MappedToIPv6 ? ip.MapToIPv4() : ip);
@@ -79,10 +79,12 @@ public sealed class StartupTests(TestContext context)
public void TrustedProxiesAreAddressesOrNetworks()
{
var root = context.CreateTempDirectory("proxies");
// Loopback only: machines of the home network reach the HTTP port directly from private addresses.
var defaults = ServerOptions.Load(new Dictionary<string, string?> { ["TITANO_DATA_PATH"] = root, ["TITANO_DB"] = "postgres" }).TrustedProxyNetworks();
foreach (var address in new[] { "127.0.0.1", "::1", "10.20.30.40", "172.18.0.3", "192.168.1.2", "fd00::7", "::ffff:172.17.0.2" })
Assert.True(defaults.Any(n => n.Contains(IPAddress.Parse(address)) || n.Contains(IPAddress.Parse(address).MapToIPv4())), address);
Assert.False(defaults.Any(n => n.Contains(IPAddress.Parse("203.0.113.5"))));
foreach (var address in new[] { "127.0.0.1", "127.0.0.53", "::1" })
Assert.True(defaults.Any(n => n.Contains(IPAddress.Parse(address))), address);
foreach (var address in new[] { "10.20.30.40", "172.18.0.3", "192.168.1.2", "fd00::7", "203.0.113.5" })
Assert.False(defaults.Any(n => n.Contains(IPAddress.Parse(address))), address);
var options = ServerOptions.Load(new Dictionary<string, string?>
{