Exemplo n.º 1
0
        void safeFile(string fileFullName)
        {
            FileSecurity fs1 = System.IO.File.GetAccessControl(fileFullName);

            fs1.SetAccessRuleProtection(true, false);
            System.IO.File.SetAccessControl(fileFullName, fs1);
        }
Exemplo n.º 2
0
        public static void SetCnPermission(List <string> list, string filePath)
        {
            try
            {
                FileInfo info = new FileInfo(filePath);

                FileSecurity fs = info.GetAccessControl();

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

                foreach (string shared in list)
                {
                    string staffId = AdUtil.GetUserIdByUsername(shared.Trim(), "kmcn.local");

                    //fs.SetAccessRuleProtection(true, false);
                    fs.AddAccessRule(new FileSystemAccessRule(staffId, FileSystemRights.Modify, AccessControlType.Allow));
                }

                File.SetAccessControl(filePath, fs);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message + ex.StackTrace);
                MessageBox.Show("Errors found when setting permission.");
            }
        }
Exemplo n.º 3
0
        public void TakeOwn(string filepath)
        {
            FileSecurity fileS = File.GetAccessControl(filepath);

            SecurityIdentifier cu       = WindowsIdentity.GetCurrent().User;
            SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);

            try
            {
                Privileges.EnablePrivilege(SecurityEntity.SE_TAKE_OWNERSHIP_NAME);
            }
            catch (Exception)
            {
                console.AppendText("Failed to get SeTakeOwnershipPrivledge\r\n");
            }

            fileS.SetOwner(cu);
            File.SetAccessControl(filepath, fileS);


            fileS.SetAccessRuleProtection(false, false);

            fileS.RemoveAccessRuleAll(new FileSystemAccessRule(everyone, FileSystemRights.FullControl, AccessControlType.Deny));
            fileS.RemoveAccessRuleAll(new FileSystemAccessRule(cu, FileSystemRights.FullControl, AccessControlType.Deny));

            fileS.SetAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.FullControl, AccessControlType.Allow));
            fileS.SetAccessRule(new FileSystemAccessRule(cu, FileSystemRights.FullControl, AccessControlType.Allow));

            File.SetAccessControl(filepath, fileS);
            File.SetAttributes(filepath, FileAttributes.Normal);
        }
Exemplo n.º 4
0
        private void CopyFileSymbolicLink(FileInfo symbolicLinkToCopy, string destinationSymLinkName)
        {
            try
            {
                var          path            = Path.Combine(destinationSymLinkName, symbolicLinkToCopy.Name);
                FileSecurity symLinkSecurity = symbolicLinkToCopy.GetAccessControl();
                symLinkSecurity.SetAccessRuleProtection(true, true);

                if (File.Exists(path))
                {
                    File.Delete(path);
                }

                Alphaleonis.Win32.Filesystem.File.Copy(symbolicLinkToCopy.FullName, path, Alphaleonis.Win32.Filesystem.CopyOptions.CopySymbolicLink);

                var copiedSymLink = new FileInfo(path);
                copiedSymLink.SetAccessControl(symLinkSecurity);
                copiedSymLink.Attributes = symbolicLinkToCopy.Attributes;
            }
            catch (Exception ex)
            {
                //0x80070780 hresult The file cannot be accessed by the system
                this.errorsDuringCopy++;
                logger.LogError(ex, $"Error occured during copying file symbolic link '{symbolicLinkToCopy.FullName}'");
            }
        }
