From 047cddfe7b78ac336b8f19cb53a47ad2dc922a43 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 12 Oct 2026 09:27:06 +0000 Subject: [PATCH 1/5] fix(server): keep Windows secrets private and the service out of user folders On Windows the data folder sits in %ProgramData%, whose ACL let every local user read the database, the password-less TLS key and the temporary admin password, and create a server.json the LocalSystem service would load (SRS-02, SRV-2). The folder now gets a protected DACL (SYSTEM, Administrators, the server's account) at every start when it names anyone else, which also replaces what the files inside inherited; server.pfx and initial-admin-password.txt are written with their own protected DACL, and with mode 0600 elsewhere. A folder whose ACL cannot be changed stops the start with a clear message. --install-service registered a LocalSystem service from any folder, so a per-user install or an unpacked zip handed SYSTEM to that user (SRS-06). It now refuses, with a localized one-line reason, unless the program folder is inside Program Files and no account besides SYSTEM, Administrators, TrustedInstaller or the registering administrator can change it or any file below it (under dotnet, the host's folder too). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- i18n/en/Server.resx | 2 + i18n/it/Server.it.resx | 2 + src/Titano.Server/Hosting/CertificateStore.cs | 4 +- src/Titano.Server/Hosting/DataFolderAccess.cs | 125 ++++++++++++++++++ src/Titano.Server/Hosting/ServerHost.cs | 3 +- .../Hosting/Windows/ServiceInstaller.cs | 103 ++++++++++++++- src/Titano.Server/Program.cs | 3 +- src/Titano.Server/Security/AdminBootstrap.cs | 10 +- .../Hosting/DataFolderAccessTests.cs | 106 +++++++++++++++ .../Hosting/WindowsServiceTests.cs | 50 ++++++- 10 files changed, 398 insertions(+), 10 deletions(-) create mode 100644 src/Titano.Server/Hosting/DataFolderAccess.cs create mode 100644 tests/Titano.Server.Tests/Hosting/DataFolderAccessTests.cs diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx index 543c7626..ef5ba78c 100644 --- a/i18n/en/Server.resx +++ b/i18n/en/Server.resx @@ -108,6 +108,8 @@ Uploader Viewer Titano time-lapse archive, uploads, jobs and rendering server.long + Titano Server is not in Program Files ({0}), so it cannot run as a service; install it for all users and register the service from there.long + Users who are not administrators can change {0}, so Titano Server cannot run as a service from there; reinstall it for all users and register the service again.long Aspect auto Batch list diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx index 8baccf97..2d35b8b3 100644 --- a/i18n/it/Server.it.resx +++ b/i18n/it/Server.it.resx @@ -106,6 +106,8 @@ Caricatore Visualizzatore Server Titano per archivio time-lapse, caricamenti, job e rendering. + Titano Server non è in Programmi ({0}), quindi non può funzionare come servizio; installalo per tutti gli utenti e registra il servizio da lì. + Anche utenti non amministratori possono modificare {0}, quindi Titano Server non può funzionare come servizio da lì; reinstallalo per tutti gli utenti e registra di nuovo il servizio. Proporzioni auto Elenco batch diff --git a/src/Titano.Server/Hosting/CertificateStore.cs b/src/Titano.Server/Hosting/CertificateStore.cs index bfcf9c24..7abcdbe4 100644 --- a/src/Titano.Server/Hosting/CertificateStore.cs +++ b/src/Titano.Server/Hosting/CertificateStore.cs @@ -34,8 +34,8 @@ public static class CertificateStore logger.LogWarning("Self-signed certificate expires {NotAfter:u}; generating a new one (clients will see a new fingerprint).", existing.NotAfter); } var created = CreateSelfSigned(options.ServerName); - File.WriteAllBytes(path, created.Export(X509ContentType.Pkcs12)); - if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite); + // The PKCS#12 export carries the private key without a password: only the server's account may read it. + DataFolderAccess.WritePrivateFile(path, created.Export(X509ContentType.Pkcs12)); logger.LogInformation("Generated self-signed TLS certificate, SHA-256 fingerprint {Fingerprint}", Fingerprint(created)); return created; } diff --git a/src/Titano.Server/Hosting/DataFolderAccess.cs b/src/Titano.Server/Hosting/DataFolderAccess.cs new file mode 100644 index 00000000..c75b0e41 --- /dev/null +++ b/src/Titano.Server/Hosting/DataFolderAccess.cs @@ -0,0 +1,125 @@ +using System.Runtime.Versioning; +using System.Security.AccessControl; +using System.Security.Principal; + +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. +/// +public static class DataFolderAccess +{ + private const UnixFileMode OwnerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite; + + /// 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). + public static void Restrict(string folder) + { + if (!OperatingSystem.IsWindows()) + { + Directory.CreateDirectory(folder); + return; + } + try + { + RestrictOnWindows(new DirectoryInfo(folder)); + } + 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); + } + } + + /// 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) + { + if (OperatingSystem.IsWindows()) + { + WritePrivateFileOnWindows(new FileInfo(path), contents); + return; + } + using (var stream = new FileStream(path, new FileStreamOptions { Mode = FileMode.Create, Access = FileAccess.Write, UnixCreateMode = OwnerOnly })) + stream.Write(contents); + // A file that already existed keeps its old mode otherwise. + File.SetUnixFileMode(path, OwnerOnly); + } + + /// True when the ACL is protected and names no account besides SYSTEM, Administrators and this process's account. + [SupportedOSPlatform("windows")] + public static bool IsPrivate(FileSystemSecurity security) + { + if (!security.AreAccessRulesProtected) return false; + var allowed = AllowedAccounts(); + foreach (FileSystemAccessRule rule in security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier))) + { + if (rule.AccessControlType == AccessControlType.Allow && !allowed.Contains((SecurityIdentifier)rule.IdentityReference)) return false; + } + return true; + } + + [SupportedOSPlatform("windows")] + private static void RestrictOnWindows(DirectoryInfo folder) + { + if (!folder.Exists) + { + if (folder.Parent is { } parent) parent.Create(); + folder.Create(PrivateFolderSecurity()); + folder.Refresh(); + } + // 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 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 protected DACL that gives the allowed accounts full control, passed on to everything inside. + [SupportedOSPlatform("windows")] + private static DirectorySecurity PrivateFolderSecurity() + { + var security = new DirectorySecurity(); + security.SetAccessRuleProtection(isProtected: true, preserveInheritance: false); + foreach (var account in AllowedAccounts()) + { + security.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.FullControl, + InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow)); + } + return security; + } + + [SupportedOSPlatform("windows")] + private static FileSecurity PrivateFileSecurity() + { + var security = new FileSecurity(); + security.SetAccessRuleProtection(isProtected: true, preserveInheritance: false); + foreach (var account in AllowedAccounts()) + 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/ServerHost.cs b/src/Titano.Server/Hosting/ServerHost.cs index 4ed24d7d..0913d48d 100644 --- a/src/Titano.Server/Hosting/ServerHost.cs +++ b/src/Titano.Server/Hosting/ServerHost.cs @@ -29,7 +29,8 @@ public static class ServerHost public static WebApplication Build(ServerOptions options, string[] args, Action? configureServices = null) { - Directory.CreateDirectory(options.DataPath); + // Before anything is written there: the folder holds the database, the TLS key and the first admin password. + DataFolderAccess.Restrict(options.DataPath); Directory.CreateDirectory(options.LogPath); Directory.CreateDirectory(options.UploadsPath); Directory.CreateDirectory(options.ArchivePath); diff --git a/src/Titano.Server/Hosting/Windows/ServiceInstaller.cs b/src/Titano.Server/Hosting/Windows/ServiceInstaller.cs index 375fa13e..73f7b29d 100644 --- a/src/Titano.Server/Hosting/Windows/ServiceInstaller.cs +++ b/src/Titano.Server/Hosting/Windows/ServiceInstaller.cs @@ -1,6 +1,8 @@ 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; @@ -9,15 +11,30 @@ namespace Titano.Server.Hosting.Windows; /// /// --install-service / --uninstall-service: registers the server with the Service Control Manager /// (automatic start, LocalSystem, command line "…\Titano.Server.exe" --service) or stops and removes it. -/// Both need an elevated prompt; failures surface as . +/// Both need an elevated prompt; failures surface as . A LocalSystem service runs whatever +/// sits at its image path, so it is registered only from a copy under Program Files that nobody but SYSTEM, +/// Administrators and TrustedInstaller can change: a per-user install or a zip unpacked elsewhere would hand SYSTEM to +/// any program of that user. Otherwise refuses with . /// [SupportedOSPlatform("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"); + + /// This copy is not in a folder that only administrators can change. public static void Install() { + if (UnsafeLocation() is { } problem) throw new InvalidOperationException(problem); var manager = OpenSCManagerW(null, null, ScManagerConnect | ScManagerCreateService); if (manager == 0) throw new Win32Exception(Marshal.GetLastPInvokeError()); try @@ -71,6 +88,90 @@ public static unsafe class ServiceInstaller } } + /// + /// Why this copy may not be registered, as a localized sentence, or null when it may: the program folder (and, when + /// run by dotnet, the host's folder) must be inside Program Files and changeable only by administrators. + /// + internal static string? UnsafeLocation() + { + var program = Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory); + if (!IsUnderProgramFiles(program)) return Loc.L("Server.Service.NotProgramFiles", program); + if (FindChangeable(new DirectoryInfo(program), recursive: true) is { } open) return Loc.L("Server.Service.Writable", open); + // Under dotnet the host runs as SYSTEM too; its folder is checked without the thousands of framework files below it. + if (Environment.ProcessPath is { } process && Path.GetDirectoryName(process) is { } host + && !string.Equals(Path.TrimEndingDirectorySeparator(host), program, StringComparison.OrdinalIgnoreCase)) + { + if (!IsUnderProgramFiles(host)) return Loc.L("Server.Service.NotProgramFiles", host); + if (FindChangeable(new DirectoryInfo(host), recursive: false) is { } hostOpen) return Loc.L("Server.Service.Writable", hostOpen); + } + return null; + } + + /// True for a path inside %ProgramFiles% or %ProgramFiles(x86)% (not the folder itself). + internal static bool IsUnderProgramFiles(string path) + { + var full = Path.GetFullPath(path); + foreach (var folder in new[] { Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolder.ProgramFilesX86 }) + { + var root = Environment.GetFolderPath(folder); + if (root.Length > 0 && full.StartsWith(Path.TrimEndingDirectorySeparator(root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + return true; + } + return false; + } + + /// + /// The first of the folder, its files and (when recursive) its subfolders whose ACL lets an account other than + /// SYSTEM, Administrators, TrustedInstaller or the registering administrator change it; null when there is none. + /// + internal static string? FindChangeable(DirectoryInfo folder, bool recursive) => FindChangeable(folder, recursive, TrustedAccounts()); + + private static string? FindChangeable(DirectoryInfo folder, bool recursive, HashSet trusted) + { + if (IsChangeableByOthers(folder.GetAccessControl(), trusted)) return folder.FullName; + foreach (var file in folder.EnumerateFiles()) + { + if (IsChangeableByOthers(file.GetAccessControl(), trusted)) return file.FullName; + } + if (!recursive) return null; + foreach (var child in folder.EnumerateDirectories()) + { + if (FindChangeable(child, recursive: true, trusted) is { } path) return path; + } + 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 + { + new(WellKnownSidType.LocalSystemSid, null), + new(WellKnownSidType.BuiltinAdministratorsSid, null), + TrustedInstaller, + }; + // Registering needs an elevated prompt, so the account doing it is an administrator; setups often name it. + using var identity = WindowsIdentity.GetCurrent(); + if (identity.User is { } user && new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)) trusted.Add(user); + return trusted; + } + /// The service's command line: this executable (or dotnet plus this assembly) with --service. private static string CommandLine() { diff --git a/src/Titano.Server/Program.cs b/src/Titano.Server/Program.cs index caed2df6..7b7ce816 100644 --- a/src/Titano.Server/Program.cs +++ b/src/Titano.Server/Program.cs @@ -50,8 +50,9 @@ static int ServiceAction(Action action, string done) Console.WriteLine(done); return 0; } - catch (Win32Exception ex) + catch (Exception ex) when (ex is Win32Exception or InvalidOperationException) { + // Win32: the Service Control Manager's reason; InvalidOperation: a folder the service must not run from. Console.Error.WriteLine(ex.Message); return 1; } diff --git a/src/Titano.Server/Security/AdminBootstrap.cs b/src/Titano.Server/Security/AdminBootstrap.cs index 027c94ef..a095dda4 100644 --- a/src/Titano.Server/Security/AdminBootstrap.cs +++ b/src/Titano.Server/Security/AdminBootstrap.cs @@ -1,14 +1,17 @@ +using System.Text; using Titano.Core.Model; using Titano.Data; using Titano.Server.Configuration; +using Titano.Server.Hosting; namespace Titano.Server.Security; /// /// First-run administrator (BRIEF §14.9): when no admin account exists, one is created from /// TITANO_ADMIN_USER/TITANO_ADMIN_PASSWORD and must change its password at first sign-in. Without a -/// configured password a temporary one is generated and written to /data/initial-admin-password.txt (owner-only), -/// never to the log; the file is removed once an administrator changes their password. +/// configured password a temporary one is generated and written to /data/initial-admin-password.txt (owner-only; +/// on Windows readable by the server's account and Administrators), never to the log; the file is removed once an +/// administrator changes their password. /// public static class AdminBootstrap { @@ -37,8 +40,7 @@ public static class AdminBootstrap { password = TemporaryPassword.Generate(); passwordFile = Path.Combine(options.DataPath, PasswordFileName); - await File.WriteAllTextAsync(passwordFile, password + Environment.NewLine, cancellationToken).ConfigureAwait(false); - if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(passwordFile, UnixFileMode.UserRead | UnixFileMode.UserWrite); + DataFolderAccess.WritePrivateFile(passwordFile, Encoding.UTF8.GetBytes(password + Environment.NewLine)); } var admin = new User diff --git a/tests/Titano.Server.Tests/Hosting/DataFolderAccessTests.cs b/tests/Titano.Server.Tests/Hosting/DataFolderAccessTests.cs new file mode 100644 index 00000000..65bed66d --- /dev/null +++ b/tests/Titano.Server.Tests/Hosting/DataFolderAccessTests.cs @@ -0,0 +1,106 @@ +using System.Runtime.Versioning; +using System.Security.AccessControl; +using System.Security.Principal; +using Titano.Server.Hosting; +using Titano.Testing; + +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. +/// +[Category("server")] +public sealed class DataFolderAccessTests(TestContext context) +{ + private const UnixFileMode OwnerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite; + + [Test] + public async Task TheTlsKeyAndTheFirstAdminPasswordAreReadableOnlyByTheServer() + { + await using var server = await TestServer.StartAsync(context, o => o.AdminPassword = null); + foreach (var file in new[] { Path.Combine(server.Options.TlsPath, "server.pfx"), Path.Combine(server.Options.DataPath, "initial-admin-password.txt") }) + { + Assert.FileExists(file); + if (OperatingSystem.IsWindows()) Assert.True(DataFolderAccess.IsPrivate(new FileInfo(file).GetAccessControl()), file); + else Assert.Equal(OwnerOnly, File.GetUnixFileMode(file)); + } + if (OperatingSystem.IsWindows()) Assert.True(DataFolderAccess.IsPrivate(new DirectoryInfo(server.Options.DataPath).GetAccessControl())); + } + + [Test] + public void ARewrittenSecretLosesTheAccessItHad() + { + var file = Path.Combine(context.CreateTempDirectory("secret"), "server.pfx"); + File.WriteAllBytes(file, [1]); + if (OperatingSystem.IsWindows()) GrantUsersRead(new FileInfo(file)); + else File.SetUnixFileMode(file, OwnerOnly | UnixFileMode.GroupRead | UnixFileMode.OtherRead); + + DataFolderAccess.WritePrivateFile(file, [1, 2, 3]); + Assert.BytesEqual([1, 2, 3], File.ReadAllBytes(file)); + if (OperatingSystem.IsWindows()) Assert.True(DataFolderAccess.IsPrivate(new FileInfo(file).GetAccessControl())); + else Assert.Equal(OwnerOnly, File.GetUnixFileMode(file)); + } + + [Test] + [WindowsOnly] + public void AFolderEveryUserCouldReadBecomesPrivateWithItsFiles() + { + if (!OperatingSystem.IsWindows()) return; + var folder = new DirectoryInfo(context.CreateTempDirectory("programdata")); + // What %ProgramData% hands down to a new folder: every local user may read it and create files in it. + var open = folder.GetAccessControl(); + open.AddAccessRule(new FileSystemAccessRule(Users, FileSystemRights.ReadAndExecute | FileSystemRights.CreateFiles, + InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow)); + folder.SetAccessControl(open); + var database = new FileInfo(Path.Combine(folder.FullName, "titano.db")); + File.WriteAllText(database.FullName, "rows"); + Assert.True(NamesUsers(database.GetAccessControl()), "the file inherited the users' entry"); + + DataFolderAccess.Restrict(folder.FullName); + Assert.True(DataFolderAccess.IsPrivate(folder.GetAccessControl())); + Assert.False(NamesUsers(folder.GetAccessControl())); + Assert.False(NamesUsers(database.GetAccessControl()), "the file still lets every user read it"); + Assert.Equal("rows", File.ReadAllText(database.FullName)); + + // Once private, a later start leaves it as it is. + DataFolderAccess.Restrict(folder.FullName); + Assert.True(DataFolderAccess.IsPrivate(folder.GetAccessControl())); + } + + [Test] + [WindowsOnly] + public void ANewDataFolderIsCreatedPrivate() + { + if (!OperatingSystem.IsWindows()) return; + var folder = new DirectoryInfo(Path.Combine(context.CreateTempDirectory("new"), "Titano Server")); + DataFolderAccess.Restrict(folder.FullName); + Assert.True(DataFolderAccess.IsPrivate(folder.GetAccessControl())); + var settings = new FileInfo(Path.Combine(folder.FullName, "server.json")); + File.WriteAllText(settings.FullName, "{}"); + Assert.False(NamesUsers(settings.GetAccessControl())); + } + + [SupportedOSPlatform("windows")] + private static SecurityIdentifier Users => new(WellKnownSidType.BuiltinUsersSid, null); + + /// True when Users, Authenticated Users or Everyone have any allow entry. + [SupportedOSPlatform("windows")] + private static bool NamesUsers(FileSystemSecurity security) + { + SecurityIdentifier[] ordinary = [Users, new(WellKnownSidType.AuthenticatedUserSid, null), new(WellKnownSidType.WorldSid, null)]; + foreach (FileSystemAccessRule rule in security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier))) + { + if (rule.AccessControlType == AccessControlType.Allow && ordinary.Contains((SecurityIdentifier)rule.IdentityReference)) return true; + } + return false; + } + + [SupportedOSPlatform("windows")] + private static void GrantUsersRead(FileInfo file) + { + var security = file.GetAccessControl(); + security.AddAccessRule(new FileSystemAccessRule(Users, FileSystemRights.Read, AccessControlType.Allow)); + file.SetAccessControl(security); + } +} diff --git a/tests/Titano.Server.Tests/Hosting/WindowsServiceTests.cs b/tests/Titano.Server.Tests/Hosting/WindowsServiceTests.cs index d09c7c7e..2d624ec0 100644 --- a/tests/Titano.Server.Tests/Hosting/WindowsServiceTests.cs +++ b/tests/Titano.Server.Tests/Hosting/WindowsServiceTests.cs @@ -1,10 +1,12 @@ +using System.Security.AccessControl; +using System.Security.Principal; using Titano.Server.Hosting; using Titano.Server.Hosting.Windows; using Titano.Testing; namespace Titano.Server.Tests.Hosting; -public sealed class WindowsServiceTests +public sealed class WindowsServiceTests(TestContext context) { [Test] public void CommandSwitchesAreParsedAndTheRestPassedOn() @@ -39,6 +41,52 @@ public sealed class WindowsServiceTests Assert.Equal(1064u, new ServiceStatusTracker().Stopped(1064).ExitCode); } + [Test] + [WindowsOnly] + public void TheServiceIsRegisteredOnlyFromInsideProgramFiles() + { + if (!OperatingSystem.IsWindows()) return; + var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); + Assert.True(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "Titano", "Titano.Server.exe"))); + Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles)); + Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles + " Tools\\Titano")); + Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "Titano"))); + Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "..", "Titano"))); + // The test build is not under Program Files: registering it is refused, naming the folder. + Assert.Contains(Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory), Assert.NotNull(ServiceInstaller.UnsafeLocation())); + } + + [Test] + [WindowsOnly] + public void AnyFileOrdinaryUsersCanChangeIsFound() + { + if (!OperatingSystem.IsWindows()) return; + using var identity = WindowsIdentity.GetCurrent(); + if (!new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)) Assert.Inconclusive("registering a service needs an administrator"); + var folder = new DirectoryInfo(context.CreateTempDirectory("program")); + File.WriteAllBytes(Path.Combine(folder.FullName, "Titano.Server.exe"), [1]); + var satellite = new FileInfo(Path.Combine(folder.CreateSubdirectory("it").FullName, "Titano.Core.resources.dll")); + File.WriteAllBytes(satellite.FullName, [1]); + + // Like Program Files: administrators may change the folder, users only read it. + var locked = new DirectorySecurity(); + locked.SetAccessRuleProtection(isProtected: true, preserveInheritance: false); + var everything = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit; + foreach (var account in new[] { new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), identity.User! }) + locked.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.FullControl, everything, PropagationFlags.None, AccessControlType.Allow)); + locked.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.ReadAndExecute, everything, + PropagationFlags.None, AccessControlType.Allow)); + folder.SetAccessControl(locked); + Assert.Null(ServiceInstaller.FindChangeable(folder, recursive: true)); + + // One satellite assembly users may replace is enough: the service would load it as SYSTEM. + var open = satellite.GetAccessControl(); + open.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.Modify, AccessControlType.Allow)); + satellite.SetAccessControl(open); + Assert.Equal(satellite.FullName, ServiceInstaller.FindChangeable(folder, recursive: true)); + Assert.Null(ServiceInstaller.FindChangeable(folder, recursive: false)); + } + [Test] [WindowsOnly] public void TheDispatcherDeclinesAConsoleProcess() From 5ec59a2e964e7469e5bcdae0d0e82cc92573401f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 12 Oct 2026 09:27:31 +0000 Subject: [PATCH 2/5] fix(server): trust forwarded headers only from known proxies In TLS mode proxy the server accepted X-Forwarded-For/Proto/Host from any peer, so a client reaching the HTTP port directly could pick a new address per sign-in (defeating the 5/min/IP limit), forge audit addresses and claim HTTPS; the admin never warned (SRS-03, SRV-3). Forwarded headers now count only from TITANO_TRUSTED_PROXIES (addresses or CIDR networks; default loopback, 10/8, 172.16/12, 192.168/16, fc00::/7), and the Dashboard and Settings show a "Not via proxy" chip with a tooltip when a page did not come through a trusted proxy over HTTPS (ProxyWarning in DashboardDto and ServerSettingsDto). TITANO_PUBLIC_HTTP_PORT and TITANO_PUBLIC_HTTPS_PORT name the ports clients reach when a container's ports are published as other host ports: the admin's HTTP-to-HTTPS redirect and the LAN beacon use them instead of the bound container ports (DOCKER-4, DOCKER-5). --help lists TITANO_LOG_LEVEL, the new variables and the container's PUID, PGID and TZ (DOCKER-7); a test keeps it in step with the variables the server reads. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- i18n/en/Admin.resx | 2 + i18n/it/Admin.it.resx | 2 + src/Titano.Protocol/Admin.cs | 14 ++- .../Admin/web/pages/dashboard.js | 6 +- src/Titano.Server/Admin/web/pages/settings.js | 5 +- src/Titano.Server/Admin/web/ui.js | 3 + src/Titano.Server/Api/AdminEndpoints.cs | 12 +- .../Configuration/ServerOptions.cs | 56 +++++++++ .../Configuration/ServerSettingsStore.cs | 4 +- src/Titano.Server/Hosting/AdminPanel.cs | 17 ++- .../Hosting/DiscoveryBeaconService.cs | 12 +- .../Hosting/ServerCommandLine.cs | 11 +- src/Titano.Server/Hosting/ServerHost.cs | 4 + .../Hosting/DiscoveryTests.cs | 13 ++ .../Hosting/ProxyModeTests.cs | 117 ++++++++++++++++++ .../Hosting/StartupTests.cs | 55 ++++++++ .../Hosting/SystemEndpointTests.cs | 29 +++++ 17 files changed, 340 insertions(+), 22 deletions(-) create mode 100644 tests/Titano.Server.Tests/Hosting/ProxyModeTests.cs diff --git a/i18n/en/Admin.resx b/i18n/en/Admin.resx index a4dc3654..677b4ffc 100644 --- a/i18n/en/Admin.resx +++ b/i18n/en/Admin.resx @@ -288,6 +288,8 @@ Network and TLS The PEM file was not found; enter its full path on the server.long Used only in Own certificate mode + Not via proxy + TLS mode is Reverse proxy, but 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. Restart required Saved ports, TLS, workers, chunk size or job history apply after a restart Server diff --git a/i18n/it/Admin.it.resx b/i18n/it/Admin.it.resx index 5bbd110c..1372f99c 100644 --- a/i18n/it/Admin.it.resx +++ b/i18n/it/Admin.it.resx @@ -288,6 +288,8 @@ Rete e TLS File PEM non trovato; inserisci il percorso completo sul server. Usato solo in modalità Certificato proprio + Senza proxy + La modalità TLS è Reverse proxy, ma questa pagina non è arrivata da un proxy attendibile in HTTPS. Aprila tramite il proxy o aggiungi l'indirizzo del proxy a TITANO_TRUSTED_PROXIES. Riavvio richiesto Porte, TLS, worker, dimensione blocchi o cronologia job salvati valgono dopo un riavvio Server diff --git a/src/Titano.Protocol/Admin.cs b/src/Titano.Protocol/Admin.cs index 17abbd28..e8b118cb 100644 --- a/src/Titano.Protocol/Admin.cs +++ b/src/Titano.Protocol/Admin.cs @@ -3,7 +3,8 @@ namespace Titano.Protocol; /// /// GET/PUT /api/v1/server/settings (admin): the editable part of the server configuration. Settings named in /// come from environment variables and cannot be changed here; says -/// that saved values (ports, TLS, workers, chunk size) wait for a restart. +/// that saved values (ports, TLS, workers, chunk size) wait for a restart. is set in +/// responses when TLS mode is proxy and the request did not come through a trusted proxy over HTTPS (ignored when saving). /// public sealed record ServerSettingsDto( string ServerName, @@ -21,7 +22,8 @@ public sealed record ServerSettingsDto( int TokenLifetimeDays, int UploadRetentionHours, IReadOnlyList Locked, - bool RestartRequired); + bool RestartRequired, + bool ProxyWarning); /// A server log file (GET /api/v1/logs/files). public sealed record LogFileDto(string Name, long Size, DateTimeOffset Modified); @@ -35,7 +37,10 @@ public sealed record JobCountsDto(int Queued, int Running, int Paused, int DoneT /// Frames committed by uploads on one UTC day. public sealed record UploadDayDto(DateOnly Day, long Frames, long Bytes); -/// GET /api/v1/server/dashboard (admin): everything the dashboard page shows in one call (BRIEF §14.8). +/// +/// GET /api/v1/server/dashboard (admin): everything the dashboard page shows in one call (BRIEF §14.8). +/// : TLS mode is proxy and this request did not come through a trusted proxy over HTTPS. +/// public sealed record DashboardDto( string ServerName, string Version, @@ -50,4 +55,5 @@ public sealed record DashboardDto( IReadOnlyList Nodes, IReadOnlyList Uploads, IReadOnlyList Activity, - IReadOnlyList ActiveJobs); + IReadOnlyList ActiveJobs, + bool ProxyWarning); diff --git a/src/Titano.Server/Admin/web/pages/dashboard.js b/src/Titano.Server/Admin/web/pages/dashboard.js index 8ef19fe9..b0de718e 100644 --- a/src/Titano.Server/Admin/web/pages/dashboard.js +++ b/src/Titano.Server/Admin/web/pages/dashboard.js @@ -1,12 +1,12 @@ // Dashboard (mockup Admin.html, BRIEF §14.8): storage, archive, jobs, render nodes, charts, activity, active jobs. import { t, plural, applyStrings, culture } from "../i18n.js"; -import { escapeHtml, attr, formatBytes, formatNumber, formatTime, formatDuration, bar, columns, toast, errorText, emptyState, redraw, fitColumns } from "../ui.js"; +import { escapeHtml, attr, formatBytes, formatNumber, formatTime, formatDuration, bar, columns, toast, errorText, emptyState, redraw, fitColumns, PROXY_WARNING } from "../ui.js"; import { kindLabel, nodeLabel, progressCell, stateCell, stateLabel, encoders } from "../jobs.js"; import { activityText } from "../audit.js"; const SCAN_BUTTON = ``; -export async function render(root, { api, setMeta, onEvent }) { +export async function render(root, { api, setMeta, actions, onEvent }) { let timer = null; const refresh = () => { clearTimeout(timer); @@ -28,6 +28,8 @@ export async function render(root, { api, setMeta, onEvent }) { const tls = `Admin.Settings.Tls.${d.tlsMode.charAt(0).toUpperCase()}${d.tlsMode.slice(1)}`; setMeta(t("Admin.Dashboard.Meta", formatDuration(d.uptimeSeconds), d.database, t(tls), t(d.discovery ? "Admin.Dashboard.DiscoveryOn" : "Admin.Dashboard.DiscoveryOff"))); + actions.innerHTML = d.proxyWarning ? PROXY_WARNING : ""; + applyStrings(actions); const a = d.archive; const used = a.capacityBytes > 0 ? (a.capacityBytes - a.freeBytes) / a.capacityBytes : 0; const online = d.nodes.filter((n) => n.state !== "offline"); diff --git a/src/Titano.Server/Admin/web/pages/settings.js b/src/Titano.Server/Admin/web/pages/settings.js index 484fe805..4f01e0f6 100644 --- a/src/Titano.Server/Admin/web/pages/settings.js +++ b/src/Titano.Server/Admin/web/pages/settings.js @@ -1,7 +1,7 @@ // Settings (BRIEF §14.8): server name, ports, TLS, discovery, limits, language, retention. Values fixed by environment // variables are read-only here; ports, TLS, workers, chunk size and job history apply at the next restart. import { t, applyStrings, languages } from "../i18n.js"; -import { escapeHtml, attr, toast, errorText, nativeName, fingerprint, markInvalid, clearInvalid, invalidText, escapeReverts } from "../ui.js"; +import { escapeHtml, attr, toast, errorText, nativeName, fingerprint, markInvalid, clearInvalid, invalidText, escapeReverts, PROXY_WARNING } from "../ui.js"; /** Setting → environment variable that can fix it (BRIEF §14.9). */ const VARIABLES = { @@ -46,7 +46,8 @@ export async function render(root, { api, info, setMeta, actions }) { ${field("discovery", ``)}
-

+

+ ${settings.proxyWarning ? PROXY_WARNING : ""}
${number("httpPort", settings.httpPort, 'min="1" max="65535"')} ${number("httpsPort", settings.httpsPort, 'min="1" max="65535"')} ${field("tlsMode", `