fix(server): refuse planted Windows data, guard new archives, trust only loopback proxies
- Windows data folder: the folder and everything in it must belong to SYSTEM, Administrators or the server's account and hold no link, checked before the ACL is rewritten; otherwise the server stops and names the entry. server.json is read only after its owner is checked on the open handle. Secrets are deleted and created anew with the private ACL, so a planted file's owner loses its rights. - Windows archive: a folder the server creates is changeable only by those accounts (users may read it) and a .titano folder it creates is private; an existing archive others can change is logged as a warning at start. - Proxy mode: only loopback is trusted by default, since LAN clients reach the HTTP port from private addresses; a cookie sign-in that did not come through a trusted proxy over HTTPS answers proxy_untrusted, naming TITANO_TRUSTED_PROXIES. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
11 files changed
+497
-64
No files matched your search
@@ -18,8 +18,18 @@ public static class AuthEndpoints
|
||||
api.MapGet("/auth/me", (Caller caller) => Results.Json(Dto.User(caller.User), ProtocolJson.Default.UserDto)).AllowDuringPasswordChange();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why the <c>Secure</c> session cookie cannot be set for this request, or null when it can (HTTPS, or the machine
|
||||
/// itself). In TLS mode proxy only a trusted proxy makes a request HTTPS, so the refusal names that setting.
|
||||
/// </summary>
|
||||
internal static string? CookieRefusal(HttpContext context, ServerOptions options)
|
||||
{
|
||||
if (SessionCookies.IsSecureTransport(context)) return null;
|
||||
return options.TlsMode == TlsMode.Proxy ? "proxy_untrusted" : "https_required";
|
||||
}
|
||||
|
||||
private static async Task<IResult> LoginAsync(HttpContext context, LoginRequest request, TitanoDatabase db, TokenService tokens, LoginGuard guard,
|
||||
AuditLog audit, TimeProvider time)
|
||||
AuditLog audit, TimeProvider time, ServerOptions options)
|
||||
{
|
||||
var ct = context.RequestAborted;
|
||||
if (!guard.TryAttempt(context.Connection.RemoteIpAddress?.ToString() ?? "unknown", out var wait)) return TooMany(context, "rate_limited", wait);
|
||||
@@ -27,7 +37,7 @@ public static class AuthEndpoints
|
||||
if (!Accounts.IsValidUsername(account) || string.IsNullOrEmpty(request.Password))
|
||||
return ApiErrors.Result(context, StatusCodes.Status401Unauthorized, "invalid_credentials");
|
||||
if (guard.IsLocked(account, out wait)) return TooMany(context, "account_locked", wait);
|
||||
if (request.Cookie && !SessionCookies.IsSecureTransport(context)) return ApiErrors.BadRequest(context, "https_required");
|
||||
if (request.Cookie && CookieRefusal(context, options) is { } refusal) return ApiErrors.BadRequest(context, refusal);
|
||||
|
||||
var user = await db.Users.GetByUsernameAsync(account, ct);
|
||||
bool valid;
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Net;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Titano.Data;
|
||||
using Titano.Server.Hosting;
|
||||
|
||||
namespace Titano.Server.Configuration;
|
||||
|
||||
@@ -59,10 +60,12 @@ public sealed class ServerOptions
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Reverse proxies whose <c>X-Forwarded-*</c> headers count in TLS mode proxy: loopback and the private networks a
|
||||
/// compose or Unraid proxy container connects from (RFC 1918, IPv6 unique local).
|
||||
/// Reverse proxies whose <c>X-Forwarded-*</c> headers count in TLS mode proxy when none are configured: loopback only.
|
||||
/// A home network's machines reach the HTTP port directly from private addresses (also through Docker's port
|
||||
/// publishing, which keeps the client's address), so trusting a private network would let them pick their own
|
||||
/// address again; a proxy in another container or on another machine is listed by its address or network.
|
||||
/// </summary>
|
||||
public const string DefaultTrustedProxies = "127.0.0.0/8, ::1/128, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7";
|
||||
public const string DefaultTrustedProxies = "127.0.0.0/8, ::1/128";
|
||||
|
||||
/// <summary>The environment variables the server reads (<c>--help</c> lists them all).</summary>
|
||||
public static IEnumerable<string> EnvironmentVariables => Variables.Select(v => v.Variable).Prepend("TITANO_DATA_PATH");
|
||||
@@ -170,7 +173,8 @@ public sealed class ServerOptions
|
||||
{
|
||||
try
|
||||
{
|
||||
options = JsonSerializer.Deserialize(File.ReadAllText(file), ServerOptionsJson.Default.ServerOptions) ?? options;
|
||||
// Its owner is checked first: a file another user planted would choose the archive, database and TLS key.
|
||||
options = JsonSerializer.Deserialize(DataFolderAccess.ReadTrustedText(file), ServerOptionsJson.Default.ServerOptions) ?? options;
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Runtime.Versioning;
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Principal;
|
||||
using Titano.Core.Archiving;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
@@ -8,15 +9,32 @@ 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 <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.
|
||||
/// SYSTEM, Administrators and the account the server runs as; everything inside inherits that. Those accounts must also
|
||||
/// own the folder and everything in it, and nothing in it may be a link: an owner can always change the ACL back, and
|
||||
/// whoever planted a file chose what it says. Elsewhere the container entrypoint owns <c>/data</c>, and secrets are
|
||||
/// written with mode 0600. An archive folder the server creates on Windows gets the same accounts (see
|
||||
/// <see cref="PrepareArchive"/>).
|
||||
/// </summary>
|
||||
public static class DataFolderAccess
|
||||
{
|
||||
private const UnixFileMode OwnerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite;
|
||||
private const int GenericAll = 0x10000000;
|
||||
private const int GenericWrite = 0x40000000;
|
||||
|
||||
/// <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>
|
||||
/// <summary>Rights that let an account replace or alter a file or folder (including the generic forms).</summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
private const FileSystemRights ChangeRights = FileSystemRights.WriteData | FileSystemRights.AppendData | FileSystemRights.WriteExtendedAttributes
|
||||
| FileSystemRights.DeleteSubdirectoriesAndFiles | FileSystemRights.Delete | FileSystemRights.ChangePermissions | FileSystemRights.TakeOwnership
|
||||
| (FileSystemRights)GenericWrite | (FileSystemRights)GenericAll;
|
||||
|
||||
/// <summary>
|
||||
/// Creates the folder if needed and, on Windows, refuses a folder that holds a link or an entry owned by anyone
|
||||
/// else, then replaces an ACL that grants anyone else access.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidOperationException">
|
||||
/// Something in the folder is a link or belongs to another account, or the ACL cannot be read or changed (the account
|
||||
/// is not an administrator).
|
||||
/// </exception>
|
||||
public static void Restrict(string folder)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
@@ -31,10 +49,22 @@ public static class DataFolderAccess
|
||||
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);
|
||||
$"Titano Server cannot check or restrict access to {folder}: {ex.Message} Run it once as an administrator; if someone else changed the folder's access, delete the folder.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a file the server acts on (<c>server.json</c>). On Windows its owner must be SYSTEM, Administrators or the
|
||||
/// server's account, checked on the handle that is read, so a file another user planted (or swapped in) is refused
|
||||
/// before any of its settings is used.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidOperationException">The file belongs to another account.</exception>
|
||||
public static string ReadTrustedText(string path)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return File.ReadAllText(path);
|
||||
return ReadTrustedText(path, AllowedAccounts());
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
@@ -49,12 +79,44 @@ public static class DataFolderAccess
|
||||
File.SetUnixFileMode(path, OwnerOnly);
|
||||
}
|
||||
|
||||
/// <summary>True when the ACL is protected and names no account besides SYSTEM, Administrators and this process's account.</summary>
|
||||
/// <summary>
|
||||
/// Creates the archive folder when it is missing, and says whether accounts other than SYSTEM, Administrators and the
|
||||
/// server's own can change it (always false off Windows, where the container entrypoint checks the archive). On
|
||||
/// Windows a folder created here gets a protected ACL: those accounts change it, other local users may only read it;
|
||||
/// a <c>.titano</c> folder (staging, trash) created here is private. Whoever can write where the server moves files
|
||||
/// can put a link in place of a folder and send the server's writes elsewhere; an existing archive is only reported,
|
||||
/// because its ACL is its owner's choice.
|
||||
/// </summary>
|
||||
public static bool PrepareArchive(string root)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
Directory.CreateDirectory(root);
|
||||
return false;
|
||||
}
|
||||
var folder = new DirectoryInfo(root);
|
||||
if (!folder.Exists)
|
||||
{
|
||||
if (folder.Parent is { } parent) parent.Create();
|
||||
folder.Create(ArchiveFolderSecurity());
|
||||
folder.Refresh();
|
||||
}
|
||||
// Created before the archive engine would create it with the archive's ACL; an existing one is left as it is.
|
||||
var meta = new DirectoryInfo(new ArchivePaths(root).MetaDirectory);
|
||||
if (!meta.Exists) meta.Create(PrivateFolderSecurity());
|
||||
return OthersCanChange(folder);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when the ACL is protected, its owner is SYSTEM, Administrators or this process's account, and it names no
|
||||
/// other account.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
public static bool IsPrivate(FileSystemSecurity security)
|
||||
{
|
||||
if (!security.AreAccessRulesProtected) return false;
|
||||
var allowed = AllowedAccounts();
|
||||
if (security.GetOwner(typeof(SecurityIdentifier)) is not SecurityIdentifier owner || !allowed.Contains(owner)) return false;
|
||||
foreach (FileSystemAccessRule rule in security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier)))
|
||||
{
|
||||
if (rule.AccessControlType == AccessControlType.Allow && !allowed.Contains((SecurityIdentifier)rule.IdentityReference)) return false;
|
||||
@@ -62,6 +124,73 @@ public static class DataFolderAccess
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The first problem with <paramref name="folder"/> or anything inside it, as a sentence for the operator, or null:
|
||||
/// a link (it would carry what the server reads, writes and secures elsewhere) or an owner outside
|
||||
/// <paramref name="owners"/> (who may have written the contents and can always change the ACL back). Links are
|
||||
/// reported, never followed.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
internal static string? FindUntrusted(DirectoryInfo folder, IReadOnlySet<SecurityIdentifier> owners)
|
||||
{
|
||||
var everything = new EnumerationOptions { AttributesToSkip = 0, IgnoreInaccessible = false };
|
||||
var pending = new Stack<DirectoryInfo>();
|
||||
pending.Push(folder);
|
||||
while (pending.TryPop(out var directory))
|
||||
{
|
||||
if (Untrusted(directory, owners) is { } problem) return problem;
|
||||
foreach (var entry in directory.EnumerateFileSystemInfos("*", everything))
|
||||
{
|
||||
if (entry is DirectoryInfo child && !IsLink(child)) pending.Push(child);
|
||||
else if (Untrusted(entry, owners) is { } entryProblem) return entryProblem;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="ReadTrustedText(string)"/>
|
||||
[SupportedOSPlatform("windows")]
|
||||
internal static string ReadTrustedText(string path, IReadOnlySet<SecurityIdentifier> owners)
|
||||
{
|
||||
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
|
||||
if (UntrustedOwner(path, stream.GetAccessControl(), owners) is { } problem) throw new InvalidOperationException(problem);
|
||||
using var reader = new StreamReader(stream);
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when the owner is outside <paramref name="trusted"/> or an allow entry gives change rights to such an
|
||||
/// account. 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>
|
||||
[SupportedOSPlatform("windows")]
|
||||
internal static bool IsChangeableByOthers(FileSystemSecurity security, IReadOnlySet<SecurityIdentifier> trusted, bool checkOwner)
|
||||
{
|
||||
if (checkOwner && (security.GetOwner(typeof(SecurityIdentifier)) is not SecurityIdentifier owner || !trusted.Contains(owner))) return true;
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>SYSTEM, Administrators and the account this process runs as (SYSTEM again for the Windows service).</summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
internal 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;
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static void RestrictOnWindows(DirectoryInfo folder)
|
||||
{
|
||||
@@ -71,18 +200,80 @@ public static class DataFolderAccess
|
||||
folder.Create(PrivateFolderSecurity());
|
||||
folder.Refresh();
|
||||
}
|
||||
// Before the ACL is touched: a folder another user created in advance, or a file planted in an older version's
|
||||
// folder, stays theirs whatever the ACL says, and a link would carry the new ACL elsewhere.
|
||||
if (FindUntrusted(folder, AllowedAccounts()) is { } problem) throw new InvalidOperationException(problem);
|
||||
// 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 string? Untrusted(FileSystemInfo entry, IReadOnlySet<SecurityIdentifier> owners)
|
||||
{
|
||||
if (IsLink(entry))
|
||||
{
|
||||
return $"{entry.FullName} is a link to {entry.LinkTarget}, and Titano Server follows no links in its data folder. "
|
||||
+ "Delete the link (TITANO_DATA_PATH moves the data folder) and start the server again.";
|
||||
}
|
||||
FileSystemSecurity security = entry is DirectoryInfo directory
|
||||
? directory.GetAccessControl(AccessControlSections.Owner)
|
||||
: ((FileInfo)entry).GetAccessControl(AccessControlSections.Owner);
|
||||
return UntrustedOwner(entry.FullName, security, owners);
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static string? UntrustedOwner(string path, FileSystemSecurity security, IReadOnlySet<SecurityIdentifier> owners)
|
||||
{
|
||||
var owner = security.GetOwner(typeof(SecurityIdentifier)) as SecurityIdentifier;
|
||||
if (owner is not null && owners.Contains(owner)) return null;
|
||||
return $"{path} belongs to {(owner is null ? "no account" : AccountName(owner))}, not to SYSTEM, Administrators or the account Titano Server "
|
||||
+ "runs as, so it cannot be trusted. Check it, then delete it or make Administrators its owner, and start the server again.";
|
||||
}
|
||||
|
||||
/// <summary>A symbolic link or junction (other reparse points, such as deduplicated files, are ordinary files).</summary>
|
||||
private static bool IsLink(FileSystemInfo entry) => (entry.Attributes & FileAttributes.ReparsePoint) != 0 && entry.LinkTarget is not null;
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static string AccountName(SecurityIdentifier account)
|
||||
{
|
||||
try
|
||||
{
|
||||
return account.Translate(typeof(NTAccount)).Value;
|
||||
}
|
||||
catch (IdentityNotMappedException)
|
||||
{
|
||||
return account.Value;
|
||||
}
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static bool OthersCanChange(DirectoryInfo folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
return IsChangeableByOthers(folder.GetAccessControl(), AllowedAccounts(), checkOwner: true);
|
||||
}
|
||||
catch (NotSupportedException)
|
||||
{
|
||||
// A volume without ACLs (FAT, exFAT): everyone can change everything.
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is UnauthorizedAccessException or IOException or InvalidOperationException)
|
||||
{
|
||||
// The ACL cannot be read (some network shares); the warning would be a guess.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
[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());
|
||||
// A file that already exists is replaced, never rewritten in place: it would keep its owner, who could change its
|
||||
// ACL back at any time, and a link would carry the secret elsewhere. The new file is owned by this account.
|
||||
file.Delete();
|
||||
using var stream = file.Create(FileMode.CreateNew, FileSystemRights.Write, FileShare.None, 4096, FileOptions.None, PrivateFileSecurity());
|
||||
stream.Write(contents);
|
||||
}
|
||||
|
||||
/// <summary>A protected DACL that gives the allowed accounts full control, passed on to everything inside.</summary>
|
||||
@@ -99,6 +290,16 @@ public static class DataFolderAccess
|
||||
return security;
|
||||
}
|
||||
|
||||
/// <summary>The private DACL, plus read access for every local user (photos and renders, never <c>.titano</c>).</summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static DirectorySecurity ArchiveFolderSecurity()
|
||||
{
|
||||
var security = PrivateFolderSecurity();
|
||||
security.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.ReadAndExecute,
|
||||
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
|
||||
return security;
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static FileSecurity PrivateFileSecurity()
|
||||
{
|
||||
@@ -108,18 +309,4 @@ public static class DataFolderAccess
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -43,7 +43,7 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<stri
|
||||
ports clients reach when the container's ports are published as other host ports
|
||||
(admin redirect to HTTPS, LAN beacon)
|
||||
TITANO_TRUSTED_PROXIES proxy mode: addresses or networks (CIDR) whose X-Forwarded-* headers count
|
||||
(default: loopback, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7)
|
||||
(default: loopback only; list a proxy in another container or on another machine)
|
||||
|
||||
Container image only: PUID, PGID (user and group the server runs as, owners of /data), TZ (local time zone)
|
||||
""";
|
||||
|
||||
@@ -33,7 +33,7 @@ public static class ServerHost
|
||||
DataFolderAccess.Restrict(options.DataPath);
|
||||
Directory.CreateDirectory(options.LogPath);
|
||||
Directory.CreateDirectory(options.UploadsPath);
|
||||
Directory.CreateDirectory(options.ArchivePath);
|
||||
var archiveOpenToOthers = DataFolderAccess.PrepareArchive(options.ArchivePath);
|
||||
|
||||
var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions { Args = args, ContentRootPath = AppContext.BaseDirectory });
|
||||
builder.Logging.ClearProviders();
|
||||
@@ -82,6 +82,12 @@ public static class ServerHost
|
||||
app.Logger.LogInformation("Titano Server {Version} · archive {Archive} · data {Data} · {Database} · TLS {Tls}{Fingerprint}",
|
||||
SystemEndpoints.Version, options.ArchivePath, options.DataPath, state.Database, options.TlsMode,
|
||||
state.TlsFingerprint is null ? string.Empty : " · SHA-256 " + state.TlsFingerprint);
|
||||
if (archiveOpenToOthers)
|
||||
{
|
||||
app.Logger.LogWarning("Accounts other than SYSTEM, Administrators and the one Titano Server runs as can change the archive {Archive}: "
|
||||
+ "they could put a link in place of a folder and redirect the files the server moves. Let only those accounts change it (others may read it).",
|
||||
options.ArchivePath);
|
||||
}
|
||||
app.Lifetime.ApplicationStopping.Register(() => app.Logger.LogInformation("Titano Server stopping"));
|
||||
app.Lifetime.ApplicationStopped.Register(() => database.DisposeAsync().AsTask().GetAwaiter().GetResult());
|
||||
return app;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
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;
|
||||
@@ -20,13 +19,6 @@ namespace Titano.Server.Hosting.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");
|
||||
@@ -128,10 +120,10 @@ public static unsafe class ServiceInstaller
|
||||
|
||||
private static string? FindChangeable(DirectoryInfo folder, bool recursive, HashSet<SecurityIdentifier> trusted)
|
||||
{
|
||||
if (IsChangeableByOthers(folder.GetAccessControl(), trusted)) return folder.FullName;
|
||||
if (DataFolderAccess.IsChangeableByOthers(folder.GetAccessControl(), trusted, checkOwner: false)) return folder.FullName;
|
||||
foreach (var file in folder.EnumerateFiles())
|
||||
{
|
||||
if (IsChangeableByOthers(file.GetAccessControl(), trusted)) return file.FullName;
|
||||
if (DataFolderAccess.IsChangeableByOthers(file.GetAccessControl(), trusted, checkOwner: false)) return file.FullName;
|
||||
}
|
||||
if (!recursive) return null;
|
||||
foreach (var child in folder.EnumerateDirectories())
|
||||
@@ -141,23 +133,6 @@ public static unsafe class ServiceInstaller
|
||||
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>
|
||||
|
||||
Reference in new issue
Block a user