Ejemplo n.º 1
0
        /// <summary>
        /// Get the ownership of a folder or file.
        /// </summary>
        /// <param name="fullPath">Full path to the folder or file for which to
        ///     query the ownership.</param>
        /// <returns>Owner's username.</returns>
        public static string GetOwner(string fullPath)
        {
            // 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);
            }

            // Owner's user name
            string username = "";

            // Depending on whether we have a file or a folder, we call different methods
            if (Directory.Exists(fullPath))
            {
                var ds = File.GetAccessControl(fullPath);
                username = ds.GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();
            }
            else if (File.Exists(fullPath))
            {
                var fs = File.GetAccessControl(fullPath);
                username = fs.GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();
            }

            //Return the username
            return(username);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Return a list of all users who have any permissions on the folder.
        /// </summary>
        /// <param name="fullPath">Full path to the folder to query form users
        ///     with permissions.</param>
        /// <returns>List of user names.</returns>
        public static List <string> GetUsersWithPermissions(string fullPath)
        {
            // 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);
            }

            // Initialize list of user names
            var userNames = new List <string>();

            // Get directory security
            DirectoryInfo     dirinfo = new DirectoryInfo(fullPath);
            DirectorySecurity dsec    = dirinfo.GetAccessControl(AccessControlSections.All);

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

            foreach (AccessRule rule in rules)
            {
                userNames.Add(rule.IdentityReference.Value);
            }

            // Return the list of user names
            return(userNames);
        }
Ejemplo n.º 3
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 + "'.");
                }
            }
        }
Ejemplo n.º 4
0
        ///<summary>
        ///Remove inherited permission from the specified folder.
        ///</summary>
        ///<param name="fullPath">Full path to the folder to which inherited
        ///    permissions should be removed.</param>
        public static void RemoveInheritedPermissionsForFolder(string fullPath)
        {
            // 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);
            }

            DirectorySecurity directorySecurity = Directory.GetAccessControl(fullPath);

            directorySecurity.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
            Directory.SetAccessControl(fullPath, directorySecurity);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Grant full access to Everyone on the specified folder.
        /// </summary>
        /// <param name="fullPath">Full path to the folder to which the permissions should be set.</param>
        public static void GrantFullAccessToEveryone(string fullPath)
        {
            // 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);
            }

            // Get a DirectoryInfo object
            DirectoryInfo dInfo = new DirectoryInfo(fullPath);

            // Make sure we are working on a directory
            if (!dInfo.Attributes.HasFlag(FileAttributes.Directory))
            {
                // Inform
                const string msg = "Directory expected!";

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

            // Set the permissions to Full Control for Everyone
            DirectorySecurity dSecurity = dInfo.GetAccessControl();

            dSecurity.AddAccessRule(new FileSystemAccessRule(
                                        new System.Security.Principal.SecurityIdentifier(
                                            System.Security.Principal.WellKnownSidType.WorldSid, null),
                                        FileSystemRights.FullControl,
                                        InheritanceFlags.ObjectInherit |
                                        InheritanceFlags.ContainerInherit,
                                        PropagationFlags.NoPropagateInherit,
                                        AccessControlType.Allow));
            dInfo.SetAccessControl(dSecurity);

            // Now recurse into subdirectories
            string[] subdirectories = Directory.GetDirectories(fullPath);
            foreach (string subdirectory in subdirectories)
            {
                GrantFullAccessToEveryone(Path.Combine(fullPath, subdirectory));
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Set the ownership on an item to the specified user.
        /// </summary>
        /// <param name="item">A FileInfo object on which to set the ownership.
        ///     </param>
        /// <param name="username">Name of the user that will take ownership. It
        ///     must exist.</param>
        private static void SetOwnershipOnDirectory(DirectoryInfo item, 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);
            }

            // Allow this process to circumvent ACL restrictions
            NativeMethods.ModifyPrivilege(PrivilegeName.SeRestorePrivilege, true);

            // Sometimes this is required and other times it works without it. Not sure when.
            NativeMethods.ModifyPrivilege(PrivilegeName.SeTakeOwnershipPrivilege, true);

            // Set owner to SYSTEM
            var fs = File.GetAccessControl(item.FullName);

            fs.SetOwner(new System.Security.Principal.NTAccount(username));
            File.SetAccessControl(item.FullName, fs);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Set the ownership on a folder to the specified user.
        /// </summary>
        /// <param name="fullPath">Full path to the folder on which to set the
        ///     ownership.</param>
        /// <param name="username">Name of the user that will take ownership. It
        ///     must exist.</param>
        public static void SetOwnership(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);
            }

            // Depending on whether we have a file or a folder, we call different methods
            if (Directory.Exists(fullPath))
            {
                DirectoryInfo dInfo = new DirectoryInfo(fullPath);
                SetOwnershipRecursively(dInfo, username);
            }
            else if (File.Exists(fullPath))
            {
                FileInfo fi = new FileInfo(fullPath);
                SetOwnershipOnFile(fi, username);
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Set the ownership on a folder to the specified user.
        /// </summary>
        /// <param name="root">Full path to the folder on which to set the
        ///     ownership.</param>
        /// <param name="username">Name of the user that will take ownership. It
        ///     must exist.</param>
        private static void SetOwnershipRecursively(DirectoryInfo root, 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);
            }

            // Set permission on the directory itself before we recurse into subfolders
            SetOwnershipOnDirectory(root, username);

            // Store files and directories to process
            FileInfo[]      children = null;
            DirectoryInfo[] subDirs  = null;

            // First, process all the files directly under this folder
            try
            {
                children = root.GetFiles("*");
            }
            // This is thrown if even one of the files requires permissions greater
            // than the application provides.
            catch (UnauthorizedAccessException e)
            {
                // Inform
                sLogger.Error("Cannot access folder '" + root + "'. The error was: " + e.Message);
            }

            catch (DirectoryNotFoundException e)
            {
                // Inform
                sLogger.Error("Folder '" + root + "' not found. The error was: " + e.Message);
            }

            if (children != null)
            {
                foreach (FileInfo fi in children)
                {
                    // In this example, we only access the existing FileInfo object. If we
                    // want to open, delete or modify the file, then
                    // a try-catch block is required here to handle the case
                    // where the file has been deleted since the call to TraverseTree().
                    SetOwnershipOnFile(fi, username);
                }

                // Now find all the subdirectories under this directory.
                subDirs = root.GetDirectories();

                foreach (DirectoryInfo dirInfo in subDirs)
                {
                    // Set ownership on the directory itself, and then recurse
                    SetOwnershipOnDirectory(dirInfo, username);

                    // Resursive call for each subdirectory.
                    SetOwnershipRecursively(dirInfo, username);
                }
            }
        }