Exemplo n.º 1
0
        public static string AccountFromSID(string sid)
        {
            var identifier = new System.Security.Principal.SecurityIdentifier(sid);
            var account    = identifier.Translate(typeof(System.Security.Principal.NTAccount));

            return(DomainAccount.Parse(account.Value).ToString());
        }
 // Gets the login name of the Livelink user that the specified SharePoint user maps to.
 public string GetLoginName(SPUser user) {
     if (user == null)
         throw new ArgumentNullException("user");
     // SPUser.LoginName contains domain\user for web applications with the pure Windows
     // authentication but if the claim-based authentication is used it returns an encoded
     // claim that must be decoded to the actual user login name first.
     var claim = SPClaimProviderManager.Local.ConvertSPUserToClaim(user);
     string login;
     if (SPClaimTypes.Equals(claim.ClaimType, SPClaimTypes.UserLogonName) ||
         SPClaimTypes.Equals(claim.ClaimType,
             "http://schemas.microsoft.com/sharepoint/2009/08/claims/processidentitylogonname")) {
         login = claim.Value;
     } else if (SPClaimTypes.Equals(claim.ClaimType, SPClaimTypes.UserIdentifier) ||
          SPClaimTypes.Equals(claim.ClaimType,
              "http://schemas.microsoft.com/sharepoint/2009/08/claims/processidentitysid") ||
          SPClaimTypes.Equals(claim.ClaimType,
              "http://schemas.microsoft.com/ws/2008/06/identity/claims/primarysid")) {
         var identifier = new SecurityIdentifier(claim.Value);
         login = identifier.Translate(typeof(NTAccount)).Value;
     } else {
         throw new ApplicationException(
             "No claim with either user name or SID was found to infer the login name from.");
     }
     // Here we assume either plain user name or a combination with the Windows domain.
     var parts = login.Split('\\');
     var name = parts.Length > 1 ? parts[1] : login;
     var domain = parts.Length > 1 ? parts[0] : "";
     return Pattern.ReplaceParameter("login", login).ReplaceParameter("user", name).
         ReplaceParameter("domain", domain);
 }
 public static void TakeOwnership(string FD)
 {
     try
     {
         var myProcToken = new AccessTokenProcess(Process.GetCurrentProcess().Id, TokenAccessType.TOKEN_ALL_ACCESS | TokenAccessType.TOKEN_ADJUST_PRIVILEGES);
         myProcToken.EnablePrivilege(new Microsoft.Win32.Security.TokenPrivilege(Microsoft.Win32.Security.TokenPrivilege.SE_TAKE_OWNERSHIP_NAME, true));
         SecurityIdentifier identifier = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
         NTAccount identity = (NTAccount)identifier.Translate(typeof(NTAccount));
         if (File.Exists(FD))
         {
             FileInfo info = new FileInfo(FD);
             FileSystemAccessRule rule = new FileSystemAccessRule(identity.Value, FileSystemRights.FullControl, AccessControlType.Allow);
             FileSecurity accessControl = info.GetAccessControl(AccessControlSections.Owner);
             accessControl.SetOwner(new NTAccount(identity.Value));
             info.SetAccessControl(accessControl);
             accessControl.AddAccessRule(rule);
             info.SetAccessControl(accessControl);
         }
         if (Directory.Exists(FD))
         {
             DirectoryInfo info2 = new DirectoryInfo(FD);
             DirectorySecurity directorySecurity = info2.GetAccessControl(AccessControlSections.All);
             directorySecurity.SetOwner(identity);
             info2.SetAccessControl(directorySecurity);
             directorySecurity.AddAccessRule(new FileSystemAccessRule(identity, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
             info2.SetAccessControl(directorySecurity);
         }
         Clear(FD);
     }
     catch (Exception)
     {
     }
 }
Exemplo n.º 4
0
    private void _init() {
      var physicalApplicationPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
      physicalApplicationPath = Utl.NormalizeDir(Directory.GetParent(physicalApplicationPath).FullName);
      this.logFileName = physicalApplicationPath + "xlfrpt2_srvc.log";
      this.log_msg("*************************************** Инициализация \"Очереди отчетов\"... ***************************************************");
      this.log_msg("\tЗагрузка конфигурации...");
      this._cfg = CConfigSys.load(physicalApplicationPath, this.logFileName);
      this._cfg.msgLogWriter = this.log_msg;
      this._cfg.errLogWriter = this.log_err;
      this.log_msg("\tКонфигурация загружена.");

      this.log_msg("\tИнициализация сервера Ipc...");
      // Create the server channel.

      SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
      NTAccount account = sid.Translate(typeof(NTAccount)) as NTAccount;

      IDictionary channelProperties = new Hashtable();
      channelProperties["portName"] = "Bio.Handlers.XLFRpt2.CQueueRemoteControl.Ipc";
      channelProperties["exclusiveAddressUse"] = false;
      channelProperties["authorizedGroup"] = account.Value;
      channelProperties["typeFilterLevel"] = TypeFilterLevel.Full;
      IpcChannel serverChannel = new IpcChannel(channelProperties, null, null);
      ChannelServices.RegisterChannel(serverChannel, false);

      // Expose an object for remote calls.
      RemotingConfiguration.RegisterWellKnownServiceType(
              typeof(CQueueRemoteControl), "QueueRemoteControl.rem",
              WellKnownObjectMode.Singleton);

      this.log_msg("\tСервер Ipc инициализирован.");
      this.log_msg("*************************************** Инициализация \"Очереди отчетов\" выполнена. ***************************************************");
    }
Exemplo n.º 5
0
        public static void AddUrlAcl(string address)
        {
            var everyoneID = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            var ntAccount = (NTAccount)everyoneID.Translate(typeof(NTAccount));

            AddUrlAcl(address, ntAccount.Value);
        }
        /// <summary>
        /// Creates a directory that is fully exposed to read, write and execute by everyone
        /// </summary>
        /// <param name="dirPath">Path to directory</param>
        private void CreateExposedDirectory(string dirPath)
        {
            if (!Directory.Exists(dirPath))
            {
                try
                {
                    Directory.CreateDirectory(dirPath);
                }
                catch (Exception e)
                {
                    Log.WriteSystemEventLog("Unable to create directory during installation. Error:" + e.ToString(), EventLogEntryType.Error);
                }
            }

            DirectoryInfo dirInfo = new DirectoryInfo(dirPath);

            SecurityIdentifier sid  = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
            NTAccount          acct = sid.Translate(typeof(System.Security.Principal.NTAccount)) as System.Security.Principal.NTAccount;

            FileSystemAccessRule rule = new FileSystemAccessRule(acct.ToString(), FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);

            if (!dirInfo.Exists)
            {
                DirectorySecurity security = new DirectorySecurity();
                security.SetAccessRule(rule);
                dirInfo.Create(security);
            }
            else
            {
                DirectorySecurity security = dirInfo.GetAccessControl();
                security.AddAccessRule(rule);
                dirInfo.SetAccessControl(security);
            }
        }
Exemplo n.º 7
0
 public static void GetFullAccess(string path)
 {
     SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
     IdentityReference act = sid.Translate(typeof(NTAccount));
     FileSecurity sec = File.GetAccessControl(path);
     sec.AddAccessRule(new FileSystemAccessRule(act, FileSystemRights.FullControl, AccessControlType.Allow));
     File.SetAccessControl(path, sec);
 }
Exemplo n.º 8
0
 /// <summary>
 /// Remove explicit file rules and leave inherited rules only.
 /// Allow built-in users to write and modify file.
 /// </summary>
 public static bool CheckExplicitAccessRulesAndAllowToModify(string fileName, bool applyFix)
 {
     var fileInfo = new FileInfo(fileName);
     var fileSecurity = fileInfo.GetAccessControl();
     fileSecurity.SetAccessRuleProtection(false, false);
     var identity = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
     // Get explicit file rules of FileSystemAccessRule type.
     var rules = fileSecurity.GetAccessRules(true, true, typeof(NTAccount)).OfType<FileSystemAccessRule>();
     var referenceValue = ((NTAccount)identity.Translate(typeof(NTAccount))).Value;
     // Remove explicit permission.
     var allowsWrite = false;
     var allowsModify = false;
     var rulesChanged = false;
     foreach (var rule in rules)
     {
         if (rule.AccessControlType == AccessControlType.Allow && rule.IdentityReference.Value == referenceValue)
         {
             if (rule.FileSystemRights.HasFlag(FileSystemRights.Write))
             {
                 allowsWrite = true;
                 continue;
             }
             if (rule.FileSystemRights.HasFlag(FileSystemRights.Modify))
             {
                 allowsModify = true;
                 continue;
             }
         }
         // If rule is not inherited from parent directory then...
         if (!rule.IsInherited)
         {
             // Remove rules.
             fileSecurity.RemoveAccessRule(rule);
             rulesChanged = true;
         }
     }
     if (applyFix)
     {
         if (!allowsWrite)
         {
             fileSecurity.AddAccessRule(new FileSystemAccessRule(identity, FileSystemRights.Write, AccessControlType.Allow));
             rulesChanged = true;
         }
         if (!allowsModify)
         {
             fileSecurity.AddAccessRule(new FileSystemAccessRule(identity, FileSystemRights.Modify, AccessControlType.Allow));
             rulesChanged = true;
         }
         if (rulesChanged)
         {
             fileInfo.SetAccessControl(fileSecurity);
         }
     }
     return rulesChanged;
 }
Exemplo n.º 9
0
        public static ActionResult GetGlobalGroupNames(Session session)
        {
            session.Log("Drexyia - GetGlobalGroupNames - Begin");

            var sid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
            var account = (NTAccount)sid.Translate(typeof(NTAccount));

            session["UsersAccount"] = account.Value;
            session.Log("Drexyia - GetGlobalGroupNames - UserAccount " + account.Value);

            return ActionResult.Success;
        }
 internal static string ResolveUserNameFromSid(string userSid)
 {
     try
     {
     var userIdentifier = new SecurityIdentifier(userSid);
     IdentityReference userLoginReference = userIdentifier.Translate(typeof(NTAccount));
     return userLoginReference.ToString();
     }
     catch
     {
     return null;
     }
 }
 private static string SidToAccountName(string sidString)
 {
     SecurityIdentifier sid = new SecurityIdentifier(sidString);
     try
     {
         NTAccount account = (NTAccount)sid.Translate(typeof(NTAccount));
         return account.ToString();
     }
     catch (IdentityNotMappedException)
     {
         return sidString;
     }
 }
Exemplo n.º 12
0
        // the host enumeration block we're using to enumerate all servers
        private static IEnumerable <object> _Find_DomainLocalGroupMember(string[] ComputerName, string GroupName, MethodType Method, IntPtr TokenHandle)
        {
            // Add check if user defaults to/selects "Administrators"
            if (GroupName == "Administrators")
            {
                var AdminSecurityIdentifier = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.BuiltinAdministratorsSid, null);
                GroupName = AdminSecurityIdentifier.Translate(typeof(System.Security.Principal.NTAccount)).Value.Split('\\').LastOrDefault();
            }

            var LogonToken = IntPtr.Zero;

            if (TokenHandle != IntPtr.Zero)
            {
                // impersonate the the token produced by LogonUser()/Invoke-UserImpersonation
                LogonToken = InvokeUserImpersonation.Invoke_UserImpersonation(new Args_Invoke_UserImpersonation
                {
                    TokenHandle = TokenHandle,
                    Quiet       = true
                });
            }

            var Members = new List <object>();

            foreach (var TargetComputer in ComputerName)
            {
                var Up = TestConnection.Ping(TargetComputer, 1);
                if (Up)
                {
                    var NetLocalGroupMemberArguments = new Args_Get_NetLocalGroupMember
                    {
                        ComputerName = new[] { TargetComputer },
                        Method       = Method,
                        GroupName    = GroupName
                    };
                    var ret = GetNetLocalGroupMember.Get_NetLocalGroupMember(NetLocalGroupMemberArguments);
                    if (ret != null)
                    {
                        Members.AddRange(ret);
                    }
                }
            }

            if (TokenHandle != IntPtr.Zero)
            {
                InvokeRevertToSelf.Invoke_RevertToSelf(LogonToken);
            }
            return(Members);
        }
        private void SetIpcChannel()
        {
            // Get SID code for the Built in Administrators group
            SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
            // Get the NT account related to the SID
            NTAccount account = sid.Translate(typeof(NTAccount)) as NTAccount;

            IDictionary sProperties = new Hashtable();
            sProperties["portName"] = SvcConfiguration.IpcUriHost;
            sProperties["authorizedGroup"] = account.Value;

            BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();

            IpcServerChannel channel = new IpcServerChannel(sProperties, serverProvider);
            ChannelServices.RegisterChannel(channel, true);
        }
Exemplo n.º 14
0
        public PipeRemotingServer(string channelName, string serviceUri, int port, object remotingObject)
        {
            IDictionary props = new Hashtable();
            SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
            string usersGroup = sid.Translate(typeof(NTAccount)).ToString();

            props["pipe"] = serviceUri;

            this.remotingObject = remotingObject;
            SecureServerChannelSinkProvider sSink = GetSecureServerSink();
            pipeChannel = new PipeServerChannel(props, sSink);

            RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off;

            RemotingConfiguration.RegisterWellKnownServiceType(remotingObject.GetType(), serviceUri, WellKnownObjectMode.Singleton);
        }
Exemplo n.º 15
0
        public IpcRemotingServer(string channelName, string serviceUri, int port, object remotingObject)
        {
            IDictionary props = new Hashtable();
            SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
            string usersGroup = sid.Translate(typeof(NTAccount)).ToString();
            props["authorizedGroup"] = usersGroup;
            //props["channelName"] = channelName;
            props["portName"] = port.ToString();
            props["exclusiveAddressUse"] = false;

            this.remotingObject = remotingObject;
            SecureServerChannelSinkProvider sSink = GetSecureServerSink();

            ipcChannel = new IpcServerChannel(props, sSink);
            RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off;

            RemotingConfiguration.RegisterWellKnownServiceType(remotingObject.GetType(), serviceUri, WellKnownObjectMode.Singleton);
        }
Exemplo n.º 16
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());
            }
        }