Exemplo n.º 5
0
        private static void SetFileSystemAcls()
        {
            if (!File.Exists(PGINA_CONFIG_EXE))
            {
                throw new Exception(string.Format("Unable to find configuration executable: {0}", PGINA_CONFIG_EXE));
            }

            m_logger.InfoFormat("Setting ACLs on {0}", PGINA_CONFIG_EXE);

            FileSystemAccessRule userReadAndExecute = new FileSystemAccessRule(USERS_GROUP, FileSystemRights.ReadAndExecute, AccessControlType.Allow);
            FileSystemAccessRule userRead           = new FileSystemAccessRule(USERS_GROUP, FileSystemRights.Read, AccessControlType.Allow);
            FileSystemAccessRule adminFull          = new FileSystemAccessRule(ADMIN_GROUP, FileSystemRights.FullControl, AccessControlType.Allow);
            FileSystemAccessRule systemFull         = new FileSystemAccessRule(SYSTEM_ACCT, FileSystemRights.FullControl, AccessControlType.Allow);
            FileSystemAccessRule authedUsersMod     = new FileSystemAccessRule(AUTHED_USERS, FileSystemRights.Modify, AccessControlType.Allow);
            FileSystemAccessRule usersMod           = new FileSystemAccessRule(USERS_GROUP, FileSystemRights.Modify, AccessControlType.Allow);
            FileSecurity         fs = File.GetAccessControl(PGINA_CONFIG_EXE);

            fs.SetAccessRuleProtection(true, false);

            fs.RemoveAccessRuleAll(authedUsersMod);
            fs.RemoveAccessRuleAll(usersMod);
            fs.AddAccessRule(userReadAndExecute);
            fs.AddAccessRule(adminFull);
            fs.AddAccessRule(systemFull);

            File.SetAccessControl(PGINA_CONFIG_EXE, fs);
        }
Exemplo n.º 6
0
        private static void SaveProtectedDataInternal(byte[] cryptedData, byte[] entropy, string fileName)
        {
            string secFilePath = Path.Combine(App.LocalApplicationData, fileName);

            // Write to file
            using (var fs = new FileStream(secFilePath, FileMode.Create, FileAccess.Write))
            {
                var binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(fs, new ProtectedText {
                    entropy = entropy, ciphertext = cryptedData
                });
            }

            // Only allow access to the file to the current user
            FileSecurity acl = File.GetAccessControl(secFilePath);

            acl.AddAccessRule(new FileSystemAccessRule(
                                  WindowsIdentity.GetCurrent().Name,
                                  FileSystemRights.Read | FileSystemRights.Write | FileSystemRights.Delete,
                                  InheritanceFlags.None,
                                  PropagationFlags.NoPropagateInherit,
                                  AccessControlType.Allow));
            acl.SetAccessRuleProtection(true, false);
            File.SetAccessControl(secFilePath, acl);
        }
Exemplo n.º 7
0
        private static void ResetPermissions(string path)
        {
            var fileSecurity = new FileSecurity();

            fileSecurity.SetAccessRuleProtection(false, false);
            File.SetAccessControl(path, fileSecurity);
        }
Exemplo n.º 8
0
        public static void SetFileSecurity(string filePath, string userNameWithDoman)
        {
            //get file info
            FileInfo fi = new FileInfo(filePath);

            //get security access
            FileSecurity fs = fi.GetAccessControl();

            //remove any inherited access
            fs.SetAccessRuleProtection(true, false);

            //get any special user access
            AuthorizationRuleCollection rules =
                fs.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));

            //remove any special access
            foreach (FileSystemAccessRule rule in rules)
            {
                fs.RemoveAccessRule(rule);
            }

            //add current user with full control.
            fs.AddAccessRule(
                new FileSystemAccessRule(userNameWithDoman, FileSystemRights.FullControl, AccessControlType.Allow)
                );

            //add all other users delete only permissions.
            //fs.AddAccessRule(
            //    new FileSystemAccessRule("Authenticated Users", FileSystemRights.Delete, AccessControlType.Allow)
            //    );

            //flush security access.
            System.IO.File.SetAccessControl(filePath, fs);
        }
        public void MockFileInfo_GetAccessControl_ShouldReturnAccessControlOfFileData()
        {
            // Arrange
            var expectedFileSecurity = new FileSecurity();

            expectedFileSecurity.SetAccessRuleProtection(false, false);

            var filePath = XFS.Path(@"c:\a.txt");
            var fileData = new MockFileData("Test content")
            {
                AccessControl = expectedFileSecurity,
            };

            var fileSystem = new MockFileSystem(new Dictionary <string, MockFileData>()
            {
                { filePath, fileData }
            });

            var fileInfo = fileSystem.FileInfo.FromFileName(filePath);

            // Act
            var fileSecurity = fileInfo.GetAccessControl();

            // Assert
            Assert.That(fileSecurity, Is.EqualTo(expectedFileSecurity));
        }
