Пример #1
0
        static PermissionsCheck()
        {
            if (PlatformCheck.CurrentlyRunningInWindows())
                groups = WindowsIdentity.GetCurrent().Groups;
            else
                groups = new IdentityReferenceCollection();

            if (PlatformCheck.CurrentlyRunningInWindows())
                sidCurrentUser = WindowsIdentity.GetCurrent().User.Value;
        }
Пример #2
0
        private IList <string> getStringNameGroups(IdentityReferenceCollection groups)
        {
            var groupsNames = new List <string>();

            groups.ToList().ForEach(g =>
            {
                var nomeArray = g.Translate(typeof(NTAccount)).ToString().Split(new char[] { '\\' });
                groupsNames.Add(nomeArray[nomeArray.Length - 1]);
            });

            return(groupsNames);
        }
        static void Main(string[] args)
        {
            while (true)
            {
                Helper.Timer(() =>
                {
                    "Calling Service".ConsoleYellow();

                    var handler = new HttpClientHandler();
                    handler.UseDefaultCredentials = true;
                    var client = new HttpClient(handler) { BaseAddress = _baseAddress };

                    var response = client.GetAsync("identity").Result;
                    response.EnsureSuccessStatusCode();

                    var identity = response.Content.ReadAsAsync<ViewClaims>().Result;
                    identity.ForEach(c => Helper.ShowClaim(c));

                    // convert SIDs to NT account names
                    "\nConvert SIDs\n".ConsoleYellow();

                    // this approach does one round trip to the authority (e.g. domain controller) per SID
                    identity.ForEach(c =>
                    {
                        if (c.ClaimType == ClaimTypes.GroupSid)
                        {
                            Console.WriteLine(c.Value);
                            var name = new SecurityIdentifier(c.Value).Translate(typeof(NTAccount));
                            name.Value.ConsoleGreen();

                            Console.WriteLine();
                        }
                    });

                    // this approach collects all SIDs first, and does a single round trip
                    var sids = new IdentityReferenceCollection(16);
                    identity.ForEach(c =>
                    {
                        if (c.ClaimType == ClaimTypes.GroupSid)
                        {
                            sids.Add(new SecurityIdentifier(c.Value));
                        }
                    });

                    "\nGroups:\n".ConsoleYellow();

                    var groups = sids.Translate(typeof(NTAccount));
                    groups.ToList().ForEach(g => Console.WriteLine(g.Value));
                });

                Console.ReadLine();
            }
        }
Пример #4
0
        // checks if a group belongs to the current user's groups
        private bool IsUserInGroup(string fsRuleReference, IdentityReferenceCollection currentUsersGroups)
        {
            foreach (IdentityReference currentUsersIndividualGroup in currentUsersGroups)
            {
                if (fsRuleReference == currentUsersIndividualGroup.Value.ToLower())
                {
                    return(true);
                }
            }

            return(false);
        }
Пример #5
0
        private List <string> GetUsergroups(IdentityReferenceCollection irc)
        {
            List <string> lista = new List <string>();

            foreach (IdentityReference group in irc)
            {
                SecurityIdentifier sid = (SecurityIdentifier)group.Translate(typeof(SecurityIdentifier));
                var name = sid.Translate(typeof(NTAccount));
                lista.Add(name.ToString());
            }

            return(lista);
        }
Пример #6
0
        private static bool AuthorizeRequest(WindowsIdentity wid)
        {
            IdentityReferenceCollection groups = wid.Groups;

            foreach (IdentityReference left in groups)
            {
                if (left == SupportApiService.s_localAdminsSid)
                {
                    return(true);
                }
            }
            return(false);
        }
Пример #7
0
        public static void showGroupsForCurrentUser()
        {
            // get the SIDs for my groups
            IdentityReferenceCollection myGroups = WindowsIdentity.GetCurrent().Groups;

            // translate them into NTaccount types
            IdentityReferenceCollection myGroups2 = myGroups.Translate(typeof(NTAccount));

            foreach (IdentityReference ir in myGroups2)
            {
                Console.WriteLine(ir.ToString());
            }
        }
Пример #8
0
        public static bool IsUserInGroup(string groupName)
        {
            WindowsIdentity currentUser = WindowsIdentity.GetCurrent();

            IdentityReferenceCollection userGroups = currentUser.Groups;

            foreach (IdentityReference group in userGroups)
            {
                IdentityReference translated = group.Translate(typeof(NTAccount));
                Console.WriteLine(translated.Value);
            }

            return(false);
        }
Пример #9
0
        //Sample Helper Function used by Listing 10.21
        private IdentityReferenceCollection ExpandTokenGroups(
            DirectoryEntry user)
        {
            user.RefreshCache(new string[] { "tokenGroups" });

            IdentityReferenceCollection irc =
                new IdentityReferenceCollection();

            foreach (byte[] sidBytes in user.Properties["tokenGroups"])
            {
                irc.Add(new SecurityIdentifier(sidBytes, 0));
            }
            return(irc);
        }
Пример #10
0
        public static List <string> Getgroups(out string name)
        {
            WindowsIdentity             currentUser = WindowsIdentity.GetCurrent();
            IdentityReferenceCollection t           = currentUser.Groups;
            List <string> groups = new List <string>();

            foreach (IdentityReference i in t)
            {
                groups.Add(new SecurityIdentifier(i.Value).Translate(typeof(NTAccount)).ToString());
                GroupList.Add(i);
            }
            name = currentUser.Name;
            return(groups);
        }
