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()