Esempio n. 1
0
        public static void FolderACL(String accountName, String folderPath)
        {
            FileSystemRights Rights;

            //What rights are we setting?

            Rights = FileSystemRights.FullControl;
            bool             modified;
            InheritanceFlags none = new InheritanceFlags();

            none = InheritanceFlags.None;

            //set on dir itself
            FileSystemAccessRule accessRule = new FileSystemAccessRule(accountName, Rights, none, PropagationFlags.NoPropagateInherit, AccessControlType.Allow);
            DirectoryInfo        dInfo      = new DirectoryInfo(folderPath);
            DirectorySecurity    dSecurity  = dInfo.GetAccessControl();

            dSecurity.ModifyAccessRule(AccessControlModification.Set, accessRule, out modified);

            //Always allow objects to inherit on a directory
            InheritanceFlags iFlags = new InheritanceFlags();

            iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;

            //Add Access rule for the inheritance
            FileSystemAccessRule accessRule2 = new FileSystemAccessRule(accountName, Rights, iFlags, PropagationFlags.InheritOnly, AccessControlType.Allow);

            dSecurity.ModifyAccessRule(AccessControlModification.Add, accessRule2, out modified);

            dInfo.SetAccessControl(dSecurity);
        }
        /// <summary>
        /// 设置目录可操作权限
        /// </summary>
        /// <param name="user">系统用户,例:Users</param>
        /// <param name="directoryPath">目录路径</param>
        /// <returns></returns>
        public static bool SetDirectoryAccess(string user, string directoryPath)
        {
            FileSystemRights rights = FileSystemRights.FullControl;

            FileSystemAccessRule rule          = new FileSystemAccessRule(user, rights, InheritanceFlags.None, PropagationFlags.NoPropagateInherit, AccessControlType.Allow);
            DirectoryInfo        directoryInfo = new DirectoryInfo(directoryPath);
            DirectorySecurity    security      = directoryInfo.GetAccessControl(AccessControlSections.Access);

            bool result = false;

            security.ModifyAccessRule(AccessControlModification.Set, rule, out result);
            if (!result)
            {
                return(false);
            }

            InheritanceFlags flags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;

            rule = new FileSystemAccessRule(user, rights, flags, PropagationFlags.InheritOnly, AccessControlType.Allow);

            security.ModifyAccessRule(AccessControlModification.Add, rule, out result);
            if (!result)
            {
                return(false);
            }

            directoryInfo.SetAccessControl(security);

            return(true);
        }
        /// <summary>
        /// Adds an ACL entry on the specified folder for the specified account.
        /// </summary>
        public static bool SetDirPermission(string dirPath, string account,
                                            FileSystemRights rights)
        {
            FileSystemAccessRule accessRule = new FileSystemAccessRule(account, rights,
                                                                       InheritanceFlags.None,
                                                                       PropagationFlags.NoPropagateInherit,
                                                                       AccessControlType.Allow);
            DirectoryInfo     dirInfo     = new DirectoryInfo(dirPath);
            DirectorySecurity dirSecurity =
                dirInfo.GetAccessControl(AccessControlSections.Access);
            bool result = false;

            dirSecurity.ModifyAccessRule(AccessControlModification.Add,
                                         accessRule, out result);
            if (result)
            {
                accessRule = new FileSystemAccessRule(account, rights,
                                                      InheritanceFlags.ContainerInherit |
                                                      InheritanceFlags.ObjectInherit,
                                                      PropagationFlags.InheritOnly,
                                                      AccessControlType.Allow);
                dirSecurity.ModifyAccessRule(AccessControlModification.Add, accessRule,
                                             out result);
                if (result)
                {
                    dirInfo.SetAccessControl(dirSecurity);
                }
            }
            return(result);
        }
Esempio n. 4
0
        /// <summary>
        /// Set permissions for a group on a directory.
        /// </summary>
        /// <param name="groupName"></param>
        /// <param name="path"></param>
        /// <param name="rights"></param>
        public static void SetGroupAcl(string groupName, string path, FileSystemRights rights)
        {
            bool result;

            // Remove trailing backslash
            path = path.TrimEnd('\\');
            DirectoryInfo     directoryInfo     = new DirectoryInfo(path);
            DirectorySecurity directorySecurity = directoryInfo.GetAccessControl(AccessControlSections.Access);

            FileSystemAccessRule directoryAccessRule = new FileSystemAccessRule(groupName, rights, InheritanceFlags.None, PropagationFlags.NoPropagateInherit, AccessControlType.Allow);

            directorySecurity.ModifyAccessRule(AccessControlModification.Set, directoryAccessRule, out result);

            if (result == false)
            {
                throw new Exception(string.Format("SetAcl failed to set directory access on {0} for group {1}", groupName, path));
            }

            FileSystemAccessRule inheritanceAccessRule = new FileSystemAccessRule(groupName, rights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow);

            directorySecurity.ModifyAccessRule(AccessControlModification.Add, inheritanceAccessRule, out result);

            if (result == false)
            {
                throw new Exception(string.Format("SetAcl failed to set inheritance access on {0} for group {1}", groupName, path));
            }

            directoryInfo.SetAccessControl(directorySecurity);
        }
