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
@@ -108,6 +108,8 @@
|
|||||||
<data name="Server.Role.Uploader" xml:space="preserve"><value>Uploader</value></data>
|
<data name="Server.Role.Uploader" xml:space="preserve"><value>Uploader</value></data>
|
||||||
<data name="Server.Role.Viewer" xml:space="preserve"><value>Viewer</value></data>
|
<data name="Server.Role.Viewer" xml:space="preserve"><value>Viewer</value></data>
|
||||||
<data name="Server.Service.Description" xml:space="preserve"><value>Titano time-lapse archive, uploads, jobs and rendering server.</value><comment>long</comment></data>
|
<data name="Server.Service.Description" xml:space="preserve"><value>Titano time-lapse archive, uploads, jobs and rendering server.</value><comment>long</comment></data>
|
||||||
|
<data name="Server.Service.NotProgramFiles" xml:space="preserve"><value>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.</value><comment>long</comment></data>
|
||||||
|
<data name="Server.Service.Writable" xml:space="preserve"><value>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.</value><comment>long</comment></data>
|
||||||
<data name="Server.Setting.Aspect" xml:space="preserve"><value>Aspect</value></data>
|
<data name="Server.Setting.Aspect" xml:space="preserve"><value>Aspect</value></data>
|
||||||
<data name="Server.Setting.Auto" xml:space="preserve"><value>auto</value></data>
|
<data name="Server.Setting.Auto" xml:space="preserve"><value>auto</value></data>
|
||||||
<data name="Server.Setting.Batch" xml:space="preserve"><value>Batch list</value></data>
|
<data name="Server.Setting.Batch" xml:space="preserve"><value>Batch list</value></data>
|
||||||
|
|||||||
@@ -106,6 +106,8 @@
|
|||||||
<data name="Server.Role.Uploader" xml:space="preserve"><value>Caricatore</value></data>
|
<data name="Server.Role.Uploader" xml:space="preserve"><value>Caricatore</value></data>
|
||||||
<data name="Server.Role.Viewer" xml:space="preserve"><value>Visualizzatore</value></data>
|
<data name="Server.Role.Viewer" xml:space="preserve"><value>Visualizzatore</value></data>
|
||||||
<data name="Server.Service.Description" xml:space="preserve"><value>Server Titano per archivio time-lapse, caricamenti, job e rendering.</value></data>
|
<data name="Server.Service.Description" xml:space="preserve"><value>Server Titano per archivio time-lapse, caricamenti, job e rendering.</value></data>
|
||||||
|
<data name="Server.Service.NotProgramFiles" xml:space="preserve"><value>Titano Server non è in Programmi ({0}), quindi non può funzionare come servizio; installalo per tutti gli utenti e registra il servizio da lì.</value></data>
|
||||||
|
<data name="Server.Service.Writable" xml:space="preserve"><value>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.</value></data>
|
||||||
<data name="Server.Setting.Aspect" xml:space="preserve"><value>Proporzioni</value></data>
|
<data name="Server.Setting.Aspect" xml:space="preserve"><value>Proporzioni</value></data>
|
||||||
<data name="Server.Setting.Auto" xml:space="preserve"><value>auto</value></data>
|
<data name="Server.Setting.Auto" xml:space="preserve"><value>auto</value></data>
|
||||||
<data name="Server.Setting.Batch" xml:space="preserve"><value>Elenco batch</value></data>
|
<data name="Server.Setting.Batch" xml:space="preserve"><value>Elenco batch</value></data>
|
||||||
|
|||||||
@@ -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);
|
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);
|
var created = CreateSelfSigned(options.ServerName);
|
||||||
File.WriteAllBytes(path, created.Export(X509ContentType.Pkcs12));
|
// The PKCS#12 export carries the private key without a password: only the server's account may read it.
|
||||||
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
DataFolderAccess.WritePrivateFile(path, created.Export(X509ContentType.Pkcs12));
|
||||||
logger.LogInformation("Generated self-signed TLS certificate, SHA-256 fingerprint {Fingerprint}", Fingerprint(created));
|
logger.LogInformation("Generated self-signed TLS certificate, SHA-256 fingerprint {Fingerprint}", Fingerprint(created));
|
||||||
return 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)
|
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.LogPath);
|
||||||
Directory.CreateDirectory(options.UploadsPath);
|
Directory.CreateDirectory(options.UploadsPath);
|
||||||
Directory.CreateDirectory(options.ArchivePath);
|
Directory.CreateDirectory(options.ArchivePath);
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
using System.ComponentModel;
|
using System.ComponentModel;
|
||||||
using System.Runtime.InteropServices;
|
using System.Runtime.InteropServices;
|
||||||
using System.Runtime.Versioning;
|
using System.Runtime.Versioning;
|
||||||
|
using System.Security.AccessControl;
|
||||||
|
using System.Security.Principal;
|
||||||
using Titano.Core.Localization;
|
using Titano.Core.Localization;
|
||||||
using static Titano.Server.Hosting.Windows.ServiceNative;
|
using static Titano.Server.Hosting.Windows.ServiceNative;
|
||||||
|
|
||||||
@@ -9,15 +11,30 @@ namespace Titano.Server.Hosting.Windows;
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// <c>--install-service</c> / <c>--uninstall-service</c>: registers the server with the Service Control Manager
|
/// <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.
|
/// (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>
|
/// </summary>
|
||||||
[SupportedOSPlatform("windows")]
|
[SupportedOSPlatform("windows")]
|
||||||
public static unsafe class ServiceInstaller
|
public static unsafe class ServiceInstaller
|
||||||
{
|
{
|
||||||
private const string DisplayName = "Titano Server";
|
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()
|
public static void Install()
|
||||||
{
|
{
|
||||||
|
if (UnsafeLocation() is { } problem) throw new InvalidOperationException(problem);
|
||||||
var manager = OpenSCManagerW(null, null, ScManagerConnect | ScManagerCreateService);
|
var manager = OpenSCManagerW(null, null, ScManagerConnect | ScManagerCreateService);
|
||||||
if (manager == 0) throw new Win32Exception(Marshal.GetLastPInvokeError());
|
if (manager == 0) throw new Win32Exception(Marshal.GetLastPInvokeError());
|
||||||
try
|
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>
|
/// <summary>The service's command line: this executable (or <c>dotnet</c> plus this assembly) with <c>--service</c>.</summary>
|
||||||
private static string CommandLine()
|
private static string CommandLine()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -50,8 +50,9 @@ static int ServiceAction(Action action, string done)
|
|||||||
Console.WriteLine(done);
|
Console.WriteLine(done);
|
||||||
return 0;
|
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);
|
Console.Error.WriteLine(ex.Message);
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,17 @@
|
|||||||
|
using System.Text;
|
||||||
using Titano.Core.Model;
|
using Titano.Core.Model;
|
||||||
using Titano.Data;
|
using Titano.Data;
|
||||||
using Titano.Server.Configuration;
|
using Titano.Server.Configuration;
|
||||||
|
using Titano.Server.Hosting;
|
||||||
|
|
||||||
namespace Titano.Server.Security;
|
namespace Titano.Server.Security;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// First-run administrator (BRIEF §14.9): when no admin account exists, one is created from
|
/// 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
|
/// <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),
|
/// 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.
|
/// 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>
|
/// </summary>
|
||||||
public static class AdminBootstrap
|
public static class AdminBootstrap
|
||||||
{
|
{
|
||||||
@@ -37,8 +40,7 @@ public static class AdminBootstrap
|
|||||||
{
|
{
|
||||||
password = TemporaryPassword.Generate();
|
password = TemporaryPassword.Generate();
|
||||||
passwordFile = Path.Combine(options.DataPath, PasswordFileName);
|
passwordFile = Path.Combine(options.DataPath, PasswordFileName);
|
||||||
await File.WriteAllTextAsync(passwordFile, password + Environment.NewLine, cancellationToken).ConfigureAwait(false);
|
DataFolderAccess.WritePrivateFile(passwordFile, Encoding.UTF8.GetBytes(password + Environment.NewLine));
|
||||||
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(passwordFile, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var admin = new User
|
var admin = new User
|
||||||
|
|||||||
@@ -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;
|
||||||
using Titano.Server.Hosting.Windows;
|
using Titano.Server.Hosting.Windows;
|
||||||
using Titano.Testing;
|
using Titano.Testing;
|
||||||
|
|
||||||
namespace Titano.Server.Tests.Hosting;
|
namespace Titano.Server.Tests.Hosting;
|
||||||
|
|
||||||
public sealed class WindowsServiceTests
|
public sealed class WindowsServiceTests(TestContext context)
|
||||||
{
|
{
|
||||||
[Test]
|
[Test]
|
||||||
public void CommandSwitchesAreParsedAndTheRestPassedOn()
|
public void CommandSwitchesAreParsedAndTheRestPassedOn()
|
||||||
@@ -39,6 +41,52 @@ public sealed class WindowsServiceTests
|
|||||||
Assert.Equal(1064u, new ServiceStatusTracker().Stopped(1064).ExitCode);
|
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]
|
[Test]
|
||||||
[WindowsOnly]
|
[WindowsOnly]
|
||||||
public void TheDispatcherDeclinesAConsoleProcess()
|
public void TheDispatcherDeclinesAConsoleProcess()
|
||||||
|
|||||||
Reference in new issue
Block a user