Пример #11
0
        /// <summary>
        /// Checks if given file is readable/writable for the current user
        /// The access rights that are expected of each file are: WriteData, ReadData, AppendData, CreateFile
        /// </summary>
        /// <param name="filePath">file to check for rights</param>
        /// <returns>true if file is readable/writable/deletable, false otherwise</returns>
        public bool IsSingleFileReadableWritable(string filePath)
        {
            WindowsIdentity             currentIdentity    = WindowsIdentity.GetCurrent();
            string                      username           = currentIdentity.Name;
            IdentityReferenceCollection currentUsersGroups = currentIdentity.Groups.Translate(typeof(NTAccount));

            FileSystemRights fsr = GetFilePermissions(username, filePath, currentUsersGroups);

            if (!IsReadableWritable(fsr))
            {
                return(false);
            }

            return(true);
        }
Пример #12
0
        public static bool IsUserAdmin(string username)
        {
            WindowsIdentity             ident  = GetWindowsIdentity(username);
            IdentityReferenceCollection groups = ident.Groups;

            foreach (IdentityReference group in groups)
            {
                if (group.Value == "S-1-5-32-544") /* BUILTIN\Administrators */
                {
                    return(true);
                }
            }

            return(false);
        }
Пример #13
0
        public virtual bool IsInRole (string role) {
            if (role == null || role.Length == 0) 
                return false;

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

            return IsInRole(sid);
        } 
        static void Main(string[] args)
        {
            while (true)
            {
                "Calling Service".ConsoleYellow();

                Helper.Timer(() =>
                    {
                        var proxy = CreateProxy();
                        var identity = proxy.GetClientIdentity();

                        identity.ForEach(c => Helper.ShowClaim(c));

                        // convert SIDs to NT account names
                        "\nConvert SIDs\n".ConsoleYellow();

                        // this approach does one round trip to the authority (e.g. domain controller) per SID
                        identity.ForEach(c =>
                        {
                            if (c.ClaimType == ClaimTypes.GroupSid)
                            {
                                Console.WriteLine(c.Value);
                                var name = new SecurityIdentifier(c.Value).Translate(typeof(NTAccount));
                                name.Value.ConsoleGreen();

                                Console.WriteLine();
                            }
                        });

                        // this approach collects all SIDs first, and does a single round trip
                        var sids = new IdentityReferenceCollection(16);
                        identity.ForEach(c =>
                        {
                            if (c.ClaimType == ClaimTypes.GroupSid)
                            {
                                sids.Add(new SecurityIdentifier(c.Value));
                            }
                        });

                        "\nGroups:\n".ConsoleYellow();

                        var groups = sids.Translate(typeof(NTAccount));
                        groups.ToList().ForEach(g => Console.WriteLine(g.Value));
                    });

                Console.ReadLine();
            }
        }
Пример #15
0
        private async Task <IActionResult> ProcessWindowsLoginAsync(string returnUrl)
        {
            // see if windows auth has already been requested and succeeded
            AuthenticateResult result = await this.HttpContext.AuthenticateAsync(AccountOptions.WindowsAuthenticationSchemeName);

            if (result?.Principal is WindowsPrincipal wp)
            {
                // we will issue the external cookie and then redirect the
                // user back to the external callback, in essence, treating windows
                // auth the same as any other external authentication mechanism
                AuthenticationProperties props = new AuthenticationProperties()
                {
                    RedirectUri = Url.Action("Callback"),
                    Items       =
                    {
                        { "returnUrl", returnUrl                                      },
                        { "scheme",    AccountOptions.WindowsAuthenticationSchemeName },
                    }
                };

                ClaimsIdentity id = new ClaimsIdentity(AccountOptions.WindowsAuthenticationSchemeName);
                id.AddClaim(new Claim(JwtClaimTypes.Subject, wp.FindFirst(ClaimTypes.PrimarySid).Value));
                id.AddClaim(new Claim(JwtClaimTypes.Name, wp.Identity.Name));

                // add the groups as claims -- be careful if the number of groups is too large
                if (AccountOptions.IncludeWindowsGroups)
                {
                    WindowsIdentity             wi     = wp.Identity as WindowsIdentity;
                    IdentityReferenceCollection groups = wi.Groups.Translate(typeof(NTAccount));
                    IEnumerable <Claim>         roles  = groups.Select(x => new Claim(JwtClaimTypes.Role, x.Value));
                    id.AddClaims(roles);
                }

                await HttpContext.SignInAsync(
                    IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme,
                    new ClaimsPrincipal(id),
                    props);

                return(Redirect(props.RedirectUri));
            }
            else
            {
                // trigger windows auth
                // since windows auth don't support the redirect uri,
                // this URL is re-triggered when we call challenge
                return(Challenge(AccountOptions.WindowsAuthenticationSchemeName));
            }
        }
Пример #16
0
        static PermissionsCheck()
        {
            if (PlatformCheck.CurrentlyRunningInWindows())
            {
                groups = WindowsIdentity.GetCurrent().Groups;
            }
            else
            {
                groups = new IdentityReferenceCollection();
            }

            if (PlatformCheck.CurrentlyRunningInWindows())
            {
                sidCurrentUser = WindowsIdentity.GetCurrent().User.Value;
            }
        }
