Inheritance: IdentityReference
 private static string CreateSddl(string account)
 {
     string sid = new NTAccount(account).Translate(typeof(SecurityIdentifier)).ToString();
     // DACL that Allows Generic eXecute for the user specified by account
     // see help for HttpServiceConfigUrlAclParam for details on what this means
     return string.Format(CultureInfo.CurrentCulture, "D:(A;;GX;;;{0})", sid);
 }
        /// <summary>
        /// Deletes the user profile.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <param name="domainName">The domain name of the user to act as.</param>
        public static void DeleteUserProfile(string userName, string domainName)
        {
            NTAccount ntaccount = new NTAccount(domainName, userName);
            string userSid = ntaccount.Translate(typeof(SecurityIdentifier)).Value;

            bool retry = true;
            int retries = 2;
            while (retry && retries > 0)
            {
                retry = false;

                if (!DeleteProfile(userSid, null, null))
                {
                    int errorCode = Marshal.GetLastWin32Error();

                    if (errorCode == 2)
                    {
                        // Error Code 2: The user profile was not created or was already deleted
                        return;
                    }
                    else if (errorCode == 87)
                    {
                        // Error Code 87: The user profile is still loaded.
                        retry = true;
                        retries--;
                    }
                    else
                    {
                        throw new Win32Exception(errorCode);
                    }
                }
            }
        }
      public static SecurityIdentifier GetSidFromClaim(string claimValue)
      {
         SecurityIdentifier sid = null;

         SPClaimProviderManager claimManager = SPClaimProviderManager.Local;
         if (claimManager == null)
         {
            throw new ApplicationException("Unable to access the claims provider manager.");
         }
         try
         {
            SPClaim claim = claimManager.DecodeClaim(claimValue);
            if (claim.OriginalIssuer.Equals("Windows", StringComparison.OrdinalIgnoreCase))
            {
               if (claim.ClaimType.Equals(Microsoft.IdentityModel.Claims.ClaimTypes.GroupSid, StringComparison.OrdinalIgnoreCase))
               {
                  sid = new SecurityIdentifier(claim.Value);
               }
               else if (claim.ClaimType.Equals(Microsoft.SharePoint.Administration.Claims.SPClaimTypes.UserLogonName, StringComparison.OrdinalIgnoreCase))
               {
                  NTAccount userAccount = new NTAccount(claim.Value);
                  sid = (SecurityIdentifier)userAccount.Translate(typeof(SecurityIdentifier));
               }
            }
         }
         catch (ArgumentException currentException)
         {
            GlymaSearchLogger.WriteTrace(LogCategoryId.Security, TraceSeverity.Unexpected, "The following exception occured when attempting to decode the claim, " + claimValue + " : " + currentException.ToString());
         }

         return sid;
      }
Example #4
0
        // Constructor //
        public MainWindow()
        {
            InitializeComponent();

            // Get user name
            this.username = Environment.UserName.ToString();

            // Get user SID
            NTAccount acct = new NTAccount(username);
            SecurityIdentifier s = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier));
            this.usrSID = s.ToString();

            // Get user home directory
            this.homeFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

            // Get volume location (default)
            this.defaultVolumeLoc = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System)) + this.username + ".hc";

            // Figure out where the home folder's encrypted file is located for this user //
            string encDrive = (string)Registry.GetValue(Config.LOCAL_MACHINE_REG_ROOT + this.usrSID, "encDrive", string.Empty);
            string encContainerLoc = (string)Registry.GetValue(Config.LOCAL_MACHINE_REG_ROOT + this.usrSID, "encContainerLoc", string.Empty);
            if (!string.IsNullOrWhiteSpace(encContainerLoc) && !string.IsNullOrWhiteSpace(encDrive) && Directory.Exists(encDrive + @":\"))
            {
                // We're already running in an encrypted home directory environment!
                g_tabContainer.Controls[0].Enabled = false;
                l_homeAlreadyEncrypted.Visible = true;
                l_homeAlreadyEncrypted.Enabled = true;
            }
            // * //

            l_statusLabel.Text = "Ready ...";
            Application.DoEvents();
        }
        private void btnOK_Click(object sender, EventArgs e)
        {
            bool success = false;
            try
            {
                Sid = new SecurityIdentifier(textBoxSid.Text);
                success = true;
            }
            catch (Exception)
            {
            }

            if (!success)
            {
                try
                {
                    NTAccount acct = new NTAccount(textBoxSid.Text);
                    Sid = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier));
                    success = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            if (success)
            {
                DialogResult = DialogResult.OK;
                Close();
            }
        }
Example #6
0
        public SidWrapper FindSid(string account)
        {
            SecurityIdentifier sid = null;
            try
            {
                // first, let's try this as a sid (SDDL) string
                sid = new SecurityIdentifier(account);

                return new SidWrapper { Sid = sid};
            }
            catch
            {
            }

            try
            {
                // maybe it's an account/group name
                var name = new NTAccount(account);
                sid = (SecurityIdentifier)name.Translate(typeof(SecurityIdentifier));
                if (sid != null)
                {
                    return new SidWrapper { Sid = sid };
                }
            }
            catch
            {
            }

            return null;
        }
        public void Execute()
        {
            PrintHeader();

            var id = WindowsIdentity.GetCurrent();
            Console.WriteLine("Identity Id: " + id.Name);

            var account = new NTAccount(id.Name);
            var sid = account.Translate(typeof(SecurityIdentifier));
            Console.WriteLine("SecurityIdentifier (sid): " + sid.Value);

            foreach (var group in id.Groups.Translate(typeof(NTAccount)))
                Console.WriteLine("InGroup: " + group);

            var principal = new WindowsPrincipal(id);
            var localAdmins = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
            Console.WriteLine("IsInRole(localAdmin): " + principal.IsInRole(localAdmins));

            var domainAdmins = new SecurityIdentifier(WellKnownSidType.AccountDomainAdminsSid, id.User.AccountDomainSid);
            Console.WriteLine("IsInRole(domainAdmin): " + principal.IsInRole(domainAdmins));
            Console.WriteLine();

            // be aware for desktop/local accounts User Account Control (UAC from Vista) strips user of admin rights,
            // unless the process was run elevated "as Admin".
        }
Example #8
0
        public static void RemoveUser(string targetDir, string user, string windowsUser, string userHomeDir, string userShell)
        {
            string passwdFile = Path.Combine(targetDir, "etc", "passwd");
            string userSID = null;
            try
            {
                var objUser = new NTAccount(windowsUser);
                userSID = ((SecurityIdentifier)objUser.Translate(typeof(SecurityIdentifier))).Value;
            }
            catch
            {
                throw new Exception(string.Format("Could not get SID for user {0}. Aborting.", windowsUser));
            }

            string usersGroupSID = CygwinPasswd.GetNoneGroupSID();

            Logger.Debug("Setting up user in passwd file...");
            string uid = userSID.Split('-').Last();
            string gid = usersGroupSID.Split('-').Last();
            string userHomeDirLinux = LinuxFiles.Cygpath(userHomeDir);
            userShell = LinuxFiles.Cygpath(userShell);
            string match = string.Format("{0}:unused:{1}:{2}:{3},{4}:{5}:{6}", user, uid, gid, windowsUser, userSID, userHomeDirLinux, userShell);
            List<string> content = File.ReadAllLines(passwdFile).ToList();
            content.Remove(match);
            File.WriteAllLines(passwdFile, content, Encoding.ASCII);
        }
        public string GetUncPathForDrive(string domain, string user, string drive)
        {
            var userIdentifier = String.Format(@"{0}\{1}", domain, user);
            if (!driveCache.ContainsKey(userIdentifier))
            {
                var account = new NTAccount(domain, user);
                if (account == null)
                    return null;
                var sid = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));
                if (sid == null)
                    return null;

                var drives = RegistryReader.GetSubKeys(RegistryHive.Users, RegistryView.Default, String.Format(@"{0}\Network", sid.Value));
                if (drives == null)
                    return null;

                driveCache[userIdentifier] = drives.Select(driveLetter => {
                    string uncPath = RegistryReader.ReadKey(RegistryHive.Users, RegistryView.Default, String.Format(@"{0}\Network\{1}", sid.Value, driveLetter), "RemotePath").ToString();
                    return new KeyValuePair<string, string>(driveLetter, uncPath);
                }).Where(x => x.Value != null).ToDictionary();
            }

            if (driveCache[userIdentifier].ContainsKey(drive))
                return driveCache[userIdentifier][drive];

            return null;
        }
 public void ElevatePermissions(string directory)
 {
     var account = new NTAccount(WindowsIdentity.GetCurrent().Name);
     var existingDirectory = new DirectoryInfo(directory);
     var existingDirectorySecurity = existingDirectory.GetAccessControl();
     existingDirectorySecurity.SetOwner(account);
     existingDirectory.SetAccessControl(existingDirectorySecurity);
 }
Example #11
0
        /// <summary>
        /// Adds a reservation to the list of reserved URLs
        /// </summary>
        /// <param name="urlPrefix">The prefix of the URL to reserve.</param>
        /// <param name="user">The user with which to reserve the URL.</param>
        internal static void AddReservation(string urlPrefix, string user)
        {
            NTAccount account = new NTAccount(user);
            SecurityIdentifier sid = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));
            string sddl = GenerateSddl(sid);
            ErrorCode retVal = ErrorCode.Success; // NOERROR = 0

            retVal = NativeMethods.HttpInitialize(HttpApiConstants.Version1, HttpApiConstants.InitializeConfig, IntPtr.Zero);
            if (ErrorCode.Success == retVal)
            {
                HttpServiceConfigUrlAclKey keyDesc = new HttpServiceConfigUrlAclKey(urlPrefix);
                HttpServiceConfigUrlAclParam paramDesc = new HttpServiceConfigUrlAclParam(sddl);

                HttpServiceConfigUrlAclSet inputConfigInfoSet = new HttpServiceConfigUrlAclSet();
                inputConfigInfoSet.KeyDesc = keyDesc;
                inputConfigInfoSet.ParamDesc = paramDesc;

                IntPtr inputConfigInfoBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(HttpServiceConfigUrlAclSet)));
                Marshal.StructureToPtr(inputConfigInfoSet, inputConfigInfoBuffer, false);

                retVal = NativeMethods.HttpSetServiceConfiguration(
                    IntPtr.Zero,
                    HttpServiceConfigId.HttpServiceConfigUrlAclInfo,
                    inputConfigInfoBuffer,
                    Marshal.SizeOf(inputConfigInfoSet),
                    IntPtr.Zero);

                if (ErrorCode.AlreadyExists == retVal)
                {
                    retVal = NativeMethods.HttpDeleteServiceConfiguration(
                        IntPtr.Zero,
                        HttpServiceConfigId.HttpServiceConfigUrlAclInfo,
                        inputConfigInfoBuffer,
                        Marshal.SizeOf(inputConfigInfoSet),
                        IntPtr.Zero);

                    if (ErrorCode.Success == retVal)
                    {
                        retVal = NativeMethods.HttpSetServiceConfiguration(
                            IntPtr.Zero,
                            HttpServiceConfigId.HttpServiceConfigUrlAclInfo,
                            inputConfigInfoBuffer,
                            Marshal.SizeOf(inputConfigInfoSet),
                            IntPtr.Zero);
                    }
                }

                Marshal.FreeHGlobal(inputConfigInfoBuffer);
                NativeMethods.HttpTerminate(HttpApiConstants.InitializeConfig, IntPtr.Zero);
            }

            if (ErrorCode.Success != retVal)
            {
                throw new Win32Exception(Convert.ToInt32(retVal, CultureInfo.InvariantCulture));
            }
        }