Esempio n. 5
0
        ///
        /// <summary>
        /// Alter the access rights for a directory.
        /// </summary>
        /// <param name="Path"></param>
        /// <param name="rights"></param>
        /// <param name="username"></param>
        /// <param name="inherentsubDir"></param>
        /// <returns></returns>
        ///
        public static bool ChangeDirectoryRights(string Path, FileSystemRights rights, string username, bool inherentsubDir)
        {
            //check to see if path exists
            if (!Directory.Exists(Path))
            {
                return(false);
            }

            // *** Add Access Rule to the actual directory
            FileSystemAccessRule AccessRule = new FileSystemAccessRule(username, rights,
                                                                       InheritanceFlags.None,
                                                                       PropagationFlags.NoPropagateInherit,
                                                                       AccessControlType.Allow);
            //Get the direcory to set the info for
            DirectoryInfo     Info     = new DirectoryInfo(Path);
            DirectorySecurity Security = Info.GetAccessControl(AccessControlSections.Access);

            bool Result = false;

            //set the the rull
            Security.ModifyAccessRule(AccessControlModification.Set, AccessRule, out Result);
            //add a see if  worked
            if (!Result)
            {
                return(false);
            }

            //just files
            InheritanceFlags iFlags = InheritanceFlags.ObjectInherit;

            if (inherentsubDir)
            {////check for the sub directories
                iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
            }

            // *** Add Access rule for the inheritance
            AccessRule = new FileSystemAccessRule(username, rights,
                                                  iFlags,                       //flags for inheritance
                                                  PropagationFlags.InheritOnly, //local already set
                                                  AccessControlType.Allow);     //make sure we allow this user


            Result = false;

            // Info.Attributes = FileAttributes.Directory | ~FileAttributes.ReadOnly;
            Security.ModifyAccessRule(AccessControlModification.Add, AccessRule, out Result);

            if (!Result)
            {
                return(false);
            }

            Info.SetAccessControl(Security);

            return(true);
        }
Esempio n. 6
0
        private static bool SetAcl(string path)
        {
            const string Users = "Users";

            try
            {
                FileSystemRights Rights = FileSystemRights.FullControl;

                // *** Add Access Rule to the actual directory itself
                FileSystemAccessRule AccessRule = new FileSystemAccessRule(Users, Rights,
                                                                           InheritanceFlags.None,
                                                                           PropagationFlags.NoPropagateInherit,
                                                                           AccessControlType.Allow);

                DirectoryInfo     Info     = new DirectoryInfo(path);
                DirectorySecurity Security = Info.GetAccessControl(AccessControlSections.Access);

                Security.ModifyAccessRule(AccessControlModification.Set, AccessRule, out bool Result);

                if (!Result)
                {
                    return(false);
                }

                // *** Always allow objects to inherit on a directory
                InheritanceFlags iFlags = InheritanceFlags.ObjectInherit;
                iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;

                // *** Add Access rule for the inheritance
                AccessRule = new FileSystemAccessRule(Users, Rights,
                                                      iFlags,
                                                      PropagationFlags.InheritOnly,
                                                      AccessControlType.Allow);
                Result = false;
                Security.ModifyAccessRule(AccessControlModification.Add, AccessRule, out Result);

                if (!Result)
                {
                    return(false);
                }

                Info.SetAccessControl(Security);
                Info.Refresh();

                return(true);
            }
            catch (Exception ex)
            {
                Program.Log.Error(path, ex);
            }

            return(false);
        }
Esempio n. 7
0
        //http://www.west-wind.com/weblog/posts/4072.aspx
        public void SetFileSystemRights(string target, string group, FileSystemRights permission, DeploymentResult r)
        {
            if (!IsDirectory(target) && !IsFile(target))
            {
                return;
            }

            var oldSecurity = Directory.GetAccessControl(target);
            var newSecurity = new DirectorySecurity();

            newSecurity.SetSecurityDescriptorBinaryForm(oldSecurity.GetSecurityDescriptorBinaryForm());

            var accessRule = new FileSystemAccessRule(group,
                                                      permission,
                                                      InheritanceFlags.None,
                                                      PropagationFlags.NoPropagateInherit,
                                                      AccessControlType.Allow);
            bool result;

            newSecurity.ModifyAccessRule(AccessControlModification.Set, accessRule, out result);

            if (!result)
            {
                r.AddError("Something wrong happened");
            }

            accessRule = new FileSystemAccessRule(group,
                                                  permission,
                                                  InheritanceFlags.ContainerInherit |
                                                  InheritanceFlags.ObjectInherit,
                                                  PropagationFlags.InheritOnly,
                                                  AccessControlType.Allow);

            result = false;
            newSecurity.ModifyAccessRule(AccessControlModification.Add, accessRule, out result);
            if (!result)
            {
                r.AddError("Something wrong happened");
            }

            Directory.SetAccessControl(target, newSecurity);

            if (result)
            {
                r.AddGood("Permissions set for '{0}' on folder '{1}'", group, target);
            }

            if (!result)
            {
                r.AddError("Something wrong happened");
            }
        }
