using System.Runtime.Versioning; using System.Security.AccessControl; using System.Security.Principal; using Chronos.Server.Hosting; using Chronos.Testing; namespace Chronos.Server.Tests.Hosting; /// /// 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. /// [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, "chronos.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"), "Chronos 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 { 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 { 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 { 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(() => 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 { 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"), "ChronosArchive"); 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"), "ChronosArchive")); 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, ".chronos")); 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 .chronos folder the server added at the first start stays its own. Assert.True(DataFolderAccess.IsPrivate(new DirectoryInfo(Path.Combine(root.FullName, ".chronos")).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))!; /// An owner this process may give a file that its new files do not get: its own account or Administrators. [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; } } /// The rights allow entries give . [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; } /// True when Users, Authenticated Users or Everyone have any allow entry. [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); } }