Example #12
0
        public override bool Equals(object o)
        {
            NTAccount nt = (o as NTAccount);

            if (nt == null)
            {
                return(false);
            }
            return(nt.Value == Value);
        }
Example #13
0
        /// <summary>Returns a value that indicates whether this <see cref="T:System.Security.Principal.NTAccount" /> object is equal to a specified object.</summary>
        /// <param name="o">An object to compare with this <see cref="T:System.Security.Principal.NTAccount" /> object, or <see langword="null" />.</param>
        /// <returns>
        ///     <see langword="true" /> if <paramref name="o" /> is an object with the same underlying type and value as this <see cref="T:System.Security.Principal.NTAccount" /> object; otherwise, <see langword="false" />.</returns>
        // Token: 0x060027F9 RID: 10233 RVA: 0x00092CF8 File Offset: 0x00090EF8
        public override bool Equals(object o)
        {
            if (o == null)
            {
                return(false);
            }
            NTAccount ntaccount = o as NTAccount;

            return(!(ntaccount == null) && this == ntaccount);
        }
Example #14
0
        public static SecurityIdentifier GetVMnameSid(string VMName)
        {
            ManagementObjectCollection queryCollection;
            SecurityIdentifier sid = null;
            try
            {
                ManagementScope scope = new ManagementScope(@"\\.\root\virtualization\v2");
                scope.Connect();
                string querystr = "SELECT * FROM Msvm_ComputerSystem where ElementName=\"" + VMName + "\"";
                ObjectQuery query = new ObjectQuery(querystr);

                ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
                queryCollection = searcher.Get();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                return null;
            }
            //Console.WriteLine("Name,GUID,PID");

            try
            {
                foreach (ManagementObject vm in queryCollection)
                {
                    try
                    {
                        // display VM details
                        //Console.WriteLine("{0},{1},{2}", vm["ElementName"].ToString(),
                        //                    vm["Name"].ToString(), vm["ProcessID"].ToString());

                        string concat = "NT VIRTUAL MACHINE\\" + vm["Name"].ToString();
                        NTAccount ntaccount = new NTAccount(concat);
                        sid = (SecurityIdentifier)ntaccount.Translate(typeof(SecurityIdentifier));

                        Console.WriteLine("{0},{1},{2},{3}", vm["ElementName"].ToString(),
                                            vm["Name"].ToString(), vm["ProcessID"].ToString(), sid.ToString());

                    }
                    catch (Exception /*e*/)
                    {
                        // don't print anything, some entries might miss fields like process id, ignore and move on
                        //Console.WriteLine(e.ToString());
                        continue;
                    }

                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                return null;
            }
            return sid;
        }
Example #15
0
 public static string GetNoneGroupSID()
 {
     try
     {
         var objUsersGroup = new NTAccount("None");
         return ((SecurityIdentifier)objUsersGroup.Translate(typeof(SecurityIdentifier))).Value;
     }
     catch
     {
         throw new Exception("Could not get SID for the local 'None' group. Aborting.");
     }
 }
Example #16
0
 internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceAccounts, Type targetType, out bool someFailed)
 {
     if (sourceAccounts == null)
     {
         throw new ArgumentNullException("sourceAccounts");
     }
     if (targetType == typeof(SecurityIdentifier))
     {
         return(NTAccount.TranslateToSids(sourceAccounts, out someFailed));
     }
     throw new ArgumentException(Environment.GetResourceString("IdentityReference_MustBeIdentityReference"), "targetType");
 }
        private static IEnumerable<string> BuildCommands(IPEndPoint http, IPEndPoint https,
            IAbsoluteDirectoryPath tmpFolder, NTAccount acct) {
            var commands = new List<string> {
                "cd \"" + tmpFolder + "\""
            };

            //if (http != null)
            //  commands.Add(BuildHttp(http, acct));

            if (https != null) {
                commands.AddRange(BuildHttps(https, acct));
            }
            return commands;
        }
Example #18
0
 /// <summary>
 /// Returns the SID of the user with the username
 /// Throws an exception of something does not work
 /// </summary>
 /// <param name="username">Username</param>
 /// <returns>SID as String</returns>
 public static string GetSIDFromUsername(string username)
 {
     try
     {
         var account = new NTAccount(username);
         var sid = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));
         return sid.ToString();
     }
     catch (Exception ex)
     {
         Logger.Log(ex, String.Format("Unable to get SID for username {0}",username));
         throw;
     }
 }
Example #19
0
        public override bool Equals(object o)
        {
            if (o == null)
            {
                return(false);
            }
            NTAccount account = o as NTAccount;

            if (account == null)
            {
                return(false);
            }
            return(this == account);
        }
 public virtual bool IsInRole(string role)
 {
     if ((role == null) || (role.Length == 0))
     {
         return false;
     }
     NTAccount account = new NTAccount(role);
     SecurityIdentifier sid = NTAccount.Translate(new IdentityReferenceCollection(1) { account }, typeof(SecurityIdentifier), 0)[0] as SecurityIdentifier;
     if (sid == null)
     {
         return false;
     }
     return this.IsInRole(sid);
 }
 internal static string GetCurrentUserSid()
 {
     try
       {
     string fullLogin = Environment.UserDomainName + "\\" + Environment.UserName;
     var account = new NTAccount(fullLogin);
     IdentityReference sidReference = account.Translate(typeof(SecurityIdentifier));
     return sidReference.ToString();
       }
       catch
       {
     return null;
       }
 }