Пример #17
0
        private void initGroup()
        {
            if (_identity != null)
            {
                IdentityReferenceCollection colGroups = _identity.Groups;
                foreach (IdentityReference group in colGroups)
                {
                    try
                    {
                        NTAccount account    = (NTAccount)group.Translate(typeof(NTAccount));
                        string    group_name = CutDomain(account.ToString());
                        if (groups.Contains(group_name) == false)
                        {
                            groups.Add(group_name);
                        }
                    }
                    catch (Exception) { }
                }
            }
            try
            {
                int    propertyCount = adUser.Properties["memberOf"].Count;
                String dn;
                int    equalsIndex, commaIndex;

                for (int propertyCounter = 0; propertyCounter < propertyCount;
                     propertyCounter++)
                {
                    dn = (String)adUser.Properties["memberOf"][propertyCounter];

                    equalsIndex = dn.IndexOf("=", 1);
                    commaIndex  = dn.IndexOf(",", 1);
                    if (-1 == equalsIndex)
                    {
                        continue;
                    }
                    string group_name = dn.Substring((equalsIndex + 1),
                                                     (commaIndex - equalsIndex) - 1);
                    if (groups.Contains(group_name) == false)
                    {
                        groups.Add(group_name);
                    }
                }
            }
            catch (Exception) { }
            _is_group_initilized = true;
        }
Пример #18
0
        public static Dictionary <string, string> TransalateActiveDirectorySids(List <string> sids)
        {
            var toReturn = new Dictionary <string, string>();

            var groups = new IdentityReferenceCollection();

            sids.ForEach(s => groups.Add(new SecurityIdentifier(s)));

            var names = groups.Translate(typeof(NTAccount), false);

            for (var i = 0; i < sids.Count; i++)
            {
                toReturn.Add(sids[i], names[i].Value);
            }

            return(toReturn);
        }
Пример #19
0
        static bool check_admin()
        {
            bool                        admin              = false;
            WindowsIdentity             windowsIdentity    = WindowsIdentity.GetCurrent();
            IdentityReferenceCollection group_current_user = windowsIdentity.Groups;
            string                      userName           = windowsIdentity.Name;
            string                      sid_admin          = "S-1-5-32-544";

            foreach (IdentityReference ir in group_current_user)
            {
                if (ir.Value == sid_admin)
                {
                    admin = true;
                }
            }
            return(admin);
        }
        private static IEnumerable<Claim> CreateGroupClaims(WindowsPrincipal principal)
        {
            var groupSidClaims = principal.FindAll(ClaimTypes.GroupSid);

            var sids = new IdentityReferenceCollection();
            foreach (var sidClaim in groupSidClaims)
            {
                sids.Add(new SecurityIdentifier(sidClaim.Value));
            }

            var groupNames = sids.Translate(typeof(NTAccount));

            var groupNameClaims = new List<Claim>(
                from n in groupNames select new Claim("role", n.Value));

            return groupNameClaims;
        }
        private static IEnumerable <Claim> CreateGroupClaims(WindowsPrincipal principal)
        {
            var groupSidClaims = principal.FindAll(ClaimTypes.GroupSid);

            var sids = new IdentityReferenceCollection();

            foreach (var sidClaim in groupSidClaims)
            {
                sids.Add(new SecurityIdentifier(sidClaim.Value));
            }

            var groupNames = sids.Translate(typeof(NTAccount));

            var groupNameClaims = new List <Claim>(
                from n in groupNames select new Claim("role", n.Value));

            return(groupNameClaims);
        }
Пример #22
0
        public void ExpandTokenGroupsFx2()
        {
            //point this to a user in the directory
            DirectoryEntry user = TestUtils.CreateDirectoryEntry(
                "CN=User1,OU=Users," + TestUtils.Settings.DefaultPartition);

            using (user)
            {
                //we use the collection in order to
                //batch the request for translation
                IdentityReferenceCollection irc
                    = ExpandTokenGroups(user).Translate(typeof(NTAccount));

                foreach (NTAccount account in irc)
                {
                    Console.WriteLine(account);
                }
            }
        }
Пример #23
0
        private static bool AuthorizeRequest()
        {
            WindowsIdentity windowsIdentity = ServiceSecurityContext.Current.PrimaryIdentity as WindowsIdentity;

            if (windowsIdentity == null)
            {
                return(false);
            }
            IdentityReferenceCollection groups = windowsIdentity.Groups;

            foreach (IdentityReference left in groups)
            {
                if (left == NotifyService.s_localAdminsSid)
                {
                    return(true);
                }
            }
            return(false);
        }
