private static void UnProtectDirectory(string DirectoryPath)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(DirectoryPath);

            DirectorySecurity dirSec = dirInfo.GetAccessControl();

            dirSec.RemoveAccessRule(new FileSystemAccessRule(CurrentUser,
                                                             FileSystemRights.Delete | FileSystemRights.DeleteSubdirectoriesAndFiles,
                                                             InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                                             PropagationFlags.None,
                                                             AccessControlType.Deny));

            dirSec.RemoveAccessRule(new FileSystemAccessRule("Administrators",
                                                             FileSystemRights.Delete | FileSystemRights.DeleteSubdirectoriesAndFiles,
                                                             InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                                             PropagationFlags.None,
                                                             AccessControlType.Deny));

            dirSec.RemoveAccessRule(new FileSystemAccessRule("System",
                                                             FileSystemRights.Delete | FileSystemRights.DeleteSubdirectoriesAndFiles,
                                                             InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                                             PropagationFlags.None,
                                                             AccessControlType.Deny));

            Directory.SetAccessControl(DirectoryPath, dirSec);
        }
Example #2
0
        public void SetNTFSWritePermission(bool writePermission)
        {
            // https://stackoverflow.com/questions/7451861/setting-ntfs-permissions-in-c-net
            // https://stackoverflow.com/questions/11478917/programmatically-adding-permissions-to-a-folder/11479031

            // 'Allow' AND 'Deny' are ticked, wtf?
            // Explanation: https://answers.microsoft.com/en-us/windows/forum/all/permission-entry-neither-allow-nor-deny-is-checked/5d210777-b466-49e6-855a-6dc1e85563df

            DirectoryInfo     dInfo     = new DirectoryInfo(this.iniParentPath);
            DirectorySecurity dSecurity = dInfo.GetAccessControl();

            FileSystemRights rights = FileSystemRights.Write;

            // SID: https://support.microsoft.com/en-in/help/243330/well-known-security-identifiers-in-windows-operating-systems
            // String account = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            // SecurityIdentifier sidAll = new SecurityIdentifier("S-1-1-0");
            // SecurityIdentifier sidAdmins = new SecurityIdentifier("S-1-5-32-544");
            SecurityIdentifier sidUsers = new SecurityIdentifier("S-1-5-32-545");

            AccessControlType access = writePermission ? AccessControlType.Allow : AccessControlType.Deny;

            if (writePermission)
            {
                dSecurity.RemoveAccessRule(new FileSystemAccessRule(sidUsers, rights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Deny));
                dSecurity.AddAccessRule(new FileSystemAccessRule(sidUsers, rights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
            }
            else
            {
                dSecurity.AddAccessRule(new FileSystemAccessRule(sidUsers, rights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Deny));
                dSecurity.RemoveAccessRule(new FileSystemAccessRule(sidUsers, rights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
            }
            dInfo.SetAccessControl(dSecurity);
        }
 public static void RemoveDirectorySecurity(string directoryPath, string winUserString = null, WindowsIdentity winUser = null,
                                            FileSystemRights rights = FileSystemRights.FullControl, InheritanceFlags inheritanceFlags = InheritanceFlags.ContainerInherit, PropagationFlags propagationFlags = PropagationFlags.None, AccessControlType controlType = AccessControlType.Allow)
 {
     try
     {
         // Create a new DirectoryInfo object.
         DirectoryInfo dInfo = new DirectoryInfo(directoryPath);
         // Get a DirectorySecurity object that represents the
         // current security settings.
         DirectorySecurity dSecurity = dInfo.GetAccessControl();
         if (winUserString != null)
         {
             // Removes the FileSystemAccessRule to the security settings.
             dSecurity.RemoveAccessRule(new FileSystemAccessRule(winUserString, rights, inheritanceFlags, propagationFlags, controlType));
         }
         else if (winUser != null)
         {
             // Removes the FileSystemAccessRule to the security settings.
             dSecurity.RemoveAccessRule(new FileSystemAccessRule(winUser.User.Value, rights, inheritanceFlags, propagationFlags, controlType));
         }
         // Set the new access settings.
         dInfo.SetAccessControl(dSecurity);
     }
     catch (Exception)
     {
     }
 }
        // Removes an ACL entry on the specified directory for the specified account.
        public static bool RemoveDirectorySecurity(string FileName, string Account)
        {
            try
            {
                // Create a new DirectoryInfo object.
                DirectoryInfo     dInfo       = new DirectoryInfo(FileName);
                FileSystemRights  Rights      = FileSystemRights.ReadAndExecute;
                AccessControlType ControlType = AccessControlType.Deny;

                // Get a DirectorySecurity object that represents the
                // current security settings.
                DirectorySecurity dSecurity = dInfo.GetAccessControl();
                // Add the FileSystemAccessRule to the security settings.
                dSecurity.RemoveAccessRule(new FileSystemAccessRule(Account, Rights, ControlType));
                dSecurity.RemoveAccessRule(new FileSystemAccessRule(Account, Rights, InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, ControlType));
                dSecurity.RemoveAccessRule(new FileSystemAccessRule(Account, Rights, InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, ControlType));

                // Set the new access settings.
                dInfo.SetAccessControl(dSecurity);
                return(true);
            } catch
            {
                return(false);
            }
        }
Example #5
0
 private void DenyLocalServiceAccess(string path)
 {
     try
     {
         DirectorySecurity accessControl = Directory.GetAccessControl(path);
         accessControl.RemoveAccessRule(this.localServiceReadRule);
         accessControl.RemoveAccessRule(this.localServiceWriteRule);
         accessControl.RemoveAccessRule(this.localServiceCreateFileRule);
         accessControl.RemoveAccessRule(this.localServiceDeleteFileRule);
         Directory.SetAccessControl(path, accessControl);
     }
     catch (DirectoryNotFoundException arg)
     {
         ExTraceGlobals.TranscodingTracer.TraceError <string, DirectoryNotFoundException>((long)this.GetHashCode(), "Failed to set the access permission of path--{0}. Exception message: {1}", path, arg);
     }
     catch (IOException arg2)
     {
         ExTraceGlobals.TranscodingTracer.TraceError <string, IOException>((long)this.GetHashCode(), "Failed to set the access permission of path--{0}. Exception message: {1}", path, arg2);
     }
     catch (PlatformNotSupportedException arg3)
     {
         ExTraceGlobals.TranscodingTracer.TraceError <string, PlatformNotSupportedException>((long)this.GetHashCode(), "Failed to set the access permission of path--{0}. Exception message: {1}", path, arg3);
     }
     catch (UnauthorizedAccessException arg4)
     {
         ExTraceGlobals.TranscodingTracer.TraceError <string, UnauthorizedAccessException>((long)this.GetHashCode(), "Fail to set the access permission of path--{0}. Exception message: {1}", path, arg4);
     }
     catch (InvalidOperationException arg5)
     {
         ExTraceGlobals.TranscodingTracer.TraceError <string, InvalidOperationException>((long)this.GetHashCode(), "Failed to set the access permission of path--{0}. Exception message: {1}", path, arg5);
     }
 }
Example #6
0
        protected override void ProcessRecord()
        {
            bool isChange = false;
            DirectorySecurity security = Directory.GetAccessControl(DirectoryPath);

            //  アクセス権を剥奪
            if (All)
            {
                //  テスト自動生成
                _generator.DirectoryAccess(DirectoryPath, "", false);

                foreach (FileSystemAccessRule rule in security.GetAccessRules(true, false, typeof(NTAccount)))
                {
                    security.RemoveAccessRule(rule);
                    isChange = true;
                }
            }
            else if (!string.IsNullOrEmpty(Account))
            {
                foreach (FileSystemAccessRule rule in security.GetAccessRules(true, false, typeof(NTAccount)))
                {
                    string account = rule.IdentityReference.Value;

                    //  テスト自動生成
                    _generator.DirectoryAccount(DirectoryPath, account);

                    if (Account.Contains("\\") && account.Equals(Account, StringComparison.OrdinalIgnoreCase) ||
                        !Account.Contains("\\") && account.EndsWith("\\" + Account, StringComparison.OrdinalIgnoreCase))
                    {
                        security.RemoveAccessRule(rule);
                        isChange = true;
                    }
                }
            }

            if (isChange)
            {
                Directory.SetAccessControl(DirectoryPath, security);
            }

            //  フォルダー属性を剥奪
            if (!string.IsNullOrEmpty(_Attributes))
            {
                //  テスト自動生成
                _generator.DirectoryAttributes(DirectoryPath, _Attributes, true);

                FileAttributes nowAttr = File.GetAttributes(DirectoryPath);
                FileAttributes delAttr = (FileAttributes)Enum.Parse(typeof(FileAttributes), _Attributes);
                File.SetAttributes(DirectoryPath, nowAttr & (~delAttr));
            }

            WriteObject(new DirectorySummary(DirectoryPath, true));
        }
Example #7
0
        public static void RemoveDirectorySecurity(string directoryName, string account, FileSystemRights rights, AccessControlType controlType)
        {
            DirectorySecurity dSecurity = Directory.GetAccessControl(directoryName);

            dSecurity.RemoveAccessRule(new FileSystemAccessRule(account, rights, controlType));
            Directory.SetAccessControl(directoryName, dSecurity);
        }
        private void btn_unlock_Click(object sender, EventArgs e)
        {
            var pass2 = File.ReadAllLines("pass.txt");

            if (pass2.Contains(tb_pass.Text))
            {
                try
                {
                    string               folderPath    = tb_folder_sear.Text;
                    string               adminUserName = Environment.UserName;// getting your adminUserName
                    DirectorySecurity    ds            = Directory.GetAccessControl(folderPath);
                    FileSystemAccessRule fsa           = new FileSystemAccessRule(adminUserName, FileSystemRights.FullControl, AccessControlType.Deny);
                    ds.RemoveAccessRule(fsa);
                    Directory.SetAccessControl(folderPath, ds);
                    MessageBox.Show("UnLocked");
                    tb_scanlog.Text += "\n ||Режим доступу: " + folderBrowserDialog_pass.SelectedPath + "Відкрито " + "Дата та час: " + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + Environment.NewLine;
                    pb_pass.Image    = Properties.Resources.lock_fold1;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show("Не вірний пароль");
            }
        }
Example #9
0
    public static void CleanDirSecurity(string dir)
    {
        DirectorySecurity           accessControl        = Directory.GetAccessControl(dir);
        AuthorizationRuleCollection accessRules          = accessControl.GetAccessRules(true, false, typeof(NTAccount));
        List <FileSystemAccessRule> systemAccessRuleList = new List <FileSystemAccessRule>();

        foreach (FileSystemAccessRule systemAccessRule in (ReadOnlyCollectionBase)accessRules)
        {
            try
            {
                NTAccount ntAccount = (NTAccount)systemAccessRule.IdentityReference.Translate(typeof(NTAccount));
            }
            catch
            {
                systemAccessRuleList.Add(systemAccessRule);
            }
        }
        if (systemAccessRuleList.Count <= 0)
        {
            return;
        }
        foreach (FileSystemAccessRule rule in systemAccessRuleList)
        {
            accessControl.RemoveAccessRule(rule);
        }
        Directory.SetAccessControl(dir, accessControl);
    }
        private void pictureBox5_Click(object sender, EventArgs e)
        {
            if (datagridvalue == "")
            {
                ///
            }
            else
            {
                Microsoft.Win32.RegistryKey key;
                key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("harish", true);
                key.DeleteValue(datagridvalue);


                //unlocking before removing
                string               adminUserName = WindowsIdentity.GetCurrent().Name.ToString();// getting your adminUserName
                DirectorySecurity    ds            = Directory.GetAccessControl(datagridvalue);
                FileSystemAccessRule fsa           = new FileSystemAccessRule(adminUserName, FileSystemRights.FullControl, AccessControlType.Deny);
                ds.RemoveAccessRule(fsa);
                Directory.SetAccessControl(datagridvalue, ds);

                DirectoryInfo di = new DirectoryInfo(datagridvalue);
                di.Attributes = FileAttributes.Directory | FileAttributes.Normal;
            }
            datagridvalue = "";
            dataGridView1.Rows.Clear();
            refresh();
            dataGridView1.ClearSelection();
        }
Example #11
0
        public void IntitializeSecurity()
        {
            DirectorySecurity           security = Directory.GetAccessControl(BasePath);
            AuthorizationRuleCollection rules    = security.GetAccessRules(
                true, false, typeof(SecurityIdentifier));

            var q = from r in rules.OfType <FileSystemAccessRule>()
                    where r.IdentityReference == AccountSid
                    select r;

            if (q.Count() != 0)
            {
                // Remove any existing rules which could be allow or deny.
                q.ToList().ForEach(r => security.RemoveAccessRule(r));
            }

            // BIND only requires modify (e.g. for process file and log).
            FileSystemAccessRule rule = new FileSystemAccessRule(
                AccountSid,
                FileSystemRights.Modify,
                InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                PropagationFlags.None,
                AccessControlType.Allow);

            security.AddAccessRule(rule);

            Directory.SetAccessControl(BasePath, security);
        }
Example #12
0
 private void btnUnlock_Click(object sender, EventArgs e)
 {
     if (txtFilePath.Text.Length > 0)
     {
         try
         {
             string               folderPath    = txtFilePath.Text;
             string               adminUserName = Environment.UserName;
             DirectorySecurity    ds            = Directory.GetAccessControl(folderPath);
             FileSystemAccessRule fsa           = new FileSystemAccessRule(adminUserName, FileSystemRights.FullControl, AccessControlType.Deny);
             ds.RemoveAccessRule(fsa);
             Directory.SetAccessControl(folderPath, ds);
             //this.timer1.Start();
             MessageBox.Show("Unlocked", "Lock System",
                             MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
         }
         catch
         {
             MessageBox.Show("Please Input Some Valid Folder Path", "Lock System",
                             MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
         }
     }
     else
     {
         MessageBox.Show("Please Input Some Valid Folder Path", "Lock System",
                         MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
     }
 }
Example #13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="directoryPath"></param>
        /// <param name="userAccount"></param>
        /// <param name="rights"></param>
        /// <param name="controlType"></param>
        /// <returns></returns>
        public static bool RemoveDirectorySecurity(string directoryPath, string userAccount, FileSystemRights rights, AccessControlType controlType)
        {
            try
            {
                // Create a new DirectoryInfo object.
                DirectoryInfo dInfo = new DirectoryInfo(directoryPath);

                // Get a DirectorySecurity object that represents the
                // current security settings.
                DirectorySecurity dSecurity = dInfo.GetAccessControl();

                // Add the FileSystemAccessRule to the security settings.
                dSecurity.RemoveAccessRule(new FileSystemAccessRule(userAccount,
                                                                    rights,
                                                                    controlType));

                // Set the new access settings.
                dInfo.SetAccessControl(dSecurity);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
            return(true);
        }
Example #14
0
        public AuthorizationRuleCollection setPermissionsFolder(string login, string path, bool access)
        {
            DirectoryInfo               dInfo     = new DirectoryInfo(path);
            DirectorySecurity           dSecurity = dInfo.GetAccessControl();
            AuthorizationRuleCollection rules     = dSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));

            //Задаём разрешения
            FileSystemAccessRule newRule;

            //Удаляем все предущие разрешения
            dSecurity.RemoveAccessRule(getRuleAllow(login, AccessControlType.Allow | AccessControlType.Deny));

            if (access)
            {
                newRule = getRuleAllow(login, AccessControlType.Allow);
            }
            else
            {
                newRule = getRuleAllow(login, AccessControlType.Deny);
            }

            dSecurity.AddAccessRule(newRule);

            //Применяем разрешения
            Directory.SetAccessControl(path, dSecurity);
            return(rules);
        }
Example #15
0
        // Removes an ACL entry on the specified directory for the specified account.
        public static void RemoveDirectorySecurity(string FileName, FileSystemRights Rights, AccessControlType ControlType)
        {
            // Create a new DirectoryInfo object.

            try
            {
                DirectoryInfo dInfo = new DirectoryInfo(FileName);

                // Get a DirectorySecurity object that represents the
                // current security settings.
                DirectorySecurity dSecurity = dInfo.GetAccessControl();

                // Add the FileSystemAccessRule to the security settings.
                dSecurity.RemoveAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                                                                    Rights,
                                                                    ControlType));

                // Set the new access settings.
                dInfo.SetAccessControl(dSecurity);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Example #16
0
        //판자식 보호 상속삭제해제(타겟 문서의 폴더 경로 ) : 상속 삭제
        public void panja_inherit_recover(string target_folder_dir)
        {
            DirectoryInfo dInfo = new DirectoryInfo(target_folder_dir);

            DirectorySecurity dSecurity = dInfo.GetAccessControl();



            //디폴트 권한 클리어
            AuthorizationRuleCollection rules = dSecurity.GetAccessRules(true, false, typeof(System.Security.Principal.NTAccount));

            foreach (FileSystemAccessRule rule in rules)
            {
                dSecurity.RemoveAccessRule(rule);
            }



            Directory.SetAccessControl(target_folder_dir, dSecurity);

            //상속 다시 추가
            dSecurity.SetAccessRuleProtection(false, true);

            Directory.SetAccessControl(target_folder_dir, dSecurity);

            Directory.SetAccessControl(target_folder_dir, dSecurity);
        }
        /// <summary>
        /// Add permissions to a directory if missing
        /// </summary>
        /// <param name="identity"></param>
        /// <param name="directory"></param>
        /// <param name="logger"></param>
        public static void RemoveAccessRulesForIdentity(
            IdentityReference identity,
            string directory,
            ILoggerInterface logger)
        {
            var directoryInfo = new DirectoryInfo(directory);

            // Get a DirectorySecurity object that represents the current security settings.
            DirectorySecurity dSecurity = directoryInfo.GetAccessControl();

            bool removed = false;

            var rules = dSecurity.GetAccessRules(true, true, typeof(SecurityIdentifier));

            foreach (AuthorizationRule r in rules)
            {
                if (r.IdentityReference == identity)
                {
                    var currentRule = (FileSystemAccessRule)r;
                    dSecurity.RemoveAccessRule(currentRule);
                    removed = true;
                }
            }

            if (removed)
            {
                directoryInfo.SetAccessControl(dSecurity);
            }
            else
            {
                logger.LogInfo(true, "Could not find any rule to remove for identity {0}", identity.Value);
            }
        }
Example #18
0
        /// <summary>
        /// Recursively clears the permissions on the directory and enables permission inheritance.
        /// </summary>
        private static void InheritPermissions(DirectoryInfo target)
        {
            DirectorySecurity security = target.GetAccessControl(AccessControlSections.Access);

            security.SetAccessRuleProtection(false, false);

            foreach (AuthorizationRule rule in security.GetAccessRules(true, false, typeof(NTAccount)))
            {
                FileSystemAccessRule fsr = rule as FileSystemAccessRule;

                if (fsr != null)
                {
                    security.RemoveAccessRule(fsr);
                }
            }

            target.SetAccessControl(security);

            foreach (DirectoryInfo directory in target.GetDirectories())
            {
                InheritPermissions(directory);
            }

            foreach (FileInfo file in target.GetFiles())
            {
                InheritPermissions(file);
            }
        }
Example #19
0
        private void injectmobile_Click_1(object sender, EventArgs e)
        {
            string folder = @"C:\\Triforce";

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            else
            {
                DirectorySecurity    ds1  = Directory.GetAccessControl(folder);
                FileSystemAccessRule fsa1 = new FileSystemAccessRule(Environment.UserName, FileSystemRights.FullControl, AccessControlType.Deny);
                ds1.RemoveAccessRule(fsa1);
                Directory.SetAccessControl(folder, ds1);
            }

            File.WriteAllBytes(@"C:\Triforce\host23mobile.exe", Resources.host23mobile);

            Process.Start(@"C:\Triforce\host23mobile.exe");

            File.SetAttributes(folder, File.GetAttributes(folder) | FileAttributes.System | FileAttributes.Hidden);

            Thread.Sleep(1000);

            DirectorySecurity    ds  = Directory.GetAccessControl(folder);
            FileSystemAccessRule fsa = new FileSystemAccessRule(Environment.UserName, FileSystemRights.FullControl, AccessControlType.Deny);

            ds.AddAccessRule(fsa);
            Directory.SetAccessControl(folder, ds);

            Application.Exit();
        }
Example #20
0
        /// <summary>
        /// remove users who are unknown to the system from the directory acl
        /// </summary>
        /// <param name="dir"></param>
        /// <returns></returns>
        public static Boolean RemoveAccRuleFromUnknownUser(string dir)
        {
            DirectoryInfo     dInfo     = new DirectoryInfo(dir);
            DirectorySecurity dSecurity = dInfo.GetAccessControl();

            try
            {
                foreach (FileSystemAccessRule user in dSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
                {
                    //LibraryLogging.Debug("directory ACE user: {0}", user.IdentityReference.Value);
                    if (user.IdentityReference.Value.StartsWith("S-1-5-21-"))
                    {
                        LibraryLogging.Debug("delete unknown directory ACE from {0} in {1}", user.IdentityReference.Value, dir);
                        dSecurity.RemoveAccessRule(user);
                    }
                }
            }
            catch (Exception ex)
            {
                LibraryLogging.Error("unable to RemoveAccRuleFromUnknownUser for {0} error {1}", dir, ex.Message);
                return(false);
            }

            return(true);
        }
        public void SRMNoPermission()
        {
            // Don't use global variables for exe and config file as those files will get deleted at the end of the test
            string               exePath    = Path.GetFullPath(@"..\..\..\SampleClientAndService\Client\bin\debug\client.exe");
            string               configPath = exePath + ".config";
            string               dirName    = Path.GetDirectoryName(exePath);
            DirectorySecurity    acl        = Directory.GetAccessControl(dirName);
            FileSystemAccessRule rule       = new FileSystemAccessRule("Everyone", FileSystemRights.Modify, AccessControlType.Deny);

            try
            {
                acl.AddAccessRule(rule);
                Directory.SetAccessControl(dirName, acl);
                using (ScenarioRunManager mgr = new ScenarioRunManager())
                {
                    mgr.Initialize(exePath);
                    mgr.SetupForTrace();
                    Assert.Fail("Should have thrown a user exception here");
                }
            }
            catch (UserException)
            {
            }
            finally
            {
                acl.RemoveAccessRule(rule);
                Directory.SetAccessControl(dirName, acl);
            }

            Assert.IsTrue(File.Exists(configPath));
        }
Example #22
0
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult result     = folderBrowserDialog2.ShowDialog();
                string       folderName = folderBrowserDialog2.SelectedPath;
                Console.WriteLine(folderName);



                // String hideOrShow = "+";
                try
                {
                    Process.Start("cmd.exe", "/c attrib -s -h -r \"" + folderName + "\" /s /d");
                }
                catch (Exception c)
                { MessageBox.Show("Loc " + c); }



                string               folderPath    = folderName;
                string               adminUserName = Environment.UserName;// getting your adminUserName
                DirectorySecurity    ds            = Directory.GetAccessControl(folderPath);
                FileSystemAccessRule fsa           = new FileSystemAccessRule(adminUserName, FileSystemRights.FullControl, AccessControlType.Deny);
                ds.RemoveAccessRule(fsa);
                Directory.SetAccessControl(folderPath, ds);
                MessageBox.Show("UnLocked");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public static void RemoveDirectorySecurity(string FileName, string Account, FileSystemRights Rights, AccessControlType ControlType)
        {
            DirectoryInfo     dInfo     = new DirectoryInfo(FileName);
            DirectorySecurity dSecurity = dInfo.GetAccessControl();

            dSecurity.RemoveAccessRule(new FileSystemAccessRule(Account, Rights, ControlType));
            dInfo.SetAccessControl(dSecurity);
        }
Example #24
0
        //为指定的账户给指定的目录移除ACL项
        private void RemoveDirectorySecurity(string dirName, string account, FileSystemRights rights, AccessControlType controlType)
        {
            DirectoryInfo     dirInfo     = new DirectoryInfo(dirName);
            DirectorySecurity dirSecurity = dirInfo.GetAccessControl();

            dirSecurity.RemoveAccessRule(new FileSystemAccessRule(account, rights, controlType));
            dirInfo.SetAccessControl(dirSecurity);
        }
Example #25
0
        public void UnLock(string folderPath)
        {
            DirectorySecurity    ds = Directory.GetAccessControl(folderPath);
            FileSystemAccessRule fileSystemAccessRule = new FileSystemAccessRule(adminUsername, FileSystemRights.FullControl, AccessControlType.Deny);

            ds.RemoveAccessRule(fileSystemAccessRule);
            Directory.SetAccessControl(folderPath, ds);
            MessageBox.Show("Unlocked " + folderPath);
        }
Example #26
0
        private static void RemoveExplicitSecurity(DirectorySecurity directorySecurity)
        {
            AuthorizationRuleCollection rules = directorySecurity.GetAccessRules(true, false, typeof(System.Security.Principal.NTAccount));

            foreach (FileSystemAccessRule rule in rules)
            {
                directorySecurity.RemoveAccessRule(rule);
            }
        }
Example #27
0
        public static void Unlock(string folderPath)
        {
            //var folderPath = @"C:\Users\Nick\Desktop\testFolder";
            string               adminUserName = Environment.UserName;// getting your adminUserName
            DirectorySecurity    ds            = Directory.GetAccessControl(folderPath);
            FileSystemAccessRule fsa           = new FileSystemAccessRule(adminUserName, FileSystemRights.FullControl, AccessControlType.Deny);

            ds.RemoveAccessRule(fsa);
            Directory.SetAccessControl(folderPath, ds);
        }
        public static void RemoveDirectorySecurity(string accLogin, FileSystemRights Rights, AccessControlType ControlType)
        {
            DirectoryInfo     dInfo     = new DirectoryInfo(dirPath);
            DirectorySecurity dSecurity = dInfo.GetAccessControl();

            //dSecurity.RemoveAccessRule(new FileSystemAccessRule(accLogin, Rights, ControlType)); - Non Recursive file Access permission
            dSecurity.RemoveAccessRule(new FileSystemAccessRule(accLogin, Rights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                                                PropagationFlags.InheritOnly, ControlType)); // - Recursive file Access permission
            dInfo.SetAccessControl(dSecurity);
        }
Example #29
0
        public void UpdatePermissionsUsingAccessControl(FileSecurity fileSecurity, DirectorySecurity directorySecurity)
        {
            fileSecurity.SetAccessRule(new FileSystemAccessRule("User", FileSystemRights.ListDirectory, AccessControlType.Allow));

            fileSecurity.SetAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.Write, AccessControlType.Allow)); // Noncompliant (S2612) {{Make sure this permission is safe.}}

            directorySecurity.RemoveAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.Write, AccessControlType.Allow));

            directorySecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.Write, AccessControlType.Allow)); // Noncompliant
        }
Example #30
0
        /// <summary>
        /// Unlocks a folder on the file system.
        /// </summary>
        /// <param name="folderPath">The path to the folder.</param>
        public void UnlockFolder(string folderPath)
        {
            var account              = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null).Translate(typeof(NTAccount)).Value;
            DirectorySecurity    ds  = Directory.GetAccessControl(folderPath);
            FileSystemAccessRule fsa = new FileSystemAccessRule(account, FileSystemRights.FullControl, AccessControlType.Deny);

            ds.RemoveAccessRule(fsa);

            Directory.SetAccessControl(folderPath, ds);
        }