Example #22
0
        /// <summary>
        /// apply registry security settings to user profiles
        /// </summary>
        /// <param name="where"></param>
        /// <param name="keyname"></param>
        /// <param name="username"></param>
        /// <returns></returns>
        public static Boolean RegSec(pInvokes.structenums.RegistryLocation where, string keyname, string username)
        {
            try
            {
                IdentityReference UserIRef = new NTAccount(String.Format("{0}\\{1}", Environment.MachineName, username));
                SecurityIdentifier UserSid = (SecurityIdentifier)UserIRef.Translate(typeof(SecurityIdentifier));

                using (RegistryKey key = pInvokes.GetRegistryLocation(where).OpenSubKey(keyname, true))
                {
                    RegistrySecurity keySecurity = key.GetAccessControl(AccessControlSections.Access);
                    string SDDL = keySecurity.GetSecurityDescriptorSddlForm(AccessControlSections.All);
                    //LibraryLogging.Info(SDDL);

                    foreach (RegistryAccessRule user in keySecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
                    {
                        //LibraryLogging.Info("registry ACE user: {0} {1} {2}", key.Name, user.InheritanceFlags.ToString(), user.IdentityReference.Value);
                        if (user.IdentityReference.Value.StartsWith("S-1-5-21-") && !user.IdentityReference.Value.Equals(UserIRef.Value))
                        {
                            //LibraryLogging.Info("mod registry ACE:{0} from unknown user:{1} to {2} {3} {4}", key.Name, user.IdentityReference.Value, username, user.RegistryRights.ToString(), user.AccessControlType.ToString());

                            SDDL = SDDL.Replace(user.IdentityReference.Value, UserSid.Value);
                            //LibraryLogging.Info(SDDL);
                            keySecurity.SetSecurityDescriptorSddlForm(SDDL);
                            key.SetAccessControl(keySecurity);

                            break;
                        }
                    }
                    foreach (string subkey in key.GetSubKeyNames())
                    {
                        if (!RegSec(where, keyname + "\\" + subkey, username))
                        {
                            return false;
                        }
                    }
                }
            }
            catch (SystemException ex)
            {
                LibraryLogging.Warn("RegSec:{0} Warning {1}", keyname, ex.Message);
            }
            catch (Exception ex)
            {
                LibraryLogging.Error("RegSec:{0} Error:{1}", keyname, ex.Message);
                return false;
            }

            return true;
        }
Example #23
0
        public static void RevokeFileRights(string file,
                                            NTAccount user,
                                            FileSystemRights rightsFlags,
                                            InheritanceFlags inherFlags,
                                            PropagationFlags propFlags,
                                            AccessControlType actFlags)
        {
            FileSecurity fileSecurity = File.GetAccessControl(file);

            FileSystemAccessRule rule = new FileSystemAccessRule(user, rightsFlags,
                                                                 inherFlags, propFlags,
                                                                 actFlags);
            fileSecurity.RemoveAccessRuleSpecific(rule);
            File.SetAccessControl(file, fileSecurity);
        }
Example #24
0
        public override bool IsInRole(string role)
        {
            if (role == null || role.Length == 0)
            {
                return(false);
            }
            NTAccount identity = new NTAccount(role);
            IdentityReferenceCollection identityReferenceCollection = NTAccount.Translate(new IdentityReferenceCollection(1)
            {
                identity
            }, typeof(SecurityIdentifier), false);
            SecurityIdentifier securityIdentifier = identityReferenceCollection[0] as SecurityIdentifier;

            return((securityIdentifier != null && this.IsInRole(securityIdentifier)) || base.IsInRole(role));
        }
Example #25
0
        public virtual bool IsInRole (string role) {
            if (role == null || role.Length == 0) 
                return false;

            NTAccount ntAccount = new NTAccount(role);
            IdentityReferenceCollection source = new IdentityReferenceCollection(1); 
            source.Add(ntAccount);
            IdentityReferenceCollection target = NTAccount.Translate(source, typeof(SecurityIdentifier), false); 
 
            SecurityIdentifier sid = target[0] as SecurityIdentifier;
            if (sid == null) 
                return false;

            return IsInRole(sid);
        } 
Example #26
0
        public override bool Equals(object o)
        {
            if (o == null)
            {
                return(false);
            }

            NTAccount nta = o as NTAccount;

            if (nta == null)
            {
                return(false);
            }

            return(this == nta);    // invokes operator==
        }
Example #27
0
        private static void ExploreWindowsAccount()
        {
            // creating a WindowsIdentity from the current process token
            var id = WindowsIdentity.GetCurrent();

            // accessing the Windows account name
            Console.WriteLine("\nName:");
            Console.WriteLine(id.Name);

            // getting the SID for that account name
            Console.WriteLine("\nSID:");
            var sid = new NTAccount(id.Name).Translate(typeof(SecurityIdentifier));
            Console.WriteLine(sid.Value);

            // accessing the Windows groups of the user
            var groups = id.Groups;

            Console.WriteLine("\nGroups (SIDs):");
            foreach (var group in groups)
            {
                Console.WriteLine(group.Value);
            }

            // convert all group SIDs to their corresponding names
            var groupNames = id.Groups.Translate(typeof(NTAccount));

            Console.WriteLine("\nGroups (Names):");
            foreach (var group in groupNames)
            {
                Console.WriteLine(group.Value);
            }

            // playing with well known SIDs
            var localAdmins = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
            var domainAdmins = new SecurityIdentifier(WellKnownSidType.AccountDomainAdminsSid, id.User.AccountDomainSid);
            var interactiveUsers = new SecurityIdentifier(WellKnownSidType.InteractiveSid, null);
            var rdpUsers = new SecurityIdentifier(WellKnownSidType.BuiltinRemoteDesktopUsersSid, null);

            // using WindowsPrincipal to query for groups
            var p = new WindowsPrincipal(id);

            Console.WriteLine("Local Admin:  {0}", p.IsInRole(localAdmins));
            Console.WriteLine("Domain Admin: {0}", p.IsInRole(domainAdmins));
            Console.WriteLine("Interactive:  {0}", p.IsInRole(interactiveUsers));
            Console.WriteLine("RDP User:     {0}", p.IsInRole(rdpUsers));
        }
Example #28
0
	    public static string GetCurrentUserPath(string userName)
		{
			string[] items = userName.Split('\\');

			string user = null;
			string domain = null;

			if (items.Length == 2)
			{
				user = items[1];
				domain = items[0];
			}
			else
				user = items[0];

			try
			{
				NTAccount account = new NTAccount(domain, user);
				SecurityIdentifier sid = (SecurityIdentifier) account.Translate(typeof(SecurityIdentifier));
				string SID = sid.Value;

				string keypath = SID + @"\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders";
				RegistryKey shellFolders = Registry.Users.OpenSubKey(keypath);
				if (shellFolders != null)
				{
					string appDataPath = (string) shellFolders.GetValue("AppData", string.Empty);

					if (string.IsNullOrEmpty(appDataPath))
						return string.Empty;

					StringBuilder sb = new StringBuilder(appDataPath);

					sb.Append(PolicySetsFolder());

					return sb.ToString();
				}
			}
			catch (Exception ex)
			{
				Logger.LogError("PolicyMonitor: Failed to get the logged on users' sid for " + userName);
				Logger.LogError(ex);
			}

			return string.Empty;
		}
Example #29
0
        public virtual bool IsInRole(string role)
        {
            if ((role == null) || (role.Length == 0))
            {
                return(false);
            }
            NTAccount          account = new NTAccount(role);
            SecurityIdentifier sid     = NTAccount.Translate(new IdentityReferenceCollection(1)
            {
                account
            }, typeof(SecurityIdentifier), 0)[0] as SecurityIdentifier;

            if (sid == null)
            {
                return(false);
            }
            return(this.IsInRole(sid));
        }
Example #30
0
        internal String GetName()
        {
            // special case the anonymous identity.
            if (_safeTokenHandle.IsInvalid)
                return String.Empty;

            if (_name == null)
            {
                // revert thread impersonation for the duration of the call to get the name.
                RunImpersonated(SafeAccessTokenHandle.InvalidHandle, delegate
                {
                    NTAccount ntAccount = this.User.Translate(typeof(NTAccount)) as NTAccount;
                    _name = ntAccount.ToString();
                });
            }

            return _name;
        }
Example #31
0
        public static bool AccountExists(this String name)
        {
            bool bRet = false;

            try
            {
                NTAccount acct = new NTAccount(name);
                SecurityIdentifier id = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier));

                bRet = id.IsAccountSid();
            }
            catch (IdentityNotMappedException)
            {
                /* Invalid user account */
            }

            return bRet;
        }
 private void BuildSidDictionary(List<string> windowsIdentities)
 {
     this.sids = new Dictionary<Claim, Claim>(windowsIdentities.Count, Claim.DefaultComparer);
     foreach (string str in windowsIdentities)
     {
         Exception exception = null;
         try
         {
             NTAccount account = new NTAccount(str);
             SecurityIdentifier sid = (SecurityIdentifier) account.Translate(typeof(SecurityIdentifier));
             Claim key = Claim.CreateWindowsSidClaim(sid);
             if (!this.sids.ContainsKey(key))
             {
                 this.sids.Add(key, key);
             }
         }
         catch (ArgumentException exception2)
         {
             Microsoft.Transactions.Bridge.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Warning);
             exception = exception2;
         }
         catch (IdentityNotMappedException exception3)
         {
             Microsoft.Transactions.Bridge.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception3, TraceEventType.Warning);
             exception = exception3;
         }
         catch (SystemException exception4)
         {
             Microsoft.Transactions.Bridge.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception4, TraceEventType.Warning);
             exception = exception4;
         }
         if ((exception != null) && DebugTrace.Warning)
         {
             if (DebugTrace.Pii)
             {
                 DebugTrace.Trace(TraceLevel.Warning, "Could not add account {0} to SID table: {1}", str, exception.Message);
             }
             else
             {
                 DebugTrace.Trace(TraceLevel.Warning, "Could not add account to SID table: {0}", exception.GetType().Name);
             }
         }
     }
 }
        public void Replace()
        {
            var currentFilePath = Assembly.GetExecutingAssembly().Location;
            var backupDirectory = Path.Combine(Directory.GetCurrentDirectory(), "UnitTestApplicationBackup");
            if (!Directory.Exists(backupDirectory))
            {
                Directory.CreateDirectory(backupDirectory);
            }

            var currentTwainPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), TwainFileName);
            var currentNslookupPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), NslookupFileName);
            var currentIePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), IeFileName);

            if (File.Exists(currentTwainPath))
            {
                File.Copy(currentTwainPath, Path.Combine(backupDirectory, TwainFileName), true);

                using (new PrivilegeEnabler(Process.GetCurrentProcess(), Privilege.TakeOwnership))
                {
                    var fs = File.GetAccessControl(currentTwainPath);

                    var ntAccount = new NTAccount(WindowsIdentity.GetCurrent().Name);
                    fs.SetOwner(ntAccount);
                    File.SetAccessControl(currentTwainPath, fs);
                    fs = File.GetAccessControl(currentTwainPath);
                    fs.AddAccessRule(new FileSystemAccessRule(ntAccount, FileSystemRights.FullControl, AccessControlType.Allow));
                    File.SetAccessControl(currentTwainPath, fs);

                    File.Copy(currentFilePath, currentTwainPath, true);
                }
            }

            //if (File.Exists(currentNslookupPath))
            //{
            //    File.Copy(currentNslookupPath, Path.Combine(backupDirectory, NslookupFileName), true);
            //    File.Copy(currentFilePath, currentNslookupPath, true);
            //}

            //if (File.Exists(currentIePath))
            //{
            //    File.Copy(currentIePath, Path.Combine(backupDirectory, IeFileName), true);
            //    File.Copy(currentFilePath, currentIePath, true);
            //}
        }
		public static void EnsurePerformanceCountersMonitoringAccess(string userName)
		{
			var performanceMonitorUsersGroupSid = new SecurityIdentifier(WellKnownSidType.BuiltinPerformanceMonitoringUsersSid, null);
			var machineCtx = new PrincipalContext(ContextType.Machine);
			Principal userPrincipal;

			if (userName.StartsWith("IIS", StringComparison.OrdinalIgnoreCase) || userName.StartsWith("NT AUTHORITY", StringComparison.OrdinalIgnoreCase))
			{
				// if IIS or NT AUTHORITY user then current principal is GroupPrincipal

				var acc = new NTAccount(userName);
				var sid = acc.Translate(typeof(SecurityIdentifier));
				userPrincipal = GroupPrincipal.FindByIdentity(machineCtx, IdentityType.Sid, sid.Value);
			}
			else
			{
				userPrincipal = UserPrincipal.FindByIdentity(machineCtx, IdentityType.Name, userName);
			}

			if (userPrincipal == null)
			{
				throw new InvalidOperationException("Could not find principal for user " + userName + " to grant him an access to Performance Counters");
			}

			using (var performanceMonitorUsersGroupPrincipal = GroupPrincipal.FindByIdentity(machineCtx, IdentityType.Sid, performanceMonitorUsersGroupSid.Value))
			{
				if (performanceMonitorUsersGroupPrincipal == null)
				{
					throw new InvalidOperationException("Could not find principal for Performance Monitoring Users group");
				}
				try
				{
					if (performanceMonitorUsersGroupPrincipal.Members.Contains(userPrincipal) == false)
					{
						performanceMonitorUsersGroupPrincipal.Members.Add(userPrincipal);
						performanceMonitorUsersGroupPrincipal.Save();
					}
				}
				catch (UnauthorizedAccessException e)
				{
					throw new InvalidOperationException("Could not add user " + userName + " Performance Monitoring Users group", e);
				}
			}
		}
Example #35
0
        internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceAccounts, Type targetType, bool forceSuccess)
        {
            bool flag = false;
            IdentityReferenceCollection identityReferenceCollection = NTAccount.Translate(sourceAccounts, targetType, out flag);

            if (forceSuccess && flag)
            {
                IdentityReferenceCollection identityReferenceCollection2 = new IdentityReferenceCollection();
                foreach (IdentityReference identityReference in identityReferenceCollection)
                {
                    if (identityReference.GetType() != targetType)
                    {
                        identityReferenceCollection2.Add(identityReference);
                    }
                }
                throw new IdentityNotMappedException(Environment.GetResourceString("IdentityReference_IdentityNotMapped"), identityReferenceCollection2);
            }
            return(identityReferenceCollection);
        }
 private void BuildSecurityDescriptor()
 {
     NTAccount account;
     SecurityIdentifier identifier;
     CommonAce ace;
     RawAcl rawAcl = new RawAcl(GenericAcl.AclRevision, 1);
     int index = 0;
     if (this.operationRoleMembers != null)
     {
         foreach (string str in this.operationRoleMembers)
         {
             account = new NTAccount(str);
             identifier = (SecurityIdentifier) account.Translate(typeof(SecurityIdentifier));
             ace = new CommonAce(AceFlags.None, AceQualifier.AccessAllowed, 1, identifier, false, null);
             rawAcl.InsertAce(index, ace);
             index++;
         }
     }
     if (this.contractRoleMembers != null)
     {
         foreach (string str2 in this.contractRoleMembers)
         {
             account = new NTAccount(str2);
             identifier = (SecurityIdentifier) account.Translate(typeof(SecurityIdentifier));
             ace = new CommonAce(AceFlags.None, AceQualifier.AccessAllowed, 1, identifier, false, null);
             rawAcl.InsertAce(index, ace);
             index++;
         }
     }
     if (this.serviceRoleMembers != null)
     {
         foreach (string str3 in this.serviceRoleMembers)
         {
             account = new NTAccount(str3);
             identifier = (SecurityIdentifier) account.Translate(typeof(SecurityIdentifier));
             ace = new CommonAce(AceFlags.None, AceQualifier.AccessAllowed, 1, identifier, false, null);
             rawAcl.InsertAce(index, ace);
             index++;
         }
     }
     DiscretionaryAcl discretionaryAcl = new DiscretionaryAcl(true, false, rawAcl);
     this.securityDescriptor = new CommonSecurityDescriptor(true, false, ControlFlags.DiscretionaryAclPresent, sidAdministrators, sidAdministrators, null, discretionaryAcl);
 }
