Remove all default file permissions - c#

I have an C# network application that prompts admins for network proxy authentication information. I ask the user if they want to save this information, which if they choose yes, I encrypt in a unique local file for the user. I would then like to remove all file permissions except the user that created it, but all other users to have the ability to delete the file.
Now, I found MS article below, but it's not helping if I don't know the default users that were setup on the file in the first place. Is there a remove all file permissions? I can then add the individual rights I'm wanting to setup for full access by current user and delete permissions for "All Users" or "Authenticated Users", which looks to be different depending on version of Windows.
http://msdn.microsoft.com/en-us/library/system.io.file.setaccesscontrol.aspx

I figured it out..
public void SetFileSecurity(String filePath, String domainName, String userName)
{
//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(domainName + "\\" + userName, FileSystemRights.FullControl, AccessControlType.Allow));
//add all other users delete only permissions.
fs.AddAccessRule(new FileSystemAccessRule("Authenticated Users", FileSystemRights.Delete, AccessControlType.Allow));
//flush security access.
File.SetAccessControl(filePath, fs);
}

If you need to remove for the specific group , you can use this method ;
public static void RemoveGroupPermission(string path, string group_name)
{
long begin = Datetime.Now.Ticks;
DirectoryInfo dirInfo = new DirectoryInfo(path);
DirectorySecurity dirSecurity = dirInfo.GetAccessControl();
dirSecurity.RemoveAccessRuleAll(new FileSystemAccessRule(Environment.UserDomainName +
#"\" + group_name, 0, 0));
dirInfo.SetAccessControl(dirSecurity);
long end = DateTime.Now.Ticks;
Console.WriteLine("Tick : " + (end - begin));
}

Impersonation may be help you to solve this out.
The term "Impersonation" in a programming context refers to a technique that executes the code under another user context than the user who originally started an application, i.e. the user context is temporarily changed once or multiple times during the execution of an application.
click Here to see implimentation

Related

Make file not moveable, copyable or deleteable? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I here from CodeProject, but they don't seem to have an answer to my question. I just want a desktop file to have security permission(make the file not moveable, copyable or deletable). This is possible to do manually in the file's "properties!. I am using C#, your help is much appreciated - thanks!
As a helper said below, if it is not possible to make a readable file uncopyable...is it possible to make it not moveable and deletable?
All these things are possible EXCEPT being uncopyable. Readable files can always be copied unless you restrict ALL copying on the system (which is a formidable task). However you can certainly prevent it from being moved or deleted.
From a file permissions perspective, you need to set the owner to an administator, then grant read-only permissions to the user in question. This will allow them to read the file but not delete or move it.
Doing so is quite simple using the FileInfo.SetAccessControl method in System.IO; here's the documentation to help out.
Edit to add example, credit to MS for the example:
using System;
using System.IO;
using System.Security.AccessControl;
namespace FileSystemExample
{
class FileExample
{
public static void Main()
{
try
{
string FileName = "c:/test.txt";
Console.WriteLine("Adding access control entry for " + FileName);
// Add the access control entry to the file.
// Before compiling this snippet, change MyDomain to your
// domain name and MyAccessAccount to the name
// you use to access your domain.
AddFileSecurity(FileName, #"MyDomain\MyAccessAccount", FileSystemRights.ReadData, AccessControlType.Allow);
Console.WriteLine("Removing access control entry from " + FileName);
// Remove the access control entry from the file.
// Before compiling this snippet, change MyDomain to your
// domain name and MyAccessAccount to the name
// you use to access your domain.
RemoveFileSecurity(FileName, #"MyDomain\MyAccessAccount", FileSystemRights.ReadData, AccessControlType.Allow);
Console.WriteLine("Done.");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
// 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 fSecurity = fInfo.GetAccessControl();
// Add the FileSystemAccessRule to the security settings.
fSecurity.AddAccessRule(new FileSystemAccessRule(Account,
Rights,
ControlType));
// Set the new access settings.
fInfo.SetAccessControl(fSecurity);
}
// Removes an ACL entry on the specified file for the specified account.
public static void RemoveFileSecurity(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 fSecurity = fInfo.GetAccessControl();
// Add the FileSystemAccessRule to the security settings.
fSecurity.RemoveAccessRule(new FileSystemAccessRule(Account,
Rights,
ControlType));
// Set the new access settings.
fInfo.SetAccessControl(fSecurity);
}
}
}

Directory.SetAccessControl set unnecessary permissions

I am trying to set program's installation folder permissions restricted only to Administrators.
There are two scenarios: the folder needs creation and folder already exists.
Here is my code:
public static void CreatePrivateFolder(string path)
{
SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
DirectorySecurity securityRules = new DirectorySecurity();
FileSystemAccessRule fsRule =
new FileSystemAccessRule(sid, FileSystemRights.FullControl,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None, AccessControlType.Allow);
securityRules.SetAccessRule(fsRule);
if (Directory.Exists(path))
{
Directory.SetAccessControl(path, securityRules);
}
else
{
Directory.CreateDirectory(path, securityRules);
}
}
When the folder needs creation, the CreateDirectory works fine, the folder's permissions restricted only to Administrators.
The strange thing is when I am re-run this code and flow to SetAccessControl - the folder's permissions being reset to regular folder with no restricted access.
What do I'm doing wrong?
Folder security results (for path c:\\folderCheck) :
Update
anrei solution answering my question.
However, it seem to be the same problem in a different way:
If the folder already exists with unrestricted permissions, anrei's code don't seem to be work.
The folder's permissions remain unrestricted.
Thanks!
Use this instead of your if (Directory.Exists(path)) block.
// what is
var existingACL = Directory.GetAccessControl(path);
// remove everything from what is
foreach (FileSystemAccessRule rule in existingACL.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
existingACL.RemoveAccessRuleAll(rule);
// add yours to what is
existingACL.AddAccessRule (fsRule);
// set again
Directory.SetAccessControl(path, existingACL);

Create File and unable users to delete it C#

I am creating a file like this:
System.IO.File.Create("file.dat").Close();
I want to set the file's permissions to disallow users from removing it. I tried the following, but it didn't work:
System.Security.AccessControl.FileSecurity fSecurity = File.GetAccessControl(dirPath + "\\" + fileName);
fSecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule("Administrators",
System.Security.AccessControl.FileSystemRights.Delete, System.Security.AccessControl.AccessControlType.Allow));
File.SetAccessControl(dirPath + "\\" + fileName, fSecurity);
File permissions can be set using System.IO.File.SetAccessControl
See documentation and examples on MSDN: http://msdn.microsoft.com/en-us/library/system.io.file.setaccesscontrol.aspx
To deny delete permissons to all users but administrators you can use this code
FileSecurity fSecurity = File.GetAccessControl(fileName);
AuthorizationRuleCollection rules = fSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
foreach (AuthorizationRule rule in rules)
{
System.Security.Principal.NTAccount account =
(System.Security.Principal.NTAccount)rule.IdentityReference.Translate(typeof(System.Security.Principal.NTAccount));
if (account.Value != "BUILTIN\\Administrators")
{
fSecurity.AddAccessRule(new FileSystemAccessRule(account.Value, FileSystemRights.Delete, AccessControlType.Deny));
}
}
File.SetAccessControl(fileName, fSecurity);

Retrieve security permissions for a Security Group from Active Directory

I am trying to create a function where I input a Security Group name and return a list of the security permissions.
How do I get a list of security permissions like read, write, full control etc. for a Security Group such as Domain Controllers, Domain Guests, etc. from Active Directory using C#?
You need to check the path of the LDAP connection that you are making to communicate with the Active Directory server.
For example:
DirectoryEntry rootDSE = null;
rootDSE = new DirectoryEntry("LDAP://OU=" + department + ",OU=Users,OU=" + ou + ",dc=corp,dc=local", username, password);
Now in that case I need only groups that exist in Department → Users → OU → DC
Same as in your case. You can define on which OU your security group exist.
After that I can fetch a group like this:
DirectorySearcher ouSearch = new DirectorySearcher(rootDSE);
ouSearch.PageSize = 1001;
ouSearch.Filter = "(objectClass=group)";
ouSearch.SearchScope = SearchScope.Subtree;
ouSearch.PropertiesToLoad.Add("name");
SearchResultCollection allOUS = ouSearch.FindAll();
foreach (SearchResult oneResult in allOUS)
{
dt.Rows.Add(oneResult.Properties["name"][0].ToString());
}
rootDSE.Dispose();
Now in case of permissions
Permissions are stored on the individual file system items, e.g. files and/or directories - or other objects (like registry keys, etc.). When you have an AD group or user account, you can read its SID (Security Identifier) property - that SID will show up in ACLs (Access Control Lists) all over Windows - but from the user or group, there's no mechanism to get all permissions it might have anywhere in the machine/server.
Permissions for files and directories can e.g. be retrieved using the .GetAccessControl() method on the FileInfo and DirectoryInfo classes:
FileInfo info = new FileInfo(#"D:\test.txt");
FileSecurity fs = info.GetAccessControl();
DirectoryInfo dir = new DirectoryInfo(#"D:\test\");
DirectorySecurity ds = dir.GetAccessControl();
I hope this is what you are looking for!

Creating XML file with write access given to all the windows account users

I am creating an XML file in the common application folder using C#:
%ALLUSERSPROFILE%\Application Data\
File will be created when application is installed. This file is something that is common to all the users of the local machine.(i.e it contains some setting information)
But my problem is when the file is created by an admin user(i.e application is installed by an admin user) the other users don't have write access to the file. When I checked the attributes of the file, it has given only 'read and execute' is given to other users.
I am using below code to save the file
XDocument.Save(filePath);
Is it possible to create file with write access given to all users? Any help much appreciated!
You can't pass information about ACL into XDocument.Save method, but you can modify permissions of file after saving your xml document. You can use the following code to perform it (don't forget to add reference to System.Security.dll):
using System.Security.AccessControl;
using System.Security.Principal;
using System.IO;
public class FileAccessRulesHelper
{
public void AddWriteRightsToEveryone(string filename)
{
// get sid of everyone group
SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
// create rule
FileSystemAccessRule rule = new FileSystemAccessRule(sid, FileSystemRights.Write, AccessControlType.Allow);
// get ACL of file
FileSecurity fsecurity = File.GetAccessControl(filename);
// modify ACL of file
fsecurity.AddAccessRule(rule);
// apply modified ACL to file
File.SetAccessControl(filename, fsecurity);
}
}
I don't think you can pass a parameter to XDocument.Save to control the permissions but you should be able to set them after the save. Something like the following should do:
System.Security.AccessControl.FileSecurity fsec = System.IO.File.GetAccessControl(fileName);
fsec.AddAccessRule( new System.Security.AccessControl.FileSystemAccessRule("Everyone", System.Security.AccessControl.FileSystemRights.Modify, System.Security.AccessControl.AccessControlType.Allow));
System.IO.File.SetAccessControl(fileName, fsec);
I had a similar problem with a service install. You can use the following code to give a folder different permissions.
public static void CreateWithFullAccess(string targetDirectory)
{
try
{
if (!Directory.Exists(targetDirectory))
{
Directory.CreateDirectory(targetDirectory);
}
DirectoryInfo info = new DirectoryInfo(targetDirectory);
SecurityIdentifier allUsersSid =
new SecurityIdentifier(WellKnownSidType.LocalServiceSid,
null);
DirectorySecurity security = info.GetAccessControl();
security.AddAccessRule(
new FileSystemAccessRule(allUsersSid,
FileSystemRights.FullControl,
AccessControlType.Allow));
info.SetAccessControl(security);
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
}
}

Categories

Resources