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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-12 09:27:06 +00:00
1 parent c11c996bc6
commit 047cddfe7b
10 files changed
+398 -10

No files matched your search

@@ -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;
/// <summary>
/// The data folder and its secrets are private (BRIEF §14.2): mode 0600 off Windows; on Windows a protected ACL that no
/// ordinary user appears in, where %ProgramData% would otherwise let every local user read the folder.
/// </summary>
[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);
/// <summary>True when Users, Authenticated Users or Everyone have any allow entry.</summary>
[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);
}
}
@@ -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()