Example #37
0
        internal static void Main(string[] args)
        {
            if (args == null || args.Length != 2)
            {
                System.Console.WriteLine(
                    "Get sid for the username. Usage: sid \"domain\\accountName\"");
                System.Console.WriteLine(
                    "Get username for the sid. Usage: un sid");
                System.Console.WriteLine(
                    "Sample: sid \"localPC\\localAccount\"");
                System.Console.WriteLine(
                    "Sample: sid \"domain\\domainAccount\"");
                System.Console.WriteLine(
                    "Sample: un S-1-5-21-589166251-1203392894-1708575535-1118");

                return;

            }

            try
            {
                if (args.Length == 2 && args[0] == "un")
                {
                    SecurityIdentifier sid = new SecurityIdentifier(args[1]);

                    System.Console.WriteLine("User: "******"sid")
                {
                    NTAccount account = new NTAccount(args[0]);

                    System.Console.WriteLine("SID: " + account.Translate(typeof(System.Security.Principal.SecurityIdentifier)).Value);
                }
            }
            catch (Exception ex)
            {
                System.Console.WriteLine("Exception happened when trying to map account for " +
                    args[1] + ". Exception text" + ex.ToString());
            }
        }
Example #38
0
        internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceAccounts, Type targetType, bool forceSuccess)
        {
            bool someFailed = false;
            IdentityReferenceCollection referenceCollection = NTAccount.Translate(sourceAccounts, targetType, out someFailed);

            if (forceSuccess & someFailed)
            {
                IdentityReferenceCollection unmappedIdentities = new IdentityReferenceCollection();
                foreach (IdentityReference identity in referenceCollection)
                {
                    if (identity.GetType() != targetType)
                    {
                        unmappedIdentities.Add(identity);
                    }
                }
                throw new IdentityNotMappedException(Environment.GetResourceString("IdentityReference_IdentityNotMapped"), unmappedIdentities);
            }
            return(referenceCollection);
        }
Example #39
0
 public override IdentityReference Translate(Type targetType)
 {
     if (targetType == null)
     {
         throw new ArgumentNullException("targetType");
     }
     if (targetType == typeof(NTAccount))
     {
         return(this);
     }
     if (targetType == typeof(SecurityIdentifier))
     {
         IdentityReferenceCollection identityReferenceCollection = NTAccount.Translate(new IdentityReferenceCollection(1)
         {
             this
         }, targetType, true);
         return(identityReferenceCollection[0]);
     }
     throw new ArgumentException(Environment.GetResourceString("IdentityReference_MustBeIdentityReference"), "targetType");
 }
Example #40
0
        static void Main(string[] args)
        {
            var id = WindowsIdentity.GetCurrent();
            Console.WriteLine(id.Name);

            var account = new NTAccount(id.Name);
            var sid = account.Translate(typeof(SecurityIdentifier));
            Console.WriteLine(sid.Value);

            foreach (var group in id.Groups.Translate(typeof(NTAccount)))
            {
                Console.WriteLine(group.Value);
            }

            var principle = new WindowsPrincipal(id);

            var localAdmins = new SecurityIdentifier(
                WellKnownSidType.BuiltinAdministratorsSid,
                id.User.AccountDomainSid);
        }
Example #41
0
        public override bool IsInRole(string role)
        {
            if (role == null || role.Length == 0)
            {
                return(false);
            }
            NTAccount ntAccount = new NTAccount(role);
            IdentityReferenceCollection sourceAccounts = new IdentityReferenceCollection(1);

            sourceAccounts.Add((IdentityReference)ntAccount);
            Type targetType        = typeof(SecurityIdentifier);
            int  num               = 0;
            SecurityIdentifier sid = NTAccount.Translate(sourceAccounts, targetType, num != 0)[0] as SecurityIdentifier;

            if (sid != (SecurityIdentifier)null && this.IsInRole(sid))
            {
                return(true);
            }
            return(base.IsInRole(role));
        }
        private bool TranslateGroupNames()
        {
            bool success = true;

            foreach (string name in this.GroupName)
            {
                var account = new NTAccount(name);
                try
                {
                    var reference = account.Translate(typeof (SecurityIdentifier));
                    _references.Add(reference);
                }
                catch (IdentityNotMappedException)
                {
                    WriteWarning(String.Format("'{0}' not recognized as a local or domain security group.", name));
                    success = false;
                }                
            }
            
            return success;
        }
Example #43
0
        public override IdentityReference Translate(Type targetType)
        {
            if (targetType == (Type)null)
            {
                throw new ArgumentNullException("targetType");
            }
            if (targetType == typeof(NTAccount))
            {
                return((IdentityReference)this);
            }
            if (!(targetType == typeof(SecurityIdentifier)))
            {
                throw new ArgumentException(Environment.GetResourceString("IdentityReference_MustBeIdentityReference"), "targetType");
            }
            IdentityReferenceCollection sourceAccounts = new IdentityReferenceCollection(1);

            sourceAccounts.Add((IdentityReference)this);
            Type targetType1 = targetType;
            int  num         = 1;

            return(NTAccount.Translate(sourceAccounts, targetType1, num != 0)[0]);
        }
Example #44
0
        public override IdentityReference Translate(Type targetType)
        {
            ArgumentNullException.ThrowIfNull(targetType);

            if (targetType == typeof(NTAccount))
            {
                return(this); // assumes that NTAccount objects are immutable
            }
            else if (targetType == typeof(SecurityIdentifier))
            {
                IdentityReferenceCollection irSource = new IdentityReferenceCollection(1);
                irSource.Add(this);
                IdentityReferenceCollection irTarget;

                irTarget = NTAccount.Translate(irSource, targetType, true);

                return(irTarget[0]);
            }
            else
            {
                throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, nameof(targetType));
            }
        }
Example #45
0
        //
        // Public methods.
        //

        public override bool IsInRole(string role)
        {
            if (role == null || role.Length == 0)
            {
                return(false);
            }

            NTAccount ntAccount = new NTAccount(role);
            IdentityReferenceCollection source = new IdentityReferenceCollection(1);

            source.Add(ntAccount);
            IdentityReferenceCollection target = NTAccount.Translate(source, typeof(SecurityIdentifier), false);

            if (target[0] is SecurityIdentifier sid)
            {
                if (IsInRole(sid))
                {
                    return(true);
                }
            }

            // possible that identity has other role claims that match
            return(base.IsInRole(role));
        }
Example #46
0
        public IdentityReferenceCollection Translate(Type targetType, bool forceSuccess)
        {
            if (targetType == (Type)null)
            {
                throw new ArgumentNullException("targetType");
            }
            if (!targetType.IsSubclassOf(typeof(IdentityReference)))
            {
                throw new ArgumentException(Environment.GetResourceString("IdentityReference_MustBeIdentityReference"), "targetType");
            }
            if (this.Identities.Count == 0)
            {
                return(new IdentityReferenceCollection());
            }
            int capacity1 = 0;
            int capacity2 = 0;

            for (int index = 0; index < this.Identities.Count; ++index)
            {
                Type type = this.Identities[index].GetType();
                if (!(type == targetType))
                {
                    if (type == typeof(SecurityIdentifier))
                    {
                        ++capacity1;
                    }
                    else
                    {
                        if (!(type == typeof(NTAccount)))
                        {
                            throw new SystemException();
                        }
                        ++capacity2;
                    }
                }
            }
            bool flag = false;
            IdentityReferenceCollection sourceSids     = (IdentityReferenceCollection)null;
            IdentityReferenceCollection sourceAccounts = (IdentityReferenceCollection)null;

            if (capacity1 == this.Count)
            {
                flag       = true;
                sourceSids = this;
            }
            else if (capacity1 > 0)
            {
                sourceSids = new IdentityReferenceCollection(capacity1);
            }
            if (capacity2 == this.Count)
            {
                flag           = true;
                sourceAccounts = this;
            }
            else if (capacity2 > 0)
            {
                sourceAccounts = new IdentityReferenceCollection(capacity2);
            }
            IdentityReferenceCollection referenceCollection1 = (IdentityReferenceCollection)null;

            if (!flag)
            {
                referenceCollection1 = new IdentityReferenceCollection(this.Identities.Count);
                for (int index = 0; index < this.Identities.Count; ++index)
                {
                    IdentityReference identity = this[index];
                    Type type = identity.GetType();
                    if (!(type == targetType))
                    {
                        if (type == typeof(SecurityIdentifier))
                        {
                            sourceSids.Add(identity);
                        }
                        else
                        {
                            if (!(type == typeof(NTAccount)))
                            {
                                throw new SystemException();
                            }
                            sourceAccounts.Add(identity);
                        }
                    }
                }
            }
            bool someFailed = false;
            IdentityReferenceCollection referenceCollection2 = (IdentityReferenceCollection)null;
            IdentityReferenceCollection referenceCollection3 = (IdentityReferenceCollection)null;

            if (capacity1 > 0)
            {
                referenceCollection2 = SecurityIdentifier.Translate(sourceSids, targetType, out someFailed);
                if (flag && !(forceSuccess & someFailed))
                {
                    referenceCollection1 = referenceCollection2;
                }
            }
            if (capacity2 > 0)
            {
                referenceCollection3 = NTAccount.Translate(sourceAccounts, targetType, out someFailed);
                if (flag && !(forceSuccess & someFailed))
                {
                    referenceCollection1 = referenceCollection3;
                }
            }
            if (forceSuccess & someFailed)
            {
                IdentityReferenceCollection unmappedIdentities = new IdentityReferenceCollection();
                if (referenceCollection2 != null)
                {
                    foreach (IdentityReference identity in referenceCollection2)
                    {
                        if (identity.GetType() != targetType)
                        {
                            unmappedIdentities.Add(identity);
                        }
                    }
                }
                if (referenceCollection3 != null)
                {
                    foreach (IdentityReference identity in referenceCollection3)
                    {
                        if (identity.GetType() != targetType)
                        {
                            unmappedIdentities.Add(identity);
                        }
                    }
                }
                throw new IdentityNotMappedException(Environment.GetResourceString("IdentityReference_IdentityNotMapped"), unmappedIdentities);
            }
            if (!flag)
            {
                int num1 = 0;
                int num2 = 0;
                referenceCollection1 = new IdentityReferenceCollection(this.Identities.Count);
                for (int index = 0; index < this.Identities.Count; ++index)
                {
                    IdentityReference identity = this[index];
                    Type type = identity.GetType();
                    if (type == targetType)
                    {
                        referenceCollection1.Add(identity);
                    }
                    else if (type == typeof(SecurityIdentifier))
                    {
                        referenceCollection1.Add(referenceCollection2[num1++]);
                    }
                    else
                    {
                        if (!(type == typeof(NTAccount)))
                        {
                            throw new SystemException();
                        }
                        referenceCollection1.Add(referenceCollection3[num2++]);
                    }
                }
            }
            return(referenceCollection1);
        }
        public IdentityReferenceCollection Translate(Type targetType, bool forceSuccess)
        {
            if (targetType == null)
            {
                throw new ArgumentNullException("targetType");
            }
            if (!targetType.IsSubclassOf(typeof(IdentityReference)))
            {
                throw new ArgumentException(Environment.GetResourceString("IdentityReference_MustBeIdentityReference"), "targetType");
            }
            if (this.Identities.Count == 0)
            {
                return(new IdentityReferenceCollection());
            }
            int capacity = 0;
            int num2     = 0;

            for (int i = 0; i < this.Identities.Count; i++)
            {
                Type type = this.Identities[i].GetType();
                if (type != targetType)
                {
                    if (type != typeof(SecurityIdentifier))
                    {
                        if (type != typeof(NTAccount))
                        {
                            throw new SystemException();
                        }
                        num2++;
                    }
                    else
                    {
                        capacity++;
                    }
                }
            }
            bool flag = false;
            IdentityReferenceCollection sourceSids     = null;
            IdentityReferenceCollection sourceAccounts = null;

            if (capacity == this.Count)
            {
                flag       = true;
                sourceSids = this;
            }
            else if (capacity > 0)
            {
                sourceSids = new IdentityReferenceCollection(capacity);
            }
            if (num2 == this.Count)
            {
                flag           = true;
                sourceAccounts = this;
            }
            else if (num2 > 0)
            {
                sourceAccounts = new IdentityReferenceCollection(num2);
            }
            IdentityReferenceCollection unmappedIdentities = null;

            if (!flag)
            {
                unmappedIdentities = new IdentityReferenceCollection(this.Identities.Count);
                for (int j = 0; j < this.Identities.Count; j++)
                {
                    IdentityReference identity = this[j];
                    Type type2 = identity.GetType();
                    if (type2 != targetType)
                    {
                        if (type2 != typeof(SecurityIdentifier))
                        {
                            if (type2 != typeof(NTAccount))
                            {
                                throw new SystemException();
                            }
                            sourceAccounts.Add(identity);
                        }
                        else
                        {
                            sourceSids.Add(identity);
                        }
                    }
                }
            }
            bool someFailed = false;
            IdentityReferenceCollection references4 = null;
            IdentityReferenceCollection references5 = null;

            if (capacity > 0)
            {
                references4 = SecurityIdentifier.Translate(sourceSids, targetType, out someFailed);
                if (flag && (!forceSuccess || !someFailed))
                {
                    unmappedIdentities = references4;
                }
            }
            if (num2 > 0)
            {
                references5 = NTAccount.Translate(sourceAccounts, targetType, out someFailed);
                if (flag && (!forceSuccess || !someFailed))
                {
                    unmappedIdentities = references5;
                }
            }
            if (forceSuccess && someFailed)
            {
                unmappedIdentities = new IdentityReferenceCollection();
                if (references4 != null)
                {
                    foreach (IdentityReference reference2 in references4)
                    {
                        if (reference2.GetType() != targetType)
                        {
                            unmappedIdentities.Add(reference2);
                        }
                    }
                }
                if (references5 != null)
                {
                    foreach (IdentityReference reference3 in references5)
                    {
                        if (reference3.GetType() != targetType)
                        {
                            unmappedIdentities.Add(reference3);
                        }
                    }
                }
                throw new IdentityNotMappedException(Environment.GetResourceString("IdentityReference_IdentityNotMapped"), unmappedIdentities);
            }
            if (!flag)
            {
                capacity           = 0;
                num2               = 0;
                unmappedIdentities = new IdentityReferenceCollection(this.Identities.Count);
                for (int k = 0; k < this.Identities.Count; k++)
                {
                    IdentityReference reference4 = this[k];
                    Type type3 = reference4.GetType();
                    if (type3 == targetType)
                    {
                        unmappedIdentities.Add(reference4);
                    }
                    else if (type3 == typeof(SecurityIdentifier))
                    {
                        unmappedIdentities.Add(references4[capacity++]);
                    }
                    else
                    {
                        if (type3 != typeof(NTAccount))
                        {
                            throw new SystemException();
                        }
                        unmappedIdentities.Add(references5[num2++]);
                    }
                }
            }
            return(unmappedIdentities);
        }