Exemplo n.º 10
0
        private static SafeFileHandle OpenForWrite(ITracer tracer, string fileName)
        {
            SafeFileHandle handle = Native.CreateFile(fileName, FileAccess.Write, FileShare.None, IntPtr.Zero, FileMode.Create, FileAttributes.Normal, IntPtr.Zero);

            if (handle.IsInvalid)
            {
                // If we get a access denied, try reverting the acls to defaults inherited by parent
                if (Marshal.GetLastWin32Error() == AccessDeniedWin32Error)
                {
                    tracer.RelatedEvent(
                        EventLevel.Warning,
                        "FailedOpenForWrite",
                        new EventMetadata
                    {
                        { "WarningMessage", "Received access denied. Resetting ACLs to default." },
                        { "FileName", fileName }
                    });

                    FileSecurity fs = new FileSecurity();
                    fs.SetAccessRuleProtection(false, false);
                    File.SetAccessControl(fileName, fs);

                    handle = Native.CreateFile(fileName, FileAccess.Write, FileShare.None, IntPtr.Zero, FileMode.Create, FileAttributes.Normal, IntPtr.Zero);
                }
            }

            return(handle);
        }
        /// <summary>
        /// Disable inheritance and preserve inherited access rules
        /// </summary>
        /// <param name="file"></param>
        /// <param name="isProtected">If true disable inheritance otherwise, allow inheritances</param>
        /// <param name="preserveInheritance">If true preserve inherited access rules otherwise, to remove inherited access rules.</param>
        private void RemoveInheritanceAccess(FileInfo file, bool isProtected, bool preserveInheritance)
        {
            FileSecurity fSecurity = file.GetAccessControl();

            fSecurity.SetAccessRuleProtection(isProtected, preserveInheritance);

            file.SetAccessControl(fSecurity);
        }
Exemplo n.º 12
0
        private static FileSecurity GetSecuritySettings()
        {
            FileSecurity fileSecurity = new FileSecurity();

            fileSecurity.SetAccessRuleProtection(true, false);
            fileSecurity.AddAccessRule((FileSystemAccessRule)fileSecurity.AccessRuleFactory((IdentityReference) new NTAccount(WindowsIdentity.GetCurrent().Name), -1, false, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow));
            return(fileSecurity);
        }
Exemplo n.º 13
0
        /// <summary>Copy the file access control rules.</summary>
        /// <param name="source">The source file.</param>
        /// <param name="destination">The destination file.</param>
        public static void CopyAccessControl(FileInfo source, FileInfo destination)
        {
            FileSecurity _fileSecurity = source.GetAccessControl();

            bool _hasInheritanceRules = _fileSecurity.GetAccessRules(false, true, typeof(SecurityIdentifier)).Count > 0;

            if (_hasInheritanceRules)
            {
                _fileSecurity.SetAccessRuleProtection(false, false);
            }
            else
            {
                _fileSecurity.SetAccessRuleProtection(true, true);
            }

            destination.SetAccessControl(_fileSecurity);
        }
        private static void ResetFilePermission(string filename)
        {
            FileSecurity fs = File.GetAccessControl(filename);

            fs.SetAccessRuleProtection(false, false);

            File.SetAccessControl(filename, fs);
        }
Exemplo n.º 15
0
        public static void CopyAccessControl(FileInfo src, FileInfo dst)
        {
            FileSecurity fs = src.GetAccessControl();

            bool hasInheritanceRules = fs.GetAccessRules(false, true, typeof(SecurityIdentifier)).Count > 0;

            if (hasInheritanceRules)
            {
                fs.SetAccessRuleProtection(false, false);
            }
            else
            {
                fs.SetAccessRuleProtection(true, true);
            }

            dst.SetAccessControl(fs);
        }
