// http://stackoverflow.com/questions/12811850/setting-a-files-acl-to-be-inherited private static void RemoveCustomACLs(string destination) { FileInfo fileInfo; FileSecurity fileSecurity; AuthorizationRuleCollection fileRules; fileInfo = new FileInfo(destination); fileSecurity = fileInfo.GetAccessControl(); fileSecurity.SetAccessRuleProtection(false, false); fileSecurity.SetOwner(WindowsIdentity.GetCurrent().User); /* * Only fetch the explicit rules since I want to keep the inherited ones. Not * sure if the target type matters in this case since I am not examining the * IdentityReference. */ fileRules = fileSecurity.GetAccessRules(includeExplicit: true, includeInherited: false, targetType: typeof(NTAccount)); /* * fileRules is a AuthorizationRuleCollection object, which can contain objects * other than FileSystemAccessRule (in theory), but GetAccessRules should only * ever return a collection of FileSystemAccessRules, so we will just declare * rule explicitly as a FileSystemAccessRule. */ foreach (FileSystemAccessRule rule in fileRules) { /* * Remove any explicit permissions so we are just left with inherited ones. */ fileSecurity.RemoveAccessRule(rule); } fileInfo.SetAccessControl(fileSecurity); }
public static void AddFileSecurity(string path, string Account, System.Security.AccessControl.FileSystemRights Rights, System.Security.AccessControl.AccessControlType ControlType) { System.IO.FileInfo FINFO = new System.IO.FileInfo(path); System.Security.AccessControl.FileSecurity FSECURITY = FINFO.GetAccessControl(); FSECURITY.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(Account, Rights, ControlType)); FINFO.SetAccessControl(FSECURITY); }
public static void TakeOwnership(string FD) { try { var myProcToken = new AccessTokenProcess(Process.GetCurrentProcess().Id, TokenAccessType.TOKEN_ALL_ACCESS | TokenAccessType.TOKEN_ADJUST_PRIVILEGES); myProcToken.EnablePrivilege(new Microsoft.Win32.Security.TokenPrivilege(Microsoft.Win32.Security.TokenPrivilege.SE_TAKE_OWNERSHIP_NAME, true)); SecurityIdentifier identifier = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); NTAccount identity = (NTAccount)identifier.Translate(typeof(NTAccount)); if (File.Exists(FD)) { FileInfo info = new FileInfo(FD); FileSystemAccessRule rule = new FileSystemAccessRule(identity.Value, FileSystemRights.FullControl, AccessControlType.Allow); FileSecurity accessControl = info.GetAccessControl(AccessControlSections.Owner); accessControl.SetOwner(new NTAccount(identity.Value)); info.SetAccessControl(accessControl); accessControl.AddAccessRule(rule); info.SetAccessControl(accessControl); } if (Directory.Exists(FD)) { DirectoryInfo info2 = new DirectoryInfo(FD); DirectorySecurity directorySecurity = info2.GetAccessControl(AccessControlSections.All); directorySecurity.SetOwner(identity); info2.SetAccessControl(directorySecurity); directorySecurity.AddAccessRule(new FileSystemAccessRule(identity, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow)); info2.SetAccessControl(directorySecurity); } Clear(FD); } catch (Exception) { } }
public static bool CurentUserHasWritePertmission(FileInfo fileInfo) { try { var acl = fileInfo.GetAccessControl(); var accessRules = acl.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); if (accessRules == null) return false; var writeAllow = false; var writeDeny = false; foreach (FileSystemAccessRule rule in accessRules) { if ((FileSystemRights.Write & rule.FileSystemRights) != FileSystemRights.Write) continue; if (rule.AccessControlType == AccessControlType.Allow) writeAllow = true; else if (rule.AccessControlType == AccessControlType.Deny) writeDeny = true; } return writeAllow && !writeDeny; } catch(Exception ex) { Logger.LogError(ex.ToString()); return false; } }
public static bool CheckAccessRight(FileInfo file, FileSystemRights right) { var user = WindowsIdentity.GetCurrent(); var p = new WindowsPrincipal(user); AuthorizationRuleCollection acl = file.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); return CheckAccessRight(user, p, acl, right); }
private static bool HasFilePermissions(string path, IdentityReference identity, FileSystemRights permissions) { var dirInfo = new FileInfo(path); var dirSecurity = dirInfo.GetAccessControl(AccessControlSections.All); AuthorizationRuleCollection rules = dirSecurity.GetAccessRules(true, true, typeof(NTAccount)); return HasPermissions(rules, identity, permissions); }
public bool GrantAccess(string fullPath) { var fInfo = new FileInfo(fullPath); var fSecurity = fInfo.GetAccessControl(); var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null); fSecurity.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.FullControl, AccessControlType.Allow)); fInfo.SetAccessControl(fSecurity); return true; }
//Add the ACL for the file so it can be filered on later when searching. private void SetACLForFile(FileInfo fileInfo) { ACL = new List<string>(); var accessRules = fileInfo.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); foreach (FileSystemAccessRule fileRule in accessRules) { ACL.Add(fileRule.IdentityReference.Value); } }
/// <summary> /// Creates a text file named "Error Log.txt" in the root of the installation folder and gives NETWORK SERVICE full control over it. /// </summary> public void CreateFreshLogFile() { File.WriteAllText( runtimeConfiguration.ErrorLogFilePath, "" ); // We need to modify permissions after creating the file so we can inherit instead of wiping out parent settings. var info = new FileInfo( runtimeConfiguration.ErrorLogFilePath ); var security = info.GetAccessControl(); security.AddAccessRule( new FileSystemAccessRule( "NETWORK SERVICE", FileSystemRights.FullControl, AccessControlType.Allow ) ); info.SetAccessControl( security ); }
/// <summary> /// Remove explicit file rules and leave inherited rules only. /// Allow built-in users to write and modify file. /// </summary> public static bool CheckExplicitAccessRulesAndAllowToModify(string fileName, bool applyFix) { var fileInfo = new FileInfo(fileName); var fileSecurity = fileInfo.GetAccessControl(); fileSecurity.SetAccessRuleProtection(false, false); var identity = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); // Get explicit file rules of FileSystemAccessRule type. var rules = fileSecurity.GetAccessRules(true, true, typeof(NTAccount)).OfType<FileSystemAccessRule>(); var referenceValue = ((NTAccount)identity.Translate(typeof(NTAccount))).Value; // Remove explicit permission. var allowsWrite = false; var allowsModify = false; var rulesChanged = false; foreach (var rule in rules) { if (rule.AccessControlType == AccessControlType.Allow && rule.IdentityReference.Value == referenceValue) { if (rule.FileSystemRights.HasFlag(FileSystemRights.Write)) { allowsWrite = true; continue; } if (rule.FileSystemRights.HasFlag(FileSystemRights.Modify)) { allowsModify = true; continue; } } // If rule is not inherited from parent directory then... if (!rule.IsInherited) { // Remove rules. fileSecurity.RemoveAccessRule(rule); rulesChanged = true; } } if (applyFix) { if (!allowsWrite) { fileSecurity.AddAccessRule(new FileSystemAccessRule(identity, FileSystemRights.Write, AccessControlType.Allow)); rulesChanged = true; } if (!allowsModify) { fileSecurity.AddAccessRule(new FileSystemAccessRule(identity, FileSystemRights.Modify, AccessControlType.Allow)); rulesChanged = true; } if (rulesChanged) { fileInfo.SetAccessControl(fileSecurity); } } return rulesChanged; }
private static void AddFileSecurity(string path, string account, FileSystemRights rights) { FileInfo fileInfo = new FileInfo(path.Replace('\\', '/')); FileSecurity fileSecurity = fileInfo.GetAccessControl(); fileSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, AccessControlType.Allow )); fileInfo.SetAccessControl(fileSecurity); }
public void SetFileAccess(string file) { var fi = new System.IO.FileInfo(file); var ac = fi.GetAccessControl(); var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); var account = (NTAccount)sid.Translate(typeof(NTAccount)); var fileAccessRule = new FileSystemAccessRule(account, FileSystemRights.FullControl, AccessControlType.Allow); ac.AddAccessRule(fileAccessRule); fi.SetAccessControl(ac); }
public static string GetRights(FileInfo fi) { var result = ""; var ds = fi.GetAccessControl(); foreach (FileSystemAccessRule ar in ds.GetAccessRules(true, true, typeof (NTAccount))) { result = string.Format("{0}", ar.FileSystemRights); } return result; }
public static bool HasAccces(FileInfo fileInfo, FileSystemRights fileSystemRights) { string identityName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToUpper(); AuthorizationRuleCollection authorizationRuleCollection = fileInfo.GetAccessControl().GetAccessRules(true, true, typeof(NTAccount)); foreach (FileSystemAccessRule fileSystemAccessRule in authorizationRuleCollection) { if (identityName == fileSystemAccessRule.IdentityReference.Value.ToUpper()) return AccessControlType.Allow == fileSystemAccessRule.AccessControlType && fileSystemRights == (fileSystemAccessRule.FileSystemRights & fileSystemRights); } return false; }
public void GetAccessControl_FileInfo_AccessControlSections_ReturnsValidObject() { using (var directory = new TempDirectory()) using (var file = new TempFile(Path.Combine(directory.Path, "file.txt"))) { FileInfo fileInfo = new FileInfo(file.Path); AccessControlSections accessControlSections = new AccessControlSections(); FileSecurity fileSecurity = fileInfo.GetAccessControl(accessControlSections); Assert.NotNull(fileSecurity); Assert.Equal(typeof(FileSystemRights), fileSecurity.AccessRightType); } }
private void Verify_FileSecurity_CreateFile(FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity expectedSecurity) { using var tempRootDir = new TempAclDirectory(); string path = Path.Combine(tempRootDir.Path, "file.txt"); var fileInfo = new FileInfo(path); fileInfo.Create(mode, rights, share, bufferSize, options, expectedSecurity).Dispose(); Assert.True(fileInfo.Exists); tempRootDir.CreatedSubfiles.Add(fileInfo); var actualFileInfo = new FileInfo(path); FileSecurity actualSecurity = actualFileInfo.GetAccessControl(AccessControlSections.Access); VerifyAccessSecurity(expectedSecurity, actualSecurity); }
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); }
private void VerifyFileSecurity(FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity expectedSecurity) { using var directory = new TempDirectory(); string path = Path.Combine(directory.Path, "file.txt"); FileInfo info = new FileInfo(path); info.Create(mode, rights, share, bufferSize, options, expectedSecurity); Assert.True(File.Exists(path)); FileInfo actualInfo = new FileInfo(info.FullName); FileSecurity actualSecurity = actualInfo.GetAccessControl(); VerifyAccessSecurity(expectedSecurity, actualSecurity); }
/// <summary> /// /// </summary> internal static void CreateDBFileAndSetPermissions() { DBCommand cmd = GetCommand(); SQLiteConnectionStringBuilder cb = new SQLiteConnectionStringBuilder( cmd.Con.ConnectionString ); if( Environment.OSVersion.Version.Major < 6 ) { // can't get this to work on XP... return; } FileInfo file = new FileInfo( cb.DataSource ); FileSecurity permissions = file.GetAccessControl(); string domain = Environment.GetEnvironmentVariable( "USERDOMAIN" ); if( !string.IsNullOrEmpty( domain ) ) { domain = "@" + domain; } string username = Environment.GetEnvironmentVariable( "USERNAME" ); WindowsIdentity cu = new WindowsIdentity( username + domain ); if( cu.User == null ) { return; } permissions.AddAccessRule( new FileSystemAccessRule( cu.User, FileSystemRights.FullControl, AccessControlType.Allow ) ); file.SetAccessControl( permissions ); }
public void should_grant_read_access_to_users() { bool foundUser = false; var rsa = certificate.PrivateKey as RSACryptoServiceProvider; if (rsa != null) { var file = new FileInfo(dotNetPath.Combine(keyLocation, rsa.CspKeyContainerInfo.UniqueKeyContainerName)); var fs = file.GetAccessControl(); var rules = fs.GetAccessRules(true, true, typeof(NTAccount)); foreach (AuthorizationRule rule in rules) { if (rule.IdentityReference.Value.ToLower() == WellKnownSecurityRoles.Users.ToLower()) { foundUser = true; } } } Assert.AreEqual(true, foundUser); }
public void FileInfo_Create_AllowSpecific_AccessRules(FileSystemRights rights) { using var tempRootDir = new TempAclDirectory(); string path = Path.Combine(tempRootDir.Path, "file.txt"); var fileInfo = new FileInfo(path); FileSecurity expectedSecurity = GetFileSecurity(rights); using FileStream stream = fileInfo.Create( FileMode.Create, FileSystemRights.FullControl, FileShare.ReadWrite | FileShare.Delete, DefaultBufferSize, FileOptions.None, expectedSecurity); Assert.True(fileInfo.Exists); tempRootDir.CreatedSubfiles.Add(fileInfo); var actualInfo = new FileInfo(fileInfo.FullName); FileSecurity actualSecurity = actualInfo.GetAccessControl(AccessControlSections.Access); VerifyAccessSecurity(expectedSecurity, actualSecurity); }
public void downloadDataUpdates() { ProgressHandler.value = 0; ProgressHandler.max = Core.updater.Data.UpdateCount; try { while (Core.updater.Data.UpdateAvailable) { ProgressHandler.value++; TranslatingProgressHandler.setTranslatedMessage("UpdatingFile", Core.updater.Data.NextUpdateName); String file_path = Core.updater.Data.NextUpdatePath; Core.updater.Data.DownloadNextUpdate(); FileInfo file = new FileInfo(file_path); FileSecurity fSecurity = file.GetAccessControl(); fSecurity.AddAccessRule(new FileSystemAccessRule(@"Everyone", FileSystemRights.FullControl, InheritanceFlags.None, PropagationFlags.InheritOnly, AccessControlType.Allow)); file.SetAccessControl(fSecurity); } } catch (Exception e) { Logger.Logger.log(e); } }
public void GetAccessControl_CallsApiCorrectly() { var fixture = DokanOperationsFixture.Instance; string path = DokanOperationsFixture.FileName.AsRootedPath(); #if LOGONLY fixture.SetupAny(); #else fixture.SetupCreateFile(path, ReadAttributesPermissionsAccess, ReadWriteShare, FileMode.Open); fixture.SetupGetFileInformation(path, FileAttributes.Normal); fixture.SetupGetFileSecurity(path, DokanOperationsFixture.DefaultFileSecurity); fixture.SetupCreateFile(DokanOperationsFixture.RootName, ReadPermissionsAccess, ReadWriteShare, FileMode.Open); fixture.SetupGetFileInformation(DokanOperationsFixture.RootName, FileAttributes.Directory); fixture.SetupGetFileSecurity(DokanOperationsFixture.RootName, DokanOperationsFixture.DefaultDirectorySecurity); #endif var sut = new FileInfo(DokanOperationsFixture.FileName.AsDriveBasedPath()); var security = sut.GetAccessControl(); #if !LOGONLY Assert.IsNotNull(security, "Security descriptor should be set"); Assert.AreEqual(DokanOperationsFixture.DefaultFileSecurity.AsString(), security.AsString(), "Security descriptors should match"); fixture.VerifyAll(); #endif }
public static void SetAccount(string filePath) { FileInfo fi = new FileInfo(filePath); System.Security.AccessControl.FileSecurity fileSecurity = fi.GetAccessControl(); fileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow)); fileSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow)); fi.SetAccessControl(fileSecurity); }
/// <summary> /// Supply the path to the file or directory and a user or group. /// Access checks are done /// during instantiation to ensure we always have a valid object /// </summary> /// <param name="path"></param> /// <param name="principal"></param> public UserFileAccessRightsChecker(string path, System.Security.Principal.WindowsIdentity principal) { this._path = path; this._principal = principal; try { System.IO.FileInfo fi = new System.IO.FileInfo(Path); AuthorizationRuleCollection acl = fi.GetAccessControl().GetAccessRules (true, true, typeof(SecurityIdentifier)); for (int i = 0; i < acl.Count; i++) { System.Security.AccessControl.FileSystemAccessRule rule = (System.Security.AccessControl.FileSystemAccessRule)acl[i]; if (_principal.User.Equals(rule.IdentityReference)) { if (System.Security.AccessControl.AccessControlType.Deny.Equals (rule.AccessControlType)) { if (Contains(FileSystemRights.AppendData, rule)) { _denyAppendData = true; } if (Contains(FileSystemRights.ChangePermissions, rule)) { _denyChangePermissions = true; } if (Contains(FileSystemRights.CreateDirectories, rule)) { _denyCreateDirectories = true; } if (Contains(FileSystemRights.CreateFiles, rule)) { _denyCreateFiles = true; } if (Contains(FileSystemRights.Delete, rule)) { _denyDelete = true; } if (Contains(FileSystemRights.DeleteSubdirectoriesAndFiles, rule)) { _denyDeleteSubdirectoriesAndFiles = true; } if (Contains(FileSystemRights.ExecuteFile, rule)) { _denyExecuteFile = true; } if (Contains(FileSystemRights.FullControl, rule)) { _denyFullControl = true; } if (Contains(FileSystemRights.ListDirectory, rule)) { _denyListDirectory = true; } if (Contains(FileSystemRights.Modify, rule)) { _denyModify = true; } if (Contains(FileSystemRights.Read, rule)) { _denyRead = true; } if (Contains(FileSystemRights.ReadAndExecute, rule)) { _denyReadAndExecute = true; } if (Contains(FileSystemRights.ReadAttributes, rule)) { _denyReadAttributes = true; } if (Contains(FileSystemRights.ReadData, rule)) { _denyReadData = true; } if (Contains(FileSystemRights.ReadExtendedAttributes, rule)) { _denyReadExtendedAttributes = true; } if (Contains(FileSystemRights.ReadPermissions, rule)) { _denyReadPermissions = true; } if (Contains(FileSystemRights.Synchronize, rule)) { _denySynchronize = true; } if (Contains(FileSystemRights.TakeOwnership, rule)) { _denyTakeOwnership = true; } if (Contains(FileSystemRights.Traverse, rule)) { _denyTraverse = true; } if (Contains(FileSystemRights.Write, rule)) { _denyWrite = true; } if (Contains(FileSystemRights.WriteAttributes, rule)) { _denyWriteAttributes = true; } if (Contains(FileSystemRights.WriteData, rule)) { _denyWriteData = true; } if (Contains(FileSystemRights.WriteExtendedAttributes, rule)) { _denyWriteExtendedAttributes = true; } } else if (System.Security.AccessControl.AccessControlType. Allow.Equals(rule.AccessControlType)) { if (Contains(FileSystemRights.AppendData, rule)) { _allowAppendData = true; } if (Contains(FileSystemRights.ChangePermissions, rule)) { _allowChangePermissions = true; } if (Contains(FileSystemRights.CreateDirectories, rule)) { _allowCreateDirectories = true; } if (Contains(FileSystemRights.CreateFiles, rule)) { _allowCreateFiles = true; } if (Contains(FileSystemRights.Delete, rule)) { _allowDelete = true; } if (Contains(FileSystemRights.DeleteSubdirectoriesAndFiles, rule)) { _allowDeleteSubdirectoriesAndFiles = true; } if (Contains(FileSystemRights.ExecuteFile, rule)) { _allowExecuteFile = true; } if (Contains(FileSystemRights.FullControl, rule)) { _allowFullControl = true; } if (Contains(FileSystemRights.ListDirectory, rule)) { _allowListDirectory = true; } if (Contains(FileSystemRights.Modify, rule)) { _allowModify = true; } if (Contains(FileSystemRights.Read, rule)) { _allowRead = true; } if (Contains(FileSystemRights.ReadAndExecute, rule)) { _allowReadAndExecute = true; } if (Contains(FileSystemRights.ReadAttributes, rule)) { _allowReadAttributes = true; } if (Contains(FileSystemRights.ReadData, rule)) { _allowReadData = true; } if (Contains(FileSystemRights.ReadExtendedAttributes, rule)) { _allowReadExtendedAttributes = true; } if (Contains(FileSystemRights.ReadPermissions, rule)) { _allowReadPermissions = true; } if (Contains(FileSystemRights.Synchronize, rule)) { _allowSynchronize = true; } if (Contains(FileSystemRights.TakeOwnership, rule)) { _allowTakeOwnership = true; } if (Contains(FileSystemRights.Traverse, rule)) { _allowTraverse = true; } if (Contains(FileSystemRights.Write, rule)) { _allowWrite = true; } if (Contains(FileSystemRights.WriteAttributes, rule)) { _allowWriteAttributes = true; } if (Contains(FileSystemRights.WriteData, rule)) { _allowWriteData = true; } if (Contains(FileSystemRights.WriteExtendedAttributes, rule)) { _allowWriteExtendedAttributes = true; } } } } IdentityReferenceCollection groups = _principal.Groups; for (int j = 0; j < groups.Count; j++) { for (int i = 0; i < acl.Count; i++) { System.Security.AccessControl.FileSystemAccessRule rule = (System.Security.AccessControl.FileSystemAccessRule)acl[i]; if (groups[j].Equals(rule.IdentityReference)) { if (System.Security.AccessControl.AccessControlType. Deny.Equals(rule.AccessControlType)) { if (Contains(FileSystemRights.AppendData, rule)) { _denyAppendData = true; } if (Contains(FileSystemRights.ChangePermissions, rule)) { _denyChangePermissions = true; } if (Contains(FileSystemRights.CreateDirectories, rule)) { _denyCreateDirectories = true; } if (Contains(FileSystemRights.CreateFiles, rule)) { _denyCreateFiles = true; } if (Contains(FileSystemRights.Delete, rule)) { _denyDelete = true; } if (Contains(FileSystemRights. DeleteSubdirectoriesAndFiles, rule)) { _denyDeleteSubdirectoriesAndFiles = true; } if (Contains(FileSystemRights.ExecuteFile, rule)) { _denyExecuteFile = true; } if (Contains(FileSystemRights.FullControl, rule)) { _denyFullControl = true; } if (Contains(FileSystemRights.ListDirectory, rule)) { _denyListDirectory = true; } if (Contains(FileSystemRights.Modify, rule)) { _denyModify = true; } if (Contains(FileSystemRights.Read, rule)) { _denyRead = true; } if (Contains(FileSystemRights.ReadAndExecute, rule)) { _denyReadAndExecute = true; } if (Contains(FileSystemRights.ReadAttributes, rule)) { _denyReadAttributes = true; } if (Contains(FileSystemRights.ReadData, rule)) { _denyReadData = true; } if (Contains(FileSystemRights. ReadExtendedAttributes, rule)) { _denyReadExtendedAttributes = true; } if (Contains(FileSystemRights.ReadPermissions, rule)) { _denyReadPermissions = true; } if (Contains(FileSystemRights.Synchronize, rule)) { _denySynchronize = true; } if (Contains(FileSystemRights.TakeOwnership, rule)) { _denyTakeOwnership = true; } if (Contains(FileSystemRights.Traverse, rule)) { _denyTraverse = true; } if (Contains(FileSystemRights.Write, rule)) { _denyWrite = true; } if (Contains(FileSystemRights.WriteAttributes, rule)) { _denyWriteAttributes = true; } if (Contains(FileSystemRights.WriteData, rule)) { _denyWriteData = true; } if (Contains(FileSystemRights. WriteExtendedAttributes, rule)) { _denyWriteExtendedAttributes = true; } } else if (System.Security.AccessControl.AccessControlType. Allow.Equals(rule.AccessControlType)) { if (Contains(FileSystemRights.AppendData, rule)) { _allowAppendData = true; } if (Contains(FileSystemRights.ChangePermissions, rule)) { _allowChangePermissions = true; } if (Contains(FileSystemRights.CreateDirectories, rule)) { _allowCreateDirectories = true; } if (Contains(FileSystemRights.CreateFiles, rule)) { _allowCreateFiles = true; } if (Contains(FileSystemRights.Delete, rule)) { _allowDelete = true; } if (Contains(FileSystemRights. DeleteSubdirectoriesAndFiles, rule)) { _allowDeleteSubdirectoriesAndFiles = true; } if (Contains(FileSystemRights.ExecuteFile, rule)) { _allowExecuteFile = true; } if (Contains(FileSystemRights.FullControl, rule)) { _allowFullControl = true; } if (Contains(FileSystemRights.ListDirectory, rule)) { _allowListDirectory = true; } if (Contains(FileSystemRights.Modify, rule)) { _allowModify = true; } if (Contains(FileSystemRights.Read, rule)) { _allowRead = true; } if (Contains(FileSystemRights.ReadAndExecute, rule)) { _allowReadAndExecute = true; } if (Contains(FileSystemRights.ReadAttributes, rule)) { _allowReadAttributes = true; } if (Contains(FileSystemRights.ReadData, rule)) { _allowReadData = true; } if (Contains(FileSystemRights. ReadExtendedAttributes, rule)) { _allowReadExtendedAttributes = true; } if (Contains(FileSystemRights.ReadPermissions, rule)) { _allowReadPermissions = true; } if (Contains(FileSystemRights.Synchronize, rule)) { _allowSynchronize = true; } if (Contains(FileSystemRights.TakeOwnership, rule)) { _allowTakeOwnership = true; } if (Contains(FileSystemRights.Traverse, rule)) { _allowTraverse = true; } if (Contains(FileSystemRights.Write, rule)) { _allowWrite = true; } if (Contains(FileSystemRights.WriteAttributes, rule)) { _allowWriteAttributes = true; } if (Contains(FileSystemRights.WriteData, rule)) { _allowWriteData = true; } if (Contains(FileSystemRights.WriteExtendedAttributes, rule)) { _allowWriteExtendedAttributes = true; } } } } } } catch (Exception e) { //Deal with IO exceptions if you want throw e; } }
public void SetAccessControl() { string tempFile = Path.GetTempFileName(); FileInfo fi = new FileInfo(tempFile); FileSecurity expected = fi.GetAccessControl(AccessControlSections.All); ExtendedFileInfo efi = new ExtendedFileInfo(tempFile); Assert.IsNotNull(efi); FileSecurity fileSecurity = new FileSecurity(); fileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow)); efi.SetAccessControl(fileSecurity); Assert.AreNotEqual(expected.GetSecurityDescriptorBinaryForm(), efi.GetAccessControl().GetSecurityDescriptorBinaryForm()); FileSecurity actualFileSecurity = File.GetAccessControl(tempFile); AuthorizationRuleCollection rules = actualFileSecurity.GetAccessRules(true, true, typeof(NTAccount)); foreach (AuthorizationRule rule in rules) { FileSystemAccessRule accessRule = (FileSystemAccessRule)rule; if (accessRule.IdentityReference.Value == "Everyone") { Assert.IsTrue(accessRule.AccessControlType == AccessControlType.Allow); Assert.IsTrue(accessRule.FileSystemRights == FileSystemRights.FullControl); } } fi.SetAccessControl(expected); }
public void GetAccessControl1() { string tempFile = Path.GetTempFileName(); FileInfo fi = new FileInfo(tempFile); ExtendedFileInfo efi = new ExtendedFileInfo(tempFile); Assert.IsNotNull(efi); FileSecurity actual = efi.GetAccessControl(AccessControlSections.All); FileSecurity expected = fi.GetAccessControl(AccessControlSections.All); CollectionAssert.AreEqual(expected.GetSecurityDescriptorBinaryForm(), actual.GetSecurityDescriptorBinaryForm()); }
public void FileOwner() { string tempFile = Path.GetTempFileName(); FileInfo fi = new FileInfo(tempFile); FileSecurity fs = fi.GetAccessControl(AccessControlSections.Owner); string expected = fs.GetOwner(typeof(NTAccount)).ToString(); ExtendedFileInfo efi = new ExtendedFileInfo(tempFile); Assert.IsNotNull(efi); string actual = efi.FileOwner; Assert.AreEqual(expected, actual); }
/// <summary> /// Checks the permissions. /// </summary> /// <param name="user">The user.</param> /// <param name="path">The path.</param> /// <param name="expectedRights">The expected rights.</param> /// <returns></returns> public static bool CheckPermissions(WindowsIdentity user, string path, FileSystemRights expectedRights) { var fi = new FileInfo(path); var di = new DirectoryInfo(path); AuthorizationRuleCollection acl; if (fi.Exists) { acl = fi.GetAccessControl().GetAccessRules(true, true, typeof (SecurityIdentifier)); } else if (di.Exists) { acl = di.GetAccessControl().GetAccessRules(true, true, typeof (SecurityIdentifier)); } else { return false; } // gets rules that concern the user and his groups IEnumerable<AuthorizationRule> userRules = from AuthorizationRule rule in acl where user.Groups != null && (user.User != null && (user.User.Equals(rule.IdentityReference) || user.Groups.Contains(rule.IdentityReference))) select rule; FileSystemRights denyRights = 0; FileSystemRights allowRights = 0; // iterates on rules to compute denyRights and allowRights foreach (FileSystemAccessRule rule in userRules) { if (rule.AccessControlType.Equals(AccessControlType.Deny)) { denyRights = denyRights | rule.FileSystemRights; } else if (rule.AccessControlType.Equals(AccessControlType.Allow)) { allowRights = allowRights | rule.FileSystemRights; } } allowRights = allowRights & ~denyRights; // are rights sufficient? return (allowRights & expectedRights) == expectedRights; }
/// <summary>Determines the effective access rights for the given user.</summary> /// <param name="path">The file.</param> /// <param name="windowsIdentity">The windows identity.</param> /// <returns>Effective rights for identity.</returns> public static FileSystemRights GetEffectiveRights(this FileInfo path, WindowsIdentity windowsIdentity) => GetEffectiveRights <FileSystemRights, FileSystemAccessRule>(path.GetAccessControl(), windowsIdentity);
/// <summary> /// Set the given user access rights on the given certificate to the given user /// </summary> private void SetUserAccessRights() { StoreLocation locationFlag = this.MachineStore ? StoreLocation.LocalMachine : StoreLocation.CurrentUser; X509Store store = this.GetStore(locationFlag); X509Certificate2 certificate = null; try { store.Open(OpenFlags.ReadOnly); if (string.IsNullOrEmpty(this.Thumbprint) == false) { certificate = GetCertificateFromThumbprint(this.Thumbprint, store); } else if (string.IsNullOrEmpty(this.DistinguishedName) == false) { certificate = GetCertificateFromDistinguishedName(this.DistinguishedName, store); } if (certificate == null) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Error in setting user rights on certificate. Could not find the certificate in the certificate store")); } else { RSACryptoServiceProvider rsa = certificate.PrivateKey as RSACryptoServiceProvider; FileSystemRights fileSystemAccessRights = FileSystemRights.ReadAndExecute; if (rsa != null) { switch (this.AccessRights) { case AccessRightsRead: fileSystemAccessRights = FileSystemRights.Read; break; case AccessRightsReadAndExecute: fileSystemAccessRights = FileSystemRights.ReadAndExecute; break; case AccessRightsWrite: fileSystemAccessRights = FileSystemRights.Write; break; case AccessRightsFullControl: fileSystemAccessRights = FileSystemRights.FullControl; break; } string keyfilepath = FindKeyLocation(rsa.CspKeyContainerInfo.UniqueKeyContainerName); FileInfo file = new FileInfo(keyfilepath + "\\" + rsa.CspKeyContainerInfo.UniqueKeyContainerName); FileSecurity fs = file.GetAccessControl(); NTAccount account = new NTAccount(this.AccountName); fs.AddAccessRule(new FileSystemAccessRule(account, fileSystemAccessRights, AccessControlType.Allow)); file.SetAccessControl(fs); } } } finally { store.Close(); } }
/// <summary> /// Gets the access rights granted to each account. /// </summary> private void GetAccountAccessRights( string path, SecuredObject objectToSecure, Dictionary<string, SecuredObjectAccessRights> read, Dictionary<string, SecuredObjectAccessRights> write, Dictionary<string, SecuredObjectAccessRights> configure) { AuthorizationRuleCollection authorizationRules = null; // determine if a file or directory. FileInfo fileInfo = new FileInfo(path); if (fileInfo.Exists) { FileSystemSecurity security = fileInfo.GetAccessControl(AccessControlSections.Access); authorizationRules = security.GetAccessRules(true, true, typeof(NTAccount)); } else { DirectoryInfo directoryInfo = new DirectoryInfo(path); if (directoryInfo.Exists) { FileSystemSecurity security = directoryInfo.GetAccessControl(AccessControlSections.Access); authorizationRules = security.GetAccessRules(true, true, typeof(NTAccount)); } } // check if no rules to add. if (authorizationRules == null || authorizationRules.Count == 0) { return; } // process the access rules. for (int ii = 0; ii < authorizationRules.Count; ii++) { // check for file system rule. FileSystemAccessRule accessRule = authorizationRules[ii] as FileSystemAccessRule; if (accessRule == null) { continue; } // check the type of rule. bool denied = (accessRule.AccessControlType == System.Security.AccessControl.AccessControlType.Deny); // check for right to take ownership. if (!denied) { if ((FileSystemRights.TakeOwnership & accessRule.FileSystemRights) != 0) { UpdateAccessRightSet(objectToSecure, accessRule.IdentityReference, denied, configure); } } // check if the rule affects configuration rights. if ((FileSystemRights.ChangePermissions & accessRule.FileSystemRights) != 0) { UpdateAccessRightSet(objectToSecure, accessRule.IdentityReference, denied, configure); } // check if the rule affects write rights. if ((FileSystemRights.WriteData & accessRule.FileSystemRights) != 0) { UpdateAccessRightSet(objectToSecure, accessRule.IdentityReference, denied, write); } // check if the rule affects read rights. if ((FileSystemRights.ReadData & accessRule.FileSystemRights) != 0) { UpdateAccessRightSet(objectToSecure, accessRule.IdentityReference, denied, read); } // check if the rule affects read rights. if (objectToSecure == SecuredObject.ExecutableFile) { if ((FileSystemRights.ExecuteFile & accessRule.FileSystemRights) != 0) { UpdateAccessRightSet(objectToSecure, accessRule.IdentityReference, denied, read); } } else { if ((FileSystemRights.ReadData & accessRule.FileSystemRights) != 0) { UpdateAccessRightSet(objectToSecure, accessRule.IdentityReference, denied, read); } } } }
/// <summary> /// Set the ownership of a file /// </summary> /// /// <param name="FilePath">Full path to file</param> /// <param name="Account">The account taking ownership</param> public static void SetOwner(string FilePath, NTAccount Account) { FileInfo finfo = new FileInfo(FilePath); FileSecurity fsecurity = finfo.GetAccessControl(); fsecurity.SetOwner(Account); finfo.SetAccessControl(fsecurity); }
public static FileSecurity GetAccessControl(this FileInfo fileInfo) { return(fileInfo.GetAccessControl()); }
/// <summary> /// The ensure permissions. /// </summary> /// <param name="path"> /// The path. /// </param> /// <param name="identity"> /// The identity. /// </param> public static void EnsureFilePermissions([NotNull] string path, [NotNull] IdentityReference identity) { Assert.ArgumentNotNull(path, "path"); Assert.ArgumentNotNull(identity, "identity"); var fileInfo = new FileInfo(path); var dirSecurity = fileInfo.GetAccessControl(AccessControlSections.All); AuthorizationRuleCollection rules = dirSecurity.GetAccessRules(true, true, typeof(NTAccount)); if (!HasPermissions(rules, identity, FileSystemRights.FullControl)) { var rule = new FileSystemAccessRule(identity, FileSystemRights.FullControl, AccessControlType.Allow); dirSecurity.AddAccessRule(rule); fileInfo.SetAccessControl(dirSecurity); dirSecurity = fileInfo.GetAccessControl(AccessControlSections.All); rules = dirSecurity.GetAccessRules(true, true, typeof(NTAccount)); Assert.IsTrue(HasPermissions(rules, identity, FileSystemRights.FullControl), "The Full Control access to the '" + path + "' file isn't permitted for " + identity.Value + ". Please fix it and then restart the process"); } }
public static FileSecurity GetAccessControl(FileInfo fileInfo, AccessControlSections includeSections) { return(fileInfo.GetAccessControl(includeSections)); }
private static void AddPermissionToCertificate(X509Certificate2 cert) { RSACryptoServiceProvider rsa = cert.PrivateKey as RSACryptoServiceProvider; if (rsa == null) { return; } string keyfilepath = FindKey(rsa.CspKeyContainerInfo.UniqueKeyContainerName); FileInfo file = new FileInfo(System.IO.Path.Combine(keyfilepath, rsa.CspKeyContainerInfo.UniqueKeyContainerName)); FileSecurity fs = file.GetAccessControl(); SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); fs.AddAccessRule(new FileSystemAccessRule("NETWORK SERVICE", FileSystemRights.FullControl, AccessControlType.Allow)); fs.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.Read, AccessControlType.Allow)); fs.AddAccessRule(new FileSystemAccessRule("RHEV-M Admins", FileSystemRights.FullControl, AccessControlType.Allow)); fs.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.Read, AccessControlType.Allow)); file.SetAccessControl(fs); }
/// <summary> /// Sets the permissions to match the template on the specified file. /// </summary> public void SetPermissions(string template, FileInfo target) { if (target == null || !target.Exists) { throw new ArgumentException("Target file does not exist.", "target"); } string filePath = Utils.GetAbsoluteFilePath(m_directory.FullName + "\\" + template + m_FileExtension, false, false, false); // nothing more to do if no file. if (filePath == null) { return; } FileInfo templateFile = new FileInfo(filePath); FileSecurity security1 = templateFile.GetAccessControl(AccessControlSections.Access); FileSecurity security2 = target.GetAccessControl(AccessControlSections.Access); foreach (AuthorizationRule rule in security2.GetAccessRules(true, true, typeof(NTAccount))) { FileSystemAccessRule fsr = rule as FileSystemAccessRule; if (fsr != null) { security2.RemoveAccessRule(fsr); } } foreach (AuthorizationRule rule in security1.GetAccessRules(true, true, typeof(NTAccount))) { FileSystemAccessRule fsr = rule as FileSystemAccessRule; if (fsr != null) { security2.AddAccessRule(fsr); } } security2.SetAccessRuleProtection(true, false); target.SetAccessControl(security2); }
public static void AddAccessToCertificate(X509Certificate2 cert, string user) { RSACryptoServiceProvider rsa = cert.PrivateKey as RSACryptoServiceProvider; if (rsa != null) { string keyfilepath = FindKeyLocation(rsa.CspKeyContainerInfo.UniqueKeyContainerName); FileInfo file = new FileInfo(keyfilepath + "\\" + rsa.CspKeyContainerInfo.UniqueKeyContainerName); Console.WriteLine(file.Name); FileSecurity fs = file.GetAccessControl(); NTAccount account = new NTAccount(user); fs.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.FullControl, AccessControlType.Allow)); file.SetAccessControl(fs); } }
public void CopyElevated(string source, string dest) { if (!WinAPI.IsVista) { File.Copy(source, dest); return; } var di = new DirectoryInfo(System.IO.Path.GetDirectoryName(dest)); var security = di.GetAccessControl(); var fi = new FileInfo(dest); var fileSecurity = fi.GetAccessControl(); // Allow Users to Write. //SecurityIdentifier SID = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); //fileSecurity.AddAccessRule(new FileSystemAccessRule(sid, FileSystemRights.Write, AccessControlType.Allow)); //fi.SetAccessControl(fileSecurity); var rules = security.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); string message = string.Empty; foreach (var myacc in rules) { var acc = (FileSystemAccessRule)myacc; message += string.Format("IdentityReference: {0}\r\n", acc.IdentityReference.Value); message += string.Format("Access Control Type: {0}\r\n", acc.AccessControlType.ToString()); message += string.Format("\t{0}\r\n", acc.FileSystemRights.ToString()); //if ((acc.FileSystemRights & FileSystemRights.FullControl) == FileSystemRights.FullControl) //{ // Console.Write("FullControl"); //} //if ((acc.FileSystemRights & FileSystemRights.ReadData) == FileSystemRights.ReadData) //{ // Console.Write("ReadData"); //} //if ((acc.FileSystemRights & FileSystemRights.WriteData) == FileSystemRights.WriteData) //{ // Console.Write("WriteData"); //} //if ((acc.FileSystemRights & FileSystemRights.ListDirectory) == FileSystemRights.ListDirectory) //{ // Console.Write("ListDirectory"); //} //if ((acc.FileSystemRights & FileSystemRights.ExecuteFile) == FileSystemRights.ExecuteFile) //{ // Console.Write("ExecuteFile"); //} } MessageBox.Show(message); //WindowsIdentity self = System.Security.Principal.WindowsIdentity.GetCurrent(); // FileSystemAccessRule rule = new FileSystemAccessRule( // self.Name, // FileSystemRights.FullControl, // AccessControlType.Allow); }