Translate() публичный Метод

public Translate ( Type targetType ) : IdentityReference
targetType Type
Результат IdentityReference
        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();
            }
        }
Пример #2
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;
        }
Пример #3
0
        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;
        }
Пример #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();
        }
Пример #5
0
        public override IdentityReference Translate(Type targetType)
        {
            if (targetType == null)
            {
                throw new ArgumentNullException("targetType");
            }
            Contract.EndContractBlock();

            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(Environment.GetResourceString("IdentityReference_MustBeIdentityReference"), "targetType");
            }
        }
        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".
        }
Пример #7
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);

            SecurityIdentifier sid = target[0] as SecurityIdentifier;

            if (sid != null)
            {
                if (IsInRole(sid))
                {
                    return(true);
                }
            }

            // possible that identity has other role claims that match
            return(base.IsInRole(role));
        }
Пример #8
0
        public override IdentityReference Translate(Type targetType)
        {
            if (targetType == null)
            {
                throw new ArgumentNullException(nameof(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));
            }
        }
Пример #9
0
      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;
      }
        /// <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);
                    }
                }
            }
        }
Пример #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));
            }
        }
Пример #12
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;
        }
Пример #13
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.");
     }
 }
 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;
       }
 }
Пример #15
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;
     }
 }
Пример #16
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;
        }
Пример #17
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));
        }
Пример #18
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;
		}
Пример #19
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));
        }
Пример #20
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;
        }
Пример #21
0
		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);
				}
			}
		}
 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);
 }
Пример #23
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());
            }
        }
Пример #24
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);
        }
Пример #25
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);
        }
Пример #26
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);
        }
Пример #27
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));
        }
Пример #28
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");
 }
        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;
        }
Пример #30
0
        /// <summary>
        /// Tries to parse the string as a username to get the SDDL format of a SID.
        /// </summary>
        /// <param name="username">The string to parse as a username.</param>
        /// <param name="sddl">The SDDL format of a SID to return.</param>
        /// <returns>Returns true if the string was parsed as a username and an SDDL was returned; otherwise, false.</returns>
        internal static bool TryParseUsername(string username, out string sddl)
        {
            if (username.IndexOf("\\", StringComparison.Ordinal) >= 0)
            {
                try
                {
                    NTAccount account = new NTAccount(username);
                    SecurityIdentifier sid = (SecurityIdentifier)account.Translate(typeof(SecurityIdentifier));

                    sddl = sid.ToString();
                    return true;
                }
                catch
                {
                }
            }

            // Coverstion failed.
            sddl = null;
            return false;
        }
Пример #31
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]);
        }
Пример #32
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)
            {
                Console.WriteLine(group.Value);
                //whoami
                Console.WriteLine(group.Translate(typeof(NTAccount)));
            }
            //alternate just to get the string names
            //Note: String names are local and culture specific -- use ids
            foreach (var group in id.Groups.Translate(typeof(NTAccount)))
            {
                Console.WriteLine(group);
            }

               //Note: String names are local and culture svapecific -- use ids
            //var principal = new WindowsPrincipal(id);
            //Console.WriteLine(principal.IsInRole(("Builtin\\Users")));
            var principal = new WindowsPrincipal(id);

            var localAdmins = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid,null);
            var domainAdmin = new SecurityIdentifier(WellKnownSidType.AccountDomainAdminsSid, id.User.AccountDomainSid);
            var user = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);

            Console.WriteLine(principal.IsInRole(localAdmins));
            Console.WriteLine(principal.IsInRole(domainAdmin));
            Console.WriteLine(principal.IsInRole(user));

            //  Console.ReadLine();
        }
        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);
        }
Пример #34
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);
        }
