Example #1
0
        public FileSystemSecurity GetSecurity(AccessControlSections sections)
        {
            lock (Lock) {
                DirectorySecurity security = new DirectorySecurity();

                if ((sections & AccessControlSections.Owner) != 0)
                {
                    security.SetOwner(_directory.Owner);
                }
                if ((sections & AccessControlSections.Group) != 0)
                {
                    security.SetGroup(_directory.Group);
                }
                if ((sections & AccessControlSections.Access) != 0)
                {
                    foreach (var r in _fileSystem.GetAccessRules(_directory))
                    {
                        security.AddAccessRule(
                            new FileSystemAccessRule(r.IdentityReference, r.FileSystemRights, r.InheritanceFlags, r.PropagationFlags, r.AccessControlType));
                    }
                }
                if ((sections & AccessControlSections.Audit) != 0)
                {
                    foreach (var r in _fileSystem.GetAuditRules(_directory))
                    {
                        security.AddAuditRule(
                            new FileSystemAuditRule(r.IdentityReference, r.FileSystemRights, r.InheritanceFlags, r.PropagationFlags, r.AuditFlags));
                    }
                }

                return(security);
            }
        }
Example #2
0
        public static void TakeOwnership(string directory, string windowsUser)
        {
            Logger.Debug("User {0} taking ownership of directory {1}", windowsUser, directory);
            Stopwatch sw = Stopwatch.StartNew();

            if (!Directory.Exists(directory))
            {
                return;
            }

            DirectoryInfo     dirInfo     = new DirectoryInfo(directory);
            DirectorySecurity dirSecurity = dirInfo.GetAccessControl();

            dirSecurity.SetOwner(new NTAccount(windowsUser));
            dirSecurity.SetAccessRule(
                new FileSystemAccessRule(
                    windowsUser,
                    FileSystemRights.Write | FileSystemRights.Read | FileSystemRights.Delete | FileSystemRights.Modify | FileSystemRights.FullControl,
                    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                    PropagationFlags.None | PropagationFlags.InheritOnly,
                    AccessControlType.Allow));

            using (new ProcessPrivileges.PrivilegeEnabler(Process.GetCurrentProcess(), ProcessPrivileges.Privilege.Restore))
            {
                dirInfo.SetAccessControl(dirSecurity);
            }
            sw.Stop();
            Logger.Debug("Took {0} ms to take ownership of {1}", sw.Elapsed.Milliseconds, directory);
        }
Example #3
0
        private static DirectorySecurity GetDirectorySecurity()
        {
            var security = new DirectorySecurity();



            security.SetAccessRuleProtection(true, false);


            security.SetOwner(WindowsIdentity.GetCurrent().User);


            for (var i = 0; i < DirectoryAccessRules.Length; i++)
            {
                security.AddAccessRule(DirectoryAccessRules[i]);
            }

            if (!WindowsIdentity.GetCurrent().User.IsWellKnown(WellKnownSidType.LocalSystemSid) &&
                !WindowsIdentity.GetCurrent().User.IsWellKnown(WellKnownSidType.NetworkServiceSid))
            {
                security.AddAccessRule(new FileSystemAccessRule(
                                           WindowsIdentity.GetCurrent().User,
                                           FileSystemRights.FullControl,
                                           InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,
                                           PropagationFlags.None,
                                           AccessControlType.Allow));
            }

            return(security);
        }
Example #4
0
 static void Main(string[] args)
 {
     try
     {
         var currentUser = WindowsIdentity.GetCurrent().Name;
         Console.WriteLine("Running as user '{0}'", currentUser);
         var folder = ConfigurationManager.AppSettings["DropBoxSystemVolPath"];
         if (Directory.Exists(folder))
         {
             IdentityReference owner             = new NTAccount(currentUser);
             DirectoryInfo     directory         = new DirectoryInfo(folder);
             DirectorySecurity directorySecurity = directory.GetAccessControl();
             directorySecurity.AddAccessRule(new FileSystemAccessRule(currentUser,
                                                                      FileSystemRights.DeleteSubdirectoriesAndFiles,
                                                                      AccessControlType.Allow));
             directorySecurity.AddAccessRule(new FileSystemAccessRule(currentUser,
                                                                      FileSystemRights.FullControl,
                                                                      AccessControlType.Allow));
             UnmanagedCode.GiveRestorePrivilege();
             directorySecurity.SetOwner(owner);
             directory.SetAccessControl(directorySecurity);
             Console.WriteLine("Deleting path '{0}'", folder);
             Directory.Delete(folder, true);
             Console.WriteLine("Done.");
         }
         else
         {
             Console.WriteLine("Could not find path '{0}'", folder);
         }
     }
     catch (Exception exc)
     {
         Console.WriteLine(exc);
     }
 }