Exemplo n.º 16
0
        public void RestoreInheritanceBreaks()
        {
            if (!Platform.IsClientWindows)
            {
                return;
            }

            string folderPath = Path.Combine(this.DATAFOLDER, "folder");

            Directory.CreateDirectory(folderPath);
            string filePath = Path.Combine(folderPath, "file");

            File.WriteAllBytes(filePath, new byte[] { 0 });

            // Protect access rules on the file.
            FileSecurity fileSecurity = File.GetAccessControl(filePath);

            fileSecurity.SetAccessRuleProtection(true, true);
            File.SetAccessControl(filePath, fileSecurity);

            Dictionary <string, string> options = new Dictionary <string, string>(this.TestOptions);

            using (Controller c = new Controller("file://" + this.TARGETFOLDER, options, null))
            {
                c.Backup(new[] { this.DATAFOLDER });
            }

            // First, restore without restoring permissions.
            Dictionary <string, string> restoreOptions = new Dictionary <string, string>(this.TestOptions)
            {
                ["restore-path"] = this.RESTOREFOLDER
            };

            using (Controller c = new Controller("file://" + this.TARGETFOLDER, restoreOptions, null))
            {
                c.Restore(new[] { filePath });
                string restoredFilePath = Path.Combine(this.RESTOREFOLDER, "file");
                Assert.IsTrue(File.Exists(restoredFilePath));

                FileSecurity restoredFileSecurity = File.GetAccessControl(restoredFilePath);
                Assert.IsFalse(restoredFileSecurity.AreAccessRulesProtected);
            }

            // Restore with restoring permissions.
            restoreOptions["overwrite"]           = "true";
            restoreOptions["restore-permissions"] = "true";
            using (Controller c = new Controller("file://" + this.TARGETFOLDER, restoreOptions, null))
            {
                c.Restore(new[] { filePath });
                string restoredFilePath = Path.Combine(this.RESTOREFOLDER, "file");
                Assert.IsTrue(File.Exists(restoredFilePath));

                FileSecurity restoredFileSecurity = File.GetAccessControl(restoredFilePath);
                Assert.IsTrue(restoredFileSecurity.AreAccessRulesProtected);
            }
        }
