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:
10 files changed
+398
-10
No files matched your search
@@ -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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
using System.Runtime.Versioning;
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Principal;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// Keeps the data folder and its secrets private (BRIEF §14.2): it holds the database, the TLS private key, the
|
||||
/// temporary admin password and <c>server.json</c>. On Windows the folder sits in <c>%ProgramData%</c>, whose ACL lets
|
||||
/// every local user read it and create files in it, so it gets a protected DACL (nothing inherited) that allows only
|
||||
/// SYSTEM, Administrators and the account the server runs as; everything inside inherits that. Elsewhere the container
|
||||
/// entrypoint owns <c>/data</c>, and secrets are written with mode 0600.
|
||||
/// </summary>
|
||||
public static class DataFolderAccess
|
||||
{
|
||||
private const UnixFileMode OwnerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite;
|
||||
|
||||
/// <summary>Creates the folder if needed and, on Windows, replaces an ACL that grants anyone else access.</summary>
|
||||
/// <exception cref="InvalidOperationException">The ACL cannot be changed (the account neither owns the folder nor is an administrator).</exception>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Writes a secret that only the server's account (and, on Windows, SYSTEM and Administrators) may read.</summary>
|
||||
public static void WritePrivateFile(string path, ReadOnlySpan<byte> contents)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>True when the ACL is protected and names no account besides SYSTEM, Administrators and this process's account.</summary>
|
||||
[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<byte> contents)
|
||||
{
|
||||
// The security descriptor applies when the file is created; one that already existed gets it afterwards.
|
||||
using (var stream = file.Create(FileMode.Create, FileSystemRights.Write, FileShare.None, 4096, FileOptions.None, PrivateFileSecurity()))
|
||||
stream.Write(contents);
|
||||
if (!IsPrivate(file.GetAccessControl())) file.SetAccessControl(PrivateFileSecurity());
|
||||
}
|
||||
|
||||
/// <summary>A protected DACL that gives the allowed accounts full control, passed on to everything inside.</summary>
|
||||
[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;
|
||||
}
|
||||
|
||||
/// <summary>SYSTEM, Administrators and the account this process runs as (SYSTEM again for the Windows service).</summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static HashSet<SecurityIdentifier> AllowedAccounts()
|
||||
{
|
||||
using var identity = WindowsIdentity.GetCurrent();
|
||||
var accounts = new HashSet<SecurityIdentifier>
|
||||
{
|
||||
new(WellKnownSidType.LocalSystemSid, null),
|
||||
new(WellKnownSidType.BuiltinAdministratorsSid, null),
|
||||
};
|
||||
if (identity.User is { } user) accounts.Add(user);
|
||||
return accounts;
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,8 @@ public static class ServerHost
|
||||
|
||||
public static WebApplication Build(ServerOptions options, string[] args, Action<IServiceCollection>? 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);
|
||||
|
||||
@@ -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;
|
||||
/// <summary>
|
||||
/// <c>--install-service</c> / <c>--uninstall-service</c>: registers the server with the Service Control Manager
|
||||
/// (automatic start, LocalSystem, command line <c>"…\Titano.Server.exe" --service</c>) or stops and removes it.
|
||||
/// Both need an elevated prompt; failures surface as <see cref="Win32Exception"/>.
|
||||
/// Both need an elevated prompt; failures surface as <see cref="Win32Exception"/>. 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 <see cref="Install"/> refuses with <see cref="InvalidOperationException"/>.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
public static unsafe class ServiceInstaller
|
||||
{
|
||||
private const string DisplayName = "Titano Server";
|
||||
private const int GenericAll = 0x10000000;
|
||||
private const int GenericWrite = 0x40000000;
|
||||
|
||||
/// <summary>Rights that let an account replace or alter a file or folder (including the generic forms).</summary>
|
||||
private const FileSystemRights ChangeRights = FileSystemRights.WriteData | FileSystemRights.AppendData | FileSystemRights.WriteExtendedAttributes
|
||||
| FileSystemRights.DeleteSubdirectoriesAndFiles | FileSystemRights.Delete | FileSystemRights.ChangePermissions | FileSystemRights.TakeOwnership
|
||||
| (FileSystemRights)GenericWrite | (FileSystemRights)GenericAll;
|
||||
|
||||
/// <summary>TrustedInstaller, the owner of Windows' own files under Program Files.</summary>
|
||||
private static readonly SecurityIdentifier TrustedInstaller = new("S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464");
|
||||
|
||||
/// <exception cref="InvalidOperationException">This copy is not in a folder that only administrators can change.</exception>
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why this copy may not be registered, as a localized sentence, or null when it may: the program folder (and, when
|
||||
/// run by <c>dotnet</c>, the host's folder) must be inside Program Files and changeable only by administrators.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>True for a path inside <c>%ProgramFiles%</c> or <c>%ProgramFiles(x86)%</c> (not the folder itself).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal static string? FindChangeable(DirectoryInfo folder, bool recursive) => FindChangeable(folder, recursive, TrustedAccounts());
|
||||
|
||||
private static string? FindChangeable(DirectoryInfo folder, bool recursive, HashSet<SecurityIdentifier> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when an allow entry gives change rights to an account outside <paramref name="trusted"/>. Entries that only
|
||||
/// pass to children count too, since new files would inherit them; CREATOR OWNER and CREATOR GROUP stand for whoever
|
||||
/// creates a child, which already takes change rights on the folder.
|
||||
/// </summary>
|
||||
private static bool IsChangeableByOthers(FileSystemSecurity security, HashSet<SecurityIdentifier> trusted)
|
||||
{
|
||||
foreach (FileSystemAccessRule rule in security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier)))
|
||||
{
|
||||
if (rule.AccessControlType != AccessControlType.Allow || (rule.FileSystemRights & ChangeRights) == 0) continue;
|
||||
var account = (SecurityIdentifier)rule.IdentityReference;
|
||||
if (trusted.Contains(account) || account.IsWellKnown(WellKnownSidType.CreatorOwnerSid) || account.IsWellKnown(WellKnownSidType.CreatorGroupSid)) continue;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static HashSet<SecurityIdentifier> TrustedAccounts()
|
||||
{
|
||||
var trusted = new HashSet<SecurityIdentifier>
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The service's command line: this executable (or <c>dotnet</c> plus this assembly) with <c>--service</c>.</summary>
|
||||
private static string CommandLine()
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// First-run administrator (BRIEF §14.9): when no admin account exists, one is created from
|
||||
/// <c>TITANO_ADMIN_USER</c>/<c>TITANO_ADMIN_PASSWORD</c> and must change its password at first sign-in. Without a
|
||||
/// configured password a temporary one is generated and written to <c>/data/initial-admin-password.txt</c> (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 <c>/data/initial-admin-password.txt</c> (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.
|
||||
/// </summary>
|
||||
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
|
||||
|
||||
Reference in new issue
Block a user