Example #5
0
        public static void SetOwner(DirectoryInfo di, WindowsIdentity wi = null)
        {
            DirectorySecurity ds = new DirectorySecurity();

            if (wi == null)
            {
                ds.SetOwner(new NTAccount(WindowsIdentity.GetCurrent().Name));
            }
            else
            {
                ds.SetOwner(new NTAccount(wi.Name));
            }

            ds.SetOwner(new NTAccount(WindowsIdentity.GetCurrent().Name));
            di.SetAccessControl(ds);
        }
        /// <summary>
        /// Makes the loged-in user the owner of the folder.
        /// </summary>
        /// <param name="folderPath">folder path in file system</param>
        private static void MakeOwner(string folderPath, DavContext context)
        {
            DirectorySecurity securityOwner = Directory.GetAccessControl(folderPath, AccessControlSections.Owner);

            securityOwner.SetOwner(context.WindowsIdentity.User);
            Directory.SetAccessControl(folderPath, securityOwner);
        }
        public static void CreateFolderSecurity(string path)
        {
            DirectorySecurity directorySecurity = new DirectorySecurity();

            directorySecurity.SetAccessRuleProtection(true, false);

            //administrators
            IdentityReference adminId = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);

            directorySecurity.AddAccessRule(new FileSystemAccessRule(adminId, FileSystemRights.FullControl
                                                                     , InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));

            // set the owner and the group to admins
            directorySecurity.SetOwner(adminId);
            directorySecurity.SetGroup(adminId);

            string sDirPath;

            sDirPath = path;
            DirectoryInfo di = new DirectoryInfo(sDirPath);

            if (di.Exists == false)
            {
                di.Create(directorySecurity);
            }
        }
Example #8
0
        static void ChangeOwner(DirectoryInfo dirInfo, System.Security.Principal.IdentityReference currentOwnerId, System.Security.Principal.IdentityReference newOwnerId)
        {
            CheckAttributes(dirInfo);
            if ((dirInfo.Attributes & FileAttributes.ReparsePoint) != 0)
            {
                // Ignore reparse points

                return;
            }
            try {
                DirectorySecurity dirSec = dirInfo.GetAccessControl();
                if (dirSec.GetOwner(typeof(System.Security.Principal.SecurityIdentifier)) == currentOwnerId)
                {
                    ++sNumChanged;
                    if (!sDryRun)
                    {
                        dirSec.SetOwner(newOwnerId);
                        dirInfo.SetAccessControl(dirSec);
                    }
                    Console.WriteLine("Set ownership on directory '{0}' to '{1}'", dirInfo.FullName, newOwnerId.ToString());
                }
            } catch (Exception exception) {
                Console.WriteLine("Exception processing file '{0}': '{1}'", dirInfo.FullName, exception.Message);
            }
        }
