using System.Runtime.Versioning;
using System.Security.AccessControl;
using System.Security.Principal;
using Chronos.Core.Archiving;
namespace Chronos.Server.Hosting;
///
/// Keeps the data folder and its secrets private (BRIEF ยง14.2): it holds the database, the TLS private key, the
/// temporary admin password and server.json. On Windows the folder sits in %ProgramData%, 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 /data, and secrets are
/// written with mode 0600. An archive folder the server creates on Windows gets the same accounts (see
/// ).
///
public static class DataFolderAccess
{
private const UnixFileMode OwnerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite;
private const int GenericAll = 0x10000000;
private const int GenericWrite = 0x40000000;
/// Rights that let an account replace or alter a file or folder (including the generic forms).
[SupportedOSPlatform("windows")]
private const FileSystemRights ChangeRights = FileSystemRights.WriteData | FileSystemRights.AppendData | FileSystemRights.WriteExtendedAttributes
| FileSystemRights.DeleteSubdirectoriesAndFiles | FileSystemRights.Delete | FileSystemRights.ChangePermissions | FileSystemRights.TakeOwnership
| (FileSystemRights)GenericWrite | (FileSystemRights)GenericAll;
///
/// 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.
///
///
/// 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).
///
public static void Restrict(string folder)
{
if (!OperatingSystem.IsWindows())
{
Directory.CreateDirectory(folder);
return;
}
try
{
RestrictOnWindows(new DirectoryInfo(folder));
}
catch (UnauthorizedAccessException ex)
{
throw new InvalidOperationException(
$"Chronos 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);
}
}
///
/// Reads a file the server acts on (server.json). 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.
///
/// The file belongs to another account.
public static string ReadTrustedText(string path)
{
if (!OperatingSystem.IsWindows()) return File.ReadAllText(path);
return ReadTrustedText(path, AllowedAccounts());
}
/// Writes a secret that only the server's account (and, on Windows, SYSTEM and Administrators) may read.
public static void WritePrivateFile(string path, ReadOnlySpan 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);
}
///
/// 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 .chronos 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.
///
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);
}
///
/// True when the ACL is protected, its owner is SYSTEM, Administrators or this process's account, and it names no
/// other account.
///
[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;
}
///
/// The first problem with 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
/// (who may have written the contents and can always change the ACL back). Links are
/// reported, never followed.
///
[SupportedOSPlatform("windows")]
internal static string? FindUntrusted(DirectoryInfo folder, IReadOnlySet owners)
{
var everything = new EnumerationOptions { AttributesToSkip = 0, IgnoreInaccessible = false };
var pending = new Stack();
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;
}
///
[SupportedOSPlatform("windows")]
internal static string ReadTrustedText(string path, IReadOnlySet 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();
}
///
/// True when the owner is outside 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.
///
[SupportedOSPlatform("windows")]
internal static bool IsChangeableByOthers(FileSystemSecurity security, IReadOnlySet 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;
}
/// SYSTEM, Administrators and the account this process runs as (SYSTEM again for the Windows service).
[SupportedOSPlatform("windows")]
internal static HashSet AllowedAccounts()
{
using var identity = WindowsIdentity.GetCurrent();
var accounts = new HashSet
{
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 owners)
{
if (IsLink(entry))
{
return $"{entry.FullName} is a link to {entry.LinkTarget}, and Chronos Server follows no links in its data folder. "
+ "Delete the link (CHRONOS_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 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 Chronos Server "
+ "runs as, so it cannot be trusted. Check it, then delete it or make Administrators its owner, and start the server again.";
}
/// A symbolic link or junction (other reparse points, such as deduplicated files, are ordinary files).
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 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);
}
/// A protected DACL that gives the allowed accounts full control, passed on to everything inside.
[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;
}
/// The private DACL, plus read access for every local user (photos and renders, never .chronos).
[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;
}
}