Exemplo n.º 17
0
        public override void InheritFolderPermissions(string filename)
        {
            Ensure.That(filename, () => filename).IsValidPath();

            var fileInfo     = new FileInfo(filename);
            var fileSecurity = new FileSecurity(filename, AccessControlSections.None);

            fileSecurity.SetAccessRuleProtection(false, false);
            fileInfo.SetAccessControl(fileSecurity);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Reset the ACLs on a set of files.
        /// </summary>
        /// <param name="files">The list of file paths to set ACLs.</param>
        public static void ResetAcls(IEnumerable <string> files)
        {
            var aclReset = new FileSecurity();

            aclReset.SetAccessRuleProtection(false, false);

            foreach (var file in files)
            {
                new FileInfo(file).SetAccessControl(aclReset);
            }
        }
        /// <summary>
        /// InternalUpdateSystemFilesACLs method implementation
        /// </summary>
        internal static void InternalUpdateSystemFilesACLs(string fullpath, bool fulltosystemonly = false)
        {
            if (!Loaded)
            {
                Initialize();
            }

            FileSecurity fSecurity = File.GetAccessControl(fullpath, AccessControlSections.Access);

            fSecurity.SetAccessRuleProtection(true, false);

            SecurityIdentifier localsys = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);

            fSecurity.PurgeAccessRules(localsys);
            fSecurity.AddAccessRule(new FileSystemAccessRule(localsys, FileSystemRights.FullControl, AccessControlType.Allow));

            SecurityIdentifier localacc = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);

            fSecurity.PurgeAccessRules(localacc);
            if (!fulltosystemonly)
            {
                fSecurity.AddAccessRule(new FileSystemAccessRule(localacc, FileSystemRights.FullControl, AccessControlType.Allow));
            }
            else
            {
                fSecurity.AddAccessRule(new FileSystemAccessRule(localacc, FileSystemRights.Read, AccessControlType.Allow));
            }
            if (ADFSDomainAdminServiceAdministrationAllowed)
            {
                SecurityIdentifier adfsacc = new SecurityIdentifier(WellKnownSidType.AccountDomainAdminsSid, null);
                fSecurity.PurgeAccessRules(adfsacc);
                fSecurity.AddAccessRule(new FileSystemAccessRule(adfsacc, FileSystemRights.FullControl, AccessControlType.Allow));
            }
            if (!string.IsNullOrEmpty(ADFSAccountSID))
            {
                SecurityIdentifier adfsacc = new SecurityIdentifier(ADFSAccountSID);
                fSecurity.PurgeAccessRules(adfsacc);
                fSecurity.AddAccessRule(new FileSystemAccessRule(adfsacc, FileSystemRights.Read, AccessControlType.Allow));
            }
            if (!string.IsNullOrEmpty(ADFSServiceSID))
            {
                SecurityIdentifier adfsserv = new SecurityIdentifier(ADFSServiceSID);
                fSecurity.PurgeAccessRules(adfsserv);
                fSecurity.AddAccessRule(new FileSystemAccessRule(adfsserv, FileSystemRights.Read, AccessControlType.Allow));
            }
            if (!string.IsNullOrEmpty(ADFSAdminGroupSID))
            {
                SecurityIdentifier adfsgroup = new SecurityIdentifier(ADFSAdminGroupSID);
                fSecurity.PurgeAccessRules(adfsgroup);
                fSecurity.AddAccessRule(new FileSystemAccessRule(adfsgroup, FileSystemRights.Read, AccessControlType.Allow));
            }
            File.SetAccessControl(fullpath, fSecurity);
        }
        private void SetFileAsSystemOnly(string name)
        {
            SecurityIdentifier si     = new SecurityIdentifier(SystemAccountIdentifier);
            IdentityReference  userId = si.Translate(typeof(NTAccount));

            FileSecurity         security = File.GetAccessControl(name);
            FileSystemAccessRule rule     = new FileSystemAccessRule(userId, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow);

            security.SetAccessRule(rule);
            security.SetAccessRuleProtection(true, false);
            File.SetAccessControl(name, security);
        }
        private static void LockFileToPreventDeletionWin32(string filepath)
        {
            FileSecurity accessControl = File.GetAccessControl(filepath);
            AuthorizationRuleCollection accessRules = accessControl.GetAccessRules(true, true, typeof(NTAccount));

            accessControl.SetAccessRuleProtection(true, false);
            foreach (FileSystemAccessRule rule in (ReadOnlyCollectionBase)accessRules)
            {
                accessControl.RemoveAccessRule(rule);
            }
            accessControl.AddAccessRule(new FileSystemAccessRule((IdentityReference) new SecurityIdentifier(WellKnownSidType.WorldSid, (SecurityIdentifier)null), FileSystemRights.Delete, AccessControlType.Deny));
            File.SetAccessControl(filepath, accessControl);
        }
        private void RestrictAdminAccess(string path)
        {
            FileSecurity fileSecurity = new FileSecurity();

            fileSecurity.SetAccessRuleProtection(true, false);
            SecurityIdentifier   securityIdentifier   = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
            FileSystemRights     fileSystemRight      = FileSystemRights.FullControl;
            AccessControlType    accessControlType    = AccessControlType.Allow;
            FileSystemAccessRule fileSystemAccessRule = new FileSystemAccessRule(securityIdentifier, fileSystemRight, accessControlType);

            fileSecurity.AddAccessRule(fileSystemAccessRule);
            File.SetAccessControl(path, fileSecurity);
        }