Пример #24
0
        private List <string> GetUserMembership()
        {
            List <string> SIDs = new List <string>();

            IntPtr             accountToken    = WindowsIdentity.GetCurrent().Token;
            WindowsIdentity    windowsIdentity = new WindowsIdentity(accountToken);
            SecurityIdentifier SIDGroup;
            string             groupName;

            //User SID
            SIDs.Add(windowsIdentity.Owner.ToString());

            IdentityReferenceCollection irc = windowsIdentity.Groups;

            foreach (IdentityReference ir in irc)
            {
                groupName = "";

                SIDGroup = new SecurityIdentifier(ir.Value);
                SIDs.Add(ir.Value);

                try
                {
                    groupName = SIDGroup.Translate(typeof(NTAccount)).Value;
                    AppLogger.WriteLine("User is member of " + groupName);
                } catch
                {
                    AppLogger.WriteLine("Error translating SID/GroupName");
                    continue;
                }

                if (groupName == Environment.MachineName + @"\" + Constants.LOCAL_SECURITYGROUP_NAME)
                {
                    AppLogger.WriteLine("Enabling Composition for User");
                    _isMemberOfDesignatedGroup = true;
                }

                SIDGroup = null;
            }
            windowsIdentity.Dispose();
            return(SIDs);
        }
        protected internal virtual async Task <IEnumerable <string> > GetCurrentWindowsUserRoles()
        {
            var securityIdentifiers = WindowsIdentity.GetCurrent().Groups
                                      .Cast <SecurityIdentifier>()
                                      .Where(securityIdentifier => securityIdentifier.AccountDomainSid != null);

            var identityReferences = new IdentityReferenceCollection();

            foreach (var securityIdentifier in securityIdentifiers)
            {
                identityReferences.Add(securityIdentifier);
            }

            var roles = identityReferences.Translate(typeof(NTAccount)).Select(ntAccount => ntAccount.Value);

            roles = roles.Where(role => !role.StartsWith($"{Environment.MachineName}\\", StringComparison.OrdinalIgnoreCase));
            roles = roles.OrderBy(item => item, StringComparer.OrdinalIgnoreCase);

            return(await Task.FromResult(roles));
        }
Пример #26
0
        /// <summary>
        /// Checks if all files in a directory are readable/writable for the current user and recursively checks all subdirectories.
        /// Also checks if current user has create/delete permissions for directories
        /// </summary>
        /// <param name="rootDirectory">Starting path to check the files in</param>
        /// <returns>false if there is at least one file which doesn't fulfill the above rights, true otherwise</returns>
        public static bool AreFilesReadableWritable(string rootDirectory)
        {
            WindowsIdentity             currentIdentity    = WindowsIdentity.GetCurrent();
            string                      username           = currentIdentity.Name;
            IdentityReferenceCollection currentUsersGroups = currentIdentity.Groups.Translate(typeof(NTAccount));

            string[] subDirectories = Directory.GetDirectories(rootDirectory);

            foreach (string directory in subDirectories)
            {
                string[] files = Directory.GetFiles(directory);

                foreach (string file in files)
                {
                    FileSystemRights fsr;

                    try
                    {
                        fsr = GetFilePermissions(username, file, currentUsersGroups);
                    }
                    catch (Exception)
                    {
                        return(false);
                    }

                    if (!IsReadableWritable(fsr))
                    {
                        return(false);
                    }
                }

                // check if can create/delete files;
                if (!CanCreateDeleteFiles(directory))
                {
                    return(false);
                }
            }

            return(true);
        }
        public static ISet <string> AsRoles(this IdentityReferenceCollection identityReferences, WindowsRolesOptions options = null)
        {
            if (identityReferences == null)
            {
                throw new ArgumentNullException(nameof(identityReferences));
            }

            options ??= new WindowsRolesOptions();

            // ReSharper disable AssignNullToNotNullAttribute
            var securityIdentifiers = identityReferences.Cast <SecurityIdentifier>();

            // ReSharper restore AssignNullToNotNullAttribute

            if (!options.BuiltInRolesEnabled)
            {
                securityIdentifiers = securityIdentifiers.Where(securityIdentifier => securityIdentifier.AccountDomainSid != null);
            }

            identityReferences = new IdentityReferenceCollection();

            foreach (var securityIdentifier in securityIdentifiers)
            {
                identityReferences.Add(securityIdentifier);
            }

            // ReSharper disable AssignNullToNotNullAttribute
            var roles = identityReferences.Translate(typeof(NTAccount)).Select(ntAccount => ntAccount.Value);

            // ReSharper restore AssignNullToNotNullAttribute

            if (!options.MachineRolesEnabled)
            {
                roles = roles.Where(role => !role.StartsWith($"{Environment.MachineName}\\", StringComparison.OrdinalIgnoreCase));
            }

            return(new SortedSet <string>(roles, StringComparer.OrdinalIgnoreCase));
        }
Пример #28
0
    public static void CloneAndProperties(bool cloneViaSerialization)
    {
        SafeAccessTokenHandle token = WindowsIdentity.GetCurrent().AccessToken;
        bool gotRef = false;

        try
        {
            token.DangerousAddRef(ref gotRef);
            IntPtr          logonToken = token.DangerousGetHandle();
            WindowsIdentity winId      = new WindowsIdentity(logonToken);

            WindowsIdentity cloneWinId = cloneViaSerialization ?
                                         BinaryFormatterHelpers.Clone(winId) :
                                         winId.Clone() as WindowsIdentity;
            Assert.NotNull(cloneWinId);

            Assert.Equal(winId.IsSystem, cloneWinId.IsSystem);
            Assert.Equal(winId.IsGuest, cloneWinId.IsGuest);
            Assert.Equal(winId.ImpersonationLevel, cloneWinId.ImpersonationLevel);

            Assert.Equal(winId.Name, cloneWinId.Name);
            Assert.Equal(winId.Owner, cloneWinId.Owner);

            IdentityReferenceCollection irc1 = winId.Groups;
            IdentityReferenceCollection irc2 = cloneWinId.Groups;
            Assert.Equal(irc1.Count, irc2.Count);

            CheckDispose(winId);
            CheckDispose(cloneWinId);
        }
        finally
        {
            if (gotRef)
            {
                token.DangerousRelease();
            }
        }
    }
Пример #29
0
        // Token: 0x060023A1 RID: 9121 RVA: 0x000A745C File Offset: 0x000A565C
        internal static bool AuthorizeRequest(WindowsIdentity wid)
        {
            List <SecurityIdentifier> list = new List <SecurityIdentifier>(2);

            if (RemoteDataProvider.s_exchangeGroupSid != null)
            {
                list.Add(RemoteDataProvider.s_exchangeGroupSid);
            }
            list.Add(RemoteDataProvider.s_localAdminsSid);
            IdentityReferenceCollection groups = wid.Groups;

            foreach (IdentityReference left in groups)
            {
                foreach (SecurityIdentifier right in list)
                {
                    if (left == right)
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Пример #30
0
    public static void CloneAndProperties()
    {
        IntPtr          logonToken = WindowsIdentity.GetCurrent().AccessToken.DangerousGetHandle();
        WindowsIdentity winId      = new WindowsIdentity(logonToken);
        WindowsIdentity cloneWinId = winId.Clone() as WindowsIdentity;

        Assert.NotNull(cloneWinId);

        Assert.Equal(winId.IsSystem, cloneWinId.IsSystem);
        Assert.Equal(winId.IsGuest, cloneWinId.IsGuest);
        Assert.Equal(winId.ImpersonationLevel, cloneWinId.ImpersonationLevel);

        Assert.Equal(winId.Name, cloneWinId.Name);
        Assert.Equal(winId.Owner, cloneWinId.Owner);

        IdentityReferenceCollection irc1 = winId.Groups;
        IdentityReferenceCollection irc2 = cloneWinId.Groups;

        Assert.Equal(irc1.Count, irc2.Count);

        CheckDispose(winId);
        CheckDispose(cloneWinId);
    }
Пример #31
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);
        }
Пример #32
0
        public KlijentServis(NetTcpBinding binding, EndpointAddress address)
            : base(binding, address)
        {
            //IPrincipal principal = Thread.CurrentPrincipal;
            //WindowsIdentity id = (WindowsIdentity)principal.Identity;
            //IdentityReferenceCollection clGroups = id.Groups;

            IdentityReferenceCollection clGroups = WindowsIdentity.GetCurrent().Groups;
            string groupName = "";

            foreach (IdentityReference group in clGroups)
            {
                SecurityIdentifier sid = (SecurityIdentifier)group.Translate(typeof(SecurityIdentifier));
                var name = sid.Translate(typeof(NTAccount));
                groupName = Formatter.ParseName(name.ToString());    /// return name of the Windows group
                if (groupName == "admini" || groupName == "radnik" || groupName == "korisnik")
                {
                    break;
                }
            }

            factory = this.CreateChannel();
        }
Пример #33
0
        public static bool CheckFileAccessRights(string path, FileSystemRights rightsToCheck)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentException();
            }
            if (!File.Exists(path))
            {
                throw new FileNotFoundException(path);
            }
            WindowsIdentity             current = WindowsIdentity.GetCurrent();
            IdentityReferenceCollection groups  = current.Groups;
            AuthorizationRuleCollection rules   = new FileInfo(path).GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier));
            bool flag  = false;
            bool flag2 = false;

            foreach (FileSystemAccessRule rule in rules)
            {
                if (groups.Contains(rule.IdentityReference) || current.User.Equals(rule.IdentityReference))
                {
                    if (rule.AccessControlType.Equals(AccessControlType.Deny))
                    {
                        if ((rule.FileSystemRights & rightsToCheck) == 0)
                        {
                            continue;
                        }
                        flag2 = true;
                        break;
                    }
                    if (rule.AccessControlType.Equals(AccessControlType.Allow) && ((rule.FileSystemRights & rightsToCheck) == rightsToCheck))
                    {
                        flag = true;
                    }
                }
            }
            return(flag & !flag2);
        }