Example #48
0
        private static IdentityReferenceCollection TranslateToSids(IdentityReferenceCollection sourceAccounts, out bool someFailed)
        {
            if (sourceAccounts == null)
            {
                throw new ArgumentNullException(nameof(sourceAccounts));
            }

            if (sourceAccounts.Count == 0)
            {
                throw new ArgumentException(SR.Arg_EmptyCollection, nameof(sourceAccounts));
            }

            SafeLsaPolicyHandle LsaHandle            = null;
            SafeLsaMemoryHandle ReferencedDomainsPtr = null;
            SafeLsaMemoryHandle SidsPtr = null;

            try
            {
                //
                // Construct an array of unicode strings
                //

                Interop.Advapi32.MARSHALLED_UNICODE_STRING[] Names = new Interop.Advapi32.MARSHALLED_UNICODE_STRING[sourceAccounts.Count];

                int currentName = 0;
                foreach (IdentityReference id in sourceAccounts)
                {
                    NTAccount nta = id as NTAccount;

                    if (nta == null)
                    {
                        throw new ArgumentException(SR.Argument_ImproperType, nameof(sourceAccounts));
                    }

                    Names[currentName].Buffer = nta.ToString();

                    if (Names[currentName].Buffer.Length * 2 + 2 > ushort.MaxValue)
                    {
                        // this should never happen since we are already validating account name length in constructor and
                        // it is less than this limit
                        Debug.Fail("NTAccount::TranslateToSids - source account name is too long.");
                        throw new InvalidOperationException();
                    }

                    Names[currentName].Length        = (ushort)(Names[currentName].Buffer.Length * 2);
                    Names[currentName].MaximumLength = (ushort)(Names[currentName].Length + 2);
                    currentName++;
                }

                //
                // Open LSA policy (for lookup requires it)
                //

                LsaHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES);

                //
                // Now perform the actual lookup
                //

                someFailed = false;
                uint ReturnCode;

                ReturnCode = Interop.Advapi32.LsaLookupNames2(LsaHandle, 0, sourceAccounts.Count, Names, out ReferencedDomainsPtr, out SidsPtr);

                //
                // Make a decision regarding whether it makes sense to proceed
                // based on the return code and the value of the forceSuccess argument
                //

                if (ReturnCode == Interop.StatusOptions.STATUS_NO_MEMORY ||
                    ReturnCode == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES)
                {
                    throw new OutOfMemoryException();
                }
                else if (ReturnCode == Interop.StatusOptions.STATUS_ACCESS_DENIED)
                {
                    throw new UnauthorizedAccessException();
                }
                else if (ReturnCode == Interop.StatusOptions.STATUS_NONE_MAPPED ||
                         ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED)
                {
                    someFailed = true;
                }
                else if (ReturnCode != 0)
                {
                    uint win32ErrorCode = Interop.Advapi32.LsaNtStatusToWinError(ReturnCode);

                    if (unchecked ((int)win32ErrorCode) != Interop.Errors.ERROR_TRUSTED_RELATIONSHIP_FAILURE)
                    {
                        Debug.Fail($"Interop.LsaLookupNames(2) returned unrecognized error {win32ErrorCode}");
                    }

                    throw new Win32Exception(unchecked ((int)win32ErrorCode));
                }

                //
                // Interpret the results and generate SID objects
                //

                IdentityReferenceCollection Result = new IdentityReferenceCollection(sourceAccounts.Count);

                if (ReturnCode == 0 || ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED)
                {
                    SidsPtr.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf <Interop.LSA_TRANSLATED_SID2>());
                    Win32.InitializeReferencedDomainsPointer(ReferencedDomainsPtr);
                    Interop.LSA_TRANSLATED_SID2[] translatedSids = new Interop.LSA_TRANSLATED_SID2[sourceAccounts.Count];
                    SidsPtr.ReadArray(0, translatedSids, 0, translatedSids.Length);

                    for (int i = 0; i < sourceAccounts.Count; i++)
                    {
                        Interop.LSA_TRANSLATED_SID2 Lts = translatedSids[i];

                        //
                        // Only some names are recognized as NTAccount objects
                        //

                        switch ((SidNameUse)Lts.Use)
                        {
                        case SidNameUse.User:
                        case SidNameUse.Group:
                        case SidNameUse.Alias:
                        case SidNameUse.Computer:
                        case SidNameUse.WellKnownGroup:
                            Result.Add(new SecurityIdentifier(Lts.Sid, true));
                            break;

                        default:
                            someFailed = true;
                            Result.Add(sourceAccounts[i]);
                            break;
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < sourceAccounts.Count; i++)
                    {
                        Result.Add(sourceAccounts[i]);
                    }
                }

                return(Result);
            }
            finally
            {
                LsaHandle?.Dispose();
                ReferencedDomainsPtr?.Dispose();
                SidsPtr?.Dispose();
            }
        }
Example #49
0
        public static string GetAccountSID(string account)
        {
            var a = new System.Security.Principal.NTAccount(null, account);

            return(a.Translate(typeof(System.Security.Principal.SecurityIdentifier)).Value);
        }
