From c6f1682cf8c4915766f65070e27718ff967f57fc Mon Sep 17 00:00:00 2001 From: mlopezsegura <90263997+mlopezsegura@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:25:33 +0100 Subject: [PATCH] Seats: keep sleep and shut down working on the console An exclusive seat removes "Shut down the system" from the Users group so its isolated user can't shut the PC down. Administrators kept it, but an administrator's UAC-filtered token (Explorer, the Start menu) doesn't get the rights of the Administrators group, so Start > Sleep/Shut down silently did nothing on the console (#105). Before removing it from Users, every enabled local account that isn't an osms- user, and whoever is signed in at the console, now gets the right on its own account. This runs every time, so it also repairs PCs where an earlier version already removed it, and the service gives it to a new console user while Users doesn't have it. The accounts it was given to are recorded and lose it again on uninstall. It takes effect at each user's next sign-in. Co-Authored-By: Claude Opus 5.5 --- Core/Api/StreamSessionService.cs | 1 + Core/Helpers/ShutdownRight.cs | 157 ++++++++++++++++-- .../OpenStreamMS.Tests/ShutdownRightTests.cs | 47 ++++++ 3 files changed, 187 insertions(+), 18 deletions(-) create mode 100644 tests/OpenStreamMS.Tests/ShutdownRightTests.cs diff --git a/Core/Api/StreamSessionService.cs b/Core/Api/StreamSessionService.cs index 6fc2f3d4..88611089 100644 --- a/Core/Api/StreamSessionService.cs +++ b/Core/Api/StreamSessionService.cs @@ -946,6 +946,7 @@ private sealed class NoConsoleUserException(string message) : Exception(message) public void MonitorAll() { StartLocalsAwaitingConsoleUser(); + ShutdownRight.EnsureConsoleUser(); WatchComposites(); try { EnsureHuds(); } catch (Exception ex) { Logger.Warning($"[HUD] {ex.Message}"); } diff --git a/Core/Helpers/ShutdownRight.cs b/Core/Helpers/ShutdownRight.cs index 5e14fe56..35af160a 100644 --- a/Core/Helpers/ShutdownRight.cs +++ b/Core/Helpers/ShutdownRight.cs @@ -1,5 +1,4 @@ using OpenStreamMS.Services; -using System.Runtime.InteropServices; using System.Security.Principal; namespace OpenStreamMS.Core.Helpers; @@ -11,17 +10,28 @@ namespace OpenStreamMS.Core.Helpers; /// quite los botones, podrían apagar con shutdown /s. El derecho es por cuenta, no por /// sesión, así que mientras haya un puesto exclusivo se le quita al grupo Usuarios y se da /// explícitamente a cada usuario aislado que sí puede (). -/// Administradores (la consola) lo conserva siempre. Vale desde el siguiente inicio de sesión -/// de cada usuario (los privilegios van en el token). Se anota en disco si se quitó al grupo, -/// para devolverlo cuando ya no haya puestos exclusivos o al desinstalar. +/// +/// Administradores no basta para la consola: un administrador usa el token filtrado del UAC +/// (Explorer, el menú Inicio), y ese token no recibe los derechos del grupo Administradores. +/// Sin el grupo Usuarios, Inicio → Suspender/Apagar no hacía nada (issue #105). Por eso las +/// cuentas locales que no son osms-* y quien tenga sesión en la consola lo reciben en su propia +/// cuenta (). +/// +/// Vale desde el siguiente inicio de sesión de cada usuario (los privilegios van en el token). +/// Se anota en disco si se quitó al grupo y a qué cuentas se dio, para deshacerlo al desinstalar. /// internal static class ShutdownRight { private const string Privilege = "SeShutdownPrivilege"; private static readonly SecurityIdentifier Users = new(WellKnownSidType.BuiltinUsersSid, null); private static readonly SecurityIdentifier Admins = new(WellKnownSidType.BuiltinAdministratorsSid, null); - private static readonly string JournalPath = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "OpenStreamMS", "shutdown-right-removed"); + private static readonly string DataDir = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "OpenStreamMS"); + private static readonly string JournalPath = Path.Combine(DataDir, "shutdown-right-removed"); + /// SIDs (uno por línea) a los que OpenStreamMS dio el derecho y que no lo tenían. + private static readonly string GrantedPath = Path.Combine(DataDir, "shutdown-right-granted"); + private static readonly object Gate = new(); + private static string? _lastConsoleUser; /// /// Antes de que el usuario aislado inicie sesión: si puede apagar, se le da el derecho a él @@ -32,12 +42,15 @@ public static void SetForUser(string username, bool allow) try { var sid = (SecurityIdentifier)new NTAccount(username).Translate(typeof(SecurityIdentifier)); - using (var policy = LsaPolicy.Open()) + lock (Gate) { - if (allow) policy.Add(sid, Privilege); - else if (policy.Has(sid, Privilege)) policy.Remove(sid, Privilege); + using (var policy = LsaPolicy.Open()) + { + if (allow) policy.Add(sid, Privilege); + else if (policy.Has(sid, Privilege)) policy.Remove(sid, Privilege); + } + if (!allow) RestrictToAdministrators(); } - if (!allow) RestrictToAdministrators(); Logger.Log($"[Seguridad] '{username}' {(allow ? "puede" : "no puede")} apagar ni reiniciar el equipo."); } catch (Exception ex) @@ -52,12 +65,14 @@ private static void RestrictToAdministrators() try { using var policy = LsaPolicy.Open(); - policy.Add(Admins, Privilege); // que la consola nunca se quede sin poder apagar + policy.Add(Admins, Privilege); // los administradores elevados + // Siempre, aunque el grupo ya no lo tenga: repara los equipos donde se quitó sin esto. + KeepForConsoleUsers(policy); if (!policy.Has(Users, Privilege)) return; - Directory.CreateDirectory(Path.GetDirectoryName(JournalPath)!); + Directory.CreateDirectory(DataDir); File.WriteAllText(JournalPath, DateTime.Now.ToString("O")); policy.Remove(Users, Privilege); - Logger.Log("[Seguridad] 'Apagar el sistema' retirado del grupo Usuarios (hay puestos exclusivos): lo conservan los administradores y los usuarios aislados que pueden."); + Logger.Log("[Seguridad] 'Apagar el sistema' retirado del grupo Usuarios (hay puestos exclusivos): lo conservan los administradores, las cuentas locales y los usuarios aislados que pueden."); } catch (Exception ex) { @@ -65,16 +80,122 @@ private static void RestrictToAdministrators() } } - /// Devuelve el derecho al grupo Usuarios si OpenStreamMS se lo quitó (sin puestos exclusivos o al desinstalar). - public static void Restore() + /// + /// Da el derecho en su propia cuenta a las cuentas locales que no son osms-* y a quien tenga + /// sesión en la consola (puede ser de dominio o de Microsoft), para que su token filtrado lo + /// tenga. Las que ya lo tenían no se apuntan: al desinstalar solo se quita lo que dio OpenStreamMS. + /// + private static void KeepForConsoleUsers(LsaPolicy policy) + { + string? consoleUser = ConsoleSession.TryGetUser(out _, out var domain, out var user) ? $"{domain}\\{user}" : null; + var names = AccountsToKeep(IsolatedUserManager.ListLocalAccounts().Select(a => a.Name), consoleUser, Environment.MachineName); + var granted = ReadGranted(); + int added = 0; + foreach (var name in names) + { + try + { + var sid = (SecurityIdentifier)new NTAccount(name).Translate(typeof(SecurityIdentifier)); + if (policy.Has(sid, Privilege)) continue; + policy.Add(sid, Privilege); + granted.Add(sid.Value); + added++; + } + catch (Exception ex) + { + Logger.Warning($"[Seguridad] No se pudo dar 'Apagar el sistema' a '{name}': {ex.Message}"); + } + } + if (added == 0) return; + Directory.CreateDirectory(DataDir); + File.WriteAllLines(GrantedPath, granted); + Logger.Log($"[Seguridad] 'Apagar el sistema' dado en su propia cuenta a {added} cuenta(s) para la consola (sin el grupo Usuarios, el menú Inicio no podía apagar ni suspender)."); + } + + /// + /// Cuentas que conservan el derecho por su cuenta: las locales que no gestiona OpenStreamMS + /// y el usuario de la consola (DOMINIO\usuario) si tampoco es osms-*. Sin repetidos: + /// una cuenta local en la consola ya está en la lista por su nombre. + /// + internal static List AccountsToKeep(IEnumerable localAccounts, string? consoleUser, string machineName) + { + var result = new List(); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var name in localAccounts) + { + if (string.IsNullOrWhiteSpace(name) || name.StartsWith("osms-", StringComparison.OrdinalIgnoreCase)) continue; + if (seen.Add(name)) result.Add(name); + } + if (!string.IsNullOrWhiteSpace(consoleUser)) + { + int slash = consoleUser.IndexOf('\\'); + string domain = slash > 0 ? consoleUser[..slash] : ""; + string user = consoleUser[(slash + 1)..]; + bool local = domain.Length == 0 || domain.Equals(machineName, StringComparison.OrdinalIgnoreCase); + string name = local ? user : consoleUser; + if (user.Length > 0 && !user.StartsWith("osms-", StringComparison.OrdinalIgnoreCase) && seen.Add(name)) + result.Add(name); + } + return result; + } + + /// + /// Llamado cada pocos segundos por el servicio: mientras el grupo Usuarios no tenga el + /// derecho, el usuario que entre en la consola lo recibe en su cuenta (una cuenta creada + /// después de quitarlo, o de dominio). Vale desde su siguiente inicio de sesión. + /// + public static void EnsureConsoleUser() { if (!File.Exists(JournalPath)) return; + string current = ConsoleSession.TryGetUser(out _, out var domain, out var user) ? $"{domain}\\{user}" : ""; + if (current == _lastConsoleUser) return; + _lastConsoleUser = current; + try + { + lock (Gate) + { + using var policy = LsaPolicy.Open(); + KeepForConsoleUsers(policy); + } + } + catch (Exception ex) + { + Logger.Warning($"[Seguridad] No se pudo comprobar 'Apagar el sistema' de la consola: {ex.Message}"); + } + } + + private static HashSet ReadGranted() + { + try + { + return File.Exists(GrantedPath) + ? new HashSet(File.ReadAllLines(GrantedPath).Select(l => l.Trim()).Where(l => l.StartsWith("S-1-")), StringComparer.OrdinalIgnoreCase) + : new HashSet(StringComparer.OrdinalIgnoreCase); + } + catch (IOException) { return new HashSet(StringComparer.OrdinalIgnoreCase); } + } + + /// + /// Devuelve el derecho al grupo Usuarios si OpenStreamMS se lo quitó y lo retira de las + /// cuentas a las que se lo dio (al desinstalar). + /// + public static void Restore() + { try { using var policy = LsaPolicy.Open(); - policy.Add(Users, Privilege); - File.Delete(JournalPath); - Logger.Log("[Seguridad] 'Apagar el sistema' devuelto al grupo Usuarios."); + if (File.Exists(JournalPath)) + { + policy.Add(Users, Privilege); + File.Delete(JournalPath); + Logger.Log("[Seguridad] 'Apagar el sistema' devuelto al grupo Usuarios."); + } + foreach (var value in ReadGranted()) + { + try { policy.Remove(new SecurityIdentifier(value), Privilege); } + catch (Exception ex) { Logger.Warning($"[Seguridad] No se pudo quitar 'Apagar el sistema' a {value}: {ex.Message}"); } + } + if (File.Exists(GrantedPath)) File.Delete(GrantedPath); } catch (Exception ex) { diff --git a/tests/OpenStreamMS.Tests/ShutdownRightTests.cs b/tests/OpenStreamMS.Tests/ShutdownRightTests.cs new file mode 100644 index 00000000..2acea137 --- /dev/null +++ b/tests/OpenStreamMS.Tests/ShutdownRightTests.cs @@ -0,0 +1,47 @@ +using OpenStreamMS.Core.Helpers; +using Xunit; + +namespace OpenStreamMS.Tests; + +/// +/// Al quitar "Apagar el sistema" al grupo Usuarios por un puesto exclusivo, la consola tiene que +/// conservarlo en su propia cuenta: el token filtrado del UAC de un administrador no recibe los +/// derechos del grupo Administradores, y el menú Inicio no podía suspender ni apagar (issue #105). +/// +public sealed class ShutdownRightTests +{ + [Fact] + public void LocalAccountsKeepTheRightButIsolatedUsersDoNot() + { + var names = ShutdownRight.AccountsToKeep(["Mario", "osms-1a2b3c4d5e6f", "Invitado2", "OSMS-ABCDEF"], null, "PC"); + Assert.Equal(["Mario", "Invitado2"], names); + } + + [Fact] + public void LocalConsoleUserIsNotAddedTwice() + { + var names = ShutdownRight.AccountsToKeep(["Mario"], @"PC\mario", "pc"); + Assert.Equal(["Mario"], names); + } + + [Fact] + public void DomainConsoleUserIsAddedWithItsDomain() + { + // Mismo nombre corto que una cuenta local, pero es otra cuenta. + var names = ShutdownRight.AccountsToKeep(["mario"], @"EMPRESA\mario", "PC"); + Assert.Equal(["mario", @"EMPRESA\mario"], names); + } + + [Fact] + public void IsolatedUserAtTheConsoleIsLeftOut() + { + var names = ShutdownRight.AccountsToKeep([], @"PC\osms-1a2b3c4d5e6f", "PC"); + Assert.Empty(names); + } + + [Fact] + public void NoConsoleUserKeepsOnlyLocalAccounts() + { + Assert.Equal(["Ana"], ShutdownRight.AccountsToKeep(["Ana", " ", ""], "", "PC")); + } +}