Пример #34
0
        protected internal virtual async Task <ISet <string> > GetWindowsRoles(WindowsIdentity windowsIdentity)
        {
            if (windowsIdentity == null)
            {
                throw new ArgumentNullException(nameof(windowsIdentity));
            }

            // ReSharper disable AssignNullToNotNullAttribute
            var securityIdentifiers = windowsIdentity.Groups.Cast <SecurityIdentifier>();
            // ReSharper restore AssignNullToNotNullAttribute

            var options = this.OptionsMonitor.CurrentValue.Roles.Windows;

            if (!options.BuiltInRolesEnabled)
            {
                securityIdentifiers = securityIdentifiers.Where(securityIdentifier => securityIdentifier.AccountDomainSid != null);
            }

            var identityReferences = new IdentityReferenceCollection();

            foreach (var securityIdentifier in securityIdentifiers)
            {
                identityReferences.Add(securityIdentifier);
            }

            // ReSharper disable AssignNullToNotNullAttribute
            var windowsRoles = identityReferences.Translate(typeof(NTAccount)).Select(ntAccount => ntAccount.Value);

            // ReSharper restore AssignNullToNotNullAttribute

            if (!options.MachineRolesEnabled)
            {
                windowsRoles = windowsRoles.Where(windowsRole => !windowsRole.StartsWith($"{Environment.MachineName}\\", StringComparison.OrdinalIgnoreCase));
            }

            return(await Task.FromResult(new SortedSet <string>(windowsRoles, StringComparer.OrdinalIgnoreCase)));
        }