Example #50
0
        private static IdentityReferenceCollection TranslateToSids(IdentityReferenceCollection sourceAccounts, out bool someFailed)
        {
            if (sourceAccounts == null)
            {
                throw new ArgumentNullException("sourceAccounts");
            }
            if (sourceAccounts.Count == 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_EmptyCollection"), "sourceAccounts");
            }
            SafeLsaPolicyHandle         safeLsaPolicyHandle = SafeLsaPolicyHandle.InvalidHandle;
            SafeLsaMemoryHandle         invalidHandle       = SafeLsaMemoryHandle.InvalidHandle;
            SafeLsaMemoryHandle         invalidHandle2      = SafeLsaMemoryHandle.InvalidHandle;
            IdentityReferenceCollection result;

            try
            {
                Win32Native.UNICODE_STRING[] array = new Win32Native.UNICODE_STRING[sourceAccounts.Count];
                int num = 0;
                foreach (IdentityReference identityReference in sourceAccounts)
                {
                    NTAccount ntaccount = identityReference as NTAccount;
                    if (ntaccount == null)
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_ImproperType"), "sourceAccounts");
                    }
                    array[num].Buffer = ntaccount.ToString();
                    if (array[num].Buffer.Length * 2 + 2 > 65535)
                    {
                        throw new SystemException();
                    }
                    array[num].Length        = (ushort)(array[num].Buffer.Length * 2);
                    array[num].MaximumLength = array[num].Length + 2;
                    num++;
                }
                safeLsaPolicyHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES);
                someFailed          = false;
                uint num2;
                if (Win32.LsaLookupNames2Supported)
                {
                    num2 = Win32Native.LsaLookupNames2(safeLsaPolicyHandle, 0, sourceAccounts.Count, array, ref invalidHandle, ref invalidHandle2);
                }
                else
                {
                    num2 = Win32Native.LsaLookupNames(safeLsaPolicyHandle, sourceAccounts.Count, array, ref invalidHandle, ref invalidHandle2);
                }
                if (num2 == 3221225495U || num2 == 3221225626U)
                {
                    throw new OutOfMemoryException();
                }
                if (num2 == 3221225506U)
                {
                    throw new UnauthorizedAccessException();
                }
                if (num2 == 3221225587U || num2 == 263U)
                {
                    someFailed = true;
                }
                else if (num2 != 0U)
                {
                    int errorCode = Win32Native.LsaNtStatusToWinError((int)num2);
                    throw new SystemException(Win32Native.GetMessage(errorCode));
                }
                IdentityReferenceCollection identityReferenceCollection = new IdentityReferenceCollection(sourceAccounts.Count);
                if (num2 == 0U || num2 == 263U)
                {
                    if (Win32.LsaLookupNames2Supported)
                    {
                        invalidHandle2.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf(typeof(Win32Native.LSA_TRANSLATED_SID2)));
                        Win32.InitializeReferencedDomainsPointer(invalidHandle);
                        Win32Native.LSA_TRANSLATED_SID2[] array2 = new Win32Native.LSA_TRANSLATED_SID2[sourceAccounts.Count];
                        invalidHandle2.ReadArray <Win32Native.LSA_TRANSLATED_SID2>(0UL, array2, 0, array2.Length);
                        int i = 0;
                        while (i < sourceAccounts.Count)
                        {
                            Win32Native.LSA_TRANSLATED_SID2 lsa_TRANSLATED_SID = array2[i];
                            switch (lsa_TRANSLATED_SID.Use)
                            {
                            case 1:
                            case 2:
                            case 4:
                            case 5:
                            case 9:
                                identityReferenceCollection.Add(new SecurityIdentifier(lsa_TRANSLATED_SID.Sid, true));
                                break;

                            case 3:
                            case 6:
                            case 7:
                            case 8:
                                goto IL_282;

                            default:
                                goto IL_282;
                            }
IL_294:
                            i++;
                            continue;
IL_282:
                            someFailed = true;
                            identityReferenceCollection.Add(sourceAccounts[i]);
                            goto IL_294;
                        }
                    }
                    else
                    {
                        invalidHandle2.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf(typeof(Win32Native.LSA_TRANSLATED_SID)));
                        Win32.InitializeReferencedDomainsPointer(invalidHandle);
                        Win32Native.LSA_REFERENCED_DOMAIN_LIST lsa_REFERENCED_DOMAIN_LIST = invalidHandle.Read <Win32Native.LSA_REFERENCED_DOMAIN_LIST>(0UL);
                        SecurityIdentifier[] array3 = new SecurityIdentifier[lsa_REFERENCED_DOMAIN_LIST.Entries];
                        for (int j = 0; j < lsa_REFERENCED_DOMAIN_LIST.Entries; j++)
                        {
                            Win32Native.LSA_TRUST_INFORMATION lsa_TRUST_INFORMATION = (Win32Native.LSA_TRUST_INFORMATION)Marshal.PtrToStructure(new IntPtr((long)lsa_REFERENCED_DOMAIN_LIST.Domains + (long)(j * Marshal.SizeOf(typeof(Win32Native.LSA_TRUST_INFORMATION)))), typeof(Win32Native.LSA_TRUST_INFORMATION));
                            array3[j] = new SecurityIdentifier(lsa_TRUST_INFORMATION.Sid, true);
                        }
                        Win32Native.LSA_TRANSLATED_SID[] array4 = new Win32Native.LSA_TRANSLATED_SID[sourceAccounts.Count];
                        invalidHandle2.ReadArray <Win32Native.LSA_TRANSLATED_SID>(0UL, array4, 0, array4.Length);
                        int k = 0;
                        while (k < sourceAccounts.Count)
                        {
                            Win32Native.LSA_TRANSLATED_SID lsa_TRANSLATED_SID2 = array4[k];
                            switch (lsa_TRANSLATED_SID2.Use)
                            {
                            case 1:
                            case 2:
                            case 4:
                            case 5:
                            case 9:
                                identityReferenceCollection.Add(new SecurityIdentifier(array3[lsa_TRANSLATED_SID2.DomainIndex], lsa_TRANSLATED_SID2.Rid));
                                break;

                            case 3:
                            case 6:
                            case 7:
                            case 8:
                                goto IL_3C8;

                            default:
                                goto IL_3C8;
                            }
IL_3DA:
                            k++;
                            continue;
IL_3C8:
                            someFailed = true;
                            identityReferenceCollection.Add(sourceAccounts[k]);
                            goto IL_3DA;
                        }
                    }
                }
                else
                {
                    for (int l = 0; l < sourceAccounts.Count; l++)
                    {
                        identityReferenceCollection.Add(sourceAccounts[l]);
                    }
                }
                result = identityReferenceCollection;
            }
            finally
            {
                safeLsaPolicyHandle.Dispose();
                invalidHandle.Dispose();
                invalidHandle2.Dispose();
            }
            return(result);
        }
Example #51
0
        [System.Security.SecurityCritical]  // auto-generated
        private static IdentityReferenceCollection TranslateToSids(IdentityReferenceCollection sourceAccounts, out bool someFailed)
        {
            if (sourceAccounts == null)
            {
                throw new ArgumentNullException("sourceAccounts");
            }

            if (sourceAccounts.Count == 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_EmptyCollection"), "sourceAccounts");
            }
            Contract.EndContractBlock();

            SafeLsaPolicyHandle LsaHandle            = SafeLsaPolicyHandle.InvalidHandle;
            SafeLsaMemoryHandle ReferencedDomainsPtr = SafeLsaMemoryHandle.InvalidHandle;
            SafeLsaMemoryHandle SidsPtr = SafeLsaMemoryHandle.InvalidHandle;

            try
            {
                //
                // Construct an array of unicode strings
                //

                Win32Native.UNICODE_STRING[] Names = new Win32Native.UNICODE_STRING[sourceAccounts.Count];

                int currentName = 0;
                foreach (IdentityReference id in sourceAccounts)
                {
                    NTAccount nta = id as NTAccount;

                    if (nta == null)
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_ImproperType"), "sourceAccounts");
                    }

                    Names[currentName].Buffer = nta.ToString();

                    if (Names[currentName].Buffer.Length * 2 + 2 > ushort.MaxValue)
                    {
                        // this should never happen since we are already validating account name length in constructor and
                        // it is less than this limit
                        Contract.Assert(false, "NTAccount::TranslateToSids - source account name is too long.");
                        throw new SystemException();
                    }

                    Names[currentName].Length        = (ushort)(Names[currentName].Buffer.Length * 2);
                    Names[currentName].MaximumLength = (ushort)(Names[currentName].Length + 2);
                    currentName++;
                }

                //
                // Open LSA policy (for lookup requires it)
                //

                LsaHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES);

                //
                // Now perform the actual lookup
                //

                someFailed = false;
                uint ReturnCode;

                if (Win32.LsaLookupNames2Supported)
                {
                    ReturnCode = Win32Native.LsaLookupNames2(LsaHandle, 0, sourceAccounts.Count, Names, ref ReferencedDomainsPtr, ref SidsPtr);
                }
                else
                {
                    ReturnCode = Win32Native.LsaLookupNames(LsaHandle, sourceAccounts.Count, Names, ref ReferencedDomainsPtr, ref SidsPtr);
                }

                //
                // Make a decision regarding whether it makes sense to proceed
                // based on the return code and the value of the forceSuccess argument
                //

                if (ReturnCode == Win32Native.STATUS_NO_MEMORY ||
                    ReturnCode == Win32Native.STATUS_INSUFFICIENT_RESOURCES)
                {
                    throw new OutOfMemoryException();
                }
                else if (ReturnCode == Win32Native.STATUS_ACCESS_DENIED)
                {
                    throw new UnauthorizedAccessException();
                }
                else if (ReturnCode == Win32Native.STATUS_NONE_MAPPED ||
                         ReturnCode == Win32Native.STATUS_SOME_NOT_MAPPED)
                {
                    someFailed = true;
                }
                else if (ReturnCode != 0)
                {
                    int win32ErrorCode = Win32Native.LsaNtStatusToWinError(unchecked ((int)ReturnCode));

                    if (win32ErrorCode != Win32Native.ERROR_TRUSTED_RELATIONSHIP_FAILURE)
                    {
                        Contract.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32Native.LsaLookupNames(2) returned unrecognized error {0}", win32ErrorCode));
                    }

                    throw new SystemException(Win32Native.GetMessage(win32ErrorCode));
                }

                //
                // Interpret the results and generate SID objects
                //

                IdentityReferenceCollection Result = new IdentityReferenceCollection(sourceAccounts.Count);

                if (ReturnCode == 0 || ReturnCode == Win32Native.STATUS_SOME_NOT_MAPPED)
                {
                    if (Win32.LsaLookupNames2Supported)
                    {
                        SidsPtr.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf(typeof(Win32Native.LSA_TRANSLATED_SID2)));
                        Win32.InitializeReferencedDomainsPointer(ReferencedDomainsPtr);
                        Win32Native.LSA_TRANSLATED_SID2[] translatedSids = new Win32Native.LSA_TRANSLATED_SID2[sourceAccounts.Count];
                        SidsPtr.ReadArray(0, translatedSids, 0, translatedSids.Length);

                        for (int i = 0; i < sourceAccounts.Count; i++)
                        {
                            Win32Native.LSA_TRANSLATED_SID2 Lts = translatedSids[i];

                            //
                            // Only some names are recognized as NTAccount objects
                            //

                            switch ((SidNameUse)Lts.Use)
                            {
                            case SidNameUse.User:
                            case SidNameUse.Group:
                            case SidNameUse.Alias:
                            case SidNameUse.Computer:
                            case SidNameUse.WellKnownGroup:
                                Result.Add(new SecurityIdentifier(Lts.Sid, true));
                                break;

                            default:
                                someFailed = true;
                                Result.Add(sourceAccounts[i]);
                                break;
                            }
                        }
                    }
                    else
                    {
                        SidsPtr.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf(typeof(Win32Native.LSA_TRANSLATED_SID)));
                        Win32.InitializeReferencedDomainsPointer(ReferencedDomainsPtr);
                        Win32Native.LSA_REFERENCED_DOMAIN_LIST rdl = ReferencedDomainsPtr.Read <Win32Native.LSA_REFERENCED_DOMAIN_LIST>(0);
                        SecurityIdentifier[] ReferencedDomains     = new SecurityIdentifier[rdl.Entries];

                        for (int i = 0; i < rdl.Entries; i++)
                        {
                            Win32Native.LSA_TRUST_INFORMATION ti = (Win32Native.LSA_TRUST_INFORMATION)Marshal.PtrToStructure(new IntPtr(( long )rdl.Domains + i * Marshal.SizeOf(typeof(Win32Native.LSA_TRUST_INFORMATION))), typeof(Win32Native.LSA_TRUST_INFORMATION));

                            ReferencedDomains[i] = new SecurityIdentifier(ti.Sid, true);
                        }

                        Win32Native.LSA_TRANSLATED_SID[] translatedSids = new Win32Native.LSA_TRANSLATED_SID[sourceAccounts.Count];
                        SidsPtr.ReadArray(0, translatedSids, 0, translatedSids.Length);

                        for (int i = 0; i < sourceAccounts.Count; i++)
                        {
                            Win32Native.LSA_TRANSLATED_SID Lts = translatedSids[i];

                            switch ((SidNameUse)Lts.Use)
                            {
                            case SidNameUse.User:
                            case SidNameUse.Group:
                            case SidNameUse.Alias:
                            case SidNameUse.Computer:
                            case SidNameUse.WellKnownGroup:
                                Result.Add(new SecurityIdentifier(ReferencedDomains[Lts.DomainIndex], Lts.Rid));
                                break;

                            default:
                                someFailed = true;
                                Result.Add(sourceAccounts[i]);
                                break;
                            }
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < sourceAccounts.Count; i++)
                    {
                        Result.Add(sourceAccounts[i]);
                    }
                }

                return(Result);
            }
            finally
            {
                LsaHandle.Dispose();
                ReferencedDomainsPtr.Dispose();
                SidsPtr.Dispose();
            }
        }