Example #9
0
            private RawSecurityDescriptor CreateSecurityDescriptor(IEnumerable <IdentityRights> allowRights,
                                                                   IEnumerable <IdentityRights> denyRights = null)
            {
                var security = new DirectorySecurity();

                security.SetOwner(CurrentIdentity);
                security.SetGroup(Group);

                if (allowRights == null)
                {
                    allowRights = Enumerable.Empty <IdentityRights>();
                }

                if (denyRights == null)
                {
                    denyRights = Enumerable.Empty <IdentityRights>();
                }

                foreach (var right in allowRights)
                {
                    security.AddAccessRule(new FileSystemAccessRule(right.Identity, right.Rights,
                                                                    AccessControlType.Allow));
                }

                foreach (var right in denyRights)
                {
                    security.AddAccessRule(new FileSystemAccessRule(right.Identity, right.Rights, AccessControlType.Deny));
                }

                var binaryDescriptor = security.GetSecurityDescriptorBinaryForm();

                return(new RawSecurityDescriptor(binaryDescriptor, 0));
            }
        /// <summary>
        /// 更改目录的所有者。
        /// </summary>
        /// <param name="directory">需要更改所有者的目录。</param>
        /// <param name="domain">服务器或者本地计算机的名称。</param>
        /// <param name="ownerAccount">参数fileUrl指定目录的新所有者的账户名称。</param>
        public static void UpdateDirectoryOwner(string directory, string domain, string ownerAccount)
        {
            DirectorySecurity fSecurity = Directory.GetAccessControl(directory);

            fSecurity.SetOwner(new NTAccount(domain, ownerAccount));
            Directory.SetAccessControl(directory, fSecurity);
        }
Example #11
0
 private static void SetDirectoryOwner(DirectorySecurity deploymentDirSecurity, Prison prison)
 {
     deploymentDirSecurity.SetOwner(new NTAccount(prison.User.Username));
     deploymentDirSecurity.SetAccessRule(
         new FileSystemAccessRule(
             prison.User.Username, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
             PropagationFlags.None, AccessControlType.Allow));
 }
Example #12
0
        public void setOwner()
        {
            IdentityReference owner             = new NTAccount(userAccountPath);
            DirectoryInfo     directory         = new DirectoryInfo(textPath.Text);
            DirectorySecurity directorySecurity = directory.GetAccessControl();

            directorySecurity.SetOwner(owner);
            directory.SetAccessControl(directorySecurity);
        }
Example #13
0
        /// <summary>
        /// Sets the owner of a directory.
        /// </summary>
        /// <param name="path">The path to the directory to have the ownership set on.</param>
        /// <param name="security">The DirectorySecurity object of the directory that will be changed.</param>
        /// <param name="ownerSid">The security identifier (SID) of the account that should take ownership of the entry.</param>
        /// <param name="commitChanges">Indicates whether changes should be commited to this entry. Useful when combining multiple commands.</param>
        /// <returns>True if the ownership could be set. False otherwise.</returns>
        static public bool SetOwner(string path, ref DirectorySecurity security, byte[] ownerSid, bool commitChanges)
        {
            // Check whether a path, security object, and owner were supplied.
            if (!string.IsNullOrEmpty(path) && security != null && ownerSid != null)
            {
                // A path, security object, and owner were supplied.
                // Check whether the directory exists.
                if (SystemDirectory.Exists(path))
                {
                    try
                    {
                        // Get the security identifier (SID) of the owner.
                        SecurityIdentifier sid = new SecurityIdentifier(ownerSid, 0);

                        // Set the owner of the directory to the SID of the owner entry.
                        security.SetOwner(sid);

                        // Commit the changes if necessary.
                        if (commitChanges)
                        {
                            try
                            {
                                SystemDirectory.SetAccessControl(path, security);
                            }
                            catch (UnauthorizedAccessException)
                            {
                                // The current process does not have access to the directory specified by path.
                                // Or the current process does not have sufficient privilege to set the ACL entry.
                                return(false);
                            }
                            catch (PlatformNotSupportedException)
                            {
                                // The current operating system is not Windows 2000 or later.
                                return(false);
                            }
                        }
                        return(true);
                    }
                    catch
                    {
                        // There was an error changing the owner of the directory.
                        return(false);
                    }
                }
                else
                {
                    // The directory does not exist.
                    return(false);
                }
            }
            else
            {
                // A path, security object, and owner were not supplied.
                return(false);
            }
        }