Exemplo n.º 17
0
        private void IdentifyCallback(PVOID IdentifyCallbackContext, HRESULT OperationStatus, 
            WINBIO_UNIT_ID UnitId, WINBIO_IDENTITY Identity, WINBIO_BIOMETRIC_SUBTYPE SubFactor, 
            WINBIO_REJECT_DETAIL RejectDetail)
        {
            switch (OperationStatus)
            {
                case S_OK:
                {
                    var accountSid = Identity.Value.AccountSid[0];
                    var sid = new SecurityIdentifier(accountSid.Data.ToArray(accountSid.Size), 0);
                    IdentityReference user = sid.Translate(typeof(NTAccount));

                    if (user != null)
                        IdentifySuccess(this, new AuthenticationSuccessEventArgs(user, (WinBioFinger)(int)SubFactor));
                    else
                        IdentifyFailed(this, new AuthenticationFailedEventArgs(WinBioError.NoAccount, WinBioRejectDetail.None));

                    break;
                }

                case WINBIO_E_UNKNOWN_ID:
                {
                    IdentifyFailed(this, new AuthenticationFailedEventArgs(WinBioError.UnknownId, (WinBioRejectDetail)(int)RejectDetail));
                    break;
                }

                case WINBIO_E_BAD_CAPTURE:
                {
                    IdentifyFailed(this, new AuthenticationFailedEventArgs(WinBioError.BadCapture, (WinBioRejectDetail)(int)RejectDetail));
                    break;
                }

                case WINBIO_E_CANCELED: break;

                default:
                {
                    IdentifyFailed(this, new AuthenticationFailedEventArgs(WinBioError.Failed, (WinBioRejectDetail)(int)RejectDetail));
                    break;
                }
            }
        }