Пример #35
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="root"></param>
        /// <param name="username"></param>
        /// <returns></returns>
        public static string[] GetRolesForUser(DirectoryEntry root, string username)
        {
            var user  = getUser(root, username);
            var roles = new List <string>();
            IdentityReferenceCollection groupCollection = ExpandTokenGroups(user).Translate(typeof(NTAccount), false);

            if (groupCollection != null)
            {
                foreach (object g in groupCollection)
                {
                    try
                    {
                        NTAccount group    = g as NTAccount;
                        String    roleName = group.ToString().Substring(group.ToString().IndexOf(@"\") + 1);
                        if (roleName != String.Empty)
                        {
                            roles.Add(roleName);
                        }
                    }
                    catch { }
                }
            }
            return(roles.ToArray());
        }
Пример #36
0
    public static void CloneAndProperties()
    {
        TestUsingAccessToken((logonToken) =>
        {
            var winId = new WindowsIdentity(logonToken);

            WindowsIdentity cloneWinId = winId.Clone() as WindowsIdentity;
            Assert.NotNull(cloneWinId);

            Assert.Equal(winId.IsSystem, cloneWinId.IsSystem);
            Assert.Equal(winId.IsGuest, cloneWinId.IsGuest);
            Assert.Equal(winId.ImpersonationLevel, cloneWinId.ImpersonationLevel);

            Assert.Equal(winId.Name, cloneWinId.Name);
            Assert.Equal(winId.Owner, cloneWinId.Owner);

            IdentityReferenceCollection irc1 = winId.Groups;
            IdentityReferenceCollection irc2 = cloneWinId.Groups;
            Assert.Equal(irc1.Count, irc2.Count);

            CheckDispose(winId);
            CheckDispose(cloneWinId);
        });
    }
Пример #37
0
        private AuthorizationRuleCollection GetRules(bool access, bool includeExplicit, bool includeInherited, System.Type targetType)
        {
            ReadLock();

            try
            {
                AuthorizationRuleCollection result = new AuthorizationRuleCollection();

                if (!IsValidTargetTypeStatic(targetType))
                {
                    throw new ArgumentException(SR.Arg_MustBeIdentityReferenceType, "targetType");
                }

                CommonAcl acl = null;

                if (access)
                {
                    if ((_securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclPresent) != 0)
                    {
                        acl = _securityDescriptor.DiscretionaryAcl;
                    }
                }
                else // !access == audit
                {
                    if ((_securityDescriptor.ControlFlags & ControlFlags.SystemAclPresent) != 0)
                    {
                        acl = _securityDescriptor.SystemAcl;
                    }
                }

                if (acl == null)
                {
                    //
                    // The required ACL was not present; return an empty collection.
                    //
                    return result;
                }

                IdentityReferenceCollection irTarget = null;

                if (targetType != typeof(SecurityIdentifier))
                {
                    IdentityReferenceCollection irSource = new IdentityReferenceCollection(acl.Count);

                    for (int i = 0; i < acl.Count; i++)
                    {
                        //
                        // Calling the indexer on a common ACL results in cloning,
                        // (which would not be the case if we were to use the internal RawAcl property)
                        // but also ensures that the resulting order of ACEs is proper
                        // However, this is a big price to pay - cloning all the ACEs just so that
                        // the canonical order could be ascertained just once.
                        // A better way would be to have an internal method that would canonicalize the ACL
                        // and call it once, then use the RawAcl.
                        //
                        QualifiedAce ace = acl[i] as QualifiedAce;

                        if (ace == null)
                        {
                            //
                            // Only consider qualified ACEs
                            //
                            continue;
                        }

                        if (ace.IsCallback == true)
                        {
                            //
                            // Ignore callback ACEs
                            //
                            continue;
                        }

                        if (access)
                        {
                            if (ace.AceQualifier != AceQualifier.AccessAllowed && ace.AceQualifier != AceQualifier.AccessDenied)
                            {
                                continue;
                            }
                        }
                        else
                        {
                            if (ace.AceQualifier != AceQualifier.SystemAudit)
                            {
                                continue;
                            }
                        }

                        irSource.Add(ace.SecurityIdentifier);
                    }

                    irTarget = irSource.Translate(targetType);
                }

                for (int i = 0; i < acl.Count; i++)
                {
                    //
                    // Calling the indexer on a common ACL results in cloning,
                    // (which would not be the case if we were to use the internal RawAcl property)
                    // but also ensures that the resulting order of ACEs is proper
                    // However, this is a big price to pay - cloning all the ACEs just so that
                    // the canonical order could be ascertained just once.
                    // A better way would be to have an internal method that would canonicalize the ACL
                    // and call it once, then use the RawAcl.
                    //
                    QualifiedAce ace = acl[i] as CommonAce;

                    if (ace == null)
                    {
                        ace = acl[i] as ObjectAce;
                        if (ace == null)
                        {
                            //
                            // Only consider common or object ACEs
                            //
                            continue;
                        }
                    }

                    if (ace.IsCallback == true)
                    {
                        //
                        // Ignore callback ACEs
                        //
                        continue;
                    }

                    if (access)
                    {
                        if (ace.AceQualifier != AceQualifier.AccessAllowed && ace.AceQualifier != AceQualifier.AccessDenied)
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (ace.AceQualifier != AceQualifier.SystemAudit)
                        {
                            continue;
                        }
                    }

                    if ((includeExplicit && ((ace.AceFlags & AceFlags.Inherited) == 0)) || (includeInherited && ((ace.AceFlags & AceFlags.Inherited) != 0)))
                    {
                        IdentityReference iref = (targetType == typeof(SecurityIdentifier)) ? ace.SecurityIdentifier : irTarget[i];

                        if (access)
                        {
                            AccessControlType type;

                            if (ace.AceQualifier == AceQualifier.AccessAllowed)
                            {
                                type = AccessControlType.Allow;
                            }
                            else
                            {
                                type = AccessControlType.Deny;
                            }

                            if (ace is ObjectAce)
                            {
                                ObjectAce objectAce = ace as ObjectAce;

                                result.AddRule(AccessRuleFactory(iref, objectAce.AccessMask, objectAce.IsInherited, objectAce.InheritanceFlags, objectAce.PropagationFlags, type, objectAce.ObjectAceType, objectAce.InheritedObjectAceType));
                            }
                            else
                            {
                                CommonAce commonAce = ace as CommonAce;

                                if (commonAce == null)
                                {
                                    continue;
                                }

                                result.AddRule(AccessRuleFactory(iref, commonAce.AccessMask, commonAce.IsInherited, commonAce.InheritanceFlags, commonAce.PropagationFlags, type));
                            }
                        }
                        else
                        {
                            if (ace is ObjectAce)
                            {
                                ObjectAce objectAce = ace as ObjectAce;

                                result.AddRule(AuditRuleFactory(iref, objectAce.AccessMask, objectAce.IsInherited, objectAce.InheritanceFlags, objectAce.PropagationFlags, objectAce.AuditFlags, objectAce.ObjectAceType, objectAce.InheritedObjectAceType));
                            }
                            else
                            {
                                CommonAce commonAce = ace as CommonAce;

                                if (commonAce == null)
                                {
                                    continue;
                                }

                                result.AddRule(AuditRuleFactory(iref, commonAce.AccessMask, commonAce.IsInherited, commonAce.InheritanceFlags, commonAce.PropagationFlags, commonAce.AuditFlags));
                            }
                        }
                    }
                }

                return result;
            }
            finally
            {
                ReadUnlock();
            }
        }
 private AuthorizationRuleCollection GetRules(bool access, bool includeExplicit, bool includeInherited, Type targetType)
 {
     AuthorizationRuleCollection rules2;
     base.ReadLock();
     try
     {
         AuthorizationRuleCollection rules = new AuthorizationRuleCollection();
         if (!SecurityIdentifier.IsValidTargetTypeStatic(targetType))
         {
             throw new ArgumentException(Environment.GetResourceString("Arg_MustBeIdentityReferenceType"), "targetType");
         }
         CommonAcl discretionaryAcl = null;
         if (access)
         {
             if ((base._securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclPresent) != ControlFlags.None)
             {
                 discretionaryAcl = base._securityDescriptor.DiscretionaryAcl;
             }
         }
         else if ((base._securityDescriptor.ControlFlags & ControlFlags.SystemAclPresent) != ControlFlags.None)
         {
             discretionaryAcl = base._securityDescriptor.SystemAcl;
         }
         if (discretionaryAcl == null)
         {
             return rules;
         }
         IdentityReferenceCollection references = null;
         if (targetType != typeof(SecurityIdentifier))
         {
             IdentityReferenceCollection references2 = new IdentityReferenceCollection(discretionaryAcl.Count);
             for (int j = 0; j < discretionaryAcl.Count; j++)
             {
                 QualifiedAce ace = discretionaryAcl[j] as QualifiedAce;
                 if ((ace == null) || ace.IsCallback)
                 {
                     continue;
                 }
                 if (access)
                 {
                     if ((ace.AceQualifier == AceQualifier.AccessAllowed) || (ace.AceQualifier == AceQualifier.AccessDenied))
                     {
                         goto Label_00DD;
                     }
                     continue;
                 }
                 if (ace.AceQualifier != AceQualifier.SystemAudit)
                 {
                     continue;
                 }
             Label_00DD:
                 references2.Add(ace.SecurityIdentifier);
             }
             references = references2.Translate(targetType);
         }
         for (int i = 0; i < discretionaryAcl.Count; i++)
         {
             QualifiedAce ace2 = discretionaryAcl[i] as CommonAce;
             if (ace2 == null)
             {
                 ace2 = discretionaryAcl[i] as ObjectAce;
                 if (ace2 == null)
                 {
                     continue;
                 }
             }
             if (ace2.IsCallback)
             {
                 continue;
             }
             if (access)
             {
                 if ((ace2.AceQualifier == AceQualifier.AccessAllowed) || (ace2.AceQualifier == AceQualifier.AccessDenied))
                 {
                     goto Label_0174;
                 }
                 continue;
             }
             if (ace2.AceQualifier != AceQualifier.SystemAudit)
             {
                 continue;
             }
         Label_0174:
             if ((includeExplicit && (((byte) (ace2.AceFlags & AceFlags.Inherited)) == 0)) || (includeInherited && (((byte) (ace2.AceFlags & AceFlags.Inherited)) != 0)))
             {
                 IdentityReference identityReference = (targetType == typeof(SecurityIdentifier)) ? ace2.SecurityIdentifier : references[i];
                 if (access)
                 {
                     AccessControlType allow;
                     if (ace2.AceQualifier == AceQualifier.AccessAllowed)
                     {
                         allow = AccessControlType.Allow;
                     }
                     else
                     {
                         allow = AccessControlType.Deny;
                     }
                     if (ace2 is ObjectAce)
                     {
                         ObjectAce ace3 = ace2 as ObjectAce;
                         rules.AddRule(this.AccessRuleFactory(identityReference, ace3.AccessMask, ace3.IsInherited, ace3.InheritanceFlags, ace3.PropagationFlags, allow, ace3.ObjectAceType, ace3.InheritedObjectAceType));
                     }
                     else
                     {
                         CommonAce ace4 = ace2 as CommonAce;
                         if (ace4 != null)
                         {
                             rules.AddRule(this.AccessRuleFactory(identityReference, ace4.AccessMask, ace4.IsInherited, ace4.InheritanceFlags, ace4.PropagationFlags, allow));
                         }
                     }
                 }
                 else if (ace2 is ObjectAce)
                 {
                     ObjectAce ace5 = ace2 as ObjectAce;
                     rules.AddRule(this.AuditRuleFactory(identityReference, ace5.AccessMask, ace5.IsInherited, ace5.InheritanceFlags, ace5.PropagationFlags, ace5.AuditFlags, ace5.ObjectAceType, ace5.InheritedObjectAceType));
                 }
                 else
                 {
                     CommonAce ace6 = ace2 as CommonAce;
                     if (ace6 != null)
                     {
                         rules.AddRule(this.AuditRuleFactory(identityReference, ace6.AccessMask, ace6.IsInherited, ace6.InheritanceFlags, ace6.PropagationFlags, ace6.AuditFlags));
                     }
                 }
             }
         }
         rules2 = rules;
     }
     finally
     {
         base.ReadUnlock();
     }
     return rules2;
 }
Пример #39
0
 internal IdentityNotMappedException(string message, IdentityReferenceCollection unmappedIdentities)
     : this(message)
 {
     _unmappedIdentities = unmappedIdentities;
 }
Пример #40
0
        private static IdentityReferenceCollection TranslateToSids(IdentityReferenceCollection sourceAccounts, out bool someFailed)
        {
            if (sourceAccounts == null)
            {
                throw new ArgumentNullException("sourceAccounts");
            }

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

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

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

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

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

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

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

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

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

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

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

                //
                // Now perform the actual lookup
                //

                someFailed = false;
                uint ReturnCode;

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

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

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

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

                    throw new Exception(Interop.mincore.GetMessage(win32ErrorCode));
                }

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

                IdentityReferenceCollection Result = new IdentityReferenceCollection(sourceAccounts.Count);

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

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

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

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

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

                return Result;
            }
            finally
            {
                LsaHandle.Dispose();
                ReferencedDomainsPtr.Dispose();
                SidsPtr.Dispose();
            }
        }
