/// <summary> /// Opens up file access for Everyone at FullAccess. /// </summary> /// <param name="filePath">File path.</param> public static void UpdateFileSecurity(string filePath) { SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null); FileInfo fInfo = new FileInfo(filePath); FileSecurity fSecurity = File.GetAccessControl(filePath); fSecurity.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.FullControl, InheritanceFlags.None, PropagationFlags.NoPropagateInherit, AccessControlType.Allow)); fInfo.SetAccessControl(fSecurity); }
// 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 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 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 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; }
protected override void ExecuteOnFile(FileInfo file) { FileSecurity fileSec = new FileSecurity(file.FullName, AccessControlSections.Access); Log(Level.Info, Resources.AddAccessRuleAdding, Rights, NTAccount, file.FullName); FileSystemAccessRule newRule = new FileSystemAccessRule(new NTAccount(NTAccount), Rights, AccessControlType); fileSec.AddAccessRule(newRule); file.SetAccessControl(fileSec); }
/// <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 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); }
protected override void ExecuteOnFile(FileInfo file) { FileSecurity fileSec = new FileSecurity(file.FullName, AccessControlSections.Access); IList<FileSystemAccessRule> targetRules = FindAccessRules(fileSec); if (targetRules.Count == 0) { Log(Level.Info, Resources.RemoveAccessRuleEmpty, NTAccount, file.FullName); } else { foreach (FileSystemAccessRule fileSystemAccessRule in targetRules) { Log(Level.Info, Resources.RemoveAccessRuleRemoving, NTAccount, file.FullName); fileSec.RemoveAccessRule(fileSystemAccessRule); } file.SetAccessControl(fileSec); } }
/// <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 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 SetAccessControl_CallsApiCorrectly() { var fixture = DokanOperationsFixture.Instance; string path = DokanOperationsFixture.FileName; var security = new FileSecurity(); security.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.FullControl, AccessControlType.Allow)); #if LOGONLY fixture.SetupAny(); #else fixture.SetupCreateFile(path.AsRootedPath(), ChangePermissionsAccess, ReadWriteShare, FileMode.Open); fixture.SetupGetFileInformation(path.AsRootedPath(), FileAttributes.Normal); fixture.SetupGetFileSecurity(path.AsRootedPath(), DokanOperationsFixture.DefaultFileSecurity); fixture.SetupSetFileSecurity(path.AsRootedPath(), security); fixture.SetupCreateFile(DokanOperationsFixture.RootName, ReadPermissionsAccess, ReadWriteShare, FileMode.Open); fixture.SetupGetFileInformation(DokanOperationsFixture.RootName, FileAttributes.Directory); fixture.SetupGetFileSecurity(DokanOperationsFixture.RootName, DokanOperationsFixture.DefaultDirectorySecurity, AccessControlSections.Access); #endif var sut = new FileInfo(path.AsDriveBasedPath()); sut.SetAccessControl(security); #if !LOGONLY fixture.VerifyAll(); #endif }
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); }
/// <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); }
/// <summary> /// Clears the permissions on the file and enables permission inheritance. /// </summary> private static void InheritPermissions(FileInfo target) { FileSecurity security = target.GetAccessControl(AccessControlSections.Access); security.SetAccessRuleProtection(false, false); foreach (AuthorizationRule rule in security.GetAccessRules(true, false, typeof(NTAccount))) { FileSystemAccessRule fsr = rule as FileSystemAccessRule; if (fsr != null) { security.RemoveAccessRule(fsr); } } target.SetAccessControl(security); }
public static void SetAccessControl(FileInfo fileInfo, FileSecurity fileSecurity) { fileInfo.SetAccessControl(fileSecurity); }
private static void AddAccessToCertificate(X509Certificate2 cert, string user) { RSACryptoServiceProvider rsa = cert.PrivateKey as RSACryptoServiceProvider; if (rsa == null) throw new ArgumentNullException("Certificate private key is null."); string keyPath = FindKeyLocation(rsa.CspKeyContainerInfo.UniqueKeyContainerName); FileInfo file = new FileInfo(Path.Combine(keyPath, rsa.CspKeyContainerInfo.UniqueKeyContainerName)); FileSecurity fs = file.GetAccessControl(); NTAccount account = new NTAccount(user); fs.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.FullControl, AccessControlType.Allow)); file.SetAccessControl(fs); }
public static void SetAccessControl(this FileInfo fileInfo, FileSecurity fileSecurity) { fileInfo.SetAccessControl(fileSecurity); }
/// <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"); } }
/// <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); }
/// <summary> /// Der Anwender möchte ein existierendes Geräteprofil verwenden. /// </summary> /// <param name="sender">Wird ignoriert.</param> /// <param name="e">Wird ignoriert.</param> private void cmdUse_Click( object sender, EventArgs e ) { // Load the name var profile = (string) selProfile.SelectedItem; // Find XML tag to update var profiles = (XmlElement) m_Configuration.SelectSingleNode( "configuration/appSettings/add[@key='Profiles']" ); // Do the update profiles.SetAttribute( "value", profile ); // Get the name var profilePath = new FileInfo( Path.Combine( ProfileManager.ProfilePath.FullName, profile + "." + ProfileManager.ProfileExtension ) ); // Make sure that adminstrator access is defined try { // Load the current rights var sec = profilePath.GetAccessControl(); // This is administrator access var admins = new SecurityIdentifier( WellKnownSidType.BuiltinAdministratorsSid, null ); // Set if update is needed var adminRights = false; // Scan all current rights foreach (FileSystemAccessRule testRule in sec.GetAccessRules( true, true, typeof( SecurityIdentifier ) )) if (adminRights = Equals( testRule.IdentityReference, admins )) break; // Add the access if (!adminRights) { // Create rule var rule = new FileSystemAccessRule( admins, FileSystemRights.FullControl, AccessControlType.Allow ); // Apply rule sec.SetAccessRule( rule ); // Save to file system profilePath.SetAccessControl( sec ); } // Done Close(); } catch { } }
/// <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> /// Creates an access template file. /// </summary> internal static void CreateFile(string filePath, params WellKnownSidType[] sids) { File.WriteAllText(filePath, String.Empty); FileInfo info = new FileInfo(filePath); FileSecurity security = info.GetAccessControl(System.Security.AccessControl.AccessControlSections.Access); foreach (FileSystemAccessRule target in security.GetAccessRules(true, true, typeof(NTAccount))) { security.RemoveAccessRule(target); } security.SetAccessRuleProtection(true, false); FileSystemAccessRule rule = new FileSystemAccessRule( new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null).Translate(typeof(NTAccount)), FileSystemRights.FullControl, InheritanceFlags.None, PropagationFlags.None, System.Security.AccessControl.AccessControlType.Allow); security.AddAccessRule(rule); if (sids != null) { foreach (WellKnownSidType sid in sids) { try { rule = new FileSystemAccessRule( new SecurityIdentifier(sid, null).Translate(typeof(NTAccount)), FileSystemRights.ReadAndExecute, InheritanceFlags.None, PropagationFlags.None, System.Security.AccessControl.AccessControlType.Allow); security.AddAccessRule(rule); } catch (Exception e) { Utils.Trace((int)Utils.TraceMasks.Error, "Could not translate SID '{0}': {1}", sid, e.Message); } } } info.SetAccessControl(security); }
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); }
public static Boolean ReplaceFileSecurity(string File, string[] Account, FileSystemRights Rights, AccessControlType ControlType, InheritanceFlags Inherit, PropagationFlags Propagation) { FileInfo fInfo = new FileInfo(File); FileSecurity fSecurity = fInfo.GetAccessControl(); try { fSecurity.SetAccessRuleProtection(true, false); foreach (string account in Account) { fSecurity.ResetAccessRule(new FileSystemAccessRule(account, Rights, Inherit, Propagation, ControlType)); } fInfo.SetAccessControl(fSecurity); } catch (Exception ex) { LibraryLogging.Error("unable to ReplaceFileSecurity for {0} error {1}", File, ex.Message); return false; } return true; }
public static void GrantAccessControl(string fileName) { var fileInfo = new FileInfo(fileName); var security = fileInfo.GetAccessControl(); security.ResetAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, AccessControlType.Allow)); fileInfo.SetAccessControl(security); }
/// <summary> /// General method trying to prevent the presence of UAC and UAC-based file-ownership from messing up for Emacs /// when it saves data back to disk from an unpriviliged proccess. /// </summary> /// <param name="fullName"></param> private void TryMakeWritable(string fullName) { FileInfo fi = new FileInfo(fullName); var everyoneUser = new SecurityIdentifier(WellKnownSidType.WorldSid, null); // ensure emacs has rights to write to the actual file. try { FileSecurity fSecurity = fi.GetAccessControl(); var rule = new FileSystemAccessRule(everyoneUser, FileSystemRights.FullControl, AccessControlType.Allow); fSecurity.SetAccessRule(rule); fi.SetAccessControl(fSecurity); } catch { } // we (not admin) need to own the file for Emacs to be able to handle backups etc without ACL failures. try { FileSecurity fSecurity = fi.GetAccessControl(); fSecurity.SetOwner(new NTAccount(Environment.UserDomainName, Environment.UserName)); fi.SetAccessControl(fSecurity); } catch { } // if we want to avoid having write-failures because of ACLs, we may need to ensure directory is writable too. DirectoryInfo di = fi.Directory; try { DirectorySecurity dSecurity = di.GetAccessControl(); var rule = new FileSystemAccessRule(everyoneUser, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow); dSecurity.AddAccessRule(rule); di.SetAccessControl(dSecurity); } catch { } }
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); }
// Adds an ACL entry on the specified file for the specified account. public static void AddFileSecurity(string FileName, string Account, FileSystemRights Rights, AccessControlType ControlType) { // Create a new FileInfo object. FileInfo fInfo = new FileInfo(FileName); // Get a FileSecurity object that represents the // current security settings. FileSecurity fileSecurity = fInfo.GetAccessControl(); // Add the FileSystemAccessRule to the security settings. fileSecurity.AddAccessRule(new FileSystemAccessRule(Account, Rights, InheritanceFlags.None, PropagationFlags.NoPropagateInherit, ControlType)); /* // *** Always allow objects to inherit on a directory FileSystemAccessRule AccessRule = null; AccessRule = new FileSystemAccessRule(Account, Rights, InheritanceFlags.None, PropagationFlags.InheritOnly, ControlType); bool Result = false; fileSecurity.ModifyAccessRule(AccessControlModification.Add, AccessRule, out Result); if (!Result) { throw (new Exception("add failed")); } */ // Set the new access settings. fInfo.SetAccessControl(fileSecurity); }
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 SetAccessControl_FileInfo_FileSecurity_InvalidArguments() { using (var directory = new TempDirectory()) using (var file = new TempFile(Path.Combine(directory.Path, "file.txt"))) { FileInfo fileInfo = new FileInfo(file.Path); AssertExtensions.Throws <ArgumentNullException>("fileSecurity", () => fileInfo.SetAccessControl((FileSecurity)null)); } }