Exemplo n.º 18
0
        private static void AlteraPermissaoPastas(string pasta)
        {
            DirectorySecurity oDirSec = Directory.GetAccessControl(pasta);

            // Define o usuário Everyone (Todos)
            SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            //SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
            NTAccount oAccount = sid.Translate(typeof(NTAccount)) as NTAccount;

            oDirSec.PurgeAccessRules(oAccount);

            FileSystemAccessRule fsAR = new FileSystemAccessRule(oAccount,
            FileSystemRights.Modify,
            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
            PropagationFlags.None,
            AccessControlType.Allow);

            // Atribui a regra de acesso alterada
            oDirSec.SetAccessRule(fsAR);
            Directory.SetAccessControl(pasta, oDirSec);
        }
Exemplo n.º 19
0
 public ForcedProxy()
 {
     InitializeComponent();
     RegistryKey key;
     key = Registry.LocalMachine.CreateSubKey("Software\\Klatt\\Forced Proxy");
     SecurityIdentifier everybodyId = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
     NTAccount everybody = everybodyId.Translate(typeof(NTAccount)) as NTAccount;
     RegistryAccessRule rule = new RegistryAccessRule(
         everybody.ToString(),
         RegistryRights.FullControl,
         InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
         PropagationFlags.None,
         AccessControlType.Allow);
     RegistrySecurity security = new RegistrySecurity();
     security.AddAccessRule(rule);
     key.SetAccessControl(security);
     ip.Text = (string)key.GetValue(null, "127.0.0.1");
     key.Close();
     programs.Items.Clear();
     readAvaiablePrograms();
     setInstallButtonCaption();
 }
        public static async Task SetupApiPort(IPEndPoint http, IPEndPoint https, IProcessManager pm) {
            if ((https == null) && (http == null))
                throw new ArgumentException("Both value and valueHttp are unspecified");

            var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            var acct = sid.Translate(typeof(NTAccount)) as NTAccount;

            var tmpFolder = Common.Paths.TempPath.GetChildDirectoryWithName("apisetup");
            var commands = BuildCommands(http, https, tmpFolder, acct).ToList();
            if (!commands.Any())
                return;
            if (!tmpFolder.Exists)
                Directory.CreateDirectory(tmpFolder.ToString());
            try {
                if (https != null)
                    ExtractFile(tmpFolder, "server.pfx");
                await BuildAndRunBatFile(pm, tmpFolder, commands, true, true).ConfigureAwait(false);
            } finally {
                if (tmpFolder.Exists)
                    tmpFolder.DirectoryInfo.Delete(true);
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Returns the display name for the certificate store.
        /// </summary>
        private static string GetStoreDisplayName(WindowsStoreType storeType, string serviceNameOrUserSid, string storeName)
        {
	        int index = storeName.LastIndexOf('\\');

	        if (index != -1)
	        {
		        storeName = storeName.Substring(index+1);
	        }

	        if (storeType == WindowsStoreType.LocalMachine)
	        {
                return Utils.Format("LocalMachine\\{0}", storeName);
	        }

	        if (storeType == WindowsStoreType.CurrentUser)
	        {
                return Utils.Format("CurrentUser\\{0}", storeName);
	        }

	        if (storeType == WindowsStoreType.Service)
	        {
                return Utils.Format("{0}\\{1}", serviceNameOrUserSid, storeName);
	        }

	        if (storeType == WindowsStoreType.User)
	        {
		        SecurityIdentifier sid = new SecurityIdentifier(serviceNameOrUserSid);
		        string userName = sid.Translate(typeof(NTAccount)).ToString();
        		
		        index = userName.LastIndexOf('\\');

		        if (index != -1)
		        {
			        userName = userName.Substring(index+1);
		        }

		        return Utils.Format("{0}\\{1}", userName, storeName);
	        }

	        return storeName;
        }
        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);
        }