Пример #35
0
        /// <summary>
        /// Builds a session SDDL based on the provided configuration hashtable.
        /// Retrieves RequiredGroups information to add conditional group membership restrictions to SDDL.
        /// Retrieves RoleDefinitions information to include role user accounts.
        /// </summary>
        /// <param name="configTable"></param>
        /// <param name="accessMode"></param>
        /// <param name="error"></param>
        /// <returns>SDDL</returns>
        internal static string ComputeSDDLFromConfiguration(
            Hashtable configTable,
            PSSessionConfigurationAccessMode accessMode,
            out ErrorRecord error)
        {
            Dbg.Assert(configTable != null, "configTable input parameter cannot be null.");

            string sddl = string.Empty;
            error = null;

            // RoleDefinitions
            if (configTable.ContainsKey(ConfigFileConstants.RoleDefinitions))
            {
                // Start with known good security descriptor.
                if (accessMode == PSSessionConfigurationAccessMode.Local)
                {
                    sddl = PSSessionConfigurationCommandBase.GetLocalSddl();
                }
                else if (accessMode == PSSessionConfigurationAccessMode.Remote)
                {
                    sddl = PSSessionConfigurationCommandBase.GetRemoteSddl();
                }
                CommonSecurityDescriptor descriptor = new CommonSecurityDescriptor(false, false, sddl);

                // Purge all existing access rules so that only role definition principals are granted access.
                List<SecurityIdentifier> sidsToRemove = new List<SecurityIdentifier>();
                foreach (CommonAce ace in descriptor.DiscretionaryAcl)
                {
                    sidsToRemove.Add(ace.SecurityIdentifier);
                }
                foreach (var sidToRemove in sidsToRemove)
                {
                    descriptor.PurgeAccessControl(sidToRemove);
                }

                Hashtable roleNamesHash = configTable[ConfigFileConstants.RoleDefinitions] as Hashtable;
                foreach (object roleName in roleNamesHash.Keys)
                {
                    string roleNameValue = roleName.ToString();

                    try
                    {
                        NTAccount ntAccount = new NTAccount(roleNameValue);
                        SecurityIdentifier accountSid = (SecurityIdentifier)ntAccount.Translate(typeof(SecurityIdentifier));
                        // AccessMask = 268435456 == 0x10000000 == GR == Generic Read
                        descriptor.DiscretionaryAcl.AddAccess(AccessControlType.Allow, accountSid, 268435456, InheritanceFlags.None, PropagationFlags.None);
                    }
                    catch (IdentityNotMappedException e)
                    {
                        string message = StringUtil.Format(RemotingErrorIdStrings.CouldNotResolveRoleDefinitionPrincipal, roleNameValue, e.Message);
                        InvalidOperationException ioe = new InvalidOperationException(message, e);
                        error = new ErrorRecord(ioe, "CouldNotResolveRoleDefinitionPrincipal", ErrorCategory.ObjectNotFound, roleNameValue);
                    }
                }

                if (descriptor.DiscretionaryAcl.Count > 0)
                {
                    sddl = descriptor.GetSddlForm(AccessControlSections.All);

                    // RequiredGroups
                    string conditionalGroupACE = CreateConditionalACEFromConfig(configTable);
                    if (conditionalGroupACE != null)
                    {
                        sddl = UpdateSDDLUsersWithGroupConditional(sddl, conditionalGroupACE);
                    }
                }
            }

            return sddl;
        }
Пример #36
0
 private static void ParseValue(
     StringBuilder sb,
     object value)
 {
     // Single value objects can be either a group name or a new logical hash table
     string groupName = value as string;
     if (groupName != null)
     {
         // Resolve group name to SID
         NTAccount ntAccount = new NTAccount(groupName);
         SecurityIdentifier accountSid = (SecurityIdentifier)ntAccount.Translate(typeof(SecurityIdentifier));
         sb.Append(StringUtil.Format(MemberOfFormat, accountSid.ToString()));
     }
     else
     {
         Hashtable recurseCondition = value as Hashtable;
         if (recurseCondition != null)
         {
             // Recurse to handle logical hash table
             AddCondition(sb, recurseCondition);
         }
         else
         {
             throw new PSInvalidOperationException(RemotingErrorIdStrings.UnknownGroupMembershipValue);
         }
     }
 }
        } // StopListening
 
        // 
        // end of IChannelReceiver implementation
        // 

        // Thread for listening
        void Listen()
        { 
            bool bOkToListen = true;
 
 
            InternalRemotingServices.RemotingTrace( "Waiting to Accept a Connection on Port: " + _portName);
 
            //
            // Wait for an incoming client connection
            //
            IntPtr handle = IntPtr.Zero; 

            bool connected = false; 
            CommonSecurityDescriptor descriptor = _securityDescriptor; 

            // Connect with exlusive flag the first time 
            if (bOkToListen)
            {
                try{
                    // If the descriptor is not explicitly set through code use the _authorizedGroup config 
                    if (descriptor == null && _authorizedGroup != null)
                    { 
                        NTAccount ntAccount = new NTAccount(_authorizedGroup); 
                        descriptor = IpcPort.CreateSecurityDescriptor((SecurityIdentifier)ntAccount.Translate(typeof(SecurityIdentifier)));
                    } 

                    _port = IpcPort.Create(_portName, descriptor, _bExclusiveAddressUse);
                }
                catch (Exception e) { 
                    _startListeningException = e;
                } 
                finally { 
                    _waitForStartListening.Set(); // allow main thread to continue now that we have tried to start the socket
                } 
                if (_port != null){
                    connected = _port.WaitForConnect();
                    bOkToListen = _bListening;
                } 
            }
 
            while (bOkToListen && _startListeningException == null) 
            {
                InternalRemotingServices.RemotingTrace("IpcChannel::Listen"); 

                // For DevDiv#220882, we need to create new IpcPort before handling the current message
                // to avoid race condition in case the message is handled and finished before
                // the new IpcPort is created.  The client will intermittently fail with Port not found. 
                IpcPort port = IpcPort.Create(_portName, descriptor, false);
 
                if (connected) 
                {
                    // Initialize the server handler and perform an async read 
                    IpcServerHandler serverHandler = new IpcServerHandler(_port, CoreChannel.RequestQueue, new PipeStream(_port));
                    serverHandler.DataArrivedCallback = new WaitCallback(_transportSink.ServiceRequest);
                    serverHandler.BeginReadMessage();
                } 
                _port = port;
                connected = _port.WaitForConnect(); 
                bOkToListen = _bListening; 
            }
       } 