Esempio n. 8
0
        static bool SetAcl()
        {
            try
            {
                System.IO.Directory.CreateDirectory("C:\\Data");

                FileSystemRights Rights = (FileSystemRights)0;
                Rights = FileSystemRights.FullControl;

                // *** Add Access Rule to the actual directory itself
                FileSystemAccessRule AccessRule = new FileSystemAccessRule("Users", Rights,
                                                                           InheritanceFlags.None,
                                                                           PropagationFlags.NoPropagateInherit,
                                                                           AccessControlType.Allow);

                DirectoryInfo     Info     = new DirectoryInfo(@"C:\Data");
                DirectorySecurity Security = Info.GetAccessControl(AccessControlSections.Access);

                bool Result = false;
                Security.ModifyAccessRule(AccessControlModification.Set, AccessRule, out Result);

                if (!Result)
                {
                    return(false);
                }

                // *** Always allow objects to inherit on a directory
                InheritanceFlags iFlags = InheritanceFlags.ObjectInherit;
                iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;

                // *** Add Access rule for the inheritance
                AccessRule = new FileSystemAccessRule("Users", Rights,
                                                      iFlags,
                                                      PropagationFlags.InheritOnly,
                                                      AccessControlType.Allow);
                Result = false;
                Security.ModifyAccessRule(AccessControlModification.Add, AccessRule, out Result);
                if (!Result)
                {
                    return(false);
                }
                Info.SetAccessControl(Security);
                return(true);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                return(false);
            }
        }
Esempio n. 9
0
        public static bool SetDirectoryOwnershipForAllUsers(string destinationDirectory)
        {
            try
            {
                FileSystemRights Rights = (FileSystemRights)0;
                Rights = FileSystemRights.FullControl;
                var usersGroup = @"BUILTIN\Users";
                // *** Add Access Rule to the actual directory itself
                FileSystemAccessRule AccessRule = new FileSystemAccessRule(usersGroup, Rights,
                                                                           InheritanceFlags.None,
                                                                           PropagationFlags.NoPropagateInherit,
                                                                           AccessControlType.Allow);

                DirectoryInfo     Info     = new DirectoryInfo(destinationDirectory);
                DirectorySecurity Security = Info.GetAccessControl(AccessControlSections.Access);

                bool Result = false;
                Security.ModifyAccessRule(AccessControlModification.Set, AccessRule, out Result);

                if (!Result)
                {
                    return(false);
                }

                // *** Always allow objects to inherit on a directory
                InheritanceFlags iFlags = InheritanceFlags.ObjectInherit;
                iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;

                // *** Add Access rule for the inheritance
                AccessRule = new FileSystemAccessRule(usersGroup, Rights,
                                                      iFlags,
                                                      PropagationFlags.InheritOnly,
                                                      AccessControlType.Allow);
                Result = false;
                Security.ModifyAccessRule(AccessControlModification.Add, AccessRule, out Result);

                if (!Result)
                {
                    return(false);
                }

                Info.SetAccessControl(Security);
            }
            catch (Exception)
            {
                // We give it a best-effort here.  If we aren't running an enterprise OS, this group may not exist (or be needed.)
            }
            return(true);
        }
Esempio n. 10
0
        private static void SetFolderFullControl(string path)
        {
            ////给Excel文件所在目录添加"Everyone,Users"用户组的完全控制权限
            //DirectoryInfo di = new DirectoryInfo(path);
            //System.Security.AccessControl.DirectorySecurity dirSecurity = di.GetAccessControl();
            //dirSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
            //dirSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
            //di.SetAccessControl(dirSecurity);

            DirectoryInfo dir = new DirectoryInfo(path);

            if (!dir.Exists)
            {
                return;
            }

            DirectorySecurity ds = dir.GetAccessControl(AccessControlSections.All);
            //继承设置
            bool             ok;
            InheritanceFlags iflag = new InheritanceFlags();

            iflag = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
            FileSystemAccessRule arules = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, iflag, PropagationFlags.None, AccessControlType.Allow);

            ds.ModifyAccessRule(AccessControlModification.Add, arules, out ok);
            dir.SetAccessControl(ds);
        }
