using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Security.Principal; using static Vanara.PInvoke.AdvApi32; namespace Vanara.Security { /// Helper methods for working with and user names. public static partial class AccountUtils { /// Returns a value indicating if the Windows identity is an administrator. /// The identity to evaluate. /// if the identity is in an Administrator role. public static bool IsAdmin(this WindowsIdentity id) => new WindowsPrincipal(id).IsInRole(WindowsBuiltInRole.Administrator); /// Returns a value indicating if the Windows identity is a service account. /// The identity to evaluate. /// if the identity is in a service account. public static bool IsServiceAccount(this WindowsIdentity id) { try { var acct = new NTAccount(id.Name); var si = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier)); return si.IsWellKnown(WellKnownSidType.LocalSystemSid) || si.IsWellKnown(WellKnownSidType.NetworkServiceSid) || si.IsWellKnown(WellKnownSidType.LocalServiceSid) || si.IsWellKnown(WellKnownSidType.ServiceSid); } catch { } return false; } /// Runs the specified function as the impersonated Windows identity. /// The impersonated identity under which to run the function. /// The System.Func to run. public static void Run(this WindowsIdentity identity, Action func) { if (identity is null) { func(); } else { #if NETFRAMEWORK using (new Principal.WindowsImpersonatedIdentity(identity)) func(); #else WindowsIdentity.RunImpersonated(identity.AccessToken, func); #endif } } /// Runs the specified function as the impersonated Windows identity. /// The type of object used by and returned by the function. /// The impersonated identity under which to run the function. /// The System.Func to run. /// The result of the function. public static T Run(this WindowsIdentity identity, Func func) { if (identity is null) return func(); #if NETFRAMEWORK using (new Principal.WindowsImpersonatedIdentity(identity)) return func(); #else return WindowsIdentity.RunImpersonated(identity.AccessToken, func); #endif } /// Gets the SDDL formatted SID value from a user name. /// Name of the user. /// The SDDL SID string. public static string SidStringFromUserName(string userName) { var acct = new NTAccount(userName); try { var si = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier)); return si.ToString(); } catch { } return null; } /// Get a user name for a supplied SDDL SID string. /// The SID string in SDDL format. /// The full user name of the identity referred to by . public static string UserNameFromSidString(string sid) { try { var si = new SecurityIdentifier(sid); var acct = (NTAccount)si.Translate(typeof(NTAccount)); return acct.Value; } catch { } return null; } } }