diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx
index ef5ba78c..73a31bf6 100644
--- a/i18n/en/Server.resx
+++ b/i18n/en/Server.resx
@@ -67,6 +67,7 @@
Not found.long
That address is not a Titano Server.long
Change your password first.long
+ 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.long
This upload would exceed your quota.long
Too many attempts; wait a minute and try again.long
Choose a password different from the current one.long
diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx
index 2d35b8b3..347d1e1d 100644
--- a/i18n/it/Server.it.resx
+++ b/i18n/it/Server.it.resx
@@ -65,6 +65,7 @@
Non trovato.
Questo indirizzo non è un Titano Server.
Cambia prima la password.
+ Questa pagina non è arrivata da un proxy attendibile in HTTPS. Aprila tramite il proxy o aggiungi l'indirizzo del proxy a TITANO_TRUSTED_PROXIES.
Questo caricamento supererebbe la tua quota.
Troppi tentativi; attendi un minuto e riprova.
Scegli una password diversa da quella attuale.
diff --git a/src/Titano.Server/Api/AuthEndpoints.cs b/src/Titano.Server/Api/AuthEndpoints.cs
index 6f9d30f3..51626076 100644
--- a/src/Titano.Server/Api/AuthEndpoints.cs
+++ b/src/Titano.Server/Api/AuthEndpoints.cs
@@ -18,8 +18,18 @@ public static class AuthEndpoints
api.MapGet("/auth/me", (Caller caller) => Results.Json(Dto.User(caller.User), ProtocolJson.Default.UserDto)).AllowDuringPasswordChange();
}
+ ///
+ /// Why the Secure 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.
+ ///
+ 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 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;
diff --git a/src/Titano.Server/Configuration/ServerOptions.cs b/src/Titano.Server/Configuration/ServerOptions.cs
index ba20b354..f971f122 100644
--- a/src/Titano.Server/Configuration/ServerOptions.cs
+++ b/src/Titano.Server/Configuration/ServerOptions.cs
@@ -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
];
///
- /// Reverse proxies whose X-Forwarded-* 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 X-Forwarded-* 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.
///
- 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";
/// The environment variables the server reads (--help lists them all).
public static IEnumerable 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)
{
diff --git a/src/Titano.Server/Hosting/DataFolderAccess.cs b/src/Titano.Server/Hosting/DataFolderAccess.cs
index c75b0e41..bb0bd2f4 100644
--- a/src/Titano.Server/Hosting/DataFolderAccess.cs
+++ b/src/Titano.Server/Hosting/DataFolderAccess.cs
@@ -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 server.json. On Windows the folder sits in %ProgramData%, 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 /data, 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 /data, and secrets are
+/// written with mode 0600. An archive folder the server creates on Windows gets the same accounts (see
+/// ).
///
public static class DataFolderAccess
{
private const UnixFileMode OwnerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite;
+ private const int GenericAll = 0x10000000;
+ private const int GenericWrite = 0x40000000;
- /// Creates the folder if needed and, on Windows, replaces an ACL that grants anyone else access.
- /// The ACL cannot be changed (the account neither owns the folder nor is an administrator).
+ /// Rights that let an account replace or alter a file or folder (including the generic forms).
+ [SupportedOSPlatform("windows")]
+ private const FileSystemRights ChangeRights = FileSystemRights.WriteData | FileSystemRights.AppendData | FileSystemRights.WriteExtendedAttributes
+ | FileSystemRights.DeleteSubdirectoriesAndFiles | FileSystemRights.Delete | FileSystemRights.ChangePermissions | FileSystemRights.TakeOwnership
+ | (FileSystemRights)GenericWrite | (FileSystemRights)GenericAll;
+
+ ///
+ /// 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.
+ ///
+ ///
+ /// 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).
+ ///
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);
}
}
+ ///
+ /// Reads a file the server acts on (server.json). 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.
+ ///
+ /// The file belongs to another account.
+ public static string ReadTrustedText(string path)
+ {
+ if (!OperatingSystem.IsWindows()) return File.ReadAllText(path);
+ return ReadTrustedText(path, AllowedAccounts());
+ }
+
/// Writes a secret that only the server's account (and, on Windows, SYSTEM and Administrators) may read.
public static void WritePrivateFile(string path, ReadOnlySpan contents)
{
@@ -49,12 +79,44 @@ public static class DataFolderAccess
File.SetUnixFileMode(path, OwnerOnly);
}
- /// True when the ACL is protected and names no account besides SYSTEM, Administrators and this process's account.
+ ///
+ /// 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 .titano 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.
+ ///
+ 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);
+ }
+
+ ///
+ /// True when the ACL is protected, its owner is SYSTEM, Administrators or this process's account, and it names no
+ /// other account.
+ ///
[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;
}
+ ///
+ /// The first problem with 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
+ /// (who may have written the contents and can always change the ACL back). Links are
+ /// reported, never followed.
+ ///
+ [SupportedOSPlatform("windows")]
+ internal static string? FindUntrusted(DirectoryInfo folder, IReadOnlySet owners)
+ {
+ var everything = new EnumerationOptions { AttributesToSkip = 0, IgnoreInaccessible = false };
+ var pending = new Stack();
+ 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;
+ }
+
+ ///
+ [SupportedOSPlatform("windows")]
+ internal static string ReadTrustedText(string path, IReadOnlySet 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();
+ }
+
+ ///
+ /// True when the owner is outside 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.
+ ///
+ [SupportedOSPlatform("windows")]
+ internal static bool IsChangeableByOthers(FileSystemSecurity security, IReadOnlySet 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;
+ }
+
+ /// SYSTEM, Administrators and the account this process runs as (SYSTEM again for the Windows service).
+ [SupportedOSPlatform("windows")]
+ internal static HashSet AllowedAccounts()
+ {
+ using var identity = WindowsIdentity.GetCurrent();
+ var accounts = new HashSet
+ {
+ 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 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 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.";
+ }
+
+ /// A symbolic link or junction (other reparse points, such as deduplicated files, are ordinary files).
+ 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 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);
}
/// A protected DACL that gives the allowed accounts full control, passed on to everything inside.
@@ -99,6 +290,16 @@ public static class DataFolderAccess
return security;
}
+ /// The private DACL, plus read access for every local user (photos and renders, never .titano).
+ [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;
}
-
- /// SYSTEM, Administrators and the account this process runs as (SYSTEM again for the Windows service).
- [SupportedOSPlatform("windows")]
- private static HashSet AllowedAccounts()
- {
- using var identity = WindowsIdentity.GetCurrent();
- var accounts = new HashSet
- {
- new(WellKnownSidType.LocalSystemSid, null),
- new(WellKnownSidType.BuiltinAdministratorsSid, null),
- };
- if (identity.User is { } user) accounts.Add(user);
- return accounts;
- }
}
diff --git a/src/Titano.Server/Hosting/ServerCommandLine.cs b/src/Titano.Server/Hosting/ServerCommandLine.cs
index e27f4392..10e2e462 100644
--- a/src/Titano.Server/Hosting/ServerCommandLine.cs
+++ b/src/Titano.Server/Hosting/ServerCommandLine.cs
@@ -43,7 +43,7 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList app.Logger.LogInformation("Titano Server stopping"));
app.Lifetime.ApplicationStopped.Register(() => database.DisposeAsync().AsTask().GetAwaiter().GetResult());
return app;
diff --git a/src/Titano.Server/Hosting/Windows/ServiceInstaller.cs b/src/Titano.Server/Hosting/Windows/ServiceInstaller.cs
index 73f7b29d..dcc404e6 100644
--- a/src/Titano.Server/Hosting/Windows/ServiceInstaller.cs
+++ b/src/Titano.Server/Hosting/Windows/ServiceInstaller.cs
@@ -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;
-
- /// Rights that let an account replace or alter a file or folder (including the generic forms).
- private const FileSystemRights ChangeRights = FileSystemRights.WriteData | FileSystemRights.AppendData | FileSystemRights.WriteExtendedAttributes
- | FileSystemRights.DeleteSubdirectoriesAndFiles | FileSystemRights.Delete | FileSystemRights.ChangePermissions | FileSystemRights.TakeOwnership
- | (FileSystemRights)GenericWrite | (FileSystemRights)GenericAll;
/// TrustedInstaller, the owner of Windows' own files under Program Files.
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 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;
}
- ///
- /// True when an allow entry gives change rights to an account outside . 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.
- ///
- private static bool IsChangeableByOthers(FileSystemSecurity security, HashSet 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 TrustedAccounts()
{
var trusted = new HashSet
diff --git a/tests/Titano.Server.Tests/Hosting/DataFolderAccessTests.cs b/tests/Titano.Server.Tests/Hosting/DataFolderAccessTests.cs
index 65bed66d..df03b16b 100644
--- a/tests/Titano.Server.Tests/Hosting/DataFolderAccessTests.cs
+++ b/tests/Titano.Server.Tests/Hosting/DataFolderAccessTests.cs
@@ -8,7 +8,8 @@ namespace Titano.Server.Tests.Hosting;
///
/// 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.
///
[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 { 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 { 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 { 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(() => 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 { 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))!;
+
+ /// An owner this process may give a file that its new files do not get: its own account or Administrators.
+ [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;
+ }
+ }
+
+ /// The rights allow entries give .
+ [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;
+ }
+
/// True when Users, Authenticated Users or Everyone have any allow entry.
[SupportedOSPlatform("windows")]
private static bool NamesUsers(FileSystemSecurity security)
diff --git a/tests/Titano.Server.Tests/Hosting/ProxyModeTests.cs b/tests/Titano.Server.Tests/Hosting/ProxyModeTests.cs
index fa5ce42f..13c1256f 100644
--- a/tests/Titano.Server.Tests/Hosting/ProxyModeTests.cs
+++ b/tests/Titano.Server.Tests/Hosting/ProxyModeTests.cs
@@ -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);
}
+ ///
+ /// Runs the server's own forwarded-headers step on a request from that claims to forward a
+ /// client at 203.0.113.7 over HTTPS: the address and scheme the rest of the server then sees.
+ ///
+ 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>());
+ 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);
diff --git a/tests/Titano.Server.Tests/Hosting/StartupTests.cs b/tests/Titano.Server.Tests/Hosting/StartupTests.cs
index a8bde8ef..82475e78 100644
--- a/tests/Titano.Server.Tests/Hosting/StartupTests.cs
+++ b/tests/Titano.Server.Tests/Hosting/StartupTests.cs
@@ -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 { ["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
{