Esempio n. 11
0
        //C# 在进行io操作时经常遇到对于路径没有操作权限的情况,这个时候我们需要动态的提供权限进行IO处理
        public static void AddDirectorySecurity(string FileName, string Account, FileSystemRights[] rights)
        {//提供读写权限
            //读取该路径的原始操作权限
            //提供权限以实现功能操作,
            //还原权限
            FileSystemRights Rights = new FileSystemRights();

            foreach (FileSystemRights item in rights)
            {
                Rights = Rights | item;
            }
            //Read  ChangePermissions FullControl Write
            bool              ok;
            DirectoryInfo     dInfo     = new DirectoryInfo(FileName);
            DirectorySecurity dSecurity = dInfo.GetAccessControl();
            InheritanceFlags  iFlags    = new InheritanceFlags();

            iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
            FileSystemAccessRule AccessRule2 = new FileSystemAccessRule(Account, Rights, iFlags, PropagationFlags.None, AccessControlType.Allow);

            dSecurity.ModifyAccessRule(AccessControlModification.Add, AccessRule2, out ok);
            dInfo.SetAccessControl(dSecurity);
            //列出目标目录所具有的权限
            DirectorySecurity sec = Directory.GetAccessControl(FileName, AccessControlSections.All);

            foreach (FileSystemAccessRule rule in sec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
            {
                if ((rule.FileSystemRights & FileSystemRights.Read) != 0)
                {
                    Console.WriteLine(rule.FileSystemRights.ToString());
                }
            }
            Console.Read();
        }
Esempio n. 12
0
        private bool SetMountpointRWAccessForUsers(string mountPointPath, string traceId)
        {
            string status  = String.Empty;
            bool   fSetACL = false;

#if DotNetCoreClrLinux
            try
            {
                const int defaultFilePermission = 0x1ed;
                Chmod(mountPointPath, defaultFilePermission);
                fSetACL = true;
            }
            catch
            {
                status = "Chmod failed";
            }
#else
            try
            {
                // Create a new DirectoryInfo object.
                DirectoryInfo dInfo = new DirectoryInfo(mountPointPath);

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

                var allUsers = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);

                // Add the FileSystemAccessRule to the security settings.
                bool fModified = false;
                dSecurity.ModifyAccessRule(AccessControlModification.Add, new FileSystemAccessRule(allUsers,
                                                                                                   FileSystemRights.Modify,
                                                                                                   InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                                                                                   PropagationFlags.None, // Make it applied to This Folder, subfolders and files
                                                                                                   AccessControlType.Allow), out fModified);

                // Set the new access settings.
                if (fModified)
                {
                    FileSystemAclExtensions.SetAccessControl(dInfo, dSecurity);
                    fSetACL = true;
                }
                else
                {
                    status = String.Format("Failed to change ACL of mountpoint {0}.", mountPointPath);
                }
            }
            catch (Exception ex)
            {
                status = String.Format("Failed to change ACL of mountpoint {0} due to exception: {1}.", mountPointPath, ex.Message);
            }
#endif

            if (!String.IsNullOrEmpty(status))
            {
                TraceWriter.WriteErrorWithId(Constants.TraceSource, traceId, status);
            }

            return(fSetACL);
        }
Esempio n. 13
0
        /// <summary>
        /// Remove all user permissions from folder.
        /// </summary>
        /// If the user with name `username` exists, it will be preserved.
        /// <param name="fullPath">Full path to the folder on which to remove
        ///     all user permissions.</param>
        /// <param name="username">Name of the user that will keep the
        ///     permissions.</param>
        public static void RemovePermissionsForAllUsersButOne(string fullPath, string username)
        {
            // Is the function being run by an administrator?
            if (!LocalUserManager.IsAdministrator())
            {
                // Inform
                const string msg = "This method must be run by an administrator.";

                sLogger.Error(msg);
                throw new InvalidOperationException(msg);
            }

            DirectoryInfo     dirinfo = new DirectoryInfo(fullPath);
            DirectorySecurity dsec    = dirinfo.GetAccessControl(AccessControlSections.All);

            AuthorizationRuleCollection rules =
                dsec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));

            foreach (AccessRule rule in rules)
            {
                if (rule.IdentityReference.Value != username)
                {
                    dsec.PurgeAccessRules(rule.IdentityReference);
                    dsec.ModifyAccessRule(AccessControlModification.RemoveAll, rule, out bool value);

                    // Inform
                    sLogger.Info("Removed permission from '" + fullPath + "' for '" + username + "'.");
                }
            }
        }
Esempio n. 14
0
        // 设置相关文件、目录权限
        // 解决以普通用户身份运行时,目录没有权限的问题
        public static void SetPermission(string path)
        {
            if (System.Environment.OSVersion.Version.Major <= 5)
            {
                return;
            }


            // 如果目录不存在,创建日志目录
            EnsureExist(path);

            // Users组
            string userGroupName = "Users";

            DirectorySecurity dirSecurity = Directory.GetAccessControl(path, AccessControlSections.All);

            //添加Users组的访问权限规则 完全控制权限
            FileSystemAccessRule usersFileSystemAccessRule = new FileSystemAccessRule(userGroupName,
                                                                                      FileSystemRights.FullControl,
                                                                                      InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                                                                      PropagationFlags.None,
                                                                                      AccessControlType.Allow);
            bool isModified = false;

            dirSecurity.ModifyAccessRule(AccessControlModification.Add, usersFileSystemAccessRule, out isModified);

            // 保存权限设置
            Directory.SetAccessControl(path, dirSecurity);
        }
