public void SecurityDescriptorSearch()
        {
            //explicitly create our searchroot
            DirectoryEntry searchRoot = TestUtils.GetDefaultPartition();

            using (searchRoot) //we are responsible for disposing
            {
                DirectorySearcher ds = new DirectorySearcher(
                    searchRoot,
                    "(cn=User1)",
                    new string[] { "ntSecurityDescriptor" }
                    );

                //Get the Security for this object
                ds.SecurityMasks = SecurityMasks.Dacl
                                   | SecurityMasks.Group
                                   | SecurityMasks.Owner;

                SearchResult sr = ds.FindOne();

                if (sr == null)
                {
                    throw new Exception("No user found");
                }

                byte[] descriptorBytes =
                    (byte[])sr.Properties["ntSecurityDescriptor"][0];


                ActiveDirectorySecurity ads = new ActiveDirectorySecurity();

                ads.SetSecurityDescriptorBinaryForm(
                    descriptorBytes,
                    AccessControlSections.All
                    );

                //helper function
                PrintSD(ads);

                AuthorizationRuleCollection rules = ads.GetAccessRules(
                    true,
                    true,
                    typeof(NTAccount)
                    );

                foreach (ActiveDirectoryAccessRule rule in rules)
                {
                    //helper function
                    PrintAce(rule);
                }
            }

            //Sample output:
            //
            //=====Security Descriptor=====
            //    Owner: S-1-450115865-2557621802-512
            //    Group: S-1-450115865-2557621802-512
            //=====ACE=====
            //    Identity: NT AUTHORITY\SELF
            //    AccessControlType: Allow
            //    ActiveDirectoryRights: ExtendedRight
            //    InheritanceType: None
            //    ObjectType: ab721a53-1e2f-11d0-9819-00aa0040529b
            //    InheritedObjectType: <null>
            //    ObjectFlags: ObjectAceTypePresent
        }
        private static void CheckWritePermission(string path)
        {
            WindowsIdentity  identity           = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal          = new WindowsPrincipal(identity);
            bool             isInRoleWithAccess = false;

            try
            {
                DirectoryInfo               di    = new DirectoryInfo(DirectoryUtils.ToLongPath(path));
                DirectorySecurity           ds    = di.GetAccessControl();
                AuthorizationRuleCollection rules = ds.GetAccessRules(true, true, typeof(NTAccount));

                foreach (AuthorizationRule rule in rules)
                {
                    FileSystemAccessRule fsAccessRule = rule as FileSystemAccessRule;
                    if (fsAccessRule == null)
                    {
                        continue;
                    }

                    if ((fsAccessRule.FileSystemRights & FileSystemRights.Write) != 0)
                    {
                        NTAccount ntAccount = rule.IdentityReference as NTAccount;
                        if (ntAccount == null)
                        {
                            continue;
                        }

                        if (principal.IsInRole(ntAccount.Value))
                        {
                            if (fsAccessRule.AccessControlType == AccessControlType.Deny)
                            {
                                isInRoleWithAccess = false;
                                break;
                            }
                            isInRoleWithAccess = true;
                        }
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
            }

            if (!isInRoleWithAccess)
            {
                // is run as administrator?
                if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    return;
                }

                // try run as admin
                Process  proc = new Process();
                string[] args = Environment.GetCommandLineArgs();
                proc.StartInfo.FileName        = args[0];
                proc.StartInfo.Arguments       = string.Join(" ", args.Skip(1).Select(t => $"\"{t}\""));
                proc.StartInfo.UseShellExecute = true;
                proc.StartInfo.Verb            = "runas";

                try
                {
                    proc.Start();
                    Environment.Exit(0);
                }
                catch (Win32Exception ex)
                {
                    //The operation was canceled by the user.
                    const int ERROR_CANCELLED = 1223;
                    if (ex.NativeErrorCode == ERROR_CANCELLED)
                    {
                        Logger.Log(LogType.Error, LogCategory.General, $"You can't export to folder {path} without Administrator permission");
                        Console.ReadKey();
                    }
                    else
                    {
                        Logger.Log(LogType.Error, LogCategory.General, $"You have to restart application as Administator in order to export to folder {path}");
                        Console.ReadKey();
                    }
                }
            }
        }
Example #3
0
        public static List <Rule> GetPermissions(AuthorizationRuleCollection rules, string format = "fdDlxXtamsocrw", string rwFormat = "madxp")
        {
            List <Rule> parsedRules = new List <Rule>();

            foreach (FileSystemAccessRule rule in rules)
            {
                Rule tempRule = new Rule();
                tempRule.User = rule.IdentityReference.Value;
                string perm = "";
                foreach (char entry in format)
                {
                    if (entry == 'f')
                    {
                        perm += rule.FileSystemRights.HasFlag(FileSystemRights.FullControl) ? 'f' : '-';
                    }

                    else if (entry == 'd')
                    {
                        perm += rule.FileSystemRights.HasFlag(FileSystemRights.Delete) ? 'd' : '-';
                    }
                    else if (entry == 'D')
                    {
                        perm += rule.FileSystemRights.HasFlag(FileSystemRights.DeleteSubdirectoriesAndFiles) ? 'D' : '-';
                    }

                    else if (entry == 'l')
                    {
                        perm += rule.FileSystemRights.HasFlag(FileSystemRights.ListDirectory) ? 'l' : '-';
                    }
                    else if (entry == 'x')
                    {
                        perm += rule.FileSystemRights.HasFlag(FileSystemRights.ExecuteFile) ? 'x' : '-';
                    }
                    else if (entry == 'X')
                    {
                        perm += rule.FileSystemRights.HasFlag(FileSystemRights.ReadAndExecute) ? 'X' : '-';
                    }
                    else if (entry == 't')
                    {
                        perm += rule.FileSystemRights.HasFlag(FileSystemRights.Traverse) ? 't' : '-';
                    }

                    else if (entry == 'a')
                    {
                        perm += rule.FileSystemRights.HasFlag(FileSystemRights.AppendData) ? 'a' : '-';
                    }
                    else if (entry == 'm')
                    {
                        perm += rule.FileSystemRights.HasFlag(FileSystemRights.Modify) ? 'm' : '-';
                    }
                    else if (entry == 's')
                    {
                        perm += rule.FileSystemRights.HasFlag(FileSystemRights.Synchronize) ? 's' : '-';
                    }
                    else if (entry == 'o')
                    {
                        perm += rule.FileSystemRights.HasFlag(FileSystemRights.TakeOwnership) ? 'o' : '-';
                    }

                    else if (entry == 'c')
                    {
                        perm += "c[";
                        perm += rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) ? 'd' : '-';
                        perm += rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles) ? 'f' : '-';
                        perm += "]";
                    }

                    else if (entry == 'r')
                    {
                        if (rwFormat == "m")
                        {
                            perm += rule.FileSystemRights.HasFlag(FileSystemRights.Read) ? 'r' : '-';
                        }
                        else
                        {
                            perm += "r[";
                            foreach (char readentry in rwFormat)
                            {
                                if (readentry == 'm')
                                {
                                    perm += rule.FileSystemRights.HasFlag(FileSystemRights.Read) ? 'r' : '-';
                                }
                                else if (readentry == 'a')
                                {
                                    perm += rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) ? 'a' : '-';
                                }
                                else if (readentry == 'd')
                                {
                                    perm += rule.FileSystemRights.HasFlag(FileSystemRights.ReadData) ? 'd' : '-';
                                }
                                else if (readentry == 'x')
                                {
                                    perm += rule.FileSystemRights.HasFlag(FileSystemRights.ReadExtendedAttributes) ? 'x' : '-';
                                }
                                else if (readentry == 'p')
                                {
                                    perm += rule.FileSystemRights.HasFlag(FileSystemRights.ReadPermissions) ? 'p' : '-';
                                }
                            }
                            perm += "]";
                        }
                    }

                    else if (entry == 'w')
                    {
                        if (rwFormat == "m")
                        {
                            perm += rule.FileSystemRights.HasFlag(FileSystemRights.Read) ? 'r' : '-';
                        }
                        else
                        {
                            perm += "w[";
                            foreach (char readentry in rwFormat)
                            {
                                if (readentry == 'm')
                                {
                                    perm += rule.FileSystemRights.HasFlag(FileSystemRights.Write) ? 'w' : '-';
                                }
                                else if (readentry == 'a')
                                {
                                    perm += rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) ? 'a' : '-';
                                }
                                else if (readentry == 'd')
                                {
                                    perm += rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) ? 'd' : '-';
                                }
                                else if (readentry == 'x')
                                {
                                    perm += rule.FileSystemRights.HasFlag(FileSystemRights.WriteExtendedAttributes) ? 'x' : '-';
                                }
                                else if (readentry == 'p')
                                {
                                    perm += rule.FileSystemRights.HasFlag(FileSystemRights.ChangePermissions) ? 'c' : '-';
                                }
                            }
                            perm += "]";
                        };
                    }
                    ;
                    tempRule.PermString = perm;
                }
                ;
                parsedRules.Add(tempRule);
            }
            ;
            return(parsedRules);
        }