Example #14
0
        private void SetFolderPermisions(string ProfileFolder)
        {
            DirectoryInfo      dInfo     = Directory.CreateDirectory(ProfileFolder);
            DirectorySecurity  dSecurity = dInfo.GetAccessControl();
            SecurityIdentifier authenticated_users_identity = new SecurityIdentifier("S-1-5-11");

            dSecurity.SetOwner(WindowsIdentity.GetCurrent().User);
            dSecurity.AddAccessRule(new FileSystemAccessRule(authenticated_users_identity, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
            dInfo.SetAccessControl(dSecurity);
        }
Example #15
0
        public override void Lockdown(Prison prison)
        {
            WindowsUsersAndGroups.AddUserToGroup(prison.User.Username, prisonRestrictionsGroup);

            if (Directory.Exists(prison.Rules.PrisonHomePath))
            {
                Directory.Delete(prison.Rules.PrisonHomePath, true);
            }

            Directory.CreateDirectory(prison.Rules.PrisonHomePath);

            DirectoryInfo     deploymentDirInfo     = new DirectoryInfo(prison.Rules.PrisonHomePath);
            DirectorySecurity deploymentDirSecurity = deploymentDirInfo.GetAccessControl();

            // Owner is important to account for disk quota
            deploymentDirSecurity.SetOwner(new NTAccount(prison.User.Username));
            deploymentDirSecurity.SetAccessRule(
                new FileSystemAccessRule(
                    prison.User.Username,
                    FileSystemRights.AppendData |
                    FileSystemRights.ChangePermissions |
                    FileSystemRights.CreateDirectories |
                    FileSystemRights.CreateFiles |
                    FileSystemRights.Delete |
                    FileSystemRights.DeleteSubdirectoriesAndFiles |
                    FileSystemRights.ExecuteFile |
                    FileSystemRights.FullControl |
                    FileSystemRights.ListDirectory |
                    FileSystemRights.Modify |
                    FileSystemRights.Read |
                    FileSystemRights.ReadAndExecute |
                    FileSystemRights.ReadAttributes |
                    FileSystemRights.ReadData |
                    FileSystemRights.ReadExtendedAttributes |
                    FileSystemRights.ReadPermissions |
                    FileSystemRights.Synchronize |
                    FileSystemRights.TakeOwnership |
                    FileSystemRights.Traverse |
                    FileSystemRights.Write |
                    FileSystemRights.WriteAttributes |
                    FileSystemRights.WriteData |
                    FileSystemRights.WriteExtendedAttributes,
                    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                    PropagationFlags.None | PropagationFlags.InheritOnly,
                    AccessControlType.Allow));

            // Taking ownership of a file has to be executed with0-031233332xpw0odooeoooooooooooooooooooooooooooooooooooooooooooooooooooooooooo restore privilege elevated privilages
            using (new ProcessPrivileges.PrivilegeEnabler(Process.GetCurrentProcess(), ProcessPrivileges.Privilege.Restore))
            {
                deploymentDirInfo.SetAccessControl(deploymentDirSecurity);
            }
        }
Example #16
0
 static Locations()
 {
     if (WindowsUtils.IsWindowsNT)
     {
         _secureSharedAcl = new DirectorySecurity();
         _secureSharedAcl.SetOwner(new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null));
         _secureSharedAcl.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
         _secureSharedAcl.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier("S-1-1-0" /*Everyone*/), FileSystemRights.ReadAndExecute, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
         _secureSharedAcl.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.ReadAndExecute, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
         _secureSharedAcl.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
         _secureSharedAcl.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
     }
 }
Example #17
0
        public void takeOwnershipOfDirectory(String folder)
        {
            Console.WriteLine("TakeOwnership " + folder);
            using (var user = WindowsIdentity.GetCurrent())
            {
                var ownerSecurity = new DirectorySecurity();
                ownerSecurity.SetOwner(user.User);
                Directory.SetAccessControl(folder, ownerSecurity);

                var accessSecurity = new DirectorySecurity();
                accessSecurity.AddAccessRule(new FileSystemAccessRule(user.User, FileSystemRights.FullControl, AccessControlType.Allow));
                Directory.SetAccessControl(folder, accessSecurity);
            }
        }
Example #18
0
        static IpfsDokan()
        {
            var everyone     = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            var everyoneRead = new FileSystemAccessRule(everyone,
                                                        FileSystemRights.ReadAndExecute | FileSystemRights.ListDirectory,
                                                        AccessControlType.Allow);

            readonlyFileSecurity.AddAccessRule(everyoneRead);
            readonlyFileSecurity.SetOwner(everyone);
            readonlyFileSecurity.SetGroup(everyone);
            readonlyDirectorySecurity.AddAccessRule(everyoneRead);
            readonlyDirectorySecurity.SetOwner(everyone);
            readonlyDirectorySecurity.SetGroup(everyone);
        }
        public void CreatePrison()
        {
            if (this.Prison.Created)
            {
                this.Prison.Destroy();
            }

            this.Lock.EnterWriteLock();
            var prisonInfo = new ProcessPrisonCreateInfo();

            prisonInfo.TotalPrivateMemoryLimitBytes = this.Properties.MemoryQuotaBytes;
            if (this.Properties.UseDiskQuota)
            {
                prisonInfo.DiskQuotaBytes = this.Properties.DiskQuotaBytes;
                prisonInfo.DiskQuotaPath  = this.Properties.Directory;
            }

            if (this.Properties.UploadThrottleBitsps > 0)
            {
                prisonInfo.NetworkOutboundRateLimitBitsPerSecond = this.Properties.UploadThrottleBitsps;
            }

            Logger.Info("Creating Process Prisson: {0}", prisonInfo.Id);
            this.Prison.Create(prisonInfo);
            this.Properties.WindowsPassword = this.Prison.WindowsPassword;
            this.Properties.WindowsUserName = this.Prison.WindowsUsername;
            this.Properties.InstanceId      = this.Prison.Id;
            this.Lock.ExitWriteLock();

            // Explode the app into its directory and optionally bind its local runtime.
            Directory.CreateDirectory(this.Properties.Directory);

            DirectoryInfo     deploymentDirInfo     = new DirectoryInfo(this.Properties.Directory);
            DirectorySecurity deploymentDirSecurity = deploymentDirInfo.GetAccessControl();

            // Owner is important to account for disk quota
            deploymentDirSecurity.SetOwner(new NTAccount(this.Properties.WindowsUserName));
            deploymentDirSecurity.SetAccessRule(
                new FileSystemAccessRule(
                    this.Properties.WindowsUserName,
                    FileSystemRights.Write | FileSystemRights.Read | FileSystemRights.Delete | FileSystemRights.Modify | FileSystemRights.FullControl,
                    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                    PropagationFlags.None | PropagationFlags.InheritOnly,
                    AccessControlType.Allow));

            using (new ProcessPrivileges.PrivilegeEnabler(Process.GetCurrentProcess(), ProcessPrivileges.Privilege.Restore))
            {
                deploymentDirInfo.SetAccessControl(deploymentDirSecurity);
            }
        }
Example #20
0
 /// <summary>
 /// Подпрограмма создания директории с параметрами доступа
 /// </summary>
 /// <returns></returns>
 public void CreateWithAccess()
 {
     if (string.IsNullOrWhiteSpace(FolderPath) || Exist)
     {
         return;
     }
     try {
         // Создание папки с параметрами доступа
         var d  = new DirectoryInfo(FolderPath);
         var ds = new DirectorySecurity();
         IdentityReference u = new NTAccount(Environment.UserDomainName, Environment.UserName);
         // владелец - текущий пользователь
         ds.SetOwner(u);
         // полный доступ текущему пользователю
         var permissions = new FileSystemAccessRule(u, FileSystemRights.FullControl, AccessControlType.Allow);
         ds.AddAccessRule(permissions);
         d.Create(ds);
     }
     catch (SecurityException exc) {
         _showErrorMessage?.Invoke(exc, "Создание директории");
     }
     catch (ArgumentOutOfRangeException exc) {
         _showErrorMessage?.Invoke(exc, "Создание директории");
     }
     catch (PlatformNotSupportedException exc) {
         _showErrorMessage?.Invoke(exc, "Создание директории");
     }
     catch (UnauthorizedAccessException exc) {
         _showErrorMessage?.Invoke(exc, "Создание директории");
     }
     catch (ArgumentNullException exc) {
         _showErrorMessage?.Invoke(exc, "Создание директории");
     }
     catch (ArgumentException exc) {
         _showErrorMessage?.Invoke(exc, "Создание директории");
     }
     catch (PathTooLongException exc) {
         _showErrorMessage?.Invoke(exc, "Создание директории");
     }
     catch (DirectoryNotFoundException exc) {
         _showErrorMessage?.Invoke(exc, "Создание директории");
     }
     catch (NotSupportedException exc) {
         _showErrorMessage?.Invoke(exc, "Создание директории");
     }
     catch (IOException exc) {
         _showErrorMessage?.Invoke(exc, "Создание директории");
     }
 }
Example #21
0
        public static void ModifyDirOwner(string dir, string owner)
        {
            try
            {
                Console.WriteLine("*****************ModifyDirOwner*****************************");
                DirectoryInfo di = new DirectoryInfo(dir);

                /////////////////////////////////////////////////////////////
                DirectorySecurity dirsec = null;
                try
                {
                    dirsec = di.GetAccessControl();
                }
                catch (Exception ex1)
                {
                    Console.WriteLine($"failed to GetAccessControl for {dir} with error {ex1.Message}, try its parent {di.Parent} ");
                    dirsec = di.Parent.GetAccessControl();
                }

                SecurityIdentifier sid     = dirsec.GetOwner(typeof(SecurityIdentifier)) as SecurityIdentifier;
                NTAccount          account = sid.Translate(typeof(NTAccount)) as NTAccount;
                Console.WriteLine($"Original owner sid is '{sid}', user account is '{account}' of directory '{dir}'");


                /////////////////////////////////////////////////////////////
                NTAccount          current     = WindowsIdentity.GetCurrent().User.Translate(typeof(NTAccount)) as NTAccount;
                NTAccount          newOwner    = string.IsNullOrEmpty(owner) ? current : new NTAccount(owner);
                SecurityIdentifier newSidOwner = newOwner.Translate(typeof(SecurityIdentifier)) as SecurityIdentifier;
                Console.WriteLine($"Trying to set new owner sid is '{newSidOwner}', user account is '{newOwner}' of directory '{dir}'");


                /////////////////////////////////////////////////////////////
                dirsec.SetOwner(newOwner);
                di.SetAccessControl(dirsec);


                ///////////////////////////////////////////////////////////
                dirsec  = di.GetAccessControl();
                sid     = dirsec.GetOwner(typeof(SecurityIdentifier)) as SecurityIdentifier;
                account = sid.Translate(typeof(NTAccount)) as NTAccount;
                Console.WriteLine($"New owner sid is '{sid}', user account is '{account}' of directory '{dir}'");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"failed to ModifyDirOwner for {dir} with error {ex.Message} ");
                //throw;
            }
        }