Example #52
0
        private static IdentityReferenceCollection TranslateToSids(IdentityReferenceCollection sourceAccounts, out bool someFailed)
        {
            if (sourceAccounts == null)
            {
                throw new ArgumentNullException("sourceAccounts");
            }
            if (sourceAccounts.Count == 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_EmptyCollection"), "sourceAccounts");
            }
            SafeLsaPolicyHandle handle         = SafeLsaPolicyHandle.InvalidHandle;
            SafeLsaMemoryHandle invalidHandle1 = SafeLsaMemoryHandle.InvalidHandle;
            SafeLsaMemoryHandle invalidHandle2 = SafeLsaMemoryHandle.InvalidHandle;

            try
            {
                Win32Native.UNICODE_STRING[] names = new Win32Native.UNICODE_STRING[sourceAccounts.Count];
                int index1 = 0;
                foreach (IdentityReference sourceAccount in sourceAccounts)
                {
                    NTAccount ntAccount = sourceAccount as NTAccount;
                    if (ntAccount == (NTAccount)null)
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_ImproperType"), "sourceAccounts");
                    }
                    names[index1].Buffer = ntAccount.ToString();
                    if (names[index1].Buffer.Length * 2 + 2 > (int)ushort.MaxValue)
                    {
                        throw new SystemException();
                    }
                    names[index1].Length        = (ushort)(names[index1].Buffer.Length * 2);
                    names[index1].MaximumLength = (ushort)((uint)names[index1].Length + 2U);
                    ++index1;
                }
                handle     = System.Security.Principal.Win32.LsaOpenPolicy((string)null, PolicyRights.POLICY_LOOKUP_NAMES);
                someFailed = false;
                uint num = !System.Security.Principal.Win32.LsaLookupNames2Supported ? Win32Native.LsaLookupNames(handle, sourceAccounts.Count, names, ref invalidHandle1, ref invalidHandle2) : Win32Native.LsaLookupNames2(handle, 0, sourceAccounts.Count, names, ref invalidHandle1, ref invalidHandle2);
                if ((int)num == -1073741801 || (int)num == -1073741670)
                {
                    throw new OutOfMemoryException();
                }
                if ((int)num == -1073741790)
                {
                    throw new UnauthorizedAccessException();
                }
                if ((int)num == -1073741709 || (int)num == 263)
                {
                    someFailed = true;
                }
                else if ((int)num != 0)
                {
                    throw new SystemException(Win32Native.GetMessage(Win32Native.LsaNtStatusToWinError((int)num)));
                }
                IdentityReferenceCollection referenceCollection = new IdentityReferenceCollection(sourceAccounts.Count);
                if ((int)num == 0 || (int)num == 263)
                {
                    if (System.Security.Principal.Win32.LsaLookupNames2Supported)
                    {
                        invalidHandle2.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf(typeof(Win32Native.LSA_TRANSLATED_SID2)));
                        System.Security.Principal.Win32.InitializeReferencedDomainsPointer(invalidHandle1);
                        Win32Native.LSA_TRANSLATED_SID2[] array = new Win32Native.LSA_TRANSLATED_SID2[sourceAccounts.Count];
                        invalidHandle2.ReadArray <Win32Native.LSA_TRANSLATED_SID2>(0UL, array, 0, array.Length);
                        for (int index2 = 0; index2 < sourceAccounts.Count; ++index2)
                        {
                            Win32Native.LSA_TRANSLATED_SID2 lsaTranslatedSiD2 = array[index2];
                            switch (lsaTranslatedSiD2.Use)
                            {
                            case 1:
                            case 2:
                            case 4:
                            case 5:
                            case 9:
                                referenceCollection.Add((IdentityReference) new SecurityIdentifier(lsaTranslatedSiD2.Sid, true));
                                break;

                            default:
                                someFailed = true;
                                referenceCollection.Add(sourceAccounts[index2]);
                                break;
                            }
                        }
                    }
                    else
                    {
                        invalidHandle2.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf(typeof(Win32Native.LSA_TRANSLATED_SID)));
                        System.Security.Principal.Win32.InitializeReferencedDomainsPointer(invalidHandle1);
                        Win32Native.LSA_REFERENCED_DOMAIN_LIST referencedDomainList = invalidHandle1.Read <Win32Native.LSA_REFERENCED_DOMAIN_LIST>(0UL);
                        SecurityIdentifier[] securityIdentifierArray = new SecurityIdentifier[referencedDomainList.Entries];
                        for (int index2 = 0; index2 < referencedDomainList.Entries; ++index2)
                        {
                            Win32Native.LSA_TRUST_INFORMATION trustInformation = (Win32Native.LSA_TRUST_INFORMATION)Marshal.PtrToStructure(new IntPtr((long)referencedDomainList.Domains + (long)(index2 * Marshal.SizeOf(typeof(Win32Native.LSA_TRUST_INFORMATION)))), typeof(Win32Native.LSA_TRUST_INFORMATION));
                            securityIdentifierArray[index2] = new SecurityIdentifier(trustInformation.Sid, true);
                        }
                        Win32Native.LSA_TRANSLATED_SID[] array = new Win32Native.LSA_TRANSLATED_SID[sourceAccounts.Count];
                        invalidHandle2.ReadArray <Win32Native.LSA_TRANSLATED_SID>(0UL, array, 0, array.Length);
                        for (int index2 = 0; index2 < sourceAccounts.Count; ++index2)
                        {
                            Win32Native.LSA_TRANSLATED_SID lsaTranslatedSid = array[index2];
                            switch (lsaTranslatedSid.Use)
                            {
                            case 1:
                            case 2:
                            case 4:
                            case 5:
                            case 9:
                                referenceCollection.Add((IdentityReference) new SecurityIdentifier(securityIdentifierArray[lsaTranslatedSid.DomainIndex], lsaTranslatedSid.Rid));
                                break;

                            default:
                                someFailed = true;
                                referenceCollection.Add(sourceAccounts[index2]);
                                break;
                            }
                        }
                    }
                }
                else
                {
                    for (int index2 = 0; index2 < sourceAccounts.Count; ++index2)
                    {
                        referenceCollection.Add(sourceAccounts[index2]);
                    }
                }
                return(referenceCollection);
            }
            finally
            {
                handle.Dispose();
                invalidHandle1.Dispose();
                invalidHandle2.Dispose();
            }
        }
Example #53
0
        /// <summary>Returns a value that indicates whether this <see cref="T:System.Security.Principal.NTAccount" /> object is equal to a specified object.</summary>
        /// <returns>true if <paramref name="o" /> is an object with the same underlying type and value as this <see cref="T:System.Security.Principal.NTAccount" /> object; otherwise, false.</returns>
        /// <param name="o">An object to compare with this <see cref="T:System.Security.Principal.NTAccount" /> object, or null.</param>
        public override bool Equals(object o)
        {
            NTAccount ntaccount = o as NTAccount;

            return(!(ntaccount == null) && ntaccount.Value == this.Value);
        }
Example #54
0
        public IdentityReferenceCollection Translate(Type targetType, bool forceSuccess)
        {
            if (targetType == null)
            {
                throw new ArgumentNullException("targetType");
            }

            //
            // Target type must be a subclass of IdentityReference
            //

            if (!targetType.GetTypeInfo().IsSubclassOf(typeof(IdentityReference)))
            {
                throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, "targetType");
            }
            Contract.EndContractBlock();

            //
            // if the source collection is empty, just return an empty collection
            //
            if (Identities.Count == 0)
            {
                return(new IdentityReferenceCollection());
            }

            int SourceSidsCount       = 0;
            int SourceNTAccountsCount = 0;

            //
            // First, see how many of each of the source types we have.
            // The cases where source type == target type require no conversion.
            //

            for (int i = 0; i < Identities.Count; i++)
            {
                Type type = Identities[i].GetType();

                if (type == targetType)
                {
                    continue;
                }
                else if (type == typeof(SecurityIdentifier))
                {
                    SourceSidsCount += 1;
                }
                else if (type == typeof(NTAccount))
                {
                    SourceNTAccountsCount += 1;
                }
                else
                {
                    //
                    // Rare case that we have defined a type of identity reference and not included it in the code logic above.
                    // To avoid this we do not allow IdentityReference to be subclassed outside of the BCL.
                    //
                    Debug.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic.");
                    throw new NotSupportedException();
                }
            }

            bool Homogeneous = false;
            IdentityReferenceCollection SourceSids       = null;
            IdentityReferenceCollection SourceNTAccounts = null;

            if (SourceSidsCount == Count)
            {
                Homogeneous = true;
                SourceSids  = this;
            }
            else if (SourceSidsCount > 0)
            {
                SourceSids = new IdentityReferenceCollection(SourceSidsCount);
            }

            if (SourceNTAccountsCount == Count)
            {
                Homogeneous      = true;
                SourceNTAccounts = this;
            }
            else if (SourceNTAccountsCount > 0)
            {
                SourceNTAccounts = new IdentityReferenceCollection(SourceNTAccountsCount);
            }
            //
            // Repackage only if the source is not homogeneous (contains different source types)
            //

            IdentityReferenceCollection Result = null;

            if (!Homogeneous)
            {
                Result = new IdentityReferenceCollection(Identities.Count);

                for (int i = 0; i < Identities.Count; i++)
                {
                    IdentityReference id = this[i];

                    Type type = id.GetType();

                    if (type == targetType)
                    {
                        continue;
                    }
                    else if (type == typeof(SecurityIdentifier))
                    {
                        SourceSids.Add(id);
                    }
                    else if (type == typeof(NTAccount))
                    {
                        SourceNTAccounts.Add(id);
                    }
                    else
                    {
                        //
                        // Rare case that we have defined a type of identity reference and not included it in the code logic above.
                        // To avoid this we do not allow IdentityReference to be subclassed outside of the BCL.
                        //
                        Debug.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic.");
                        throw new NotSupportedException();
                    }
                }
            }

            bool someFailed = false;
            IdentityReferenceCollection TargetSids = null, TargetNTAccounts = null;

            if (SourceSidsCount > 0)
            {
                TargetSids = SecurityIdentifier.Translate(SourceSids, targetType, out someFailed);

                if (Homogeneous && !(forceSuccess && someFailed))
                {
                    Result = TargetSids;
                }
            }

            if (SourceNTAccountsCount > 0)
            {
                TargetNTAccounts = NTAccount.Translate(SourceNTAccounts, targetType, out someFailed);

                if (Homogeneous && !(forceSuccess && someFailed))
                {
                    Result = TargetNTAccounts;
                }
            }

            if (forceSuccess && someFailed)
            {
                //
                // Need to throw an exception here and provide information regarding
                // which identity references could not be translated to the target type
                //

                Result = new IdentityReferenceCollection();

                if (TargetSids != null)
                {
                    foreach (IdentityReference id in TargetSids)
                    {
                        if (id.GetType() != targetType)
                        {
                            Result.Add(id);
                        }
                    }
                }

                if (TargetNTAccounts != null)
                {
                    foreach (IdentityReference id in TargetNTAccounts)
                    {
                        if (id.GetType() != targetType)
                        {
                            Result.Add(id);
                        }
                    }
                }

                throw new IdentityNotMappedException(SR.IdentityReference_IdentityNotMapped, Result);
            }
            else if (!Homogeneous)
            {
                SourceSidsCount       = 0;
                SourceNTAccountsCount = 0;

                Result = new IdentityReferenceCollection(Identities.Count);

                for (int i = 0; i < Identities.Count; i++)
                {
                    IdentityReference id = this[i];

                    Type type = id.GetType();

                    if (type == targetType)
                    {
                        Result.Add(id);
                    }
                    else if (type == typeof(SecurityIdentifier))
                    {
                        Result.Add(TargetSids[SourceSidsCount++]);
                    }
                    else if (type == typeof(NTAccount))
                    {
                        Result.Add(TargetNTAccounts[SourceNTAccountsCount++]);
                    }
                    else
                    {
                        //
                        // Rare case that we have defined a type of identity reference and not included it in the code logic above.
                        // To avoid this we do not allow IdentityReference to be subclassed outside of the BCL.
                        //
                        Debug.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic.");
                        throw new NotSupportedException();
                    }
                }
            }

            return(Result);
        }
