/// <summary> /// Initializes a registry state given a key and value name /// </summary> /// <param name="userSid">Security Identifier of the user making the registry key change. This value can be null.</param> /// <param name="keyName">Key to track, with format "HKEY_CURRENT_USER\SOFTWARE"</param> /// <param name="valueName">Name of value to track. For the default value, set to string.empty</param> public RegistryState(string userSid, string keyName, string valueName) : base() { if (string.IsNullOrEmpty(keyName)) { throw new ArgumentNullException(@"Key Name must be specified using format HKEY_CURRENT_USER\SOFTWARE\..."); } if (valueName == null) { throw new ArgumentNullException("Value Name must not be null. For default, use string.empty"); } if (!String.IsNullOrEmpty(userSid) && !String.IsNullOrEmpty(keyName)) { SecurityIdentifier sid = new SecurityIdentifier(userSid); if (!sid.IsAccountSid()) { throw new ArgumentException("The sid must be from a valid user account"); } if (keyName.Contains("HKCU")) { keyName = keyName.Replace("HKCU", @"HKEY_USERS\" + userSid); } else if (keyName.Contains("HKEY_CURRENT_USER")) { keyName = keyName.Replace("HKEY_CURRENT_USER", @"HKEY_USERS\" + userSid); } } this.keyName = keyName; this.valueName = valueName; }
private string GetUpnFromSelection(UnsafeNativeMethods.DsSelection selection) { if (!string.IsNullOrEmpty(selection.pwzUPN)) { return(selection.pwzUPN); } const string sidPropertyName = "objectSid"; string upn = selection.pwzADsPath; // Try to get the UPN value from AD path try { using (DirectoryEntry entry = new DirectoryEntry(upn)) { if (entry.Properties.Contains(sidPropertyName)) { SecurityIdentifier sid = new SecurityIdentifier((byte[])entry.Properties[sidPropertyName].Value, 0); if (sid.IsAccountSid()) { NTAccount acc = (NTAccount)sid.Translate(typeof(NTAccount)); upn = acc.Value; } } } } catch (Exception e) { Trace.TraceError(e.Message); } return(upn); }
private RawSecurityDescriptor ApplyAcesToTargetSecurityDescriptor(RawSecurityDescriptor targetSd, List <GenericAce> sourceAces) { List <GenericAce> list = new List <GenericAce>(); foreach (GenericAce genericAce in targetSd.DiscretionaryAcl) { SecurityIdentifier sidFromAce = TenantRelocationSecurityDescriptorHandler.GetSidFromAce(genericAce); if (!(sidFromAce == null)) { SecurityIdentifier accountDomainSid = sidFromAce.AccountDomainSid; if (sidFromAce.IsAccountSid() && !accountDomainSid.Equals(this.targetDomainSid)) { ExTraceGlobals.TenantRelocationTracer.TraceDebug <string>((long)this.GetHashCode(), "ApplyAcesToTargetSecurityDescriptor: customized SID found {0} on target object, removed.", sidFromAce.ToString()); } else { list.Add(genericAce); } } } RawAcl rawAcl = new RawAcl(targetSd.DiscretionaryAcl.Revision, list.Count + sourceAces.Count); int num = 0; foreach (GenericAce ace in list) { rawAcl.InsertAce(num++, ace); } foreach (GenericAce ace2 in sourceAces) { rawAcl.InsertAce(num++, ace2); } targetSd.DiscretionaryAcl = rawAcl; return(targetSd); }
private static string GetAccountNameFromSID(string sidString) { SecurityIdentifier sid = new SecurityIdentifier(sidString); if (sid.IsAccountSid() && sid.IsValidTargetType(typeof(NTAccount))) { try { NTAccount account = (NTAccount)sid.Translate(typeof(NTAccount)); return(account.Value); } catch (IdentityNotMappedException) { // Some or all identity references could not be translated. return(null); } catch (System.ArgumentNullException) { // The target translation type is null. return(null); } catch (System.ArgumentException) { // The target translation type is not an IdentityReference type. return(null); } catch (System.SystemException) { // A Win32 error code was returned. return(null); } } else { return(null); } }
internal protected SecurityAccount(SecurityCache parent, IdentityReference ident) { NTAccount = ident as NTAccount; if (NTAccount != null) { Sid = (SecurityIdentifier)NTAccount.Translate(typeof(SecurityIdentifier)); IsMapped = true; } else { Sid = (SecurityIdentifier)ident; try { NTAccount = (NTAccount)Sid.Translate(typeof(NTAccount)); IsMapped = true; } catch { NTAccount = new NTAccount("unknown", Sid.Value); } } IsAccoundSid = Sid.IsAccountSid(); for (int i = 0; i < wellKnownTypes.Length; i++) { if (!Sid.IsWellKnown(wellKnownTypes[i])) { continue; } WellKnownSid = wellKnownTypes[i]; break; } IsGroup = IsMapped && isGroup(parent); }
// Token: 0x06000DF6 RID: 3574 RVA: 0x00029F34 File Offset: 0x00028134 private static string GetUserAccountNameFromSid(SecurityIdentifier sid, string user, Task.TaskErrorLoggingDelegate logError) { string result = null; if (sid != null && sid.IsAccountSid()) { try { string text = sid.Translate(typeof(NTAccount)).ToString(); string[] array = text.Split(new char[] { '\\' }); if (array.Length == 2 && string.Compare(array[0], Environment.MachineName, StringComparison.OrdinalIgnoreCase) == 0 && !ADSession.IsBoundToAdam && logError != null) { logError(new CannotHaveLocalAccountException(user), ErrorCategory.InvalidData, null); } result = text; } catch (IdentityNotMappedException) { } catch (SystemException innerException) { if (logError != null) { logError(new LocalizedException(Strings.ForeignForestTrustFailedException(user), innerException), ErrorCategory.InvalidOperation, null); } } } return(result); }
private bool ShouldFilter(SecurityIdentifier sid, out DiscoveryError filteredReason) { if (!sid.IsAccountSid()) { filteredReason = null; if (settings.FilterNonAccountSids) { logger.LogInformation("Silently filtering non-account SID {sid}", sid); //filteredReason = new DiscoveryError() { Message = "The principal is not an account SID", Principal = sid.ToString(), Type = DiscoveryErrorType.Warning }; return(true); } else { return(false); } } ISecurityPrincipal principal = principalCache.GetOrAdd(sid, (value) => { if (this.directory.TryGetPrincipal(sid, out ISecurityPrincipal p)) { return(p); } else { return(null); } }); if (settings.PrincipalFilter.Contains(sid)) { filteredReason = new DiscoveryError() { Message = "The principal matched the import filter", Principal = principal?.MsDsPrincipalName ?? sid.ToString(), Type = DiscoveryErrorType.Informational }; return(true); } if (principal == null) { filteredReason = new DiscoveryError() { Message = "The principal was not found in the directory", Principal = sid.ToString(), Type = DiscoveryErrorType.Warning }; return(true); } if (!(principal is IUser || principal is IGroup)) { filteredReason = new DiscoveryError() { Message = "The principal was not a user or group", Principal = principal.MsDsPrincipalName, Type = DiscoveryErrorType.Error }; return(true); } filteredReason = null; return(false); }
public static string GetProcessUser(IntPtr hProcess, RunningProcess pre) { int MAX_INTPTR_BYTE_ARR_SIZE = 512; IntPtr tokenHandle; byte[] sidBytes; try { winaudits.AdjustPrevilege.AddDebugPrevilege(); // Get the Process Token if (!OpenProcessToken(hProcess, TOKEN_READ, out tokenHandle)) { return(null); } uint tokenInfoLength = 0; bool result; result = GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS.TokenUser, IntPtr.Zero, tokenInfoLength, out tokenInfoLength); // get the token info length IntPtr tokenInfo = Marshal.AllocHGlobal((int)tokenInfoLength); result = GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS.TokenUser, tokenInfo, tokenInfoLength, out tokenInfoLength); // get the token info // Get the User SID if (result) { TOKEN_USER tokenUser = (TOKEN_USER)Marshal.PtrToStructure(tokenInfo, typeof(TOKEN_USER)); sidBytes = new byte[MAX_INTPTR_BYTE_ARR_SIZE]; // Since I don't yet know how to be more precise w/ the size of the byte arr, it is being set to 512 Marshal.Copy(tokenUser.User.Sid, sidBytes, 0, MAX_INTPTR_BYTE_ARR_SIZE); // get a byte[] representation of the SID var sid = new SecurityIdentifier(sidBytes, 0); if (sid != null) { pre.SID = sid.ToString(); if (sid.IsAccountSid() == true) { pre.SIDType = "Account SID"; } else { pre.SIDType = "WellKnown"; } } return(GetUserNameFromSID(sidBytes)); } } catch (Exception) { return(null); } return(null); }
/// <summary> /// /// </summary> /// <param name="directory"></param> /// <param name="user"></param> /// <returns></returns> public static bool CanWrite(string directory, WindowsIdentity user) { bool bAllowed = false; try { //Get the directory security DirectorySecurity sec = Directory.GetAccessControl(directory, AccessControlSections.Access); System.Security.AccessControl.AuthorizationRuleCollection dacls = sec.GetAccessRules(true, true, typeof(SecurityIdentifier)); //Enumerate each access rule foreach (FileSystemAccessRule dacl in dacls) { SecurityIdentifier sid = (SecurityIdentifier)dacl.IdentityReference; //If the right is either create files or write access if (((dacl.FileSystemRights & FileSystemRights.CreateFiles) == FileSystemRights.CreateFiles) || ((dacl.FileSystemRights & FileSystemRights.Write) == FileSystemRights.Write)) { //If the sid matches the user or a group the user is in if ((sid.IsAccountSid() && user.User == sid) || (!sid.IsAccountSid() && user.Groups.Contains(sid))) { //If this is a deny right then the user has no access if (dacl.AccessControlType == AccessControlType.Deny) { return(false); } //Allowed, for now bAllowed = true; } } } return(bAllowed); } catch (SecurityException) { throw; } }
/// /// <summary> /// Returns true if the specified SIDs are from the same domain. /// Otherwise return false. /// </summary> /// <param name="sid1"></param> /// <param name="sid2"></param> /// <returns>Returns true if the specified SIDs are from the same domain. /// Otherwise return false /// </returns> /// static internal bool AreSidsInSameDomain(SecurityIdentifier sid1, SecurityIdentifier sid2) { if (sid1.IsAccountSid() && sid2.IsAccountSid()) { return(sid1.AccountDomainSid.Equals(sid2.AccountDomainSid)); } else { return(false); } }
public static void Main(string[] args) { using (var windowsIdentity = WindowsIdentity.GetCurrent()) { using (var token = new TokenHandle(windowsIdentity)) { var groups = token.GetGroupsTokenInformation(TokenInformationClass.TokenLogonSid); SecurityIdentifier securityIdentifier = groups.Single().SecurityIdentifier; Console.WriteLine("Is Account: {0}", securityIdentifier.IsAccountSid()); Console.WriteLine("SID: {0}", securityIdentifier); Console.WriteLine("ProfilePath: {0}", token.GetUserProfileDirectory().FullName); } } }
/// <summary> /// Obtains a list of users SID that have previously logged into the device /// </summary> /// <returns>List of user SIDs</returns> public static UserPrincipal GetLastLoggedInUser() { PrincipalContext domainContext = null; if (Program.IsDomainJoined) { domainContext = new PrincipalContext(ContextType.Domain); } PrincipalContext machineContext = new PrincipalContext(ContextType.Machine); UserPrincipal user; // Get users that have logged in SelectQuery query = new SelectQuery("Win32_UserProfile"); var searcher = new ManagementObjectSearcher(query); var results = searcher.Get(); var OrderedResults = results.Cast <ManagementObject>().OrderBy(o => o["LastUseTime"]); //https://stackoverflow.com/questions/18835134/how-to-create-windowsidentity-windowsprincipal-from-username-in-domain-user-form/32165726 foreach (ManagementObject sid in OrderedResults) { SecurityIdentifier sidObject = new SecurityIdentifier(sid["SID"].ToString()); if (!sidObject.IsAccountSid()) { continue; } // Is domain user? if (domainContext != null) { user = UserPrincipal.FindByIdentity(domainContext, IdentityType.Sid, sid["SID"].ToString()); if (user != null) { return(user); } } // Is machine user? user = UserPrincipal.FindByIdentity(machineContext, IdentityType.Sid, sid["SID"].ToString()); if (user != null) { return(user); //Users.Add(user.SamAccountName); } } throw new Exception("No previously logged users found"); }
public static bool AccountExists(string name) { bool bRet = false; try { NTAccount acct = new NTAccount(name); SecurityIdentifier id = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier)); bRet = id.IsAccountSid(); } catch (IdentityNotMappedException) { /* Invalid account */ } return(bRet); }
/// <summary>Creates the specified SID as the <see cref="AccountSid"/> object.</summary> /// <param name="sid">The SID value.</param> /// <returns>A <see cref="Result"/> which represents whether the SID was created or not.</returns> public static Result <AccountSid> Create(string sid) { if (string.IsNullOrWhiteSpace(sid)) { return(Result.Fail <AccountSid>("Empty or null SID")); } try { var s = new SecurityIdentifier(sid); return(s.IsAccountSid() ? Result.Ok(new AccountSid(sid)) : Result.Fail <AccountSid>("Not an Account SID, perhaps a Well-known SID")); } catch (Exception ex) { return(Result.Fail <AccountSid>($"Invalid SID. {ex.Message}")); } }
public bool CanDirectoryProcessing(DirectoryInfo directory) { WindowsIdentity user = WindowsIdentity.GetCurrent(); bool bAllowed = false; try { //Получает набор разрешений для папки DirectorySecurity sec = directory.GetAccessControl(AccessControlSections.Access); AuthorizationRuleCollection dacls = sec.GetAccessRules(true, true, typeof(SecurityIdentifier)); //Перечисляет access rule foreach (FileSystemAccessRule dacl in dacls) { SecurityIdentifier sid = (SecurityIdentifier)dacl.IdentityReference; //If the right is either create files or write access if ( ((dacl.FileSystemRights & FileSystemRights.Write) == FileSystemRights.Write) || ((dacl.FileSystemRights & FileSystemRights.DeleteSubdirectoriesAndFiles) == FileSystemRights.DeleteSubdirectoriesAndFiles) ) { if ((sid.IsAccountSid() && user.User == sid) || (/*sid.IsAccountSid() &&*/ user.Groups.Contains(sid))) { if (dacl.AccessControlType == AccessControlType.Deny) { return(false); } bAllowed = true; } ; } ; } ; return(bAllowed); } catch (SecurityException e) { return(false); } catch (UnauthorizedAccessException) { return(false); } }
/// <summary> /// Returns machine and domain groups user is a member of. /// </summary> /// <param name="sid">User SID</param> public static List <GroupPrincipal> GetUserGroups(SecurityIdentifier sid) { var groups = new List <GroupPrincipal>(); if (sid == null) { return(groups); } if (!sid.IsAccountSid()) { return(groups); } var isLocal = IsLocalUser(sid) || IsLocalGroup(sid); // If local user or group then... if (isLocal) { var machineContext = new PrincipalContext(ContextType.Machine); var principal = Principal.FindByIdentity(machineContext, sid.Value); groups = principal.GetGroups().Cast <GroupPrincipal>().ToList(); } // If domain user then... else { var domainContext = new PrincipalContext(ContextType.Domain); var principal = Principal.FindByIdentity(domainContext, sid.Value); // Can take 1-2 seconds. groups = principal.GetGroups().Cast <GroupPrincipal>().ToList(); // Domain user can be a member of local machine group. var localGroups = GetAllGroups(ContextType.Machine); foreach (var lg in localGroups) { // Add group to the list if user is a member. if (principal.IsMemberOf(lg)) { groups.Add(lg); } } } return(groups); }
private void GetNTAcctForPath(String path) { FileSecurity fs = File.GetAccessControl(path); AuthorizationRuleCollection ntarc = fs.GetAccessRules(true, true, typeof(NTAccount)); AuthorizationRuleCollection siarc = fs.GetAccessRules(true, true, typeof(SecurityIdentifier)); Console.WriteLine("Checking SIDs on path: {0}", path); Console.WriteLine("\n== By NTAccount =="); foreach (FileSystemAccessRule fsar in ntarc) { NTAccount nta = (NTAccount)fsar.IdentityReference; Console.WriteLine("{0} <=> {1}", nta.Value, nta.IsValidTargetType(typeof(SecurityIdentifier)) ? nta.Translate(typeof(SecurityIdentifier)).ToString() : "-"); } Console.WriteLine("\n== By SecurityIdentifier == "); foreach (FileSystemAccessRule siar in siarc) { SecurityIdentifier sia = (SecurityIdentifier)siar.IdentityReference; try { Console.WriteLine("SDDL:{0} <=> {1}", sia.Value, (sia.IsAccountSid() ? (sia.IsValidTargetType(typeof(NTAccount)) ? sia.Translate(typeof(NTAccount)).ToString() : "-") : "Not a real Windows Account")); } catch (Exception e) { Console.WriteLine("Error: {0}", e.Message); } } }