Esempio n. 15
0
        internal GlobalFileWritingSystemStore(string path)
        {
            m_path = path;
            if (!Directory.Exists(m_path))
            {
                DirectoryInfo di;

                // Provides FW on Linux multi-user access. Overrides the system
                // umask and creates the directory with the permissions "775".
                // The "fieldworks" group was created outside the app during
                // configuration of the package which allows group access.
                using (new FileModeOverride())
                {
                    di = Directory.CreateDirectory(m_path);
                }

                if (!MiscUtils.IsUnix)
                {
                    // NOTE: GetAccessControl/ModifyAccessRule/SetAccessControl is not implemented in Mono
                    DirectorySecurity ds = di.GetAccessControl();
                    var        sid       = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
                    AccessRule rule      = new FileSystemAccessRule(sid, FileSystemRights.Write | FileSystemRights.ReadAndExecute
                                                                    | FileSystemRights.Modify, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                                                    PropagationFlags.InheritOnly, AccessControlType.Allow);
                    bool modified;
                    ds.ModifyAccessRule(AccessControlModification.Add, rule, out modified);
                    di.SetAccessControl(ds);
                }
            }
            m_mutex = SingletonsContainer.Get(typeof(Mutex).FullName + m_path,
                                              () => new Mutex(false, m_path.Replace('\\', '_').Replace('/', '_')));
        }