Example #4
0
        /// <summary>
        /// Exporting permissions of directory
        /// </summary>
        /// <param name="directory">Папка права которой требуется вычислить</param>
        private void WalkDirectoryTree(string directory)
        {
            if (allow_work)
            {
                DirectoryInfo root = new DirectoryInfo(directory);
                if (root.Exists)
                {
                    AuthorizationRuleCollection ACLs_temp = root.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
                    AuthorizationRuleCollection ACLs      = new AuthorizationRuleCollection();
                    foreach (FileSystemAccessRule ACL_temp in ACLs_temp)
                    {
                        if (checkBox2.Checked && !IsSystemUser(ACL_temp.IdentityReference.ToString()))
                        {
                            ACLs.AddRule(ACL_temp);//add only not system
                        }
                        else //not skip
                        {
                            ACLs.AddRule(ACL_temp);//add all
                        }
                    }
                    ACLs_temp = null;
                    if (ACLs.Count > 0)
                    {
                        foreach (FileSystemAccessRule ACL in ACLs)
                        {
                            string[] rights_Temp = ACL.FileSystemRights.ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                            foreach (string right_Temp in rights_Temp)
                            {
                                string ACL_string = ACL.IdentityReference.ToString();
                                string ACL_IF     = ACL.InheritanceFlags.ToString();
                                string ACL_IsI    = ACL.IsInherited.ToString();
                                string right      = right_Temp.Trim();
                                switch (right_Temp)//Печатаем большими буквами чтобы визуально отличать, но при сортировке и фильтре чтобы не отличалось
                                {
                                case "268435456":
                                    right = "FULLCONTROLL";
                                    break;

                                case "-536805376":
                                    right = "EXECUTE";
                                    break;

                                case "-1073741824":
                                    right = "WRITE";
                                    break;

                                case "2147483648":
                                    right = "READ";
                                    break;

                                case "-1610612736":    //https://coderoad.ru/26427967/Get-acl-%D0%BF%D0%BE%D0%B2%D1%82%D0%BE%D1%80%D1%8F%D1%8E%D1%89%D0%B8%D0%B5%D1%81%D1%8F-%D0%B3%D1%80%D1%83%D0%BF%D0%BF%D1%8B-Powershell
                                    right = "READANDEXECUTE";

                                    if (ACL.AccessControlType.ToString().Equals("Allow"))
                                    {
                                        Invoke((ThreadStart) delegate { listView1.Items.Add(new ListViewItem(new string[] { directory, ACL_string, "SYNCHRONIZE", string.Empty, ACL_IF, ACL_IsI })); });
                                    }
                                    if (ACL.AccessControlType.ToString().Equals("Deny"))
                                    {
                                        Invoke((ThreadStart) delegate { listView1.Items.Add(new ListViewItem(new string[] { directory, ACL_string, string.Empty, "SYNCHRONIZE", ACL_IF, ACL_IsI })); });
                                    }
                                    break;

                                default:
                                    break;
                                }
                                try
                                {
                                    if (ACL.AccessControlType.ToString().Equals("Allow"))
                                    {
                                        Invoke((ThreadStart) delegate { listView1.Items.Add(new ListViewItem(new string[] { directory, ACL_string, right, string.Empty, ACL_IF, ACL_IsI })); });
                                    }
                                    if (ACL.AccessControlType.ToString().Equals("Deny"))
                                    {
                                        Invoke((ThreadStart) delegate { listView1.Items.Add(new ListViewItem(new string[] { directory, ACL_string, string.Empty, right, ACL_IF, ACL_IsI })); });
                                    }
                                }
                                catch (UnauthorizedAccessException ee) { MessageBox.Show(ee.StackTrace); }
                                catch (Exception ee) { MessageBox.Show(ee.StackTrace); }
                            }
                        }
                    }
                    try
                    {
                        List <DirectoryInfo> subDirs = new List <DirectoryInfo>(root.GetDirectories()); // рекурсией проверяем все подпапки
                        if (checkBox2.Checked == true)                                                  //remove system directories
                        {
                            foreach (string systemfolder in systemfolders)
                            {
                                foreach (DirectoryInfo subDir in subDirs)
                                {
                                    if (subDir.Name.ToString().Equals(systemfolder, StringComparison.CurrentCultureIgnoreCase))
                                    {
                                        subDirs.Remove(subDir);
                                        break;
                                    }
                                }
                            }
                            foreach (string systemfolder in systemfolders)
                            {
                                foreach (DirectoryInfo subDir in subDirs)
                                {
                                    if (subDir.Attributes.ToString().Contains("System"))
                                    {
                                        subDirs.Remove(subDir);
                                        break;
                                    }
                                }
                            }
                        }

                        List <string> Tree = new List <string>(root.FullName.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries));
                        if (Tree.Count < root_layer + Convert.ToInt32(textBox2.Text))
                        {
                            foreach (DirectoryInfo dirInfo in subDirs)
                            {
                                if (allow_work)
                                {
                                    WalkDirectoryTree(dirInfo.FullName);
                                }
                            }
                        }
                    }
                    catch { Invoke((ThreadStart) delegate { listView1.Items.Add(new ListViewItem(new string[] { directory, "Failed to get subfolders list. Acceess denied!?", string.Empty, string.Empty, string.Empty, string.Empty })); }); }
                }
                else
                {
                    MessageBox.Show("The folder does not exist. Canceling an operation.");
                }
            }
        }
