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
@@ -0,0 +1,284 @@
|
||||
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, with owners the
|
||||
/// server trusts and no links. On Windows a new archive folder lets other users only read it.
|
||||
/// </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()));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void ASecretAnotherAccountOwnedIsReplacedByOneTheServerOwns()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var folder = context.CreateTempDirectory("planted");
|
||||
var own = OwnerOf(NewFile(Path.Combine(folder, "probe.txt")));
|
||||
// Planted before the first start: whoever owns it keeps the right to change its ACL, whatever the server sets.
|
||||
var secret = NewFile(Path.Combine(folder, "initial-admin-password.txt"));
|
||||
if (!TrySetOwner(secret, OtherOwner(own))) Assert.Inconclusive("giving a file to another owner needs an elevated administrator");
|
||||
GrantUsersRead(secret);
|
||||
|
||||
DataFolderAccess.WritePrivateFile(secret.FullName, [1, 2, 3]);
|
||||
secret.Refresh();
|
||||
Assert.Equal(own, OwnerOf(secret));
|
||||
Assert.True(DataFolderAccess.IsPrivate(secret.GetAccessControl()));
|
||||
Assert.False(NamesUsers(secret.GetAccessControl()));
|
||||
Assert.BytesEqual([1, 2, 3], File.ReadAllBytes(secret.FullName));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AnythingAnotherAccountOwnsIsFound()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var folder = new DirectoryInfo(context.CreateTempDirectory("squatted"));
|
||||
var key = NewFile(Path.Combine(folder.CreateSubdirectory("tls").FullName, "server.pfx"));
|
||||
var own = OwnerOf(key);
|
||||
Assert.Null(DataFolderAccess.FindUntrusted(folder, new HashSet<SecurityIdentifier> { own }));
|
||||
// A folder someone else created before the first start is reported before anything inside it.
|
||||
Assert.Contains(folder.FullName, Assert.NotNull(DataFolderAccess.FindUntrusted(folder, new HashSet<SecurityIdentifier> { LocalSystem })));
|
||||
|
||||
if (!TrySetOwner(key, OtherOwner(own))) Assert.Inconclusive("giving a file to another owner needs an elevated administrator");
|
||||
Assert.Contains(key.FullName, Assert.NotNull(DataFolderAccess.FindUntrusted(folder, new HashSet<SecurityIdentifier> { own })));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void ALinkInTheDataFolderStopsTheServerBeforeTheAclChanges()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var folder = new DirectoryInfo(context.CreateTempDirectory("linked"));
|
||||
var link = Path.Combine(folder.FullName, "logs");
|
||||
try
|
||||
{
|
||||
Directory.CreateSymbolicLink(link, context.CreateTempDirectory("elsewhere"));
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Assert.Inconclusive("creating a symbolic link needs an elevated administrator or developer mode");
|
||||
}
|
||||
|
||||
var refused = Assert.Throws<InvalidOperationException>(() => DataFolderAccess.Restrict(folder.FullName));
|
||||
Assert.Contains(link, refused.Message);
|
||||
// The ACL change would have followed the link; it never started.
|
||||
Assert.False(folder.GetAccessControl().AreAccessRulesProtected);
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void SettingsAnotherAccountOwnsAreNotRead()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var settings = NewFile(Path.Combine(context.CreateTempDirectory("settings"), "server.json"), """{ "ArchivePath": "D:\\Elsewhere" }""");
|
||||
Assert.Contains("Elsewhere", DataFolderAccess.ReadTrustedText(settings.FullName));
|
||||
// As if another account had planted it: the owner is not among those the server trusts.
|
||||
InvalidOperationException? refused = null;
|
||||
try
|
||||
{
|
||||
DataFolderAccess.ReadTrustedText(settings.FullName, new HashSet<SecurityIdentifier> { LocalSystem });
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
refused = ex;
|
||||
}
|
||||
Assert.Contains(settings.FullName, Assert.NotNull(refused).Message);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AMissingArchiveFolderIsCreated()
|
||||
{
|
||||
var root = Path.Combine(context.CreateTempDirectory("archive"), "TitanoArchive");
|
||||
Assert.False(DataFolderAccess.PrepareArchive(root));
|
||||
Assert.True(Directory.Exists(root));
|
||||
// An existing folder is left as it is.
|
||||
Assert.False(DataFolderAccess.PrepareArchive(root));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void ANewArchiveIsReadableByUsersButOnlyTheServerChangesIt()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
// Under C:\ a new folder would inherit "Authenticated Users: modify" and every local user could plant links
|
||||
// where the service moves uploads.
|
||||
var root = new DirectoryInfo(Path.Combine(context.CreateTempDirectory("archive"), "TitanoArchive"));
|
||||
Assert.False(DataFolderAccess.PrepareArchive(root.FullName));
|
||||
var security = root.GetAccessControl();
|
||||
Assert.True(security.AreAccessRulesProtected);
|
||||
Assert.Equal(FileSystemRights.ReadAndExecute, RightsOf(security, Users) & FileSystemRights.ReadAndExecute);
|
||||
Assert.Equal((FileSystemRights)0, RightsOf(security, Users) & (FileSystemRights.Write | FileSystemRights.Delete | FileSystemRights.ChangePermissions));
|
||||
|
||||
// Staging and trash are the server's alone.
|
||||
var meta = new DirectoryInfo(Path.Combine(root.FullName, ".titano"));
|
||||
Assert.True(DataFolderAccess.IsPrivate(meta.GetAccessControl()));
|
||||
Assert.False(NamesUsers(meta.CreateSubdirectory("staging").GetAccessControl()));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AnArchiveOtherUsersCanChangeIsReportedButLeftAsItIs()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var root = new DirectoryInfo(context.CreateTempDirectory("shared"));
|
||||
DataFolderAccess.PrepareArchive(root.FullName);
|
||||
var open = root.GetAccessControl();
|
||||
open.AddAccessRule(new FileSystemAccessRule(Users, FileSystemRights.Modify,
|
||||
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
|
||||
root.SetAccessControl(open);
|
||||
|
||||
Assert.True(DataFolderAccess.PrepareArchive(root.FullName));
|
||||
Assert.Equal(FileSystemRights.Modify, RightsOf(root.GetAccessControl(), Users) & FileSystemRights.Modify);
|
||||
// The .titano folder the server added at the first start stays its own.
|
||||
Assert.True(DataFolderAccess.IsPrivate(new DirectoryInfo(Path.Combine(root.FullName, ".titano")).GetAccessControl()));
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static SecurityIdentifier Users => new(WellKnownSidType.BuiltinUsersSid, null);
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static SecurityIdentifier LocalSystem => new(WellKnownSidType.LocalSystemSid, null);
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static SecurityIdentifier Administrators => new(WellKnownSidType.BuiltinAdministratorsSid, null);
|
||||
|
||||
private static FileInfo NewFile(string path, string contents = "x")
|
||||
{
|
||||
File.WriteAllText(path, contents);
|
||||
return new FileInfo(path);
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static SecurityIdentifier OwnerOf(FileInfo file) => (SecurityIdentifier)file.GetAccessControl().GetOwner(typeof(SecurityIdentifier))!;
|
||||
|
||||
/// <summary>An owner this process may give a file that its new files do not get: its own account or Administrators.</summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static SecurityIdentifier OtherOwner(SecurityIdentifier own)
|
||||
{
|
||||
using var identity = WindowsIdentity.GetCurrent();
|
||||
return own == Administrators ? identity.User! : Administrators;
|
||||
}
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static bool TrySetOwner(FileInfo file, SecurityIdentifier owner)
|
||||
{
|
||||
var security = new FileSecurity();
|
||||
security.SetOwner(owner);
|
||||
try
|
||||
{
|
||||
file.SetAccessControl(security);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidOperationException or UnauthorizedAccessException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The rights allow entries give <paramref name="account"/>.</summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
private static FileSystemRights RightsOf(FileSystemSecurity security, SecurityIdentifier account)
|
||||
{
|
||||
FileSystemRights rights = 0;
|
||||
foreach (FileSystemAccessRule rule in security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier)))
|
||||
{
|
||||
if (rule.AccessControlType == AccessControlType.Allow && rule.IdentityReference.Equals(account)) rights |= rule.FileSystemRights;
|
||||
}
|
||||
return rights;
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,19 @@ public sealed class DiscoveryTests(TestContext context)
|
||||
Assert.Equal((await info.ReadAsync(ProtocolJson.Default.ServerInfo)).TlsFingerprint, beacon.TlsFingerprint);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheBeaconAdvertisesThePortsClientsReach()
|
||||
{
|
||||
// Container ports published as other host ports: a client on the LAN must use the host's.
|
||||
await using var server = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.PublicHttpPort = 18080;
|
||||
o.PublicHttpsPort = 18443;
|
||||
});
|
||||
var beacon = server.Services.GetRequiredService<DiscoveryBeaconService>().CreateBeacon();
|
||||
Assert.Equal((18080, 18443), (beacon.HttpPort, beacon.HttpsPort));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ForeignDatagramsAreIgnored()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Api;
|
||||
using Titano.Server.Configuration;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Server.Tests.Hosting;
|
||||
|
||||
/// <summary>TLS mode proxy (BRIEF §14.2): forwarded headers count only from trusted proxies, and the admin warns otherwise.</summary>
|
||||
[Category("server")]
|
||||
public sealed class ProxyModeTests(TestContext context)
|
||||
{
|
||||
/// <summary>A documentation network (RFC 5737) the test client never connects from.</summary>
|
||||
private const string ElsewhereOnly = "192.0.2.0/24";
|
||||
|
||||
[Test]
|
||||
public async Task AClientOutsideTheTrustedProxiesCannotChooseItsAddress()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.TlsMode = TlsMode.Proxy;
|
||||
o.TrustedProxies = ElsewhereOnly;
|
||||
o.LoginAttemptsPerMinute = 5;
|
||||
});
|
||||
for (var i = 0; i < 5; i++)
|
||||
{
|
||||
using var failed = await LoginAsync(server, "user" + i, $"203.0.113.{i + 1}");
|
||||
await failed.ExpectErrorAsync(HttpStatusCode.Unauthorized, "invalid_credentials");
|
||||
}
|
||||
// A new X-Forwarded-For per attempt does not buy a new budget: the limit stays on the real address.
|
||||
using var limited = await LoginAsync(server, "admin", "203.0.113.99");
|
||||
await limited.ExpectErrorAsync(HttpStatusCode.TooManyRequests, "rate_limited");
|
||||
|
||||
var audit = await server.Database.Audit.ListAsync(null, "login_failed", 50, null, context.Cancellation);
|
||||
Assert.Count(5, audit.Items);
|
||||
Assert.True(audit.Items.All(e => IsLoopback(e.RemoteAddress)), string.Join(", ", audit.Items.Select(e => e.RemoteAddress)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ATrustedProxyReportsTheClientAddress()
|
||||
{
|
||||
// The default trusts loopback, where a proxy on the same machine (and this test) connects from.
|
||||
await using var server = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.TlsMode = TlsMode.Proxy;
|
||||
o.LoginAttemptsPerMinute = 5;
|
||||
});
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
using var failed = await LoginAsync(server, "user" + i, $"203.0.113.{i + 1}");
|
||||
await failed.ExpectErrorAsync(HttpStatusCode.Unauthorized, "invalid_credentials");
|
||||
}
|
||||
var audit = await server.Database.Audit.ListAsync(null, "login_failed", 50, null, context.Cancellation);
|
||||
Assert.Contains("203.0.113.8", audit.Items.Select(e => e.RemoteAddress));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ByDefaultAMachineOfTheHomeNetworkIsNoProxy()
|
||||
{
|
||||
// The machines of a home network reach the HTTP port directly from private addresses, also through Docker's
|
||||
// port publishing (which keeps the client's address): none of them may choose its own address.
|
||||
await using var server = await TestServer.StartAsync(context, o => o.TlsMode = TlsMode.Proxy);
|
||||
foreach (var peer in new[] { "192.168.1.50", "10.0.0.7", "172.17.0.1", "fd00::7" })
|
||||
Assert.Equal((peer, false), await ForwardAsync(server, peer));
|
||||
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "127.0.0.1"));
|
||||
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "::ffff:127.0.0.1"));
|
||||
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "::1"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AProxyNetworkCountsOnceListed()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.TlsMode = TlsMode.Proxy;
|
||||
o.TrustedProxies = "172.18.0.0/16";
|
||||
});
|
||||
Assert.Equal(("203.0.113.7", true), await ForwardAsync(server, "172.18.0.5"));
|
||||
Assert.Equal(("192.168.1.50", false), await ForwardAsync(server, "192.168.1.50"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AnAdminSignInThroughAnUntrustedProxyNamesTheSetting()
|
||||
{
|
||||
// The warning chip needs a session first: the sign-in refusal itself points at TITANO_TRUSTED_PROXIES.
|
||||
var request = new DefaultHttpContext();
|
||||
request.Connection.RemoteIpAddress = IPAddress.Parse("172.18.0.5");
|
||||
request.Request.Scheme = "http";
|
||||
Assert.Equal("proxy_untrusted", AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Proxy }));
|
||||
Assert.Equal("https_required", AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Auto }));
|
||||
Assert.Contains("TITANO_TRUSTED_PROXIES", Loc.L("Server.Error.ProxyUntrusted"));
|
||||
|
||||
request.Request.Scheme = "https";
|
||||
Assert.Null(AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Proxy }));
|
||||
request.Request.Scheme = "http";
|
||||
request.Connection.RemoteIpAddress = IPAddress.Loopback;
|
||||
Assert.Null(AuthEndpoints.CookieRefusal(request, new ServerOptions { TlsMode = TlsMode.Proxy }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheAdminWarnsWhenAPageDidNotComeThroughATrustedProxyOverHttps()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o => o.TlsMode = TlsMode.Proxy);
|
||||
var admin = await server.AdminAsync();
|
||||
Assert.True((await DashboardAsync(admin, forwardedProto: null)).ProxyWarning, "plain HTTP to the server's own port");
|
||||
Assert.False((await DashboardAsync(admin, "https")).ProxyWarning, "HTTPS through a trusted proxy");
|
||||
Assert.True((await DashboardAsync(admin, "http")).ProxyWarning, "plain HTTP through the proxy");
|
||||
Assert.True((await SettingsAsync(admin, forwardedProto: null)).ProxyWarning);
|
||||
Assert.False((await SettingsAsync(admin, "https")).ProxyWarning);
|
||||
|
||||
await using var untrusted = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.TlsMode = TlsMode.Proxy;
|
||||
o.TrustedProxies = ElsewhereOnly;
|
||||
});
|
||||
var other = await untrusted.AdminAsync();
|
||||
Assert.True((await DashboardAsync(other, "https")).ProxyWarning, "a claim of HTTPS from a peer that is no trusted proxy");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OtherTlsModesNeverWarn()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var admin = await server.AdminAsync();
|
||||
Assert.False((await DashboardAsync(admin, forwardedProto: null)).ProxyWarning);
|
||||
Assert.False((await SettingsAsync(admin, forwardedProto: null)).ProxyWarning);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the server's own forwarded-headers step on a request from <paramref name="peer"/> that claims to forward a
|
||||
/// client at 203.0.113.7 over HTTPS: the address and scheme the rest of the server then sees.
|
||||
/// </summary>
|
||||
private static async Task<(string? Address, bool Https)> ForwardAsync(TestServer server, string peer)
|
||||
{
|
||||
var request = new DefaultHttpContext();
|
||||
request.Connection.RemoteIpAddress = IPAddress.Parse(peer);
|
||||
request.Request.Scheme = "http";
|
||||
request.Request.Headers["X-Forwarded-For"] = "203.0.113.7";
|
||||
request.Request.Headers["X-Forwarded-Proto"] = "https";
|
||||
var forwarded = new ForwardedHeadersMiddleware(_ => Task.CompletedTask, NullLoggerFactory.Instance,
|
||||
server.Services.GetRequiredService<IOptions<ForwardedHeadersOptions>>());
|
||||
await forwarded.Invoke(request);
|
||||
var address = request.Connection.RemoteIpAddress;
|
||||
return ((address is { IsIPv4MappedToIPv6: true } ? address.MapToIPv4() : address)?.ToString(), request.Request.IsHttps);
|
||||
}
|
||||
|
||||
private static bool IsLoopback(string? address) =>
|
||||
IPAddress.TryParse(address, out var ip) && IPAddress.IsLoopback(ip.IsIPv4MappedToIPv6 ? ip.MapToIPv4() : ip);
|
||||
|
||||
private static async Task<HttpResponseMessage> LoginAsync(TestServer server, string username, string forwardedFor)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/v1/auth/login")
|
||||
{
|
||||
Content = JsonContent.Create(new LoginRequest(username, "wrong-password-x", "tests"), ProtocolJson.Default.LoginRequest),
|
||||
};
|
||||
request.Headers.Add("X-Forwarded-For", forwardedFor);
|
||||
return await server.Client.SendAsync(request);
|
||||
}
|
||||
|
||||
private static async Task<DashboardDto> DashboardAsync(HttpClient admin, string? forwardedProto)
|
||||
{
|
||||
using var response = await SendAsync(admin, "/api/v1/server/dashboard", forwardedProto);
|
||||
return await response.ReadAsync(ProtocolJson.Default.DashboardDto);
|
||||
}
|
||||
|
||||
private static async Task<ServerSettingsDto> SettingsAsync(HttpClient admin, string? forwardedProto)
|
||||
{
|
||||
using var response = await SendAsync(admin, "/api/v1/server/settings", forwardedProto);
|
||||
return await response.ReadAsync(ProtocolJson.Default.ServerSettingsDto);
|
||||
}
|
||||
|
||||
private static async Task<HttpResponseMessage> SendAsync(HttpClient client, string path, string? forwardedProto)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, path);
|
||||
if (forwardedProto is not null) request.Headers.Add("X-Forwarded-Proto", forwardedProto);
|
||||
return await client.SendAsync(request);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
using Titano.Data;
|
||||
using Titano.Server.Configuration;
|
||||
using Titano.Server.Hosting;
|
||||
@@ -72,4 +74,59 @@ public sealed class StartupTests(TestContext context)
|
||||
Assert.SequenceEqual(["Database", "HttpPort", "Discovery"], options.Locked);
|
||||
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?> { ["TITANO_DATA_PATH"] = root, ["TITANO_DB"] = "postgres", ["TITANO_WORKERS"] = "many" }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TrustedProxiesAreAddressesOrNetworks()
|
||||
{
|
||||
var root = context.CreateTempDirectory("proxies");
|
||||
// Loopback only: machines of the home network reach the HTTP port directly from private addresses.
|
||||
var defaults = ServerOptions.Load(new Dictionary<string, string?> { ["TITANO_DATA_PATH"] = root, ["TITANO_DB"] = "postgres" }).TrustedProxyNetworks();
|
||||
foreach (var address in new[] { "127.0.0.1", "127.0.0.53", "::1" })
|
||||
Assert.True(defaults.Any(n => n.Contains(IPAddress.Parse(address))), address);
|
||||
foreach (var address in new[] { "10.20.30.40", "172.18.0.3", "192.168.1.2", "fd00::7", "203.0.113.5" })
|
||||
Assert.False(defaults.Any(n => n.Contains(IPAddress.Parse(address))), address);
|
||||
|
||||
var options = ServerOptions.Load(new Dictionary<string, string?>
|
||||
{
|
||||
["TITANO_DATA_PATH"] = root,
|
||||
["TITANO_DB"] = "postgres",
|
||||
["TITANO_TRUSTED_PROXIES"] = "10.1.2.3, 2001:db8::/32;172.20.0.5/16",
|
||||
});
|
||||
Assert.Contains("TrustedProxies", options.Locked);
|
||||
Assert.SequenceEqual(["10.1.2.3/32", "2001:db8::/32", "172.20.0.0/16"], options.TrustedProxyNetworks().Select(n => n.ToString()));
|
||||
foreach (var invalid in new[] { "proxy.lan", "10.0.0.0/33", "fe80::1%2" })
|
||||
{
|
||||
var error = Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?>
|
||||
{
|
||||
["TITANO_DATA_PATH"] = root,
|
||||
["TITANO_DB"] = "postgres",
|
||||
["TITANO_TRUSTED_PROXIES"] = "127.0.0.1," + invalid,
|
||||
}));
|
||||
Assert.Contains(invalid, error.Message);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PublicPortsComeFromTheEnvironment()
|
||||
{
|
||||
var root = context.CreateTempDirectory("public");
|
||||
var options = ServerOptions.Load(new Dictionary<string, string?>
|
||||
{
|
||||
["TITANO_DATA_PATH"] = root,
|
||||
["TITANO_DB"] = "postgres",
|
||||
["TITANO_PUBLIC_HTTP_PORT"] = "18080",
|
||||
["TITANO_PUBLIC_HTTPS_PORT"] = "18443",
|
||||
});
|
||||
Assert.Equal((18080, 18443), (options.PublicHttpPort, options.PublicHttpsPort));
|
||||
Assert.Null(ServerOptions.Load(new Dictionary<string, string?> { ["TITANO_DATA_PATH"] = root, ["TITANO_DB"] = "postgres" }).PublicHttpsPort);
|
||||
foreach (var invalid in new[] { "0", "70000", "https" })
|
||||
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?> { ["TITANO_DATA_PATH"] = root, ["TITANO_DB"] = "postgres", ["TITANO_PUBLIC_HTTPS_PORT"] = invalid }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HelpListsEveryVariable()
|
||||
{
|
||||
foreach (var variable in ServerOptions.EnvironmentVariables.Concat(["PUID", "PGID", "TZ"]))
|
||||
Assert.True(Regex.IsMatch(ServerCommandLine.Usage, $@"\b{variable}\b"), variable);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,11 @@ using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Text.RegularExpressions;
|
||||
using Microsoft.AspNetCore.Hosting.Server;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Hosting;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Server.Tests.Hosting;
|
||||
@@ -89,6 +93,31 @@ public sealed class SystemEndpointTests(TestContext context)
|
||||
Assert.Equal(HttpStatusCode.NotModified, cached.StatusCode);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PlainHttpFromAnotherMachineGoesToThePublicHttpsPort()
|
||||
{
|
||||
// The container listens on 8443, published on the host as 18443 (BRIEF §19.6: the template's ports are editable).
|
||||
await using var server = await TestServer.StartAsync(context, o => o.PublicHttpsPort = 18443);
|
||||
var kestrel = server.Services.GetRequiredService<IServer>();
|
||||
var request = AdminRequest(IPAddress.Parse("10.0.0.7"));
|
||||
Assert.Equal("https://10.0.0.5:18443/admin/?page=jobs", AdminPanel.HttpsLocation(request, server.Options, kestrel));
|
||||
|
||||
server.Options.PublicHttpsPort = null;
|
||||
Assert.Equal($"https://10.0.0.5:{Assert.NotNull(server.HttpsBase).Port}/admin/?page=jobs", AdminPanel.HttpsLocation(request, server.Options, kestrel));
|
||||
Assert.Null(AdminPanel.HttpsLocation(AdminRequest(IPAddress.Loopback), server.Options, kestrel));
|
||||
}
|
||||
|
||||
private static DefaultHttpContext AdminRequest(IPAddress from)
|
||||
{
|
||||
var request = new DefaultHttpContext();
|
||||
request.Connection.RemoteIpAddress = from;
|
||||
request.Request.Scheme = "http";
|
||||
request.Request.Host = new HostString("10.0.0.5", 18080);
|
||||
request.Request.Path = "/admin/";
|
||||
request.Request.QueryString = new QueryString("?page=jobs");
|
||||
return request;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AdminPanelRunsUnderAStrictPolicyAndIsNeverFramed()
|
||||
{
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Principal;
|
||||
using Titano.Server.Hosting;
|
||||
using Titano.Server.Hosting.Windows;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Server.Tests.Hosting;
|
||||
|
||||
public sealed class WindowsServiceTests
|
||||
public sealed class WindowsServiceTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public void CommandSwitchesAreParsedAndTheRestPassedOn()
|
||||
@@ -39,6 +41,52 @@ public sealed class WindowsServiceTests
|
||||
Assert.Equal(1064u, new ServiceStatusTracker().Stopped(1064).ExitCode);
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void TheServiceIsRegisteredOnlyFromInsideProgramFiles()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
|
||||
Assert.True(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "Titano", "Titano.Server.exe")));
|
||||
Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles));
|
||||
Assert.False(ServiceInstaller.IsUnderProgramFiles(programFiles + " Tools\\Titano"));
|
||||
Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "Titano")));
|
||||
Assert.False(ServiceInstaller.IsUnderProgramFiles(Path.Combine(programFiles, "..", "Titano")));
|
||||
// The test build is not under Program Files: registering it is refused, naming the folder.
|
||||
Assert.Contains(Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory), Assert.NotNull(ServiceInstaller.UnsafeLocation()));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void AnyFileOrdinaryUsersCanChangeIsFound()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
using var identity = WindowsIdentity.GetCurrent();
|
||||
if (!new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)) Assert.Inconclusive("registering a service needs an administrator");
|
||||
var folder = new DirectoryInfo(context.CreateTempDirectory("program"));
|
||||
File.WriteAllBytes(Path.Combine(folder.FullName, "Titano.Server.exe"), [1]);
|
||||
var satellite = new FileInfo(Path.Combine(folder.CreateSubdirectory("it").FullName, "Titano.Core.resources.dll"));
|
||||
File.WriteAllBytes(satellite.FullName, [1]);
|
||||
|
||||
// Like Program Files: administrators may change the folder, users only read it.
|
||||
var locked = new DirectorySecurity();
|
||||
locked.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
|
||||
var everything = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
|
||||
foreach (var account in new[] { new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), identity.User! })
|
||||
locked.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.FullControl, everything, PropagationFlags.None, AccessControlType.Allow));
|
||||
locked.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.ReadAndExecute, everything,
|
||||
PropagationFlags.None, AccessControlType.Allow));
|
||||
folder.SetAccessControl(locked);
|
||||
Assert.Null(ServiceInstaller.FindChangeable(folder, recursive: true));
|
||||
|
||||
// One satellite assembly users may replace is enough: the service would load it as SYSTEM.
|
||||
var open = satellite.GetAccessControl();
|
||||
open.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.Modify, AccessControlType.Allow));
|
||||
satellite.SetAccessControl(open);
|
||||
Assert.Equal(satellite.FullName, ServiceInstaller.FindChangeable(folder, recursive: true));
|
||||
Assert.Null(ServiceInstaller.FindChangeable(folder, recursive: false));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void TheDispatcherDeclinesAConsoleProcess()
|
||||
|
||||
Reference in new issue
Block a user