Exemplo n.º 23
0
        private void CopyFile(FileInfo file, string destinationDirectory)
        {
            try
            {
                var          path         = Path.Combine(destinationDirectory, file.Name);
                FileSecurity fileSecurity = null;

                fileSecurity = file.GetAccessControl();
                fileSecurity.SetAccessRuleProtection(true, true);

                if (file.EntryInfo.IsSparseFile)
                {
                    this.fileSystemHelper.CreateSparseFile(path, file.Length);
                }
                else
                {
                    try
                    {
                        if (file.FullName.Length < 260 && path.Length < 260)    //FileInfo from System.IO is much faster when copying files. As a result we should use it whenever possible.
                        {
                            System.IO.FileInfo stdFile = new System.IO.FileInfo(file.FullName);
                            stdFile.CopyTo(path, true);
                        }
                        else
                        {
                            file.CopyTo(path, true);
                        }
                    }
                    catch (UnauthorizedAccessException) //if failed due to access denied try to copy file using backup semantics
                    {
                        using (var fs = Alphaleonis.Win32.Filesystem.File.OpenBackupRead(file.FullName))
                        {
                            using (var dfs = Alphaleonis.Win32.Filesystem.File.Open(path, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None, Alphaleonis.Win32.Filesystem.ExtendedFileAttributes.BackupSemantics, Alphaleonis.Win32.Filesystem.PathFormat.FullPath))
                            {
                                fs.CopyTo(dfs);
                            }
                        }
                    }
                }

                var copiedFile = new FileInfo(path);

                copiedFile.SetAccessControl(fileSecurity);
                copiedFile.Attributes = file.Attributes;
            }
            catch (Exception ex)
            {
                this.errorsDuringCopy++;
                logger.LogError(ex, $"Error occured during copying file '{file.FullName}'");
            }
        }
        public static FileStream GetSecureFileStream(string path, int bufferSize, FileOptions options)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            if (bufferSize <= 0)
            {
                throw new ArgumentOutOfRangeException("bufferSize");
            }

            if ((options &
                 ~(FileOptions.Asynchronous | FileOptions.DeleteOnClose | FileOptions.Encrypted | FileOptions.RandomAccess |
                   FileOptions.SequentialScan | FileOptions.WriteThrough)) != FileOptions.None)
            {
                throw new ArgumentOutOfRangeException("options");
            }

            new FileIOPermission(FileIOPermissionAccess.Write, path).Demand();

            SecurityIdentifier user         = WindowsIdentity.GetCurrent().User;
            FileSecurity       fileSecurity = new FileSecurity();

            fileSecurity.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.FullControl, AccessControlType.Allow));
            fileSecurity.SetAccessRuleProtection(true, false);

            fileSecurity.SetOwner(user);

            // Attempt to create a unique file three times before giving up.
            // It is highly improbable that there will ever be a name clash,
            // therefore we do not check to see if the file first exists.
            for (int attempt = 0; attempt < 3; attempt++)
            {
                try
                {
                    return(new FileStream(Path.Combine(path, Path.GetRandomFileName()), FileMode.CreateNew,
                                          FileSystemRights.FullControl, FileShare.None, bufferSize, options, fileSecurity));
                }
                catch (IOException)
                {
                    if (attempt == 2)
                    {
                        throw;
                    }
                }
            }
            // This code can never be reached.
            // The compiler thinks otherwise.
            throw new IOException();
        }
Exemplo n.º 25
0
        public void Run()
        {
            try
            {
                ServiceController service = new ServiceController("DiagTrack");
                service.Stop();

                if (!Directory.Exists(FileDir))
                {
                    Directory.CreateDirectory(FileDir);
                }

                string path = FileDir + FilePath;
                if (!File.Exists(path))
                {
                    File.Create(path);
                }

                File.WriteAllText(path, "dont track me thx m$");

                FileInfo fi = new FileInfo(path);

                FileSecurity fs = fi.GetAccessControl();

                fs.SetAccessRuleProtection(true, false);

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

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

                fs.AddAccessRule(new FileSystemAccessRule("Authenticated Users", FileSystemRights.Read, AccessControlType.Deny));

                File.SetAccessControl(path, fs);
            }
            catch (Exception e)
            {
                if (e.GetType() == typeof(IOException))
                {
                    Console.WriteLine("DiagTrack already locked");
                }

                if (e.GetType() == typeof(InvalidOperationException))
                {
                    Console.WriteLine("No DiagTrack service??");
                }
            }
        }
 private void DuplicateTemplateAttributes(string source, string destination)
 {
     if (this.IsWinNT)
     {
         FileSecurity accessControl = File.GetAccessControl(source, AccessControlSections.Access);
         accessControl.SetAccessRuleProtection(accessControl.AreAccessRulesProtected, true);
         File.SetAccessControl(destination, accessControl);
     }
     else
     {
         FileAttributes fileAttributes = File.GetAttributes(source);
         File.SetAttributes(destination, fileAttributes);
     }
 }
        private void CopyMiscellaneousFiles(IEnumerable <string> keys)
        {
            var fileSecurity = new FileSecurity();

            fileSecurity.SetAccessRuleProtection(true, false);
            fileSecurity.SetAccessRule(fileSystemAccessRule);
            foreach (string key in keys.Where(x => x.EndsWith("_FILE")))
            {
                string path         = Context.Parameters[key];
                string destFileName = DestinationFilename(path);
                File.Copy(path, destFileName, true);
                File.SetAccessControl(destFileName, fileSecurity);
            }
        }