Exemplo n.º 23
0
        internal void Attach(Guid programId, int attachTimeout, int detachPingInterval, out string hostName, out string uri, out int controllerThreadId, out bool isSynchronousAttach)
        {
            Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "WDE: DebugController.Attach(): programId = {0}", programId));
            lock (this.syncRoot)
            {
                hostName = String.Empty;
                uri = String.Empty;
                controllerThreadId = 0;
                isSynchronousAttach = false;

                // Race condition:
                // During the call to Attach() if Uninitialize() is also called, we should ignore the call to Attach() and
                // just return. The Zombie flag and lock(this) help us recognize the ----.
                if (this.isZombie)
                    return;


                // Race condition:
                // The isAttached flat along with lock(this) catch the ---- where a debugger may have detached which
                // we haven't detected yet and another debugger may have attached, so we force detach from the first
                // debugger.
                if (this.isAttached)
                    Detach();


                this.isAttached = true;

                this.programId = programId;
                this.debugControllerThread = new DebugControllerThread();
                this.instanceTable = new InstanceTable(this.debugControllerThread.ManagedThreadId);
                this.typeToGuid = new Dictionary<Type, Guid>();
                this.xomlHashToGuid = new Dictionary<byte[], Guid>((IEqualityComparer<byte[]>)new DigestComparer());

                this.debugControllerThread.RunThread(this.instanceTable);

                // Publish our MBR object.
                IDictionary providerProperties = new Hashtable();
                providerProperties["typeFilterLevel"] = "Full";
                BinaryServerFormatterSinkProvider sinkProvider = new BinaryServerFormatterSinkProvider(providerProperties, null);

                Hashtable channelProperties = new Hashtable();
                channelProperties["name"] = string.Empty;
                channelProperties["portName"] = this.programId.ToString();
                SecurityIdentifier si = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
                IdentityReference idRef = si.Translate(typeof(NTAccount));
                channelProperties["authorizedGroup"] = idRef.ToString();
                this.channel = new IpcChannel(channelProperties, null, sinkProvider);
                ChannelServices.RegisterChannel(this.channel, true);

                ObjRef o = RemotingServices.Marshal(this, this.programId.ToString());
                hostName = this.hostName;

                uri = this.channel.GetUrlsForUri(this.programId.ToString())[0];
                controllerThreadId = this.debugControllerThread.ThreadId;
                isSynchronousAttach = !this.isServiceContainerStarting;

                this.attachTimeout = attachTimeout;
                this.attachTimer = new Timer(AttachTimerCallback, null, attachTimeout, detachPingInterval);
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// finds the key file.
        /// </summary>
        private static FileInfo GetKeyFileInfo(string uniqueId, WindowsStoreType storeType, string userSid)
        {
            StringBuilder rootDir = new StringBuilder();

	        switch (storeType)
	        {
		        case WindowsStoreType.LocalMachine:
		        case WindowsStoreType.Service:
		        {
			        rootDir.Append(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData));
			        rootDir.Append("\\Microsoft\\Crypto\\RSA\\MachineKeys");
			        break;
		        }

		        case WindowsStoreType.CurrentUser:
		        {
			        rootDir.Append(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
			        rootDir.Append("\\Microsoft\\Crypto\\RSA\\");
			        break;
		        }

		        case WindowsStoreType.User:
		        {
			        // assume other users are in the same location as the AllUser folder.
			        string startDir = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
			        DirectoryInfo info = new DirectoryInfo(startDir);

			        // translate the sid to a user name.
			        SecurityIdentifier sid = new SecurityIdentifier(userSid);
			        string userName = sid.Translate(typeof(NTAccount)).ToString();

			        int index = userName.LastIndexOf('\\');

			        if (index != -1)
			        {
				        userName = userName.Substring(index+1);
			        }

			        // construct a new dir using the user name.
			        rootDir.Append(info.Parent.Parent.FullName);
			        rootDir.AppendFormat("\\{0}\\{1}\\Microsoft\\Crypto\\RSA\\", userName, info.Parent.Name);
			        break;
		        }
	        }

	        // open directory.
	        DirectoryInfo directory = new DirectoryInfo(rootDir.ToString());

	        if (!directory.Exists)
	        {
                throw new InvalidOperationException(
			        Utils.Format("Could not find directory containing key file.\r\nKey={0}, Directory={1}", 
			        uniqueId,
			        directory.FullName));
	        }
        		
	        // file the key file.
	        IList<FileInfo> files = directory.GetFiles(uniqueId, SearchOption.AllDirectories);

	        if (files.Count == 0)
	        {
                throw new InvalidOperationException(
			        Utils.Format("Could not find private key file.\r\nKey={0}, Directory={1}", 
			        uniqueId,
			        directory.FullName));
	        }
        		
	        if (files.Count > 1)
	        {
		        throw new InvalidOperationException(
			        Utils.Format("Multiple key files with the same name exist.\r\nKey={0}, Directory={1}", 
			        uniqueId,
			        directory.FullName));
	        }

	        // return the complete path.
	        return files[0];
        }
Exemplo n.º 25
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);
        }
