From 94fdd47cdaddc67a50f34a781e7aa9a5de4ac2b5 Mon Sep 17 00:00:00 2001 From: Peter Kirmeier Date: Sat, 12 Aug 2023 14:00:26 +0200 Subject: [PATCH] [BUG] Child processes won't elevate (#488) (cherry picked from commit 68258eb1048b7f4b51240a86eeae714a64254d99) --- Business/Program.cs | 1 + Utilities/Log.cs | 8 +++++++- Utilities/PrivilegeChecker.cs | 29 +++++++++++++++++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 Utilities/PrivilegeChecker.cs diff --git a/Business/Program.cs b/Business/Program.cs index f751a7e..e176e3c 100644 --- a/Business/Program.cs +++ b/Business/Program.cs @@ -23,6 +23,7 @@ namespace SystemTrayMenu Config.SetFolderByWindowsContextMenu(args); Config.LoadOrSetByUser(); Config.Initialize(); + PrivilegeChecker.Initialize(); // Without a valid path we cannot do anything, just close application if (string.IsNullOrEmpty(Config.Path)) diff --git a/Utilities/Log.cs b/Utilities/Log.cs index 9d264e8..8678103 100644 --- a/Utilities/Log.cs +++ b/Utilities/Log.cs @@ -160,6 +160,12 @@ namespace SystemTrayMenu.Utilities try { + string verb = string.Empty; + if (!PrivilegeChecker.IsCurrentUserInAdminGroup) + { + verb = "runas"; + } + using Process p = new() { StartInfo = new ProcessStartInfo(fileName) @@ -169,7 +175,7 @@ namespace SystemTrayMenu.Utilities WorkingDirectory = workingDirectory ?? string.Empty, CreateNoWindow = createNoWindow, UseShellExecute = true, - Verb = "runas", + Verb = verb, }, }; p.Start(); diff --git a/Utilities/PrivilegeChecker.cs b/Utilities/PrivilegeChecker.cs new file mode 100644 index 0000000..b2e639d --- /dev/null +++ b/Utilities/PrivilegeChecker.cs @@ -0,0 +1,29 @@ +// +// Copyright (c) PlaceholderCompany. All rights reserved. +// + +namespace SystemTrayMenu.Utilities +{ + using System.Linq; + using System.Security.Principal; + + internal static class PrivilegeChecker + { + public static bool IsCurrentUserInAdminGroup { get; set; } + + public static void Initialize() + { + // https://stackoverflow.com/questions/3600322/check-if-the-current-user-is-administrator + // https://learn.microsoft.com/en-us/troubleshoot/windows-server/identity/security-identifiers-in-windows + // S-1-5-32-544 + // A built-in group. After the initial installation of the operating system, + // the only member of the group is the Administrator account. + // When a computer joins a domain, the Domain Admins group is added to + // the Administrators group. When a server becomes a domain controller, + // the Enterprise Admins group also is added to the Administrators group. + var principal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); + var claims = principal.Claims; + IsCurrentUserInAdminGroup = claims.FirstOrDefault(c => c.Value == "S-1-5-32-544") != null; + } + } +} \ No newline at end of file