Esempio n. 16
0
        private void Authority()//设置APP的目录权限
        {
            string               dirPath     = Environment.CurrentDirectory;
            DirectoryInfo        dir         = new DirectoryInfo(dirPath);
            DirectorySecurity    dirSecurity = dir.GetAccessControl(AccessControlSections.All);
            InheritanceFlags     inherits    = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
            FileSystemAccessRule everyoneFileSystemAccessRule = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
            FileSystemAccessRule usersFileSystemAccessRule    = new FileSystemAccessRule("Users", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
            bool isModified = false;

            dirSecurity.ModifyAccessRule(AccessControlModification.Add, everyoneFileSystemAccessRule, out isModified);
            dirSecurity.ModifyAccessRule(AccessControlModification.Add, usersFileSystemAccessRule, out isModified);
            dir.SetAccessControl(dirSecurity);
            Start();
            exit();
        }
Esempio n. 17
0
        public static async Task <bool> CreateHomeDir(Account account)
        {
            return(await Task.Run(() =>
            {
                try
                {
                    if (!System.IO.Directory.Exists(account.HomeDirectory))
                    {
                        System.IO.Directory.CreateDirectory(account.HomeDirectory);
                    }

                    FileSystemRights rights = FileSystemRights.FullControl;
                    InheritanceFlags flags = new InheritanceFlags();
                    flags = InheritanceFlags.None;

                    FileSystemAccessRule accessRule = new FileSystemAccessRule(account.UID, rights, flags, PropagationFlags.NoPropagateInherit, AccessControlType.Allow);
                    DirectoryInfo dInfo = new DirectoryInfo(account.HomeDirectory);
                    DirectorySecurity dSec = dInfo.GetAccessControl();

                    bool modified;
                    dSec.ModifyAccessRule(AccessControlModification.Set, accessRule, out modified);

                    InheritanceFlags iFlags = new InheritanceFlags();
                    iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;

                    FileSystemAccessRule accessRule2 = new FileSystemAccessRule(account.UID, rights, iFlags, PropagationFlags.InheritOnly, AccessControlType.Allow);
                    dSec.ModifyAccessRule(AccessControlModification.Add, accessRule2, out modified);

                    dInfo.SetAccessControl(dSec);
                    return true;
                } catch (Exception e)
                {
                    Connector.Log.AddError(Origin.Directory, "Unable to create homedir: " + e.Message);
                    if (System.IO.Directory.Exists(account.HomeDirectory))
                    {
                        try
                        {
                            System.IO.Directory.Delete(account.HomeDirectory);
                        } catch (Exception ex)
                        {
                            Connector.Log.AddError(Origin.Directory, ex.Message);
                        }
                    }
                    return false;
                }
            }));
        }
        static bool SetAcl(string destinationDirectory)
        {
            FileSystemRights Rights = (FileSystemRights)0;

            Rights = FileSystemRights.FullControl;

            // *** Add Access Rule to the actual directory itself
            FileSystemAccessRule AccessRule = new FileSystemAccessRule("Users", Rights,
                                                                       InheritanceFlags.None,
                                                                       PropagationFlags.NoPropagateInherit,
                                                                       AccessControlType.Allow);

            DirectoryInfo     Info     = new DirectoryInfo(destinationDirectory);
            DirectorySecurity Security = Info.GetAccessControl(AccessControlSections.Access);

            bool Result = false;

            Security.ModifyAccessRule(AccessControlModification.Set, AccessRule, out Result);

            if (!Result)
            {
                return(false);
            }

            // *** Always allow objects to inherit on a directory
            InheritanceFlags iFlags = InheritanceFlags.ObjectInherit;

            iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;

            // *** Add Access rule for the inheritance
            AccessRule = new FileSystemAccessRule("Users", Rights,
                                                  iFlags,
                                                  PropagationFlags.InheritOnly,
                                                  AccessControlType.Allow);
            Result = false;
            Security.ModifyAccessRule(AccessControlModification.Add, AccessRule, out Result);

            if (!Result)
            {
                return(false);
            }

            Info.SetAccessControl(Security);

            return(true);
        }
Esempio n. 19
0
        static bool SetAccessRule()
        {
            FileSystemRights pRights = (FileSystemRights)0;

            pRights = FileSystemRights.FullControl;

            // [HocPD]: Add Access Rule to the actual directory itself
            FileSystemAccessRule pAccessRule = new FileSystemAccessRule("Users", pRights,
                                                                        InheritanceFlags.None,
                                                                        PropagationFlags.NoPropagateInherit,
                                                                        AccessControlType.Allow);

            DirectoryInfo     pInfo     = new DirectoryInfo(Application.StartupPath);
            DirectorySecurity pSecurity = pInfo.GetAccessControl(AccessControlSections.Access);

            bool pResult = false;

            pSecurity.ModifyAccessRule(AccessControlModification.Set, pAccessRule, out pResult);

            if (!pResult)
            {
                return(false);
            }

            // [HocPD]: Always allow objects to inherit on a directory
            InheritanceFlags iFlags = InheritanceFlags.ObjectInherit;

            iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;

            // [HocPD]: Add Access rule for the inheritance
            pAccessRule = new FileSystemAccessRule("Users", pRights,
                                                   iFlags,
                                                   PropagationFlags.InheritOnly,
                                                   AccessControlType.Allow);
            pResult = false;
            pSecurity.ModifyAccessRule(AccessControlModification.Add, pAccessRule, out pResult);

            if (!pResult)
            {
                return(false);
            }

            pInfo.SetAccessControl(pSecurity);

            return(true);
        }
        /// <summary>
        /// 设置文件权限
        /// </summary>
        /// <param name="FileName">文件路径</param>
        /// <param name="Account">系统管理员:administrator</param>
        /// <param name="UserRights">文件的权限(R=读,C=更改权限,F=完全控制,W=文件可写)</param>
        /// <returns></returns>
        public string SetFilePermission(string FileName, string Account, string UserRights)
        {
            string getPermission = "";
            //系统文件权限实例化
            FileSystemRights Rights = new FileSystemRights();

            if (UserRights.IndexOf("R") >= 0)
            {
                //系统文件只读
                Rights = Rights | FileSystemRights.Read;
            }
            if (UserRights.IndexOf("C") >= 0)
            {
                //更改系统文件权限
                Rights = Rights | FileSystemRights.ChangePermissions;
            }
            if (UserRights.IndexOf("F") >= 0)
            {
                //完全控制
                Rights = Rights | FileSystemRights.FullControl;
            }
            if (UserRights.IndexOf("W") >= 0)
            {
                //系统文件可写
                Rights = Rights | FileSystemRights.Write;
            }

            bool ok;
            //将文件路径修改为f\a\..
            DirectoryInfo dInfo = new DirectoryInfo(FileName);
            //获取文件的访问控制
            DirectorySecurity dSecurity = dInfo.GetAccessControl();
            //继承标志
            InheritanceFlags iFlags = new InheritanceFlags();

            //获得继承方向:容器继承或对象继承
            iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
            //系统文件的访问规则:Account是否管理员;Rights是否读写或全部操作;iFlags如何继承;不允许传播;允许访问控制
            FileSystemAccessRule AccessRule2 = new FileSystemAccessRule(Account, Rights, iFlags, PropagationFlags.None, AccessControlType.Allow);

            //修改文件的访问规则
            dSecurity.ModifyAccessRule(AccessControlModification.Add, AccessRule2, out ok);
            //为该路径下得文件设置访问控制权限
            dInfo.SetAccessControl(dSecurity);

            //列出目标目录所具有的权限
            DirectorySecurity sec = Directory.GetAccessControl(FileName, AccessControlSections.All);

            foreach (FileSystemAccessRule rule in sec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
            {
                if ((rule.FileSystemRights & FileSystemRights.Read) != 0)
                {
                    getPermission = rule.FileSystemRights.ToString();
                }
            }
            return(getPermission);
        }
Esempio n. 21
0
        /// <summary>
        /// 添加 指定目录 指定用户 指定的 权限
        /// </summary>
        /// <param name="FileName">指定目录</param>
        /// <param name="Account">指定用户</param>
        /// <param name="UserRights"></param>
        /// <returns></returns>
        public static bool AddDirectorySecurity(string FileName, string Account, FileSystemRights rights)
        {
            bool                 ok;
            DirectoryInfo        dInfo       = new DirectoryInfo(FileName);
            DirectorySecurity    dSecurity   = dInfo.GetAccessControl();
            InheritanceFlags     iFlags      = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
            FileSystemAccessRule AccessRule2 = new FileSystemAccessRule(Account, rights, iFlags, PropagationFlags.None, AccessControlType.Allow);

            dSecurity.ModifyAccessRule(AccessControlModification.Add, AccessRule2, out ok);
            dInfo.SetAccessControl(dSecurity);
            return(ok);
        }
        /// <summary>
        /// 项目中用,文件夹只保留everyone权限,其中允许用户读,但不允许写
        /// by the way,代码结果是给文件夹一个特殊权限,点进去高级看,会发现这个特殊权限的子项和写入权限的子项是一样的
        /// </summary>
        /// <param name="dirName"></param>
        public static void OnlyKeepEveryonePermissionsWithWriteNotAllowed(string dirName)
        {
            DirectoryInfo               dirinfo   = new DirectoryInfo(dirName);
            DirectorySecurity           objSecObj = dirinfo.GetAccessControl();
            AuthorizationRuleCollection acl       = objSecObj.GetAccessRules(true, true,
                                                                             typeof(System.Security.Principal.NTAccount));

            objSecObj.SetAccessRuleProtection(true, false);        //to remove inherited permissions
            foreach (FileSystemAccessRule ace in acl)              //to remove any other permission
            {
                objSecObj.PurgeAccessRules(ace.IdentityReference); //same as use objSecObj.RemoveAccessRuleSpecific(ace);
            }
            InheritanceFlags     inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
            FileSystemAccessRule everyoneFileSystemAccessRule  = new FileSystemAccessRule("Everyone", FileSystemRights.ReadAndExecute | FileSystemRights.ListDirectory | FileSystemRights.Read, inherits, PropagationFlags.None, AccessControlType.Allow);
            FileSystemAccessRule everyoneFileSystemAccessRule2 = new FileSystemAccessRule("Everyone", FileSystemRights.Write, AccessControlType.Deny);
            bool isModified = false;

            objSecObj.ModifyAccessRule(AccessControlModification.Add, everyoneFileSystemAccessRule2, out isModified);
            objSecObj.ModifyAccessRule(AccessControlModification.Add, everyoneFileSystemAccessRule, out isModified);
            dirinfo.SetAccessControl(objSecObj);
        }
Esempio n. 23
0
        private static void SetCommonAppDataPermissions(string path)
        {
            DirectoryInfo     di = Directory.CreateDirectory(path);
            DirectorySecurity ds = di.GetAccessControl();
            var        sid       = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
            AccessRule rule      = new FileSystemAccessRule(sid, FileSystemRights.Write | FileSystemRights.ReadAndExecute
                                                            | FileSystemRights.Modify, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                                            PropagationFlags.InheritOnly, AccessControlType.Allow);
            bool modified;

            ds.ModifyAccessRule(AccessControlModification.Add, rule, out modified);
            di.SetAccessControl(ds);
        }
Esempio n. 24
0
        /// <summary>
        /// 设置文件夹访问权限
        /// </summary>
        /// <param name="folderPath">文件夹路径</param>
        /// <param name="userName">需要设置权限的用户名</param>
        /// <param name="rights">访问权限</param>
        /// <param name="allowOrDeny">允许拒绝访问</param>
        /// <param name="inherits">继承标志指定访问控制项 (ACE) 的继承语义</param>
        /// <param name="propagateToChildren">指定如何将访问面控制项 (ACE) 传播到子对象。仅当存在继承标志时,这些标志才有意义</param>
        /// <param name="addResetOrRemove">指定要执行的访问控制修改的类型。此枚举由 System.Security.AccessControl.ObjectSecurity 类及其子类的方法使用</param>
        private bool SetFolderACL(string folderPath, string userName, FileSystemRights rights, AccessControlType allowOrDeny, InheritanceFlags inherits, PropagationFlags propagateToChildren, AccessControlModification addResetOrRemove)
        {
            DirectoryInfo        folder    = new DirectoryInfo(folderPath);
            DirectorySecurity    dSecurity = folder.GetAccessControl(AccessControlSections.All);
            FileSystemAccessRule accRule   = new FileSystemAccessRule(userName, rights, inherits, propagateToChildren, allowOrDeny);

            bool modified;

            dSecurity.ModifyAccessRule(addResetOrRemove, accRule, out modified);
            folder.SetAccessControl(dSecurity);

            return(modified);
        }
Esempio n. 25
0
 public static bool SetAcl(string destinationDirectory)
 {
     bool flag;
     try
     {
         FileSystemRights fileSystemRight = (FileSystemRights)0;
         fileSystemRight = FileSystemRights.FullControl;
         FileSystemAccessRule fileSystemAccessRule = new FileSystemAccessRule("Users", FileSystemRights.FullControl, InheritanceFlags.None, PropagationFlags.NoPropagateInherit, AccessControlType.Allow);
         DirectoryInfo directoryInfo = new DirectoryInfo(destinationDirectory);
         DirectorySecurity accessControl = directoryInfo.GetAccessControl(AccessControlSections.Access);
         bool flag1 = false;
         accessControl.ModifyAccessRule(AccessControlModification.Set, fileSystemAccessRule, out flag1);
         if (flag1)
         {
             fileSystemAccessRule = new FileSystemAccessRule("Users", fileSystemRight, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow);
             flag1 = false;
             accessControl.ModifyAccessRule(AccessControlModification.Add, fileSystemAccessRule, out flag1);
             if (flag1)
             {
                 directoryInfo.SetAccessControl(accessControl);
                 flag = true;
             }
             else
             {
                 flag = false;
             }
         }
         else
         {
             flag = false;
         }
     }
     catch (Exception exception)
     {
         flag = false;
     }
     return flag;
 }
Esempio n. 26
0
        public static DirectorySecurity CreateDirectorySecurity(string[] identities)
        {
            System.Security.AccessControl.DirectorySecurity dirSecurity = new DirectorySecurity();
            //设定文件ACL继承
            InheritanceFlags inherits   = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
            bool             isModified = false;

            foreach (var item in identities)
            {
                FileSystemAccessRule fileSystemAccessRule = new FileSystemAccessRule(item, FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
                dirSecurity.ModifyAccessRule(AccessControlModification.Add, fileSystemAccessRule, out isModified);
            }
            return(dirSecurity);
        }
Esempio n. 27
0
 public static bool SetupDirectory(string strPath)
 {
     if (!Directory.Exists(strPath))
     {
         DirectoryInfo      directoryInfo      = Directory.CreateDirectory(strPath);
         DirectorySecurity  directorySecurity  = directoryInfo.GetAccessControl();
         SecurityIdentifier securityIdentifier = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
         AccessRule         rule = new FileSystemAccessRule(securityIdentifier, FileSystemRights.Write | FileSystemRights.ReadAndExecute | FileSystemRights.Modify, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow);
         bool modified;
         directorySecurity.ModifyAccessRule(AccessControlModification.Add, rule, out modified);
         directoryInfo.SetAccessControl(directorySecurity);
     }
     return(Directory.Exists(strPath));
 }
Esempio n. 28
0
        private static void SetSecurityRights(DirectoryInfo directoryInfo)
        {
            bool modified;
            DirectorySecurity  directorySecurity  = directoryInfo.GetAccessControl();
            SecurityIdentifier securityIdentifier = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
            AccessRule         rule = new FileSystemAccessRule(
                securityIdentifier,
                FileSystemRights.Write |
                FileSystemRights.ReadAndExecute |
                FileSystemRights.Modify,
                AccessControlType.Allow);

            directorySecurity.ModifyAccessRule(AccessControlModification.Add, rule, out modified);
            directoryInfo.SetAccessControl(directorySecurity);
        }
        public override void Install(System.Collections.IDictionary stateSaver)
        {
            base.Install(stateSaver);
            Form frm = new AppConfigModifier(this.Context);

            frm.BringToFront();
            frm.ShowDialog();

            try
            {
                var filepath = this.Context.Parameters["assemblypath"];
                filepath = Path.GetDirectoryName(filepath);
                //filepath = Path.Combine(filepath, "Logs");

                // This gets the "Authenticated Users" group, no matter what it's called
                SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);

                // Create the rules
                FileSystemAccessRule writerule = new FileSystemAccessRule(sid, FileSystemRights.FullControl, AccessControlType.Allow);

                if (!string.IsNullOrEmpty(filepath) && Directory.Exists(filepath))
                {
                    // Get your file's ACL
                    DirectorySecurity fsecurity = Directory.GetAccessControl(filepath);

                    // Add the new rule to the ACL
                    fsecurity.AddAccessRule(writerule);

                    // Set the ACL back to the file
                    Directory.SetAccessControl(filepath, fsecurity);


                    // *** Always allow objects to inherit on a directory
                    InheritanceFlags iFlags = InheritanceFlags.ObjectInherit;
                    iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;

                    // *** Add Access rule for the inheritance
                    var  AccessRule = new FileSystemAccessRule(sid, FileSystemRights.FullControl, iFlags, PropagationFlags.InheritOnly, AccessControlType.Allow);
                    bool Result     = false;
                    fsecurity.ModifyAccessRule(AccessControlModification.Add, AccessRule, out Result);
                    Directory.SetAccessControl(filepath, fsecurity);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="Path">Directory path</param>
        /// <param name="Name">Directory Name</param>
        /// <param name="Username">Username</param>
        /// <return>True or False</return>
        public static void RemovePermissions(String Path, String Name, String Username)
        {
            String                      strDirectory = BuildDirectory(Path, Name);
            DirectoryInfo               dirinfo      = new DirectoryInfo(strDirectory);
            DirectorySecurity           dsec         = dirinfo.GetAccessControl(AccessControlSections.All);
            AuthorizationRuleCollection rules        = dsec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));

            foreach (AccessRule rule in rules)
            {
                if (rule.IdentityReference.Value == Username)
                {
                    bool value;
                    dsec.PurgeAccessRules(rule.IdentityReference);
                    dsec.ModifyAccessRule(AccessControlModification.RemoveAll, rule, out value);
                    dirinfo.SetAccessControl(dsec);
                }
            }
        }