Пример #41
0
        internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceAccounts, Type targetType, out bool someFailed)
        {
            if (sourceAccounts == null)
            {
                throw new ArgumentNullException("sourceAccounts");
            }
            Contract.EndContractBlock();

            if (targetType == typeof(SecurityIdentifier))
            {
                return TranslateToSids(sourceAccounts, out someFailed);
            }

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

                    default:
                        for (int m = 0; m < sourceAccounts.Count; m++)
                        {
                            references.Add(sourceAccounts[m]);
                        }
                        break;
                }
                references2 = references;
            }
            finally
            {
                invalidHandle.Dispose();
                referencedDomains.Dispose();
                sids.Dispose();
            }
            return references2;
        }
 private AuthorizationRuleCollection GetRules(bool access, bool includeExplicit, bool includeInherited, Type targetType)
 {
     AuthorizationRuleCollection rules2;
     base.ReadLock();
     try
     {
         AuthorizationRuleCollection rules = new AuthorizationRuleCollection();
         if (!SecurityIdentifier.IsValidTargetTypeStatic(targetType))
         {
             throw new ArgumentException(Environment.GetResourceString("Arg_MustBeIdentityReferenceType"), "targetType");
         }
         CommonAcl discretionaryAcl = null;
         if (access)
         {
             if ((base._securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclPresent) != ControlFlags.None)
             {
                 discretionaryAcl = base._securityDescriptor.DiscretionaryAcl;
             }
         }
         else if ((base._securityDescriptor.ControlFlags & ControlFlags.SystemAclPresent) != ControlFlags.None)
         {
             discretionaryAcl = base._securityDescriptor.SystemAcl;
         }
         if (discretionaryAcl == null)
         {
             return rules;
         }
         IdentityReferenceCollection references = null;
         if (targetType != typeof(SecurityIdentifier))
         {
             IdentityReferenceCollection references2 = new IdentityReferenceCollection(discretionaryAcl.Count);
             for (int j = 0; j < discretionaryAcl.Count; j++)
             {
                 CommonAce ace = discretionaryAcl[j] as CommonAce;
                 if (this.AceNeedsTranslation(ace, access, includeExplicit, includeInherited))
                 {
                     references2.Add(ace.SecurityIdentifier);
                 }
             }
             references = references2.Translate(targetType);
         }
         int num2 = 0;
         for (int i = 0; i < discretionaryAcl.Count; i++)
         {
             CommonAce ace2 = discretionaryAcl[i] as CommonAce;
             if (this.AceNeedsTranslation(ace2, access, includeExplicit, includeInherited))
             {
                 IdentityReference identityReference = (targetType == typeof(SecurityIdentifier)) ? ace2.SecurityIdentifier : references[num2++];
                 if (access)
                 {
                     AccessControlType allow;
                     if (ace2.AceQualifier == AceQualifier.AccessAllowed)
                     {
                         allow = AccessControlType.Allow;
                     }
                     else
                     {
                         allow = AccessControlType.Deny;
                     }
                     rules.AddRule(this.AccessRuleFactory(identityReference, ace2.AccessMask, ace2.IsInherited, ace2.InheritanceFlags, ace2.PropagationFlags, allow));
                 }
                 else
                 {
                     rules.AddRule(this.AuditRuleFactory(identityReference, ace2.AccessMask, ace2.IsInherited, ace2.InheritanceFlags, ace2.PropagationFlags, ace2.AuditFlags));
                 }
             }
         }
         rules2 = rules;
     }
     finally
     {
         base.ReadUnlock();
     }
     return rules2;
 }
Пример #46
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(SR.IdentityReference_MustBeIdentityReference, "targetType");
            }
        }
Пример #47
0
        internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceAccounts, Type targetType, bool forceSuccess)
        {
            bool SomeFailed = false;
            IdentityReferenceCollection Result;

            Result = Translate(sourceAccounts, targetType, out SomeFailed);

            if (forceSuccess && SomeFailed)
            {
                IdentityReferenceCollection UnmappedIdentities = new IdentityReferenceCollection();

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

                throw new IdentityNotMappedException(SR.IdentityReference_IdentityNotMapped, UnmappedIdentities);
            }

            return Result;
        }