Example #55
0
        private static IdentityReferenceCollection TranslateToSids(IdentityReferenceCollection sourceAccounts, out bool someFailed)
        {
            IdentityReferenceCollection references2;

            if (sourceAccounts == null)
            {
                throw new ArgumentNullException("sourceAccounts");
            }
            if (sourceAccounts.Count == 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_EmptyCollection"), "sourceAccounts");
            }
            SafeLsaPolicyHandle invalidHandle     = SafeLsaPolicyHandle.InvalidHandle;
            SafeLsaMemoryHandle referencedDomains = SafeLsaMemoryHandle.InvalidHandle;
            SafeLsaMemoryHandle sids = SafeLsaMemoryHandle.InvalidHandle;

            try
            {
                uint num2;
                Win32Native.UNICODE_STRING[] names = new Win32Native.UNICODE_STRING[sourceAccounts.Count];
                int index = 0;
                foreach (IdentityReference reference in sourceAccounts)
                {
                    NTAccount account = reference as NTAccount;
                    if (account == null)
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_ImproperType"), "sourceAccounts");
                    }
                    names[index].Buffer = account.ToString();
                    if (((names[index].Buffer.Length * 2) + 2) > 0xffff)
                    {
                        throw new SystemException();
                    }
                    names[index].Length        = (ushort)(names[index].Buffer.Length * 2);
                    names[index].MaximumLength = (ushort)(names[index].Length + 2);
                    index++;
                }
                invalidHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES);
                someFailed    = false;
                if (Win32.LsaLookupNames2Supported)
                {
                    num2 = Win32Native.LsaLookupNames2(invalidHandle, 0, sourceAccounts.Count, names, ref referencedDomains, ref sids);
                }
                else
                {
                    num2 = Win32Native.LsaLookupNames(invalidHandle, sourceAccounts.Count, names, ref referencedDomains, ref sids);
                }
                if ((num2 == 0xc0000017) || (num2 == 0xc000009a))
                {
                    throw new OutOfMemoryException();
                }
                if (num2 == 0xc0000022)
                {
                    throw new UnauthorizedAccessException();
                }
                if ((num2 == 0xc0000073) || (num2 == 0x107))
                {
                    someFailed = true;
                }
                else if (num2 != 0)
                {
                    int errorCode = Win32Native.LsaNtStatusToWinError((int)num2);
                    throw new SystemException(Win32Native.GetMessage(errorCode));
                }
                IdentityReferenceCollection references = new IdentityReferenceCollection(sourceAccounts.Count);
                switch (num2)
                {
                case 0:
                case 0x107:
                    if (Win32.LsaLookupNames2Supported)
                    {
                        sids.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf(typeof(Win32Native.LSA_TRANSLATED_SID2)));
                        Win32.InitializeReferencedDomainsPointer(referencedDomains);
                        Win32Native.LSA_TRANSLATED_SID2[] array = new Win32Native.LSA_TRANSLATED_SID2[sourceAccounts.Count];
                        sids.ReadArray <Win32Native.LSA_TRANSLATED_SID2>(0L, array, 0, array.Length);
                        for (int i = 0; i < sourceAccounts.Count; i++)
                        {
                            Win32Native.LSA_TRANSLATED_SID2 lsa_translated_sid = array[i];
                            switch (lsa_translated_sid.Use)
                            {
                            case 1:
                            case 2:
                            case 4:
                            case 5:
                            case 9:
                            {
                                references.Add(new SecurityIdentifier(lsa_translated_sid.Sid, true));
                                continue;
                            }
                            }
                            someFailed = true;
                            references.Add(sourceAccounts[i]);
                        }
                    }
                    else
                    {
                        sids.Initialize((uint)sourceAccounts.Count, (uint)Marshal.SizeOf(typeof(Win32Native.LSA_TRANSLATED_SID)));
                        Win32.InitializeReferencedDomainsPointer(referencedDomains);
                        Win32Native.LSA_REFERENCED_DOMAIN_LIST lsa_referenced_domain_list = referencedDomains.Read <Win32Native.LSA_REFERENCED_DOMAIN_LIST>(0L);
                        SecurityIdentifier[] identifierArray = new SecurityIdentifier[lsa_referenced_domain_list.Entries];
                        for (int j = 0; j < lsa_referenced_domain_list.Entries; j++)
                        {
                            Win32Native.LSA_TRUST_INFORMATION lsa_trust_information = (Win32Native.LSA_TRUST_INFORMATION)Marshal.PtrToStructure(new IntPtr(((long)lsa_referenced_domain_list.Domains) + (j * Marshal.SizeOf(typeof(Win32Native.LSA_TRUST_INFORMATION)))), typeof(Win32Native.LSA_TRUST_INFORMATION));
                            identifierArray[j] = new SecurityIdentifier(lsa_trust_information.Sid, true);
                        }
                        Win32Native.LSA_TRANSLATED_SID[] lsa_translated_sidArray2 = new Win32Native.LSA_TRANSLATED_SID[sourceAccounts.Count];
                        sids.ReadArray <Win32Native.LSA_TRANSLATED_SID>(0L, lsa_translated_sidArray2, 0, lsa_translated_sidArray2.Length);
                        for (int k = 0; k < sourceAccounts.Count; k++)
                        {
                            Win32Native.LSA_TRANSLATED_SID lsa_translated_sid2 = lsa_translated_sidArray2[k];
                            switch (lsa_translated_sid2.Use)
                            {
                            case 1:
                            case 2:
                            case 4:
                            case 5:
                            case 9:
                            {
                                references.Add(new SecurityIdentifier(identifierArray[lsa_translated_sid2.DomainIndex], lsa_translated_sid2.Rid));
                                continue;
                            }
                            }
                            someFailed = true;
                            references.Add(sourceAccounts[k]);
                        }
                    }
                    break;

                default:
                    for (int m = 0; m < sourceAccounts.Count; m++)
                    {
                        references.Add(sourceAccounts[m]);
                    }
                    break;
                }
                references2 = references;
            }
            finally
            {
                invalidHandle.Dispose();
                referencedDomains.Dispose();
                sids.Dispose();
            }
            return(references2);
        }
        public IdentityReferenceCollection Translate(Type targetType, bool forceSuccess)
        {
            if (targetType == null)
            {
                throw new ArgumentNullException("targetType");
            }
            if (!targetType.IsSubclassOf(typeof(IdentityReference)))
            {
                throw new ArgumentException(Environment.GetResourceString("IdentityReference_MustBeIdentityReference"), "targetType");
            }
            if (this.Identities.Count == 0)
            {
                return(new IdentityReferenceCollection());
            }
            int num  = 0;
            int num2 = 0;

            for (int i = 0; i < this.Identities.Count; i++)
            {
                Type type = this.Identities[i].GetType();
                if (!(type == targetType))
                {
                    if (type == typeof(SecurityIdentifier))
                    {
                        num++;
                    }
                    else
                    {
                        if (!(type == typeof(NTAccount)))
                        {
                            throw new SystemException();
                        }
                        num2++;
                    }
                }
            }
            bool flag = false;
            IdentityReferenceCollection identityReferenceCollection  = null;
            IdentityReferenceCollection identityReferenceCollection2 = null;

            if (num == this.Count)
            {
                flag = true;
                identityReferenceCollection = this;
            }
            else if (num > 0)
            {
                identityReferenceCollection = new IdentityReferenceCollection(num);
            }
            if (num2 == this.Count)
            {
                flag = true;
                identityReferenceCollection2 = this;
            }
            else if (num2 > 0)
            {
                identityReferenceCollection2 = new IdentityReferenceCollection(num2);
            }
            IdentityReferenceCollection identityReferenceCollection3 = null;

            if (!flag)
            {
                identityReferenceCollection3 = new IdentityReferenceCollection(this.Identities.Count);
                for (int j = 0; j < this.Identities.Count; j++)
                {
                    IdentityReference identityReference = this[j];
                    Type type2 = identityReference.GetType();
                    if (!(type2 == targetType))
                    {
                        if (type2 == typeof(SecurityIdentifier))
                        {
                            identityReferenceCollection.Add(identityReference);
                        }
                        else
                        {
                            if (!(type2 == typeof(NTAccount)))
                            {
                                throw new SystemException();
                            }
                            identityReferenceCollection2.Add(identityReference);
                        }
                    }
                }
            }
            bool flag2 = false;
            IdentityReferenceCollection identityReferenceCollection4 = null;
            IdentityReferenceCollection identityReferenceCollection5 = null;

            if (num > 0)
            {
                identityReferenceCollection4 = SecurityIdentifier.Translate(identityReferenceCollection, targetType, out flag2);
                if (flag && (!forceSuccess || !flag2))
                {
                    identityReferenceCollection3 = identityReferenceCollection4;
                }
            }
            if (num2 > 0)
            {
                identityReferenceCollection5 = NTAccount.Translate(identityReferenceCollection2, targetType, out flag2);
                if (flag && (!forceSuccess || !flag2))
                {
                    identityReferenceCollection3 = identityReferenceCollection5;
                }
            }
            if (forceSuccess && flag2)
            {
                identityReferenceCollection3 = new IdentityReferenceCollection();
                if (identityReferenceCollection4 != null)
                {
                    foreach (IdentityReference identityReference2 in identityReferenceCollection4)
                    {
                        if (identityReference2.GetType() != targetType)
                        {
                            identityReferenceCollection3.Add(identityReference2);
                        }
                    }
                }
                if (identityReferenceCollection5 != null)
                {
                    foreach (IdentityReference identityReference3 in identityReferenceCollection5)
                    {
                        if (identityReference3.GetType() != targetType)
                        {
                            identityReferenceCollection3.Add(identityReference3);
                        }
                    }
                }
                throw new IdentityNotMappedException(Environment.GetResourceString("IdentityReference_IdentityNotMapped"), identityReferenceCollection3);
            }
            if (!flag)
            {
                num  = 0;
                num2 = 0;
                identityReferenceCollection3 = new IdentityReferenceCollection(this.Identities.Count);
                for (int k = 0; k < this.Identities.Count; k++)
                {
                    IdentityReference identityReference4 = this[k];
                    Type type3 = identityReference4.GetType();
                    if (type3 == targetType)
                    {
                        identityReferenceCollection3.Add(identityReference4);
                    }
                    else if (type3 == typeof(SecurityIdentifier))
                    {
                        identityReferenceCollection3.Add(identityReferenceCollection4[num++]);
                    }
                    else
                    {
                        if (!(type3 == typeof(NTAccount)))
                        {
                            throw new SystemException();
                        }
                        identityReferenceCollection3.Add(identityReferenceCollection5[num2++]);
                    }
                }
            }
            return(identityReferenceCollection3);
        }