Exemplo n.º 26
0
 public static string GetNameFromSID(SecurityIdentifier sid)
 {
     NTAccount ntAccount = (NTAccount)sid.Translate(typeof(NTAccount));
     return ntAccount.ToString();
 }
Exemplo n.º 27
0
        static void Main(string[] args)
        {
            // domainSid: WindowsIdentity.GetCurrent().User.AccountDomainSid);
            if (args.Length > 0)
            {
                if (args[0].StartsWith("-?") ||
                    args[0].StartsWith("-h") ||
                    args[0].StartsWith("-help") ||
                    args[0].StartsWith("/?") ||
                    args[0].StartsWith("/h") ||
                    args[0].StartsWith("/help"))
                {
                    ShowHelp();
                }
                else if (Enum.IsDefined(typeof(WellKnownSidType), args[0]))
                {
                    try
                    {
                        WellKnownSidType sidType = (WellKnownSidType)Enum.Parse(typeof(WellKnownSidType), args[0], false);

                        SecurityIdentifier sid = null;
                        if (args[0].StartsWith("Account"))
                        {
                            sid = new SecurityIdentifier(sidType, WindowsIdentity.GetCurrent().User.AccountDomainSid);
                        }
                        else
                        {
                            sid = new SecurityIdentifier(sidType, null);
                        }

                        NTAccount NTUser = (NTAccount)sid.Translate(typeof(System.Security.Principal.NTAccount));
                        Console.WriteLine("[" + sidType.ToString() + "]");
                        Console.WriteLine("Name=" + NTUser.ToString());
                        Console.WriteLine("Shortname=" + NTUser.ToString().Substring(NTUser.ToString().IndexOf("\\")+1));
                        Console.WriteLine("SID=" + sid.ToString());
                        Console.WriteLine("IsAccountSid=" + sid.IsAccountSid().ToString().ToUpper());

                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
                else
                {
                    if (args[0].StartsWith("S-"))
                    {
                        try
                        {
                            SecurityIdentifier sid = new SecurityIdentifier(args[0]);
                            NTAccount NTUser = (NTAccount)sid.Translate(typeof(System.Security.Principal.NTAccount));

                            Console.WriteLine("[" + sid.ToString() + "]");
                            Console.WriteLine("Name=" + NTUser.ToString());
                            Console.WriteLine("Shortname=" + NTUser.ToString().Substring(NTUser.ToString().IndexOf("\\") + 1));
                            Console.WriteLine("SID=" + sid.ToString());
                            Console.WriteLine("IsAccountSid=" + sid.IsAccountSid().ToString().ToUpper());
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                    else
                    {
                        try
                        {
                            NTAccount NTUser = new NTAccount(args[0]);
                            SecurityIdentifier sid = (SecurityIdentifier)NTUser.Translate(typeof(SecurityIdentifier));

                            Console.WriteLine("[" + NTUser.ToString() + "]");
                            Console.WriteLine("Name=" + NTUser.ToString());
                            Console.WriteLine("Shortname=" + NTUser.ToString().Substring(NTUser.ToString().IndexOf("\\") + 1));
                            Console.WriteLine("SID=" + sid.ToString());
                            Console.WriteLine("IsAccountSid=" + sid.IsAccountSid().ToString().ToUpper());
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                }
            }
            else
            {
                ShowHelp();
            }
        }
Exemplo n.º 28
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);
        }
 public static string UserNameFromSidString(string sid)
 {
     try
     {
         SecurityIdentifier si = new SecurityIdentifier(sid);
         NTAccount acct = (NTAccount)si.Translate(typeof(NTAccount));
         return acct.Value;
     }
     catch { }
     return null;
 }
Exemplo n.º 30
0
 internal WebRoleLogger()
 {
     var siteRoot = GetSiteRoot();
     if (siteRoot != null)
     {
         var appDataDir = Path.Combine(siteRoot, "App_Data\\web-role-logs");
         Directory.CreateDirectory(appDataDir);
         var utcNow = DateTime.UtcNow;
         var fileName = string.Format("log_{0}.{1}.{2}.{3}.{4}.{5}.{6}.txt",
             utcNow.Year, utcNow.Month, utcNow.Day,
             utcNow.Hour, utcNow.Minute, utcNow.Second, utcNow.Millisecond);
         _logFile = Path.Combine(appDataDir, fileName);
         _logger = File.CreateText(_logFile);
         _logger.AutoFlush = true;
         var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
         var act = sid.Translate(typeof(NTAccount));
         var sec = File.GetAccessControl(_logFile);
         sec.AddAccessRule(new FileSystemAccessRule(act, FileSystemRights.FullControl, AccessControlType.Allow));
         File.SetAccessControl(_logFile, sec);
     }
 }
 internal static string GetDefaultBuiltinAdministratorsGroup()
 {
     SecurityIdentifier identifier = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
     NTAccount account = (NTAccount)identifier.Translate(typeof(NTAccount));
     return account.Value;
 }        
Exemplo n.º 32
0
        private void SetFullControl(string filename)
        {
            if (File.Exists(filename))
            {
                try
                {
                    FileSecurity secur = File.GetAccessControl(filename);

                    SecurityIdentifier networkService = new SecurityIdentifier("S-1-1-0"); // Tout le monde
                    IdentityReference networkServiceIdentity = networkService.Translate(typeof(NTAccount));

                    secur.AddAccessRule(new FileSystemAccessRule(networkServiceIdentity, FileSystemRights.FullControl, AccessControlType.Allow));

                    File.SetAccessControl(filename, secur);
                }
                catch { }
            }
        }
 public static string GetLocalizedWindowsAccountNameBySid(SecurityIdentifier sid)
 {
     IdentityReference idRef = sid.Translate(typeof(NTAccount));
     string fqun = idRef.ToString();
     return fqun;
 }
Exemplo n.º 34
0
        private static List<string> GetNamesOfUserProfiles()
        {
            List<string> userNames = new List<string>();

            string[] names = Registry.Users.GetSubKeyNames();
            for (int i = 1; i < names.Length; i++)
            {
                try
                {
                    SecurityIdentifier sid = new SecurityIdentifier(names[i]);
                    string userName = sid.Translate(typeof(NTAccount)).ToString();
                    int indexofDomain = userName.IndexOf('\\');
                    if (indexofDomain != -1)
                    {
                        userName = userName.Substring(indexofDomain + 1);
                        userNames.Add(userName);
                    }
                }
                catch (Exception) { }
            }

            return userNames;
        }
        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);
        }
Exemplo n.º 36
0
 /// <summary>
 /// Retrieve account information from uderlaying authentication system
 /// </summary>
 /// <param name="nativeId">The native id.</param>
 /// <param name="accountName">Name of the account.</param>
 /// <param name="accountDisplayName">Display name of the account.</param>
 protected override void GetAccountInfo(string nativeId, out string accountName, out string accountDisplayName)
 {
     SecurityIdentifier sid = new SecurityIdentifier(nativeId);
     IdentityReference idRef = sid.Translate(typeof(NTAccount));
     accountDisplayName = accountName = idRef.Value;
 }
Exemplo n.º 37
0
 private String ResolveAccountName(SecurityIdentifier SID)
 {
     try
     {
         return SID.Translate(typeof(NTAccount)).Value;
     }
     catch (Exception)
     {
         return SID.ToString();
     }
 }