Пример #38
0
 /// <summary>
 /// Determines the owner
 /// </summary>
 public void SetOwner( NTAccount newOwner )
 {
     if ( IsRoot )
     {
         throw new NotSupportedException( "Root directory does not provide owner access" );
     }
     GetFileSystemSecurity( ).FileSystemSecurityInformation.SetOwner( newOwner.Translate( typeof( SecurityIdentifier ) ) );
 }
Пример #39
0
        /// <summary>
        /// Adds an ACL entry on the specified file for the specified account to 
        /// give every user of the local machine rights to modify configuration file
        /// </summary>
        /// <param name="fileName"></param>
        public static void SetEditablePermissionOnConfigFile(string fileName)
        {
            // Get a FileSecurity object that represents the 
            // current security settings.
            FileSecurity accessControl = File.GetAccessControl(fileName);

            // Give every user of the local machine rights to modify configuration file
            var userGroup = new NTAccount("BUILTIN\\Users");
            var userIdentityReference = userGroup.Translate(typeof(SecurityIdentifier));

            // Add the FileSystemAccessRule to the security settings.
            accessControl.SetAccessRule(
                new FileSystemAccessRule(userIdentityReference,
                                         FileSystemRights.FullControl,
                                         AccessControlType.Allow));
            // Set the new access settings.
            File.SetAccessControl(fileName, accessControl);
        }
Пример #40
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 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);
        }
Пример #42
0
 public static SecurityIdentifier GetSIDFromName(string name)
 {
     NTAccount ntAccount = new NTAccount(name);
     return (SecurityIdentifier)ntAccount.Translate(typeof(SecurityIdentifier));
 }
Пример #43
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);
        }
Пример #44
0
 private static string GetLocalUserSid(string windowsUsername)
 {
     NTAccount ntaccount = new NTAccount(string.Empty, windowsUsername);
     return ntaccount.Translate(typeof(SecurityIdentifier)).Value;
 }
        internal SecurityIdentifier GetUpnSid()
        {
            Fx.Assert(ClaimTypes.Upn.Equals(this.IdentityClaim.ClaimType), "");
            if (!hasUpnSidBeenComputed)
            {
                lock (thisLock)
                {
                    string upn = (string)this.IdentityClaim.Resource;
                    if (!hasUpnSidBeenComputed)
                    {
                        try
                        {
                            NTAccount userAccount = new NTAccount(upn);
                            this.upnSid = userAccount.Translate(typeof(SecurityIdentifier)) as SecurityIdentifier;
                        }
#pragma warning suppress 56500 // covered by FxCOP
                        catch (Exception e)
                        {
                            // Always immediately rethrow fatal exceptions.
                            if (Fx.IsFatal(e))
                            {
                                throw;
                            }

                            if (e is NullReferenceException)
                            {
                                throw;
                            }

                            SecurityTraceRecordHelper.TraceSpnToSidMappingFailure(upn, e);
                        }
                        finally
                        {
                            hasUpnSidBeenComputed = true;
                        }
                    }
                }
            }
            return this.upnSid;
        }