Merge branch 'fix/server-hardening': Windows secrets, trusted proxies, Docker and Unraid fixes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
33 files changed
+1261
-49
No files matched your search
@@ -1,12 +1,12 @@
|
||||
// Dashboard (mockup Admin.html, BRIEF §14.8): storage, archive, jobs, render nodes, charts, activity, active jobs.
|
||||
import { t, plural, applyStrings, culture } from "../i18n.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, formatTime, formatDuration, bar, columns, toast, errorText, emptyState, redraw, fitColumns } from "../ui.js";
|
||||
import { escapeHtml, attr, formatBytes, formatNumber, formatTime, formatDuration, bar, columns, toast, errorText, emptyState, redraw, fitColumns, PROXY_WARNING } from "../ui.js";
|
||||
import { kindLabel, nodeLabel, progressCell, stateCell, stateLabel, encoders } from "../jobs.js";
|
||||
import { activityText } from "../audit.js";
|
||||
|
||||
const SCAN_BUTTON = `<button class="btn small" data-scan data-i18n="Admin.Archive.Scan" data-i18n-title="Admin.Archive.Scan.Tip"></button>`;
|
||||
|
||||
export async function render(root, { api, setMeta, onEvent }) {
|
||||
export async function render(root, { api, setMeta, actions, onEvent }) {
|
||||
let timer = null;
|
||||
const refresh = () => {
|
||||
clearTimeout(timer);
|
||||
@@ -28,6 +28,8 @@ export async function render(root, { api, setMeta, onEvent }) {
|
||||
const tls = `Admin.Settings.Tls.${d.tlsMode.charAt(0).toUpperCase()}${d.tlsMode.slice(1)}`;
|
||||
setMeta(t("Admin.Dashboard.Meta", formatDuration(d.uptimeSeconds), d.database, t(tls),
|
||||
t(d.discovery ? "Admin.Dashboard.DiscoveryOn" : "Admin.Dashboard.DiscoveryOff")));
|
||||
actions.innerHTML = d.proxyWarning ? PROXY_WARNING : "";
|
||||
applyStrings(actions);
|
||||
const a = d.archive;
|
||||
const used = a.capacityBytes > 0 ? (a.capacityBytes - a.freeBytes) / a.capacityBytes : 0;
|
||||
const online = d.nodes.filter((n) => n.state !== "offline");
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Settings (BRIEF §14.8): server name, ports, TLS, discovery, limits, language, retention. Values fixed by environment
|
||||
// variables are read-only here; ports, TLS, workers, chunk size and job history apply at the next restart.
|
||||
import { t, applyStrings, languages } from "../i18n.js";
|
||||
import { escapeHtml, attr, toast, errorText, nativeName, fingerprint, markInvalid, clearInvalid, invalidText, escapeReverts } from "../ui.js";
|
||||
import { escapeHtml, attr, toast, errorText, nativeName, fingerprint, markInvalid, clearInvalid, invalidText, escapeReverts, PROXY_WARNING } from "../ui.js";
|
||||
|
||||
/** Setting → environment variable that can fix it (BRIEF §14.9). */
|
||||
const VARIABLES = {
|
||||
@@ -46,7 +46,8 @@ export async function render(root, { api, info, setMeta, actions }) {
|
||||
${field("discovery", `<span class="inline"><input type="checkbox" name="discovery" ${settings.discovery ? "checked" : ""} ${lock("discovery")}></span>`)}
|
||||
</section>
|
||||
<section class="panel" aria-labelledby="network-title">
|
||||
<h2 id="network-title" data-i18n="Admin.Settings.Network"></h2>
|
||||
<div class="panel-head"><h2 id="network-title" data-i18n="Admin.Settings.Network"></h2>
|
||||
${settings.proxyWarning ? PROXY_WARNING : ""}</div>
|
||||
${number("httpPort", settings.httpPort, 'min="1" max="65535"')}
|
||||
${number("httpsPort", settings.httpsPort, 'min="1" max="65535"')}
|
||||
${field("tlsMode", `<select class="input" name="tlsMode" ${lock("tlsMode")}>${["auto", "pem", "proxy"].map((m) =>
|
||||
|
||||
@@ -97,6 +97,9 @@ export function fitColumns(table) {
|
||||
|
||||
window.addEventListener("resize", () => document.querySelectorAll(".table[data-levels]").forEach(fitColumns));
|
||||
|
||||
/** Chip of the Dashboard and Settings: TLS mode is proxy, but this page did not come through a trusted proxy over HTTPS (BRIEF §14.2). */
|
||||
export const PROXY_WARNING = `<span class="chip warn" data-i18n="Admin.Settings.ProxyBypassed" data-i18n-title="Admin.Settings.ProxyBypassed.Tip"></span>`;
|
||||
|
||||
/** An empty state: one sentence and one button (BRIEF §0.2). */
|
||||
export function emptyState(sentenceKey, button = "") {
|
||||
return `<div class="empty"><span data-i18n="${attr(sentenceKey)}"></span>${button}</div>`;
|
||||
|
||||
@@ -3,6 +3,7 @@ using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Configuration;
|
||||
using Titano.Server.Hosting;
|
||||
using Titano.Server.Jobs;
|
||||
using Titano.Server.Security;
|
||||
using Titano.Server.Storage;
|
||||
@@ -18,7 +19,8 @@ public static class AdminEndpoints
|
||||
public static void Map(RouteGroupBuilder api)
|
||||
{
|
||||
api.MapGet("/server/dashboard", DashboardAsync).Requires(Permissions.ManageArchive | Permissions.ManageUsers);
|
||||
api.MapGet("/server/settings", (ServerSettingsStore store) => Results.Json(store.Current(), ProtocolJson.Default.ServerSettingsDto))
|
||||
api.MapGet("/server/settings", (HttpContext context, ServerSettingsStore store, ServerOptions options) =>
|
||||
Results.Json(store.Current() with { ProxyWarning = AdminPanel.BypassesProxy(context, options) }, ProtocolJson.Default.ServerSettingsDto))
|
||||
.Requires(Permissions.ManageArchive);
|
||||
api.MapPut("/server/settings", SaveSettingsAsync).Requires(Permissions.ManageArchive);
|
||||
api.MapGet("/audit", AuditAsync).Requires(Permissions.ManageUsers | Permissions.ManageArchive);
|
||||
@@ -65,11 +67,13 @@ public static class AdminEndpoints
|
||||
[.. nodes.Select(n => Dto.Node(n, names.GetValueOrDefault(n.UserId, string.Empty)))],
|
||||
[.. uploads.Select(u => new UploadDayDto(u.Day, u.Count, u.Bytes))],
|
||||
[.. activity.Items.Select(Dto.Audit)],
|
||||
[.. running.Items.Concat(queued.Items.OrderByDescending(j => j.Priority).ThenBy(j => j.Created)).Take(10).Select(Dto.Job)]),
|
||||
[.. running.Items.Concat(queued.Items.OrderByDescending(j => j.Priority).ThenBy(j => j.Created)).Take(10).Select(Dto.Job)],
|
||||
AdminPanel.BypassesProxy(context, options)),
|
||||
ProtocolJson.Default.DashboardDto);
|
||||
}
|
||||
|
||||
private static async Task<IResult> SaveSettingsAsync(HttpContext context, Caller caller, ServerSettingsDto request, ServerSettingsStore store, AuditLog audit)
|
||||
private static async Task<IResult> SaveSettingsAsync(HttpContext context, Caller caller, ServerSettingsDto request, ServerSettingsStore store, ServerOptions options,
|
||||
AuditLog audit)
|
||||
{
|
||||
switch (store.Save(request))
|
||||
{
|
||||
@@ -79,7 +83,7 @@ public static class AdminEndpoints
|
||||
return ApiErrors.BadRequest(context, code, setting, setting);
|
||||
}
|
||||
await audit.WriteAsync(caller, context, "server_settings", "server", null, request.ServerName);
|
||||
return Results.Json(store.Current(), ProtocolJson.Default.ServerSettingsDto);
|
||||
return Results.Json(store.Current() with { ProxyWarning = AdminPanel.BypassesProxy(context, options) }, ProtocolJson.Default.ServerSettingsDto);
|
||||
}
|
||||
|
||||
/// <summary>The audit log, newest first; <c>action</c> may list several actions separated by commas (<c>login,login_failed</c>).</summary>
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Titano.Data;
|
||||
using Titano.Server.Hosting;
|
||||
|
||||
namespace Titano.Server.Configuration;
|
||||
|
||||
@@ -45,15 +47,29 @@ public sealed class ServerOptions
|
||||
("TITANO_DB_SSLMODE", nameof(DbSslMode), (o, v) => o.DbSslMode = v),
|
||||
("TITANO_HTTP_PORT", nameof(HttpPort), (o, v) => o.HttpPort = Int("TITANO_HTTP_PORT", v)),
|
||||
("TITANO_HTTPS_PORT", nameof(HttpsPort), (o, v) => o.HttpsPort = Int("TITANO_HTTPS_PORT", v)),
|
||||
("TITANO_PUBLIC_HTTP_PORT", nameof(PublicHttpPort), (o, v) => o.PublicHttpPort = Int("TITANO_PUBLIC_HTTP_PORT", v)),
|
||||
("TITANO_PUBLIC_HTTPS_PORT", nameof(PublicHttpsPort), (o, v) => o.PublicHttpsPort = Int("TITANO_PUBLIC_HTTPS_PORT", v)),
|
||||
("TITANO_TLS_MODE", nameof(TlsMode), (o, v) => o.TlsMode = Enum.Parse<TlsMode>(v, ignoreCase: true)),
|
||||
("TITANO_TLS_CERT", nameof(TlsCert), (o, v) => o.TlsCert = v),
|
||||
("TITANO_TLS_KEY", nameof(TlsKey), (o, v) => o.TlsKey = v),
|
||||
("TITANO_TRUSTED_PROXIES", nameof(TrustedProxies), (o, v) => o.TrustedProxies = v),
|
||||
("TITANO_LANG", nameof(Language), (o, v) => o.Language = v),
|
||||
("TITANO_WORKERS", nameof(Workers), (o, v) => o.Workers = Math.Max(1, Int("TITANO_WORKERS", v))),
|
||||
("TITANO_DISCOVERY", nameof(Discovery), (o, v) => o.Discovery = bool.Parse(v)),
|
||||
("TITANO_LOG_LEVEL", nameof(LogLevel), (o, v) => o.LogLevel = Enum.Parse<LogLevel>(v, ignoreCase: true)),
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// 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";
|
||||
|
||||
/// <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");
|
||||
|
||||
public string ServerName { get; set; } = "Titano Server";
|
||||
public string ArchivePath { get; set; } = OperatingSystem.IsWindows() ? @"C:\TitanoArchive" : "/archive";
|
||||
public string DataPath { get; set; } = OperatingSystem.IsWindows() ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Titano Server") : "/data";
|
||||
@@ -72,9 +88,26 @@ public sealed class ServerOptions
|
||||
public string DbSslMode { get; set; } = "prefer";
|
||||
public int HttpPort { get; set; } = 8080;
|
||||
public int HttpsPort { get; set; } = 8443;
|
||||
|
||||
/// <summary>
|
||||
/// Port clients reach the HTTP listener on, when it differs from <see cref="HttpPort"/> (a container port published
|
||||
/// as another host port); advertised by LAN discovery. Null: <see cref="HttpPort"/>.
|
||||
/// </summary>
|
||||
public int? PublicHttpPort { get; set; }
|
||||
|
||||
/// <summary>Port clients reach the HTTPS listener on (admin redirect, LAN discovery). Null: <see cref="HttpsPort"/>.</summary>
|
||||
public int? PublicHttpsPort { get; set; }
|
||||
|
||||
public TlsMode TlsMode { get; set; } = TlsMode.Auto;
|
||||
public string? TlsCert { get; set; }
|
||||
public string? TlsKey { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Addresses or networks (CIDR), separated by commas or spaces, of the reverse proxies trusted in TLS mode proxy.
|
||||
/// Forwarded headers from any other peer are ignored, so a client that reaches the HTTP port directly cannot choose
|
||||
/// the address the sign-in rate limit and the audit log see.
|
||||
/// </summary>
|
||||
public string TrustedProxies { get; set; } = DefaultTrustedProxies;
|
||||
public string Language { get; set; } = "en";
|
||||
public int Workers { get; set; } = Math.Max(1, Environment.ProcessorCount / 2);
|
||||
public bool Discovery { get; set; } = true;
|
||||
@@ -140,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)
|
||||
{
|
||||
@@ -192,12 +226,38 @@ public sealed class ServerOptions
|
||||
// Port 0 asks the OS for a free port (used by the in-process test host).
|
||||
if (HttpPort is < 0 or > 65535 || HttpsPort is < 0 or > 65535)
|
||||
throw new InvalidOperationException("Ports must be between 0 and 65535.");
|
||||
if (PublicHttpPort is < 1 or > 65535 || PublicHttpsPort is < 1 or > 65535)
|
||||
throw new InvalidOperationException("TITANO_PUBLIC_HTTP_PORT and TITANO_PUBLIC_HTTPS_PORT must be between 1 and 65535.");
|
||||
try
|
||||
{
|
||||
TrustedProxyNetworks();
|
||||
}
|
||||
catch (FormatException ex)
|
||||
{
|
||||
throw new InvalidOperationException($"TITANO_TRUSTED_PROXIES must list IP addresses or networks such as 172.16.0.0/12: {ex.Message}", ex);
|
||||
}
|
||||
if (ChunkSizeBytes is < 64 * 1024 or > 64 * 1024 * 1024)
|
||||
throw new InvalidOperationException("The chunk size must be between 64 KiB and 64 MiB.");
|
||||
if (MaxUploadBytes < 1 || TokenLifetimeDays < 1 || JobHistoryDays < 1 || UploadRetentionHours < 1)
|
||||
throw new InvalidOperationException("Upload size, token lifetime, job history and upload retention must be positive.");
|
||||
}
|
||||
|
||||
/// <summary>The parsed <see cref="TrustedProxies"/>; a single address is a network of one.</summary>
|
||||
/// <exception cref="FormatException">An entry is neither an IP address nor a network in CIDR notation.</exception>
|
||||
public IReadOnlyList<IPNetwork> TrustedProxyNetworks()
|
||||
{
|
||||
var networks = new List<IPNetwork>();
|
||||
foreach (var entry in TrustedProxies.Split([',', ';', ' ', '\t'], StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (IPNetwork.TryParse(entry, out var network)) networks.Add(network);
|
||||
else if (!entry.Contains('/', StringComparison.Ordinal) && IPAddress.TryParse(entry, out var address)
|
||||
&& (address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6 || address.ScopeId == 0))
|
||||
networks.Add(new IPNetwork(address, address.GetAddressBytes().Length * 8));
|
||||
else throw new FormatException($"'{entry}' is neither an address nor a network.");
|
||||
}
|
||||
return networks;
|
||||
}
|
||||
|
||||
/// <summary>TITANO_DB is <c>postgres</c>, <c>sqlite</c> or a complete connection string (<c>Host=…</c> / <c>Data Source=…</c>).</summary>
|
||||
private void ApplyDatabase(string value)
|
||||
{
|
||||
|
||||
@@ -47,14 +47,14 @@ public sealed class ServerSettingsStore(ServerOptions options)
|
||||
|| !string.Equals(request.TlsMode, options.TlsMode.ToString(), StringComparison.OrdinalIgnoreCase)
|
||||
|| request.TlsCert != options.TlsCert || request.TlsKey != options.TlsKey || request.Workers != options.Workers
|
||||
|| request.ChunkSizeBytes != options.ChunkSizeBytes || request.JobHistoryDays != options.JobHistoryDays;
|
||||
_saved = request with { ServerName = request.ServerName.Trim(), Locked = [.. options.Locked], RestartRequired = restart };
|
||||
_saved = request with { ServerName = request.ServerName.Trim(), Locked = [.. options.Locked], RestartRequired = restart, ProxyWarning = false };
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static ServerSettingsDto Snapshot(ServerOptions o, bool restartRequired) => new(
|
||||
o.ServerName, o.HttpPort, o.HttpsPort, o.TlsMode.ToString().ToLowerInvariant(), o.TlsCert, o.TlsKey, o.Language, o.Workers, o.Discovery,
|
||||
o.MaxUploadBytes, o.ChunkSizeBytes, o.JobHistoryDays, o.TokenLifetimeDays, o.UploadRetentionHours, [.. o.Locked], restartRequired);
|
||||
o.MaxUploadBytes, o.ChunkSizeBytes, o.JobHistoryDays, o.TokenLifetimeDays, o.UploadRetentionHours, [.. o.Locked], restartRequired, ProxyWarning: false);
|
||||
|
||||
private static string? Validate(ServerSettingsDto r)
|
||||
{
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using Microsoft.AspNetCore.Hosting.Server;
|
||||
using Microsoft.AspNetCore.Hosting.Server.Features;
|
||||
@@ -7,7 +8,9 @@ namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// Serves the embedded admin panel at <c>/admin</c>. Requests over plain HTTP from another machine are redirected to
|
||||
/// the HTTPS listener, because the session cookie is <c>Secure</c> (BRIEF §14.2) and would not survive plain HTTP.
|
||||
/// the HTTPS listener, on the port clients reach it on (<see cref="ServerOptions.PublicHttpsPort"/> when a container
|
||||
/// port is published as another host port), because the session cookie is <c>Secure</c> (BRIEF §14.2) and would not
|
||||
/// survive plain HTTP.
|
||||
/// </summary>
|
||||
public static class AdminPanel
|
||||
{
|
||||
@@ -33,14 +36,22 @@ public static class AdminPanel
|
||||
});
|
||||
}
|
||||
|
||||
private static string? HttpsLocation(HttpContext context, ServerOptions options, IServer server)
|
||||
/// <summary>
|
||||
/// True when TLS mode is proxy but this request did not reach the server through a trusted proxy over HTTPS (BRIEF
|
||||
/// §14.2: the admin warns). The server has no HTTPS listener in that mode, so a request is HTTPS only when a proxy
|
||||
/// listed in <see cref="ServerOptions.TrustedProxies"/> forwarded it as such.
|
||||
/// </summary>
|
||||
public static bool BypassesProxy(HttpContext context, ServerOptions options) =>
|
||||
options.TlsMode == TlsMode.Proxy && !context.Request.IsHttps;
|
||||
|
||||
internal static string? HttpsLocation(HttpContext context, ServerOptions options, IServer server)
|
||||
{
|
||||
if (context.Request.IsHttps || options.TlsMode == TlsMode.Proxy) return null;
|
||||
if (context.Connection.RemoteIpAddress is { } remote && IPAddress.IsLoopback(remote)) return null;
|
||||
foreach (var address in server.Features.Get<IServerAddressesFeature>()?.Addresses ?? [])
|
||||
{
|
||||
if (!address.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
var port = address[(address.LastIndexOf(':') + 1)..].TrimEnd('/');
|
||||
var port = options.PublicHttpsPort?.ToString(CultureInfo.InvariantCulture) ?? address[(address.LastIndexOf(':') + 1)..].TrimEnd('/');
|
||||
return $"https://{context.Request.Host.Host}:{port}{context.Request.PathBase}{context.Request.Path}{context.Request.QueryString}";
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -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,312 @@
|
||||
using System.Runtime.Versioning;
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Principal;
|
||||
using Titano.Core.Archiving;
|
||||
|
||||
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. 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>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())
|
||||
{
|
||||
Directory.CreateDirectory(folder);
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
RestrictOnWindows(new DirectoryInfo(folder));
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"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)
|
||||
{
|
||||
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>
|
||||
/// 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;
|
||||
}
|
||||
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)
|
||||
{
|
||||
if (!folder.Exists)
|
||||
{
|
||||
if (folder.Parent is { } parent) parent.Create();
|
||||
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)
|
||||
{
|
||||
// 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>
|
||||
[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;
|
||||
}
|
||||
|
||||
/// <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()
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,8 @@ namespace Titano.Server.Hosting;
|
||||
/// <summary>
|
||||
/// LAN discovery (BRIEF §14.9, <c>TITANO_DISCOVERY</c>): every few seconds a <see cref="DiscoveryBeacon"/> is broadcast on
|
||||
/// UDP port <see cref="DiscoveryBeacon.Port"/> of every IPv4 network, so clients can offer this server on first run.
|
||||
/// Switching discovery off in the settings stops it without a restart.
|
||||
/// Switching discovery off in the settings stops it without a restart. In a container the broadcasts reach the LAN
|
||||
/// only with host networking; on a bridge network they stay on the bridge.
|
||||
/// </summary>
|
||||
public sealed class DiscoveryBeaconService(ServerOptions options, ServerState state, IServer server, ILogger<DiscoveryBeaconService> logger) : BackgroundService
|
||||
{
|
||||
@@ -51,12 +52,15 @@ public sealed class DiscoveryBeaconService(ServerOptions options, ServerState st
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The beacon for the ports Kestrel actually listens on (HTTPS 0 when TLS is terminated elsewhere).</summary>
|
||||
/// <summary>
|
||||
/// The beacon for the ports clients reach: the public ports when set, else the ports Kestrel actually listens on
|
||||
/// (HTTPS 0 when TLS is terminated elsewhere).
|
||||
/// </summary>
|
||||
public DiscoveryBeacon CreateBeacon() => new(
|
||||
options.ServerName,
|
||||
SystemEndpoints.Version,
|
||||
BoundPort(Uri.UriSchemeHttp) ?? options.HttpPort,
|
||||
state.TlsFingerprint is null ? 0 : BoundPort(Uri.UriSchemeHttps) ?? options.HttpsPort,
|
||||
options.PublicHttpPort ?? BoundPort(Uri.UriSchemeHttp) ?? options.HttpPort,
|
||||
state.TlsFingerprint is null ? 0 : options.PublicHttpsPort ?? BoundPort(Uri.UriSchemeHttps) ?? options.HttpsPort,
|
||||
state.TlsFingerprint);
|
||||
|
||||
public async Task SendOnceAsync(UdpClient udp, IEnumerable<IPEndPoint> targets, CancellationToken cancellationToken)
|
||||
|
||||
@@ -36,7 +36,16 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<stri
|
||||
TITANO_ARCHIVE_PATH TITANO_DATA_PATH TITANO_SERVER_NAME TITANO_ADMIN_USER TITANO_ADMIN_PASSWORD
|
||||
TITANO_DB (postgres | sqlite | connection string) TITANO_DB_HOST TITANO_DB_PORT TITANO_DB_NAME TITANO_DB_USER
|
||||
TITANO_DB_PASSWORD TITANO_DB_SSLMODE TITANO_HTTP_PORT TITANO_HTTPS_PORT TITANO_TLS_MODE (auto | pem | proxy)
|
||||
TITANO_TLS_CERT TITANO_TLS_KEY TITANO_LANG TITANO_WORKERS TITANO_DISCOVERY
|
||||
TITANO_TLS_CERT TITANO_TLS_KEY TITANO_LANG TITANO_WORKERS
|
||||
TITANO_LOG_LEVEL (Trace | Debug | Information | Warning | Error)
|
||||
TITANO_DISCOVERY LAN beacon (true | false); in a container it needs host networking
|
||||
TITANO_PUBLIC_HTTP_PORT, TITANO_PUBLIC_HTTPS_PORT
|
||||
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 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)
|
||||
""";
|
||||
|
||||
public static ServerCommandLine Parse(IReadOnlyList<string> args)
|
||||
|
||||
@@ -29,10 +29,11 @@ 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);
|
||||
var archiveOpenToOthers = DataFolderAccess.PrepareArchive(options.ArchivePath);
|
||||
|
||||
var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions { Args = args, ContentRootPath = AppContext.BaseDirectory });
|
||||
builder.Logging.ClearProviders();
|
||||
@@ -81,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;
|
||||
@@ -105,11 +112,15 @@ public static class ServerHost
|
||||
services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(30));
|
||||
if (options.TlsMode == TlsMode.Proxy)
|
||||
{
|
||||
// Only the configured proxies may say who the client is: a client that reaches the HTTP port directly would
|
||||
// otherwise pick its own address for the sign-in rate limit and the audit log, and claim HTTPS.
|
||||
var trusted = options.TrustedProxyNetworks();
|
||||
services.Configure<ForwardedHeadersOptions>(f =>
|
||||
{
|
||||
f.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
|
||||
f.KnownIPNetworks.Clear();
|
||||
f.KnownProxies.Clear();
|
||||
foreach (var network in trusted) f.KnownIPNetworks.Add(network);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Versioning;
|
||||
using System.Security.Principal;
|
||||
using Titano.Core.Localization;
|
||||
using static Titano.Server.Hosting.Windows.ServiceNative;
|
||||
|
||||
@@ -9,15 +10,23 @@ 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";
|
||||
|
||||
/// <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 +80,73 @@ 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 (DataFolderAccess.IsChangeableByOthers(folder.GetAccessControl(), trusted, checkOwner: false)) return folder.FullName;
|
||||
foreach (var file in folder.EnumerateFiles())
|
||||
{
|
||||
if (DataFolderAccess.IsChangeableByOthers(file.GetAccessControl(), trusted, checkOwner: false)) 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;
|
||||
}
|
||||
|
||||
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