Example #5
0
        /// <summary>
        /// Supply the path to the file or directory and a user or group.
        /// Access checks are done
        /// during instantiation to ensure we always have a valid object
        /// </summary>
        /// <param name="path"></param>
        /// <param name="principal"></param>
        public UserFileAccessRights(string path,
                                    System.Security.Principal.WindowsIdentity principal)
        {
            this._path      = path;
            this._principal = principal;

            try
            {
                System.IO.FileInfo          fi  = new System.IO.FileInfo(_path);
                AuthorizationRuleCollection acl = fi.GetAccessControl().GetAccessRules
                                                      (true, true, typeof(SecurityIdentifier));
                for (int i = 0; i < acl.Count; i++)
                {
                    System.Security.AccessControl.FileSystemAccessRule rule =
                        (System.Security.AccessControl.FileSystemAccessRule)acl[i];
                    if (_principal.User.Equals(rule.IdentityReference))
                    {
                        if (System.Security.AccessControl.AccessControlType.Deny.Equals
                                (rule.AccessControlType))
                        {
                            if (contains(FileSystemRights.AppendData, rule))
                            {
                                _denyAppendData = true;
                            }
                            if (contains(FileSystemRights.ChangePermissions, rule))
                            {
                                _denyChangePermissions = true;
                            }
                            if (contains(FileSystemRights.CreateDirectories, rule))
                            {
                                _denyCreateDirectories = true;
                            }
                            if (contains(FileSystemRights.CreateFiles, rule))
                            {
                                _denyCreateFiles = true;
                            }
                            if (contains(FileSystemRights.Delete, rule))
                            {
                                _denyDelete = true;
                            }
                            if (contains(FileSystemRights.DeleteSubdirectoriesAndFiles,
                                         rule))
                            {
                                _denyDeleteSubdirectoriesAndFiles = true;
                            }
                            if (contains(FileSystemRights.ExecuteFile, rule))
                            {
                                _denyExecuteFile = true;
                            }
                            if (contains(FileSystemRights.FullControl, rule))
                            {
                                _denyFullControl = true;
                            }
                            if (contains(FileSystemRights.ListDirectory, rule))
                            {
                                _denyListDirectory = true;
                            }
                            if (contains(FileSystemRights.Modify, rule))
                            {
                                _denyModify = true;
                            }
                            if (contains(FileSystemRights.Read, rule))
                            {
                                _denyRead = true;
                            }
                            if (contains(FileSystemRights.ReadAndExecute, rule))
                            {
                                _denyReadAndExecute = true;
                            }
                            if (contains(FileSystemRights.ReadAttributes, rule))
                            {
                                _denyReadAttributes = true;
                            }
                            if (contains(FileSystemRights.ReadData, rule))
                            {
                                _denyReadData = true;
                            }
                            if (contains(FileSystemRights.ReadExtendedAttributes, rule))
                            {
                                _denyReadExtendedAttributes = true;
                            }
                            if (contains(FileSystemRights.ReadPermissions, rule))
                            {
                                _denyReadPermissions = true;
                            }
                            if (contains(FileSystemRights.Synchronize, rule))
                            {
                                _denySynchronize = true;
                            }
                            if (contains(FileSystemRights.TakeOwnership, rule))
                            {
                                _denyTakeOwnership = true;
                            }
                            if (contains(FileSystemRights.Traverse, rule))
                            {
                                _denyTraverse = true;
                            }
                            if (contains(FileSystemRights.Write, rule))
                            {
                                _denyWrite = true;
                            }
                            if (contains(FileSystemRights.WriteAttributes, rule))
                            {
                                _denyWriteAttributes = true;
                            }
                            if (contains(FileSystemRights.WriteData, rule))
                            {
                                _denyWriteData = true;
                            }
                            if (contains(FileSystemRights.WriteExtendedAttributes, rule))
                            {
                                _denyWriteExtendedAttributes = true;
                            }
                        }
                        else if (System.Security.AccessControl.AccessControlType.
                                 Allow.Equals(rule.AccessControlType))
                        {
                            if (contains(FileSystemRights.AppendData, rule))
                            {
                                _allowAppendData = true;
                            }
                            if (contains(FileSystemRights.ChangePermissions, rule))
                            {
                                _allowChangePermissions = true;
                            }
                            if (contains(FileSystemRights.CreateDirectories, rule))
                            {
                                _allowCreateDirectories = true;
                            }
                            if (contains(FileSystemRights.CreateFiles, rule))
                            {
                                _allowCreateFiles = true;
                            }
                            if (contains(FileSystemRights.Delete, rule))
                            {
                                _allowDelete = true;
                            }
                            if (contains(FileSystemRights.DeleteSubdirectoriesAndFiles,
                                         rule))
                            {
                                _allowDeleteSubdirectoriesAndFiles = true;
                            }
                            if (contains(FileSystemRights.ExecuteFile, rule))
                            {
                                _allowExecuteFile = true;
                            }
                            if (contains(FileSystemRights.FullControl, rule))
                            {
                                _allowFullControl = true;
                            }
                            if (contains(FileSystemRights.ListDirectory, rule))
                            {
                                _allowListDirectory = true;
                            }
                            if (contains(FileSystemRights.Modify, rule))
                            {
                                _allowModify = true;
                            }
                            if (contains(FileSystemRights.Read, rule))
                            {
                                _allowRead = true;
                            }
                            if (contains(FileSystemRights.ReadAndExecute, rule))
                            {
                                _allowReadAndExecute = true;
                            }
                            if (contains(FileSystemRights.ReadAttributes, rule))
                            {
                                _allowReadAttributes = true;
                            }
                            if (contains(FileSystemRights.ReadData, rule))
                            {
                                _allowReadData = true;
                            }
                            if (contains(FileSystemRights.ReadExtendedAttributes, rule))
                            {
                                _allowReadExtendedAttributes = true;
                            }
                            if (contains(FileSystemRights.ReadPermissions, rule))
                            {
                                _allowReadPermissions = true;
                            }
                            if (contains(FileSystemRights.Synchronize, rule))
                            {
                                _allowSynchronize = true;
                            }
                            if (contains(FileSystemRights.TakeOwnership, rule))
                            {
                                _allowTakeOwnership = true;
                            }
                            if (contains(FileSystemRights.Traverse, rule))
                            {
                                _allowTraverse = true;
                            }
                            if (contains(FileSystemRights.Write, rule))
                            {
                                _allowWrite = true;
                            }
                            if (contains(FileSystemRights.WriteAttributes, rule))
                            {
                                _allowWriteAttributes = true;
                            }
                            if (contains(FileSystemRights.WriteData, rule))
                            {
                                _allowWriteData = true;
                            }
                            if (contains(FileSystemRights.WriteExtendedAttributes, rule))
                            {
                                _allowWriteExtendedAttributes = true;
                            }
                        }
                    }
                }

                IdentityReferenceCollection groups = _principal.Groups;
                for (int j = 0; j < groups.Count; j++)
                {
                    for (int i = 0; i < acl.Count; i++)
                    {
                        System.Security.AccessControl.FileSystemAccessRule rule =
                            (System.Security.AccessControl.FileSystemAccessRule)acl[i];
                        if (groups[j].Equals(rule.IdentityReference))
                        {
                            if (System.Security.AccessControl.AccessControlType.
                                Deny.Equals(rule.AccessControlType))
                            {
                                if (contains(FileSystemRights.AppendData, rule))
                                {
                                    _denyAppendData = true;
                                }
                                if (contains(FileSystemRights.ChangePermissions, rule))
                                {
                                    _denyChangePermissions = true;
                                }
                                if (contains(FileSystemRights.CreateDirectories, rule))
                                {
                                    _denyCreateDirectories = true;
                                }
                                if (contains(FileSystemRights.CreateFiles, rule))
                                {
                                    _denyCreateFiles = true;
                                }
                                if (contains(FileSystemRights.Delete, rule))
                                {
                                    _denyDelete = true;
                                }
                                if (contains(FileSystemRights.
                                             DeleteSubdirectoriesAndFiles, rule))
                                {
                                    _denyDeleteSubdirectoriesAndFiles = true;
                                }
                                if (contains(FileSystemRights.ExecuteFile, rule))
                                {
                                    _denyExecuteFile = true;
                                }
                                if (contains(FileSystemRights.FullControl, rule))
                                {
                                    _denyFullControl = true;
                                }
                                if (contains(FileSystemRights.ListDirectory, rule))
                                {
                                    _denyListDirectory = true;
                                }
                                if (contains(FileSystemRights.Modify, rule))
                                {
                                    _denyModify = true;
                                }
                                if (contains(FileSystemRights.Read, rule))
                                {
                                    _denyRead = true;
                                }
                                if (contains(FileSystemRights.ReadAndExecute, rule))
                                {
                                    _denyReadAndExecute = true;
                                }
                                if (contains(FileSystemRights.ReadAttributes, rule))
                                {
                                    _denyReadAttributes = true;
                                }
                                if (contains(FileSystemRights.ReadData, rule))
                                {
                                    _denyReadData = true;
                                }
                                if (contains(FileSystemRights.
                                             ReadExtendedAttributes, rule))
                                {
                                    _denyReadExtendedAttributes = true;
                                }
                                if (contains(FileSystemRights.ReadPermissions, rule))
                                {
                                    _denyReadPermissions = true;
                                }
                                if (contains(FileSystemRights.Synchronize, rule))
                                {
                                    _denySynchronize = true;
                                }
                                if (contains(FileSystemRights.TakeOwnership, rule))
                                {
                                    _denyTakeOwnership = true;
                                }
                                if (contains(FileSystemRights.Traverse, rule))
                                {
                                    _denyTraverse = true;
                                }
                                if (contains(FileSystemRights.Write, rule))
                                {
                                    _denyWrite = true;
                                }
                                if (contains(FileSystemRights.WriteAttributes, rule))
                                {
                                    _denyWriteAttributes = true;
                                }
                                if (contains(FileSystemRights.WriteData, rule))
                                {
                                    _denyWriteData = true;
                                }
                                if (contains(FileSystemRights.
                                             WriteExtendedAttributes, rule))
                                {
                                    _denyWriteExtendedAttributes = true;
                                }
                            }
                            else if (System.Security.AccessControl.AccessControlType.
                                     Allow.Equals(rule.AccessControlType))
                            {
                                if (contains(FileSystemRights.AppendData, rule))
                                {
                                    _allowAppendData = true;
                                }
                                if (contains(FileSystemRights.ChangePermissions, rule))
                                {
                                    _allowChangePermissions = true;
                                }
                                if (contains(FileSystemRights.CreateDirectories, rule))
                                {
                                    _allowCreateDirectories = true;
                                }
                                if (contains(FileSystemRights.CreateFiles, rule))
                                {
                                    _allowCreateFiles = true;
                                }
                                if (contains(FileSystemRights.Delete, rule))
                                {
                                    _allowDelete = true;
                                }
                                if (contains(FileSystemRights.
                                             DeleteSubdirectoriesAndFiles, rule))
                                {
                                    _allowDeleteSubdirectoriesAndFiles = true;
                                }
                                if (contains(FileSystemRights.ExecuteFile, rule))
                                {
                                    _allowExecuteFile = true;
                                }
                                if (contains(FileSystemRights.FullControl, rule))
                                {
                                    _allowFullControl = true;
                                }
                                if (contains(FileSystemRights.ListDirectory, rule))
                                {
                                    _allowListDirectory = true;
                                }
                                if (contains(FileSystemRights.Modify, rule))
                                {
                                    _allowModify = true;
                                }
                                if (contains(FileSystemRights.Read, rule))
                                {
                                    _allowRead = true;
                                }
                                if (contains(FileSystemRights.ReadAndExecute, rule))
                                {
                                    _allowReadAndExecute = true;
                                }
                                if (contains(FileSystemRights.ReadAttributes, rule))
                                {
                                    _allowReadAttributes = true;
                                }
                                if (contains(FileSystemRights.ReadData, rule))
                                {
                                    _allowReadData = true;
                                }
                                if (contains(FileSystemRights.
                                             ReadExtendedAttributes, rule))
                                {
                                    _allowReadExtendedAttributes = true;
                                }
                                if (contains(FileSystemRights.ReadPermissions, rule))
                                {
                                    _allowReadPermissions = true;
                                }
                                if (contains(FileSystemRights.Synchronize, rule))
                                {
                                    _allowSynchronize = true;
                                }
                                if (contains(FileSystemRights.TakeOwnership, rule))
                                {
                                    _allowTakeOwnership = true;
                                }
                                if (contains(FileSystemRights.Traverse, rule))
                                {
                                    _allowTraverse = true;
                                }
                                if (contains(FileSystemRights.Write, rule))
                                {
                                    _allowWrite = true;
                                }
                                if (contains(FileSystemRights.WriteAttributes, rule))
                                {
                                    _allowWriteAttributes = true;
                                }
                                if (contains(FileSystemRights.WriteData, rule))
                                {
                                    _allowWriteData = true;
                                }
                                if (contains(FileSystemRights.WriteExtendedAttributes,
                                             rule))
                                {
                                    _allowWriteExtendedAttributes = true;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                //Deal with IO exceptions if you want
                return;
            }
        }
Example #6
0
        public static JObject GetFileDaclJObject(string filePathString)
        {
            if (!GlobalVar.OnlineChecks)
            {
                return(new JObject());
            }
            JObject      fileDaclsJObject = new JObject();
            FileSecurity filePathSecObj;

            try
            {
                filePathSecObj = File.GetAccessControl(filePathString);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Tried to check file permissions on invalid path: " + filePathString);
                return(null);
            }
            catch (UnauthorizedAccessException e)
            {
                if (GlobalVar.DebugMode)
                {
                    DebugWrite(e.ToString());
                }
                return(null);
            }

            AuthorizationRuleCollection fileAccessRules =
                filePathSecObj.GetAccessRules(true, true, typeof(SecurityIdentifier));

            foreach (FileSystemAccessRule fileAccessRule in fileAccessRules)
            {
                // get inheritance and access control type values
                string isInheritedString = "False";
                if (fileAccessRule.IsInherited)
                {
                    isInheritedString = "True";
                }
                string accessControlTypeString = "Allow";
                if (fileAccessRule.AccessControlType == AccessControlType.Deny)
                {
                    accessControlTypeString = "Deny";
                }

                // get the user's SID
                string identityReferenceString = fileAccessRule.IdentityReference.ToString();
                string displayNameString       = LDAPstuff.GetUserFromSid(identityReferenceString);
                // get the rights
                string fileSystemRightsString = fileAccessRule.FileSystemRights.ToString();
                // strip spaces
                fileSystemRightsString = fileSystemRightsString.Replace(" ", "");
                // turn them into an array
                string[] fileSystemRightsArray = fileSystemRightsString.Split(',');
                // then into a JArray
                JArray fileSystemRightsJArray = new JArray();
                foreach (string x in fileSystemRightsArray)
                {
                    fileSystemRightsJArray.Add(x);
                }

                JObject fileDaclJObject = new JObject
                {
                    { accessControlTypeString, displayNameString },
                    { "Inherited?", isInheritedString },
                    { "Rights", fileSystemRightsJArray }
                };
                try
                {
                    fileDaclsJObject.Merge(fileDaclJObject, new JsonMergeSettings
                    {
                        // union array values together to avoid duplicates
                        MergeArrayHandling = MergeArrayHandling.Union
                    });
                    //fileDaclsJObject.Add((identityReferenceString + " - " + accessControlTypeString), fileDaclJObject);
                }
                catch (ArgumentException e)
                {
                    if (GlobalVar.DebugMode)
                    {
                        DebugWrite(e.ToString());
                        DebugWrite("\n" + "Trying to Add:");
                        DebugWrite(fileDaclJObject.ToString());
                        DebugWrite("\n" + "To:");
                        DebugWrite(fileDaclsJObject.ToString());
                    }
                }
            }

            return(fileDaclsJObject);
        }
Example #7
0
        /// <summary>
        /// Gets the application access rules implied by the access rights to the file.
        /// </summary>
        public static IList <ApplicationAccessRule> GetAccessRules(String filePath)
        {
            // get the current permissions from the file or directory.
            FileSystemSecurity security = null;

            FileInfo      fileInfo      = new FileInfo(filePath);
            DirectoryInfo directoryInfo = null;

            if (!fileInfo.Exists)
            {
                directoryInfo = new DirectoryInfo(filePath);

                if (!directoryInfo.Exists)
                {
                    throw new FileNotFoundException("File or directory does not exist.", filePath);
                }

                security = directoryInfo.GetAccessControl(AccessControlSections.Access);
            }
            else
            {
                security = fileInfo.GetAccessControl(AccessControlSections.Access);
            }

            // combine the access rules into a set of abstract application rules.
            List <ApplicationAccessRule> accessRules = new List <ApplicationAccessRule>();

            AuthorizationRuleCollection authorizationRules = security.GetAccessRules(true, true, typeof(NTAccount));

            for (int ii = 0; ii < authorizationRules.Count; ii++)
            {
                FileSystemAccessRule accessRule = authorizationRules[ii] as FileSystemAccessRule;

                // only care about file system rules.
                if (accessRule == null)
                {
                    continue;
                }

                ApplicationAccessRule rule = new ApplicationAccessRule();

                rule.RuleType     = ApplicationAccessRule.Convert(accessRule.AccessControlType);
                rule.IdentityName = accessRule.IdentityReference.Value;
                rule.Right        = ApplicationAccessRight.None;

                // create an allow rule.
                if (rule.RuleType == AccessControlType.Allow)
                {
                    // check if all rights required for configuration access exist.
                    if (((int)accessRule.FileSystemRights & (int)Configure) == (int)Configure)
                    {
                        rule.Right = ApplicationAccessRight.Configure;
                    }

                    // check if all rights required for update access exist.
                    else if (((int)accessRule.FileSystemRights & (int)Update) == (int)Update)
                    {
                        rule.Right = ApplicationAccessRight.Update;
                    }

                    // check if all rights required for read access exist.
                    else if (((int)accessRule.FileSystemRights & (int)Read) == (int)Read)
                    {
                        rule.Right = ApplicationAccessRight.Run;
                    }
                }

                // create a deny rule.
                else if (rule.RuleType == AccessControlType.Deny)
                {
                    // check if any rights required for read access are denied.
                    if (((int)accessRule.FileSystemRights & (int)Read) != 0)
                    {
                        rule.Right = ApplicationAccessRight.Run;
                    }

                    // check if any rights required for update access are denied.
                    else if (((int)accessRule.FileSystemRights & (int)Update) != 0)
                    {
                        rule.Right = ApplicationAccessRight.Update;
                    }

                    // check if any rights required for configure access are denied.
                    else if (((int)accessRule.FileSystemRights & (int)Configure) != 0)
                    {
                        rule.Right = ApplicationAccessRight.Configure;
                    }
                }

                // add rule if not trivial.
                if (rule.Right != ApplicationAccessRight.None)
                {
                    accessRules.Add(rule);
                }
            }

            return(accessRules);
        }
Example #8
0
        /// <summary>
        /// Creates ftp site.
        /// </summary>
        /// <param name="site">Ftp site to be created.</param>
        /// <returns>Created site id.</returns>
        /// <exception cref="ArgumentNullException">Is thrown in case supplied argument is null.</exception>
        /// <exception cref="ArgumentException">
        /// Is thrown in case site id or its name is null or empty or if site id is not equal to default ftp site name.
        /// </exception>
        public string CreateSite(FtpSite site)
        {
            if (site == null)
            {
                throw new ArgumentNullException("site");
            }

            if (String.IsNullOrEmpty(site.SiteId) || String.IsNullOrEmpty(site.Name))
            {
                throw new ArgumentException("Site id or name is null or empty.");
            }

            this.CheckFtpServerBindings(site);

            PropertyBag siteBag = this.ftpSitesService.GetSiteDefaults();

            // Set site name
            siteBag[FtpSiteGlobals.Site_Name] = site.Name;
            // Set site physical path
            siteBag[FtpSiteGlobals.VirtualDirectory_PhysicalPath] = site.ContentPath;
            PropertyBag ftpBinding = new PropertyBag();

            // Set site binding protocol
            ftpBinding[FtpSiteGlobals.BindingProtocol] = "ftp";
            // fill binding summary info
            ftpBinding[FtpSiteGlobals.BindingInformation] = site.Bindings[0].ToString();

            // Set site binding
            siteBag[FtpSiteGlobals.Site_SingleBinding] = ftpBinding;

            // Auto-start
            siteBag[FtpSiteGlobals.FtpSite_AutoStart] = true;

            // Set anonumous authentication
            siteBag[FtpSiteGlobals.Authentication_AnonymousEnabled] = true;
            siteBag[FtpSiteGlobals.Authentication_BasicEnabled]     = true;

            this.ftpSitesService.AddSite(siteBag);

            AuthorizationRuleCollection rules = this.ftpSitesService.GetAuthorizationRuleCollection(site.Name);

            rules.Add(AuthorizationRuleAccessType.Allow, "*", String.Empty, PermissionsFlags.Read);

            IisFtpSite iisFtpSite = this.ftpSitesService.GetIisFtpSite(site.Name);

            iisFtpSite.UserIsolation.Mode = Mode.StartInUsersDirectory;
            iisFtpSite.Security.Ssl.ControlChannelPolicy = ControlChannelPolicy.SslAllow;
            iisFtpSite.Security.Ssl.DataChannelPolicy    = DataChannelPolicy.SslAllow;

            this.FillIisFromFtpSite(site);

            this.ftpSitesService.CommitChanges();

            // Do not start the site because it is started during creation.
            try
            {
                this.ChangeSiteState(site.Name, ServerState.Started);
            }
            catch
            {
                // Ignore the error if happened.
            }
            return(site.Name);
        }
 public static void DisplayDACL(AuthorizationRuleCollection dACL)
 {
     DisplayACL(true, dACL);
 }
Example #10
0
        /// <summary>
        /// Gets the application access rules implied by the access rights to the file.
        /// </summary>
        public static void SetAccessRules(String filePath, IList <ApplicationAccessRule> accessRules, bool replaceExisting)
        {
            // get the current permissions from the file or directory.
            FileSystemSecurity security = null;

            FileInfo      fileInfo      = new FileInfo(filePath);
            DirectoryInfo directoryInfo = null;

            if (!fileInfo.Exists)
            {
                directoryInfo = new DirectoryInfo(filePath);

                if (!directoryInfo.Exists)
                {
                    throw new FileNotFoundException("File or directory does not exist.", filePath);
                }

                security = directoryInfo.GetAccessControl(AccessControlSections.Access);
            }
            else
            {
                security = fileInfo.GetAccessControl(AccessControlSections.Access);
            }

            if (replaceExisting)
            {
                // can't use inhieritance when setting permissions
                security.SetAccessRuleProtection(true, false);

                // remove all existing access rules.
                AuthorizationRuleCollection authorizationRules = security.GetAccessRules(true, true, typeof(NTAccount));

                for (int ii = 0; ii < authorizationRules.Count; ii++)
                {
                    FileSystemAccessRule accessRule = authorizationRules[ii] as FileSystemAccessRule;

                    // only care about file system rules.
                    if (accessRule == null)
                    {
                        continue;
                    }

                    security.RemoveAccessRule(accessRule);
                }
            }

            // allow children to inherit rules for directories.
            InheritanceFlags flags = InheritanceFlags.None;

            if (directoryInfo != null)
            {
                flags = InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit;
            }

            // add the new rules.
            for (int ii = 0; ii < accessRules.Count; ii++)
            {
                ApplicationAccessRule applicationRule = accessRules[ii];

                IdentityReference identityReference = applicationRule.IdentityReference;

                if (identityReference == null)
                {
                    if (applicationRule.IdentityName.StartsWith("S-"))
                    {
                        SecurityIdentifier sid = new SecurityIdentifier(applicationRule.IdentityName);

                        if (!sid.IsValidTargetType(typeof(NTAccount)))
                        {
                            continue;
                        }

                        identityReference = sid.Translate(typeof(NTAccount));
                    }
                    else
                    {
                        identityReference = new NTAccount(applicationRule.IdentityName);
                    }
                }

                FileSystemAccessRule fileRule = null;

                switch (applicationRule.Right)
                {
                case ApplicationAccessRight.Run:
                {
                    fileRule = new FileSystemAccessRule(
                        identityReference,
                        (applicationRule.RuleType == AccessControlType.Allow) ? Read : Configure,
                        flags,
                        PropagationFlags.None,
                        ApplicationAccessRule.Convert(applicationRule.RuleType));

                    break;
                }

                case ApplicationAccessRight.Update:
                {
                    fileRule = new FileSystemAccessRule(
                        identityReference,
                        (applicationRule.RuleType == AccessControlType.Allow) ? Update : ConfigureOnly | UpdateOnly,
                        flags,
                        PropagationFlags.None,
                        ApplicationAccessRule.Convert(applicationRule.RuleType));

                    security.SetAccessRule(fileRule);
                    break;
                }

                case ApplicationAccessRight.Configure:
                {
                    fileRule = new FileSystemAccessRule(
                        identityReference,
                        (applicationRule.RuleType == AccessControlType.Allow) ? Configure : ConfigureOnly,
                        flags,
                        PropagationFlags.None,
                        ApplicationAccessRule.Convert(applicationRule.RuleType));

                    break;
                }
                }

                try
                {
                    security.SetAccessRule(fileRule);
                }
                catch (Exception e)
                {
                    Utils.Trace(
                        "Could not set access rule for account '{0}' on file '{1}'. Error={2}",
                        applicationRule.IdentityName,
                        filePath,
                        e.Message);
                }
            }

            if (directoryInfo != null)
            {
                directoryInfo.SetAccessControl((DirectorySecurity)security);
                return;
            }

            fileInfo.SetAccessControl((FileSecurity)security);
        }
Example #11
0
 public static void DisplaySACL(AuthorizationRuleCollection sACL)
 {
     DisplayACL(false, sACL);
 }
        public static bool CheckPermission(FileSystemRights Permission, string Path)
        {
            try
            {
                bool InheritedDeny  = false;
                bool InheritedAllow = false;

                WindowsIdentity  CurrentUser      = WindowsIdentity.GetCurrent();
                WindowsPrincipal CurrentPrincipal = new WindowsPrincipal(CurrentUser);

                FileSystemSecurity Security;

                if (Directory.Exists(Path))
                {
                    Security = Directory.GetAccessControl(Path);
                }
                else if (File.Exists(Path))
                {
                    Security = File.GetAccessControl(Path);
                }
                else
                {
                    //Relative path will come here, so we won't check its permission becasue no full path available
                    return(true);
                }

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

                AuthorizationRuleCollection AccessRules = Security.GetAccessRules(true, true, typeof(SecurityIdentifier));

                foreach (FileSystemAccessRule Rule in AccessRules)
                {
                    if (CurrentUser.User.Equals(Rule.IdentityReference) || CurrentPrincipal.IsInRole((SecurityIdentifier)Rule.IdentityReference))
                    {
                        if (Rule.AccessControlType == AccessControlType.Deny)
                        {
                            if ((Rule.FileSystemRights & Permission) == Permission)
                            {
                                if (Rule.IsInherited)
                                {
                                    InheritedDeny = true;
                                }
                                else
                                {
                                    // Non inherited "deny" takes overall precedence.
                                    return(false);
                                }
                            }
                        }
                        else if (Rule.AccessControlType == AccessControlType.Allow)
                        {
                            if ((Rule.FileSystemRights & Permission) == Permission)
                            {
                                if (Rule.IsInherited)
                                {
                                    InheritedAllow = true;
                                }
                                else
                                {
                                    // Non inherited "allow" takes precedence over inherited rules
                                    return(true);
                                }
                            }
                        }
                    }
                }

                return(InheritedAllow && !InheritedDeny);
            }
            catch
            {
                return(false);
            }
        }
Example #13
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            Debug.WriteLine("btnSave_Click");
            try
            {
                dgvDocSetup.EndEdit();

                List <string> queryList = new List <string>();

                foreach (DataGridViewRow row in dgvDocSetup.Rows)
                {
                    string fileName        = row.Cells[0].Value.ToString();
                    string keyword         = row.Cells[1].Value.ToString();
                    string favSelection    = row.Cells[2].Value.ToString();
                    string selection       = row.Cells[3].Value.ToString();
                    string directory       = row.Cells[4].Value.ToString();
                    string targetDirectory = row.Cells[5].Value.ToString();
                    string vpath           = row.Cells[6].Value.ToString();
                    string type            = row.Cells[7].Value.ToString();
                    string shared          = row.Cells[8].Value.ToString();
                    string sharedPerson    = shared;

                    string favorite = favSelection == "---" ? "False" : "True";

                    string autoDelete = selection == "7 days" ? DateTime.Today.AddDays(7).ToString("yyyy/MM/dd")
                        : selection == "30 days" ? DateTime.Today.AddDays(30).ToString("yyyy/MM/dd")
                        : selection == "60 days" ? DateTime.Today.AddDays(60).ToString("yyyy/MM/dd")
                        : selection == "90 days" ? DateTime.Today.AddDays(90).ToString("yyyy/MM/dd") : "2099/12/31";

                    if (keyword == "")
                    {
                        keyword = fileName;
                    }

                    //if (!File.Exists(targetDirectory))
                    File.Copy(directory, targetDirectory, true);

                    string sPath = targetDirectory;

                    if (sPath.Contains("'"))
                    {
                        sPath = sPath.Replace("'", "''");
                    }

                    if (DataUtil.IsRecordExists(targetDirectory))
                    {
                        List <string> list = DataUtil.GetSharedList(GlobalService.DbTable, targetDirectory);

                        if (list.Count > 0)
                        {
                            foreach (string item in list)
                            {
                                string tbName = "TB_" + AdUtil.GetUserId();

                                string delText = string.Format("delete from " + tbName + " where r_path = N'{0}' and r_owner = N'{1}'", sPath, GlobalService.User);
                                DataService.GetInstance().ExecuteNonQuery(delText);
                            }
                        }

                        string delOwnerText = string.Format("delete from " + GlobalService.DbTable + " where r_path = N'{0}'", sPath);
                        DataService.GetInstance().ExecuteNonQuery(delOwnerText);
                    }

                    FileInfo     info = new FileInfo(targetDirectory);
                    FileSecurity fs   = info.GetAccessControl();
                    AuthorizationRuleCollection rules = fs.GetAccessRules(true, true, typeof(NTAccount));
                    string lastmodified = info.LastWriteTime.ToString("yyyy/MM/dd HH:mm:ss");
                    string now          = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                    string extension    = targetDirectory.Contains(".") ? targetDirectory.Substring(targetDirectory.LastIndexOf("."), targetDirectory.Length - targetDirectory.LastIndexOf(".")) : "file";

                    foreach (FileSystemAccessRule rule in rules)
                    {
                        fs.RemoveAccessRuleSpecific(rule);
                    }

                    fs.SetAccessRuleProtection(true, false);
                    fs.AddAccessRule(new FileSystemAccessRule(@"kmhk\itadmin", FileSystemRights.FullControl, AccessControlType.Allow));

                    if (GlobalService.User == "Chow Chi To(周志滔,Sammy)")
                    {
                        fs.AddAccessRule(new FileSystemAccessRule(@"kmas\as1600048", FileSystemRights.FullControl, AccessControlType.Allow));
                    }
                    if (GlobalService.User == "Ling Wai Man(凌慧敏,Velma)")
                    {
                        fs.AddAccessRule(new FileSystemAccessRule(@"kmas\as1600049", FileSystemRights.FullControl, AccessControlType.Allow));
                    }
                    if (GlobalService.User == "Ng Lau Yu, Lilith (吳柳如)")
                    {
                        fs.AddAccessRule(new FileSystemAccessRule(@"kmas\as1600051", FileSystemRights.FullControl, AccessControlType.Allow));
                    }
                    if (GlobalService.User == "Lee Miu Wah(李苗華)")
                    {
                        fs.AddAccessRule(new FileSystemAccessRule(@"kmas\as1600053", FileSystemRights.FullControl, AccessControlType.Allow));
                    }

                    fs.AddAccessRule(new FileSystemAccessRule(AdUtil.GetUserId(), FileSystemRights.FullControl, AccessControlType.Allow));

                    List <string> sharedList = new List <string>();

                    if (fileName.Contains("'"))
                    {
                        fileName = fileName.Replace("'", "''");
                    }

                    if (keyword.Contains("'"))
                    {
                        keyword = keyword.Replace("'", "''");
                    }

                    if (shared != "-")
                    {
                        sharedList = shared.Split(';').ToList();
                    }

                    //foreach (string item in sharedList)
                    // Debug.WriteLine("Item: " + item);

                    List <string> hklist = new List <string>();
                    List <string> cnlist = new List <string>();
                    List <string> vnlist = new List <string>();
                    List <string> jplist = new List <string>();

                    foreach (string item in sharedList)
                    {
                        if (UserUtil.IsCnMember(item.Trim()))
                        {
                            cnlist.Add(item.Trim());
                        }
                        else if (UserUtil.IsVnMember(item.Trim()))
                        {
                            vnlist.Add(item.Trim());
                        }
                        else if (UserUtil.IsJpMember(item.Trim()))
                        {
                            jplist.Add(item.Trim());
                        }
                        else
                        {
                            hklist.Add(item.Trim());
                        }
                    }

                    if (hklist.Count > 0)
                    {
                        foreach (string item in hklist)
                        {
                            string sharedId  = AdUtil.GetUserIdByUsername(item.Trim());
                            string tableName = "TB_" + sharedId;

                            string sharedDivision   = SystemUtil.GetDivision(item.Trim());
                            string sharedDepartment = SystemUtil.GetDepartment(item.Trim());

                            fs.AddAccessRule(new FileSystemAccessRule(sharedId, FileSystemRights.Modify, AccessControlType.Allow));

                            if (UserUtil.IsSpecialUser(item))
                            //if (item == "Chow Chi To(周志滔,Sammy)" || item == "Ling Wai Man(凌慧敏,Velma)" || item == "Chan Fai Lung(陳輝龍,Onyx)" || item == "Ng Lau Yu, Lilith (吳柳如)" ||
                            //    item == "Lee Miu Wah(李苗華)" || item == "Lee Ming Fung(李銘峯)" || item == "Ho Kin Hang(何健恒,Ken)" || item == "Yeung Wai, Gabriel (楊偉)")
                            {
                                string asText = string.Format("select as_userid from TB_USER_AS where as_user = N'{0}'", item.Trim());
                                string asId   = DataService.GetInstance().ExecuteScalar(asText).ToString().Trim();

                                fs.AddAccessRule(new FileSystemAccessRule(asId, FileSystemRights.Modify, AccessControlType.Allow));
                            }

                            string sharedVpath = sharedDivision != GlobalService.Division && vpath.StartsWith(@"\" + GlobalService.Division) ? @"\Documents" + vpath
                                : sharedDepartment != GlobalService.Department && vpath.StartsWith(@"\Common") ? @"\Documents" + vpath : vpath;

                            if (sharedVpath.Contains("'"))
                            {
                                sharedVpath = sharedVpath.Replace("'", "''");
                            }

                            string sharedText = string.Format("insert into " + tableName + " (r_filename, r_extension, r_keyword, r_lastaccess, r_lastmodified, r_owner, r_shared, r_path, r_vpath, r_deletedate)" +
                                                              " values (N'{0}', '{1}', N'{2}', '{3}', '{4}', N'{5}', N'{6}', N'{7}', N'{8}', '{9}')", fileName, extension, keyword, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), lastmodified, GlobalService.User,
                                                              item.Trim(), sPath, sharedVpath, "2099/12/31");

                            queryList.Add(sharedText);
                        }
                    }

                    if (targetDirectory.StartsWith(@"\\kdthk-dm1\project\KDTHK-DM"))
                    {
                        File.SetAccessControl(targetDirectory, fs);
                    }
                    else
                    {
                        if (!targetDirectory.StartsWith(@"L:\") && !targetDirectory.StartsWith(@"M:\") && !targetDirectory.StartsWith(@"\\kdthk-dm1\project") && !targetDirectory.StartsWith(@"\\kdthk-dm1"))
                        {
                            File.SetAccessControl(targetDirectory, fs);
                        }
                    }
                    /* Commented out by Cato Yeung */

                    if (cnlist.Count > 0)
                    {
                        PermissionUtil.SetGlobalPermission(cnlist, targetDirectory, "kmcn.local");
                        SharedUtil.SharedCN(cnlist, sPath, fileName, keyword);
                    }

                    if (vnlist.Count > 0)
                    {
                        PermissionUtil.SetGlobalPermission(vnlist, targetDirectory, "kdtvn.local");
                        SharedUtil.SharedVN(vnlist, sPath, fileName, keyword);
                    }

                    if (jplist.Count > 0)
                    {
                        PermissionUtil.SetGlobalPermission(jplist, targetDirectory, "km.local");
                        SharedUtil.SharedJp(jplist, sPath, fileName, keyword);
                    }

                    try
                    {
                        List <string> receiverlist = cnlist.Concat(vnlist).Concat(jplist).ToList();
                        //receiverlist.Add(GlobalService.User);
                        if (receiverlist.Count > 0)
                        {
                            EmailUtil.SendNotificationEmail(receiverlist);
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message + ex.StackTrace);
                    }
                    //SharedUtil.SharedGlobal(cnList, sPath, fileName, keyword);

                    /*sharedList = sharedList.Distinct().ToList();
                     *
                     * if (sharedList.Count > 0)
                     *  sharedPerson = string.Join(";", sharedList.ToArray());*/

                    if (vpath.Contains("'"))
                    {
                        vpath = vpath.Replace("'", "''");
                    }

                    GlobalService.RootTable.Rows.Add(fileName, keyword, lastmodified, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), GlobalService.User, shared, targetDirectory, vpath, 0, favorite, "False");

                    string ownerText = string.Format("insert into " + GlobalService.DbTable + " (r_filename, r_extension, r_keyword, r_lastaccess, r_lastmodified, r_owner, r_shared, r_path, r_vpath, r_deletedate)" +
                                                     " values (N'{0}', '{1}', N'{2}', '{3}', '{4}', N'{5}', N'{6}', N'{7}', N'{8}', '{9}')", fileName, extension, keyword, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), lastmodified, GlobalService.User,
                                                     shared, sPath, vpath, autoDelete);

                    queryList.Add(ownerText);

                    if (directory.StartsWith(Environment.SpecialFolder.Desktop + @"\MyCloud Sync"))
                    {
                        File.Delete(directory);
                    }
                }
                queryList = queryList.Distinct().ToList();


                foreach (string text in queryList)
                {
                    DataService.GetInstance().ExecuteNonQuery(text);
                }
                //DataUtil.SyncDataToServer();
                GlobalService.RootTable = RootUtil.RootDataTable();
                this.DialogResult       = DialogResult.OK;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message + ex.StackTrace);

                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }
        static void Main(string[] args)
        {
            // Display title and info.
            Console.WriteLine("ASP.NET Configuration Info");
            Console.WriteLine("Type: CommaDelimitedStringCollection");
            Console.WriteLine();

            // Set the path of the config file.
            string configPath = "/aspnet";

            // Get the Web application configuration object.
            Configuration config =
                WebConfigurationManager.OpenWebConfiguration(configPath);

            // Get the section related object.
            AuthorizationSection configSection =
                (AuthorizationSection)config.GetSection("system.web/authorization");

            // Get the authorization rule collection.
            AuthorizationRuleCollection authorizationRuleCollection =
                configSection.Rules;

            // <Snippet2>
            // Create a CommaDelimitedStringCollection object.
            CommaDelimitedStringCollection myStrCollection =
                new CommaDelimitedStringCollection();

            // </Snippet2>

            for (int i = 0; i < authorizationRuleCollection.Count; i++)
            {
                if (authorizationRuleCollection.Get(i).Action.ToString().ToLower()
                    == "allow")
                {
                    // <Snippet3>
                    // Add values to the CommaDelimitedStringCollection object.
                    myStrCollection.AddRange(
                        authorizationRuleCollection.Get(i).Users.ToString().Split(
                            ",".ToCharArray()));
                    // </Snippet3>
                }
            }

            Console.WriteLine("Allowed Users: {0}",
                              myStrCollection.ToString());

            // <Snippet4>
            // Count the elements in the collection.
            Console.WriteLine("Allowed User Count: {0}",
                              myStrCollection.Count);
            // </Snippet4>

            // <Snippet5>
            // Call the Contains method.
            Console.WriteLine("Contains 'userName1': {0}",
                              myStrCollection.Contains("userName1"));
            // </Snippet5>

            // <Snippet6>
            // Determine the index of an element
            // in the collection.
            Console.WriteLine("IndexOf 'userName0': {0}",
                              myStrCollection.IndexOf("userName0"));
            // </Snippet6>

            // <Snippet7>
            // Call IsModified.
            Console.WriteLine("IsModified: {0}",
                              myStrCollection.IsModified);
            // </Snippet7>

            // <Snippet8>
            // Call IsReadyOnly.
            Console.WriteLine("IsReadOnly: {0}",
                              myStrCollection.IsReadOnly);
            // </Snippet8>

            Console.WriteLine();
            Console.WriteLine("Add a user name to the collection.");
            // <Snippet9>
            // Insert a new element in the collection.
            myStrCollection.Insert(myStrCollection.Count, "userNameX");
            // </Snippet9>

            Console.WriteLine("Collection Value: {0}",
                              myStrCollection.ToString());

            Console.WriteLine();
            Console.WriteLine("Remove a user name from the collection.");
            // <Snippet10>
            // Remove an element of the collection.
            myStrCollection.Remove("userNameX");
            // </Snippet10>

            Console.WriteLine("Collection Value: {0}",
                              myStrCollection.ToString());

            // Display and wait
            Console.ReadLine();
        }
Example #15
0
        public static bool CheckModifiableAccess(string Path)
        {
            // checks if the current user has rights to modify the given file/directory
            // adapted from https://stackoverflow.com/questions/1410127/c-sharp-test-if-user-has-write-access-to-a-folder/21996345#21996345

            if (string.IsNullOrEmpty(Path))
            {
                return(false);
            }
            // TODO: check if file exists, check file's parent folder

            // rights that signify modiable access
            FileSystemRights[] ModifyRights =
            {
                FileSystemRights.ChangePermissions,
                FileSystemRights.FullControl,
                FileSystemRights.Modify,
                FileSystemRights.TakeOwnership,
                FileSystemRights.Write,
                FileSystemRights.WriteData,
                FileSystemRights.CreateDirectories,
                FileSystemRights.CreateFiles
            };

            ArrayList paths = new ArrayList();

            paths.Add(Path);

            try
            {
                FileAttributes attr = System.IO.File.GetAttributes(Path);
                if ((attr & FileAttributes.Directory) != FileAttributes.Directory)
                {
                    string parentFolder = System.IO.Path.GetDirectoryName(Path);
                    paths.Add(parentFolder);
                }
            }
            catch
            {
                return(false);
            }


            try
            {
                foreach (string candidatePath in paths)
                {
                    AuthorizationRuleCollection rules    = Directory.GetAccessControl(candidatePath).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
                    WindowsIdentity             identity = WindowsIdentity.GetCurrent();

                    foreach (FileSystemAccessRule rule in rules)
                    {
                        if (identity.Groups.Contains(rule.IdentityReference))
                        {
                            foreach (FileSystemRights AccessRight in ModifyRights)
                            {
                                if ((AccessRight & rule.FileSystemRights) == AccessRight)
                                {
                                    if (rule.AccessControlType == AccessControlType.Allow)
                                    {
                                        return(true);
                                    }
                                }
                            }
                        }
                    }
                }
                return(false);
            }
            catch
            {
                return(false);
            }
        }
Example #16
0
 public static void GetComputerShares(string computer, Utilities.Options.Arguments argumetns)
 {
     //Error 53 - network path was not found
     //Error 5 - Access Denied
     string[]       errors         = { "ERROR=53", "ERROR=5" };
     SHARE_INFO_1[] computerShares = EnumNetShares(computer);
     if (computerShares.Length > 0)
     {
         List <string> readableShares     = new List <string>();
         List <string> writeableShares    = new List <string>();
         List <string> unauthorizedShares = new List <string>();
         // get current user's identity to compare against ACL of shares
         WindowsIdentity identity = WindowsIdentity.GetCurrent();
         string          userSID  = identity.User.Value;
         foreach (SHARE_INFO_1 share in computerShares)                                                              // <------------ go to next share -----------+
         {                                                                                                           // |
             if ((argumetns.filter != null) && (argumetns.filter.Contains(share.shi1_netname.ToString().ToUpper()))) // |
             {                                                                                                       // |
                 continue;                                                                                           // Skip the remainder of this iteration. --------------------------------+
             }
             //share.shi1_netname returns the error code when caught
             if (argumetns.stealth && !errors.Contains(share.shi1_netname))
             {
                 Console.WriteLine("[?] \\\\{0}\\{1}", computer, share.shi1_netname);
                 continue; //do not perform access checks
             }
             try
             {
                 string path  = String.Format("\\\\{0}\\{1}", computer, share.shi1_netname);
                 var    files = Directory.GetFiles(path);
                 readableShares.Add(share.shi1_netname);
                 AuthorizationRuleCollection rules = Directory.GetAccessControl(path).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
                 foreach (FileSystemAccessRule rule in rules)
                 {
                     //https://stackoverflow.com/questions/130617/how-do-you-check-for-permissions-to-write-to-a-directory-or-file
                     // compare SID of group referenced in ACL to groups the current user is a member of
                     if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))
                     {
                         // plenty of other FileSystem Rights to look for
                         // https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights
                         if ((//rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles) ||
                              //rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) ||
                              //rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) ||
                              //rule.FileSystemRights.HasFlag(FileSystemRights.WriteExtendedAttributes) ||
                              //rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) ||
                                 rule.FileSystemRights.HasFlag(FileSystemRights.Write)) && rule.AccessControlType == AccessControlType.Allow)
                         {
                             writeableShares.Add(share.shi1_netname);
                             break;
                         }
                     }
                 }
             }
             catch
             {
                 //share.shi1_netname returns the error code when caught
                 if (!errors.Contains(share.shi1_netname))
                 {
                     unauthorizedShares.Add(share.shi1_netname);
                 }
             }
         }
         if (readableShares.Count > 0)
         {
             foreach (string share in readableShares)
             {
                 string output = String.Format("[r] \\\\{0}\\{1}", computer, share);
                 if (!String.IsNullOrEmpty(argumetns.outfile))
                 {
                     try
                     {
                         WriteToFileThreadSafe(output, argumetns.outfile);
                     }
                     catch (Exception ex)
                     {
                         Console.WriteLine("[!] Outfile Error: {0}", ex.Message);
                         Environment.Exit(0);
                     }
                 }
                 else
                 {
                     Console.WriteLine(output);
                 }
             }
         }
         if (writeableShares.Count > 0)
         {
             foreach (string share in writeableShares)
             {
                 string output = String.Format("[w] \\\\{0}\\{1}", computer, share);
                 if (!String.IsNullOrEmpty(argumetns.outfile))
                 {
                     try
                     {
                         WriteToFileThreadSafe(output, argumetns.outfile);
                     }
                     catch (Exception ex)
                     {
                         Console.WriteLine("[!] Outfile Error: {0}", ex.Message);
                         Environment.Exit(0);
                     }
                 }
                 else
                 {
                     Console.WriteLine(output);
                 }
             }
         }
         if (argumetns.verbose && unauthorizedShares.Count > 0)
         {
             foreach (string share in unauthorizedShares)
             {
                 string output = String.Format("[-] \\\\{0}\\{1}", computer, share);
                 if (!String.IsNullOrEmpty(argumetns.outfile))
                 {
                     try
                     {
                         WriteToFileThreadSafe(output, argumetns.outfile);
                     }
                     catch (Exception ex)
                     {
                         Console.WriteLine("[!] Outfile Error: {0}", ex.Message);
                         Environment.Exit(0);
                     }
                 }
                 else
                 {
                     Console.WriteLine(output);
                 }
             }
         }
     }
     Utilities.Status.currentCount += 1;
 }
Example #17
0
        public static void GetComputerShares(string computer, bool publicOnly = false)
        {
            string[]       errors         = { "ERROR=53", "ERROR=5" };
            SHARE_INFO_1[] computerShares = EnumNetShares(computer);
            if (computerShares.Length > 0)
            {
                //这一段,标准写法
                List <string>   readableShares     = new List <string>();
                List <string>   unauthorizedShares = new List <string>();
                List <string>   writeableShares    = new List <string>();
                WindowsIdentity identity           = WindowsIdentity.GetCurrent();
                string          userSID            = identity.User.Value;
                foreach (SHARE_INFO_1 share in computerShares)
                {
                    try
                    {
                        string path  = String.Format("\\\\{0}\\{1}", computer, share.shi1_netname);
                        var    files = System.IO.Directory.GetFiles(path);
                        readableShares.Add(share.shi1_netname);//可读
                        AuthorizationRuleCollection rules = Directory.GetAccessControl(path).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));

                        //列出可写
                        foreach (FileSystemAccessRule rule in rules)
                        {
                            //https://stackoverflow.com/questions/130617/how-do-you-check-for-permissions-to-write-to-a-directory-or-file
                            // compare SID of group referenced in ACL to groups the current user is a member of
                            if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))
                            {
                                // plenty of other FileSystem Rights to look for
                                // https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemrights
                                if ((//rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles) ||
                                     //rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) ||
                                     //rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) ||
                                     //rule.FileSystemRights.HasFlag(FileSystemRights.WriteExtendedAttributes) ||
                                     //rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) ||
                                        rule.FileSystemRights.HasFlag(FileSystemRights.Write)) && rule.AccessControlType == AccessControlType.Allow)
                                {
                                    writeableShares.Add(share.shi1_netname);
                                    break;
                                }
                            }
                        }
                    }
                    //可写参考https://github.com/mitchmoser/SharpShares/blob/master/SharpShares/Program.cs



                    catch
                    {
                        if (!errors.Contains(share.shi1_netname))
                        {
                            unauthorizedShares.Add(share.shi1_netname);
                        }
                    }
                }



                if (unauthorizedShares.Count > 0 || readableShares.Count > 0)
                {
                    if (publicOnly)
                    {
                        if (readableShares.Count > 0)
                        {
                            string output = string.Format("[+]{0}机器开启的共享如下:\n", computer);
                            //output += "[--- Listable Shares ---]\n";
                            //Console.WriteLine("Shares for {0}:", computer);
                            //Console.WriteLine("\t[--- Listable Shares ---]");
                            foreach (string share in readableShares)
                            {
                                output += string.Format("\t\t{0}\n", share);
                            }
                            Console.WriteLine(output);
                        }
                    }
                    else
                    {
                        string output = string.Format("[+]{0}机器开启的共享如下:\n", computer);
                        if (unauthorizedShares.Count > 0)
                        {
                            output += "[+]不可读共享\n";
                            foreach (string share in unauthorizedShares)
                            {
                                output += string.Format("\t[>]{0}\n", share);
                            }
                        }
                        if (readableShares.Count > 0)
                        {
                            output += "[+]可读共享\n";
                            foreach (string share in readableShares)
                            {
                                output += string.Format("\t[>]{0}\n", share);
                                //string pathshare = string.Format("\\\\{0}\\{1}", computer, share);//列出文件
                                //ListFiles(new DirectoryInfo(pathshare));
                            }
                        }
                        if (writeableShares.Count > 0)
                        {
                            output += "[+]可写共享\n";
                            foreach (string share in writeableShares)
                            {
                                output += String.Format("\t[>]{0}\n", share);
                            }
                        }
                        Console.WriteLine(output);
                    }
                }
            }
        }
        private async Task SetInstallationDataPath(MCProfile p, BLInstallation i)
        {
            await Task.Run(() =>
            {
                try
                {
                    string LocalStateFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Packages", MINECRAFT_PACKAGE_FAMILY, "LocalState");
                    string PackageFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Packages", MINECRAFT_PACKAGE_FAMILY, "LocalState", "games", "com.mojang");
                    string PackageBakFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Packages", MINECRAFT_PACKAGE_FAMILY, "LocalState", "games", "com.mojang.default");
                    string ProfileFolder = Path.GetFullPath(LauncherModel.Default.FilepathManager.GetInstallationsFolderPath(p.Name, i.DirectoryName_Full));

                    if (Directory.Exists(PackageFolder))
                    {
                        var dir = new DirectoryInfo(PackageFolder);
                        if (!dir.IsSymbolicLink()) dir.MoveTo(PackageBakFolder);
                        else dir.Delete(true);
                    }

                    DirectoryInfo profileDir = Directory.CreateDirectory(ProfileFolder);
                    SymLinkHelper.CreateSymbolicLink(PackageFolder, ProfileFolder, SymLinkHelper.SymbolicLinkType.Directory);
                    DirectoryInfo pkgDir = Directory.CreateDirectory(PackageFolder);
                    DirectoryInfo lsDir = Directory.CreateDirectory(LocalStateFolder);

                    SecurityIdentifier owner = WindowsIdentity.GetCurrent().User;
                    SecurityIdentifier authenticated_users_identity = new SecurityIdentifier("S-1-5-11");

                    FileSystemAccessRule owner_access_rules = new FileSystemAccessRule(owner, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);
                    FileSystemAccessRule au_access_rules = new FileSystemAccessRule(authenticated_users_identity, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);

                    var lsSecurity = lsDir.GetAccessControl();
                    AuthorizationRuleCollection rules = lsSecurity.GetAccessRules(true, true, typeof(NTAccount));
                    List<FileSystemAccessRule> needed_rules = new List<FileSystemAccessRule>();
                    foreach (AccessRule rule in rules)
                    {
                        if (rule.IdentityReference is SecurityIdentifier)
                        {
                            var required_rule = new FileSystemAccessRule(rule.IdentityReference, FileSystemRights.FullControl, rule.InheritanceFlags, rule.PropagationFlags, rule.AccessControlType);
                            needed_rules.Add(required_rule);
                        }
                    }

                    var pkgSecurity = pkgDir.GetAccessControl();
                    pkgSecurity.SetOwner(owner);
                    pkgSecurity.AddAccessRule(au_access_rules);
                    pkgSecurity.AddAccessRule(owner_access_rules);
                    pkgDir.SetAccessControl(pkgSecurity);

                    var profileSecurity = profileDir.GetAccessControl();
                    profileSecurity.SetOwner(owner);
                    profileSecurity.AddAccessRule(au_access_rules);
                    profileSecurity.AddAccessRule(owner_access_rules);
                    needed_rules.ForEach(x => profileSecurity.AddAccessRule(x));
                    profileDir.SetAccessControl(profileSecurity);
                }
                catch (Exception e)
                {
                    ErrorScreenShow.exceptionmsg(e);
                    throw e;
                }
            });
            Thread.Sleep(1000);
        }