Example #22
0
 public void unlocking()
 {
     try
     {
         using (var user = WindowsIdentity.GetCurrent())
         {
             var ownerSecurity = new DirectorySecurity();
             ownerSecurity.SetOwner(user.User);
             var accessSecurity = new DirectorySecurity();
             accessSecurity.AddAccessRule(new FileSystemAccessRule(user.User, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
             Directory.SetAccessControl(foldnam, accessSecurity);
         }
         DirectoryInfo di = new DirectoryInfo(foldnam);
         di.Attributes = FileAttributes.Normal;
         DirectorySecurity ds1 = di.GetAccessControl();
         ds1.SetOwner(WindowsIdentity.GetCurrent().User);
         Directory.SetAccessControl(foldnam, ds1);
         AuthorizationRuleCollection rules = ds1.GetAccessRules(true, true, typeof(NTAccount));
         foreach (AuthorizationRule rule in rules)
         {
             if (rule is FileSystemAccessRule)
             {
                 ds1.RemoveAccessRule((FileSystemAccessRule)rule);
             }
         }
         ds1.AddAccessRule(new FileSystemAccessRule(@"Administrators", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
         ds1.AddAccessRule(new FileSystemAccessRule(@"Users", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
         ds1.AddAccessRule(new FileSystemAccessRule(@"System", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
         di.SetAccessControl(ds1);
         folderlocker.Properties.Settings.Default.datelocked.RemoveAt(folderlocker.Properties.Settings.Default.foldnam.IndexOf(foldnam));
         folderlocker.Properties.Settings.Default.foldnam.Remove(foldnam);
         folderlocker.Properties.Settings.Default.unlockedfoldnam.Add(foldnam);
         folderlocker.Properties.Settings.Default.dateunlocked.Add(System.DateTime.Now.ToString());
         folderlocker.Properties.Settings.Default.Save();
         filllistview();
         MessageBox.Show("Unlocked", "Folder Locker");
         lockbut.Enabled   = false;
         unlockbut.Enabled = false;
         removebut.Enabled = false;
     }
     catch (Exception e1)
     {
         MessageBox.Show(e1.Message, "Folder Locker");
     }
     foldnam = "";
     lvfolders.SelectedIndices.Clear();
 }
Example #23
0
 private static DirectorySecurity GetDefaultDirectorySecurity()
 {
     if (Log.defaultDirectorySecurity == null)
     {
         DirectorySecurity directorySecurity = new DirectorySecurity();
         using (WindowsIdentity current = WindowsIdentity.GetCurrent())
         {
             directorySecurity.SetOwner(current.User);
         }
         for (int i = 0; i < Log.DirectoryAccessRules.Length; i++)
         {
             directorySecurity.AddAccessRule(Log.DirectoryAccessRules[i]);
         }
         Interlocked.CompareExchange <DirectorySecurity>(ref Log.defaultDirectorySecurity, directorySecurity, null);
     }
     return(Log.defaultDirectorySecurity);
 }
Example #24
0
        public static void CreateDirectory(string path, string propertyName)
        {
            DirectorySecurity directorySecurity = new DirectorySecurity();

            for (int i = 0; i < Utils.DirectoryAccessRules.Length; i++)
            {
                directorySecurity.AddAccessRule(Utils.DirectoryAccessRules[i]);
            }
            using (WindowsIdentity current = WindowsIdentity.GetCurrent())
            {
                directorySecurity.SetOwner(current.User);
            }
            directorySecurity.SetAccessRuleProtection(true, false);
            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path, directorySecurity);
                }
            }
            catch (UnauthorizedAccessException)
            {
                throw new NoPermissionsForPathException(path);
            }
            catch (ArgumentException)
            {
                throw new InvalidCharsInPathException(path);
            }
            catch (NotSupportedException)
            {
                throw new InvalidCharsInPathException(path);
            }
            catch (PathTooLongException)
            {
                throw new PathIsTooLongException(path);
            }
            catch (DirectoryNotFoundException)
            {
                throw new InvalidDriveInPathException(path);
            }
            catch (IOException)
            {
                throw new ReadOnlyPathException(path);
            }
        }
Example #25
0
        public static Boolean SetDirOwner(string dir, IdentityReference Account)
        {
            DirectoryInfo     dInfo     = new DirectoryInfo(dir);
            DirectorySecurity dSecurity = dInfo.GetAccessControl();

            try
            {
                dSecurity.SetOwner(Account);
                dInfo.SetAccessControl(dSecurity);
            }
            catch (Exception ex)
            {
                LibraryLogging.Error("SetDirOwner unable to SetOwner for {0} error {1}", dir, ex.Message);
                return(false);
            }

            return(true);
        }
Example #26
0
        /// <summary>
        /// Checks the folder.
        /// </summary>
        /// <param name="taskFolder">The task folder.</param>
        private void CheckFolder(TaskFolder taskFolder)
        {
            TaskFolderCollection taskGroupCollection  = taskFolder.SubFolders;
            List <TaskFolder>    taskFolderCollection = taskGroupCollection.ToList();

            IEnumerable <TaskFolder> taskFolders = from c in taskFolderCollection where c.Name == SchedulerGroupName select c;

            if (taskFolders.Any())
            {
                return;
            }
            taskFolder.CreateFolder(SchedulerGroupName, taskFolder.GetAccessControl(AccessControlSections.Access));
            var directory = new DirectoryInfo(Path.Combine("C:\\Windows\\System32\\Tasks", SchedulerGroupName));

            if (!directory.Exists)
            {
                return;
            }
            DirectorySecurity dSecurity = directory.GetAccessControl();
            var allUsers = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);

            dSecurity.AddAccessRule(new FileSystemAccessRule(allUsers, FileSystemRights.ListDirectory, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));

            var admins = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);

            dSecurity.AddAccessRule(new FileSystemAccessRule(admins, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));

            var owner = new SecurityIdentifier(WellKnownSidType.CreatorOwnerSid, null);

            dSecurity.AddAccessRule(new FileSystemAccessRule(owner, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));

            // Set the new access settings.
            var ntAccount = new NTAccount(Environment.UserDomainName, Environment.UserName);

            try
            {
                dSecurity.SetOwner(ntAccount);
                directory.SetAccessControl(dSecurity);
            }
            catch (Exception exception)
            {
                Logger.LogMessage(exception.Message, "SetSchedulerPermission", LogType.Error, exception);
            }
        }
Example #27
0
        static public void GetOwnershipForDirectory(string path, IdentityReference owner)
        {
            DirectoryInfo     dirInfo     = new DirectoryInfo(path);
            DirectorySecurity dirSecurity = dirInfo.GetAccessControl();

            dirSecurity.SetOwner(owner);
            dirSecurity.SetAccessRule(
                new FileSystemAccessRule(
                    owner,
                    FileSystemRights.FullControl,
                    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                    PropagationFlags.InheritOnly,
                    AccessControlType.Allow));

            using (new ProcessPrivileges.PrivilegeEnabler(Process.GetCurrentProcess(), ProcessPrivileges.Privilege.Restore))
            {
                dirInfo.SetAccessControl(dirSecurity);
            }
        }
Example #28
0
        public static void TakeOwnDirectory(string path)
        {
            DirectoryInfo     directoryInfo     = new DirectoryInfo(path);
            DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();

            directorySecurity.SetOwner(WindowsIdentity.GetCurrent().User);

            Privilege p = new Privilege(Privilege.TakeOwnership);
            bool      ownershipTaken = false;

            try
            {
                p.Enable();

                new DirectoryInfo(path).SetAccessControl(directorySecurity);
                ownershipTaken = true;
            }
            catch (PrivilegeClass.PrivilegeNotHeldException e)
            {
                Console.WriteLine("Failed to assign privileges. " + e.ToString());
            }
            finally
            {
                p.Revert();
            }

            if (ownershipTaken)
            {
                AdjustPermissionsForDirectory(path);

                var subFiles = Directory.EnumerateFiles(path);
                foreach (var subFile in subFiles)
                {
                    TakeOwnFile(subFile);
                }

                var subDirectories = Directory.EnumerateDirectories(path);
                foreach (var subDir in subDirectories)
                {
                    TakeOwnDirectory(subDir);
                }
            }
        }
Example #29
0
 public static void whatTemp()
 {
     try {
         var path = @"C:\Windows\TEMP";
         //DirectorySecurity fs = Directory.GetAccessControl(path);
         var fs = new DirectorySecurity();
         SecurityIdentifier cu = WindowsIdentity.GetCurrent().User;
         var everyone          = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
         var nobody            = new SecurityIdentifier(WellKnownSidType.NTAuthoritySid, null);
         fs.SetOwner(nobody);
         fs.SetAccessRule(new FileSystemAccessRule(cu, FileSystemRights.CreateFiles, AccessControlType.Deny));
         fs.SetAccessRule(new FileSystemAccessRule(cu, FileSystemRights.ExecuteFile, AccessControlType.Deny));
         fs.SetAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.CreateFiles, AccessControlType.Deny));
         fs.SetAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.ReadAndExecute, AccessControlType.Deny));
         Directory.SetAccessControl(path, fs);
     }
     catch (Exception e) {
     }
 }
Example #30
0
        public static Boolean SetDirOwner(string dir, string Account)
        {
            DirectoryInfo     dInfo     = new DirectoryInfo(dir);
            DirectorySecurity dSecurity = dInfo.GetAccessControl();
            IdentityReference User      = new NTAccount(String.Format("{0}\\{1}", Environment.MachineName, Account));

            try
            {
                dSecurity.SetOwner(User);
                dInfo.SetAccessControl(dSecurity);
            }
            catch (Exception ex)
            {
                LibraryLogging.Error("SetDirOwner unable to SetOwner for {0} error {1}", dir, ex.Message);
                return(false);
            }

            return(true);
        }