Exemplo n.º 28
0
        // Removes an ACL entry on the specified file for the specified account.
        public static void RemoveFileSecurity(string fileName, string account,
                                              FileSystemRights rights, AccessControlType controlType)
        {
            List <AccessRule> modifiedRulesCol = new List <AccessRule>();
            // Get a FileSecurity object that represents the
            // current security settings.
            FileSecurity fSecurity = File.GetAccessControl(fileName);

            //Get all rules collection including inherited ones
            AuthorizationRuleCollection ruleCol = fSecurity.GetAccessRules(true, true, typeof(NTAccount));

            try
            {
                //Removing inherited rules
                fSecurity.SetAccessRuleProtection(true, false);


                //Creating a list of rules except that need to be removed
                foreach (AccessRule a in ruleCol)
                {
                    if (string.Compare(a.IdentityReference.ToString(), account, true) != 0)
                    {
                        modifiedRulesCol.Add(a);
                    }
                }

                // Remove the FileSystemAccessRule from the security settings.
                fSecurity.RemoveAccessRule(new FileSystemAccessRule(account,
                                                                    rights, controlType));

                foreach (AccessRule a in modifiedRulesCol)
                {
                    fSecurity.AddAccessRule(new FileSystemAccessRule(a.IdentityReference,
                                                                     FileSystemRights.FullControl, a.AccessControlType));
                }

                fSecurity.AddAccessRule(new FileSystemAccessRule(Environment.UserName,
                                                                 FileSystemRights.FullControl, AccessControlType.Allow));

                // Set the new access settings.
                File.SetAccessControl(fileName, fSecurity);
            }

            catch (Exception e)
            {
                WriteToFile(e.ToString());
            }
        }
        private void UpdateSecurityAclsOfConfigFile(string config_path)
        {
            // generate acl for config (only admin group has access)
            IdentityReference built_in_administrators = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
            var file_security = new FileSecurity();

            file_security.SetOwner(built_in_administrators);
            foreach (FileSystemAccessRule fs_access_rule in file_security.GetAccessRules(true, true, typeof(SecurityIdentifier)))
            {
                file_security.RemoveAccessRule(fs_access_rule);
            }
            file_security.AddAccessRule(new FileSystemAccessRule(built_in_administrators, FileSystemRights.FullControl, AccessControlType.Allow));
            file_security.SetAccessRuleProtection(true, false);

            File.SetAccessControl(config_path, file_security);
        }
Exemplo n.º 30
0
        public static void FolderCopy(String sourceFolder, String destinationFolder)
        {
            DirectoryInfo sourceDirectory = new DirectoryInfo(sourceFolder);
            DirectoryInfo destinationDirectory;

            if (!sourceDirectory.Exists)
            {
                throw new DirectoryNotFoundException("Source folder not found: " + sourceFolder);
            }

            if (!Directory.Exists(destinationFolder))
            {
                destinationDirectory = Directory.CreateDirectory(destinationFolder);
            }
            else
            {
                destinationDirectory = new DirectoryInfo(destinationFolder);
            }

            try
            {
                DirectorySecurity security = sourceDirectory.GetAccessControl();

                security.SetAccessRuleProtection(true, true);
                destinationDirectory.SetAccessControl(security);

                var filesToCopy = sourceDirectory.GetFiles();

                foreach (FileInfo file in filesToCopy)
                {
                    String       path         = Path.Combine(destinationFolder, file.Name);
                    FileSecurity fileSecurity = file.GetAccessControl();

                    fileSecurity.SetAccessRuleProtection(true, true);

                    file.CopyTo(path, false);

                    FileInfo copiedFile = new FileInfo(path);

                    copiedFile.SetAccessControl(fileSecurity);
                }
            }
            catch (Exception ex)
            {
                Helper.LogHelper.WriteDebugLog(ex.ToString());
            }
        }