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
@@ -8,7 +8,8 @@ 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.
|
||||
/// 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)
|
||||
@@ -81,9 +82,186 @@ public sealed class DataFolderAccessTests(TestContext context)
|
||||
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)
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
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;
|
||||
|
||||
@@ -39,7 +47,7 @@ public sealed class ProxyModeTests(TestContext context)
|
||||
[Test]
|
||||
public async Task ATrustedProxyReportsTheClientAddress()
|
||||
{
|
||||
// The default trusts loopback and the private networks a compose or Unraid proxy container connects from.
|
||||
// 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;
|
||||
@@ -54,6 +62,49 @@ public sealed class ProxyModeTests(TestContext context)
|
||||
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()
|
||||
{
|
||||
@@ -83,6 +134,24 @@ public sealed class ProxyModeTests(TestContext context)
|
||||
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);
|
||||
|
||||
|
||||
@@ -79,10 +79,12 @@ public sealed class StartupTests(TestContext context)
|
||||
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", "::1", "10.20.30.40", "172.18.0.3", "192.168.1.2", "fd00::7", "::ffff:172.17.0.2" })
|
||||
Assert.True(defaults.Any(n => n.Contains(IPAddress.Parse(address)) || n.Contains(IPAddress.Parse(address).MapToIPv4())), address);
|
||||
Assert.False(defaults.Any(n => n.Contains(IPAddress.Parse("203.0.113.5"))));
|
||||
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?>
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user