Example #19
0
        AuthorizationRuleCollection IAuthorizationRuleProvider.GetRules()
        {
            var rules = new AuthorizationRuleCollection();

            return(new AuthorizationRuleCollection());
        }
Example #20
0
 public AuthorizationLocation()
 {
     Rules = new AuthorizationRuleCollection();
 }
        /// <summary>
        /// Checks that a directory can be read by the current process
        /// </summary>
        /// <param name="directoryName"></param>
        /// <returns></returns>
        public static bool CheckReadAccess(DirectoryInfo directory, List <string> diagnostics = null)
        {
            if (!directory.Exists)
            {
                return(false);
            }

            System.Security.Principal.WindowsIdentity  user      = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new WindowsPrincipal(user);

            // Get the collection of authorization rules that apply to the current directory
            AuthorizationRuleCollection acl = directory.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));

            if (diagnostics != null)
            {
                diagnostics.Add("Checking process group membership...");
                foreach (IdentityReference idref in user.Groups)
                {
                    diagnostics.Add("- " + SidToAccountName(idref));
                }
                diagnostics.Add("Now testing access rules...");
            }
            // These are set to true if either the allow read or deny read access rights are set
            bool allowRead = false;
            bool denyRead  = false;

            for (int x = 0; x < acl.Count; x++)
            {
                FileSystemAccessRule currentRule = (FileSystemAccessRule)acl[x];
                // If the current rule applies to the current user
                if (user.User.Equals(currentRule.IdentityReference) || principal.IsInRole((SecurityIdentifier)currentRule.IdentityReference))
                {
                    if (diagnostics != null)
                    {
                        diagnostics.Add("Current process is a member of " + SidToAccountName(currentRule.IdentityReference));
                    }
                    if (currentRule.AccessControlType.Equals(AccessControlType.Deny))
                    {
                        if ((currentRule.FileSystemRights & FileSystemRights.Read) == FileSystemRights.Read)
                        {
                            denyRead = true;
                            if (diagnostics != null)
                            {
                                diagnostics.Add("Read access explicitly denied");
                            }
                        }
                    }
                    else if (currentRule.AccessControlType.Equals(AccessControlType.Allow))
                    {
                        if ((currentRule.FileSystemRights & FileSystemRights.Read) == FileSystemRights.Read)
                        {
                            allowRead = true;
                            if (diagnostics != null)
                            {
                                diagnostics.Add("Read access explicitly granted");
                            }
                        }
                    }
                }
                else if (diagnostics != null)
                {
                    diagnostics.Add("Current process is not a member of " + SidToAccountName(currentRule.IdentityReference));
                }
            }
            if (denyRead)
            {
                return(false);
            }
            if (allowRead)
            {
                return(true);
            }

            // Shouldn't get to here
            if (diagnostics != null)
            {
                diagnostics.Add("No Read access rules found for current user or role");
                diagnostics.Add("Read access not explicity granted");
            }

            return(false);
        }