C#, how to prevent user from changing a folder permissions? - c#

I have a folder that I want to protect its contents,
I'm denying full control to it by this code:
void changeFolderPermission(string folder, FileSystemRights rights, AccessControlType type)
{
DirectoryInfo myDirInfo = new DirectoryInfo(folder);
DirectorySecurity myDirSecurity = myDirInfo.GetAccessControl();
string user = System.Environment.UserName;
myDirSecurity.ResetAccessRule(new FileSystemAccessRule(user, rights, type));
myDirInfo.SetAccessControl(myDirSecurity);
}
I'm using it like this:
changeFolderPermission(FolderName, FileSystemRights.FullControl, AccessControlType.Deny);
It's working fine, I mean, when i try to open the folder, it won't let me.
Problem is, I could easily remove that permission by right clicking on the folder,
going to security, look for that special permission and just deleting it ..
is there a way to prevent someone from doing this ?
I want the folder to be fully secured.
Now I know that there's something like this:
hangeFolderPermission(FolderName, FileSystemRights.ChangePermissions, AccessControlType.Deny);
but I'm still being able to change the permissions.
any help would be appreciated .. thanx alot in advance .. :)

You can not prevent a user with admin rights from accessing a folder or file.
If the user does not have admin rights, then set the permissions (via an admin account) to deny the user access. Properly configured permissions will prevent the non-admin user from accessing the folder/file.

You never said anything in your original post about sending the folder to other people. Presumably this sending mechanism involves email, ftp, etc to ANOTHER COMPUTER. Assumption #2 is that your C# program is what will be reading the contents of said folder.
In this case its simple, create a password-protected zip file of your directory and send that. Then embed the password within your C# code and open the zip file and read its contents.
There are several really good zip manipulation libraries out there such as dotnetzip and #ziplib

Related

How can I create a protected directory that I can guarantee has only been modified by a specific user?

I am developing a .NET Windows Service using C# that runs as the SYSTEM user so that it has permissions to install software updates etc.
I want the service to download an executable file to a protected directory and launch it. However, I want to make sure that I've considered security and that it isn't possible for another user to copy a file into the directory that the service uses and then have the file executed with SYSTEM privileges.
I've looked into creating a directory that only the SYSTEM user has access to using an ACL as follows.
var localSystemIdentifier = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
var directorySecurity = new DirectorySecurity();
directorySecurity.AddAccessRule(new FileSystemAccessRule(localSystemIdentifier, FileSystemRights.FullControl, AccessControlType.Allow));
directorySecurity.SetOwner(_localSystemIdentifier);
Directory.CreateDirectory(_pathToTempBootstrapperDirectory, directorySecurity);
Subsequent to this, I check that the owner of the directory is the SYSTEM user before I allow a cached copy of the executable file that has been downloaded to be used.
var acl = Directory.GetAccessControl(_pathToTempBootstrapperDirectory);
if (acl.GetOwner(typeof(SecurityIdentifier)) != localSystemIdentifier)
{
cache = false;
}
However, if a user with the right permissions was able to change the owner of the directory to themselves, copy in a file, and then change the owner back to the SYSTEM user, the above check would not be of any benefit.
Perhaps the only option is to always recreate the download folder with the strict ACL and redownload the file every time to prevent the possibility of the scenario above.
In short, my question is as follows; is there a way that I can create a protected directory that I can guarantee has only ever been created or modified by the SYSTEM user?
if a user with the right permissions was able to change the owner of the directory
If a user has administrative permissions he/she can just do whatever he/she wants without the help from your program. Raymond Chen calls this the "airtight hatchway", i.e. you need to protect against a user doing things he/she would not otherwise be allowed to, but there is no reason to protect against things the user already have permission to do.
I'm not an expert in windows permissions, but think that taking over ownership of a directory owned by SYSTEM requires admin permission.

WPF app writes files/data into "C:\ProgramData" but fails to write into other folders

We have developed WPF application which allows user to select folder path. WPF application writes files/data into this selected path. When we select "C:\ProgramData" as the path, it creates the file and write the data. But when the path is other than "C:\ProgramData", file is generated but data is not written into the file and it seems a permission issue. Can anybody help us in finding out , how we can assign the same kind of permission to selected folder same as "C:\ProgramData" so that it allows to write data into the file. In conclustion what is the extra permission does "ProgramData" has which is not their for other folders?
Note: it only works properly with ProgramData folder.
Whenever your application is launched with standard user rights, it can write to only those folders to which a standard user can write to. E.g. are:
C:\Users\USERNAME\
C:\ProgramData\
D:\
It will not be able to write to folders like:
C:\
C:\Users\SOME_OTHER_USERNAME\
c:\Windows
C:\Windows\System32 etc
For that you either need to disable UAC or launch the application with administrative permissions.
I would suggest that whenever user selects a folder from your application check if you can create a file/ folder in that location before accepting the path.
solution what i can give is let's user select the path after you get the folder path just check whether you can write data to it , see this code
bool HasAccessToWrite(string path)
{
try
{
using (FileStream fs = File.Create(Path.Combine(path, "Access.txt"), 1, FileOptions.DeleteOnClose))
{
}
return true;
}
catch
{
return false;
}
}
#Ganesh is right but you may go with one of the following options:
Run the installer with admin rights, ask user to select target folder during installation and set the permissions to everyone or required groups of users/roles.
If above is not applicable then configure your application to always run under admin account, in that way it will have access to all folder to write data. To configure run as admin user application manifest as explained here:
Turn off UAC, not a recommended approach though.
I had same issue so, I forced installer to be run under admin rights and asked user to create target folders during installation. Used a custom action to set full rights for everyone user group on the target folder. Since security was not issue for us so, it was ok to allow everyone but consider your environment before using this option.

Upload images acces to path denied

Hi I seem to be having a problem when uploading images in asp.net.When I tryed to upload an Image I get this error:
Access to the path 'D:\Projects IDE\Visual Studio\MyWork\Websites\Forum\Images\avatar\userAvatars\aleczandru' is denied.
I have set application pools Identoty to NETWORKSERVICE ando also added the NETWORK SERVICE account to the Images folder with full permision but I still get the same error.
This is my code:
private void addImageToApp()
{
string path = "~/Images/avatar/userAvatars/" + User.Identity.Name;
createPath(path);
if( Directory.Exists(HostingEnvironment.MapPath(path)))
{
//try {
UploadImage.SaveAs(HostingEnvironment.MapPath(path));
// MultiViewIndex.ActiveViewIndex = 0;
//}catch(Exception ex)
//{
// AvatarDetails.Text = ex.Message;
//}
}
}
private void createPath(string path)
{
string activeDir = HostingEnvironment.MapPath("~/Images/avatar/userAvatars");
if( !Directory.Exists(Server.MapPath(path)) )
{
string newPath = Path.Combine(activeDir, User.Identity.Name);
Directory.CreateDirectory(newPath);
}
}
What else can I do to solve this problem?
EDIT
Hi at this point I have full permision control to the following USERS:
Authetificated Users
IUSR
SYSTEM
NETWORK SERVICE
IIS_WPG
Administrator
USers
Is it posible that I need to set any configuration to IIS in order for this to work?
EDIT
I have messed around with SQL-SERVER for the last couple of days in order to make this work so I might have missconfigured something form what I understand NETWORK SERVICE is stored in SQL-SERVER master.db database.I seem to be having two network service logins may this be the problem?I remember when I first checked it I had none now I have two:
EDIT
This is the print with the permisions I added to the folder:
EDIT : Complete error
StackTrace:
In method CreatePath you are creating folder 'D:\Projects IDE\Visual Studio\MyWork\Websites\Forum\Images\avatar\userAvatars\aleczandru'.
Then, you try to save the uploaded image with the filename 'D:\Projects IDE\Visual Studio\MyWork\Websites\Forum\Images\avatar\userAvatars\aleczandru'.
You can't have a folder and a file with the same name. If you try to do this, the OS will tell you access is denied.
I suppose you want to either create a filename inside folder aleczandru, or you meant to save the file as aleczandru.png or something in folder userAvatars.
Assuming your UploadImage is a FileUpload control, you can save the file to the user's folder using the original file name of the uploaded file.
UploadImage.SaveAs(HostingEnvironment.MapPath(
Path.Combine(path, UploadImage.FileName)));
Pls make sure you have full filename with file extention in you path.
Ok... I have done this before for a project to implement a PUT method for http. I dont clearly remember it.. but some hints... if I were in my office I could tell you correctly. here are the hints
You need to add IIS_IUSRS to have access to the folder in windows.
Go to IIS admin console click the deployed site node, and set the permission for the same folder/website requests coming in... I dont remember the which category was it.. that settings pane will allow you to add/modify permissions for POST, GET and other verbs for that matter... when you edit that, you should see options for Administrator, a particular user account, anonymous etc.
may be I will write back tomorrow... exactly how to do it :-)
Try to give the group called users the permission to modify this directory (under security)
You need to find out what user the asp.net upload page is running under. If you haven't changed it, and are not running under impersonation, it should default to the ASPNET user on the local machine. Whatever it turns out to be, give that user read/write permissions on the folder.

Access denied error

I am trying to delete the excel file from a specipic location . but can't deleting. having error :
Access to the path 'C:\mypath\sample.xlsx' is denied.
I write a code as :
protected void imgbtnImport_Click(object sender, ImageClickEventArgs e)
{
try
{
string strApplicationPath = HttpContext.Current.Request.MapPath(HttpContext.Current.Request.ApplicationPath);
string strXLStoredDirectoryPath = strApplicationPath + "/Information Documents/";
DirectoryInfo di = new DirectoryInfo(strXLStoredDirectoryPath);
string fileName = flUpldSelectFile.FileName;
if (!File.Exists(strXLStoredDirectoryPath))
{
Directory.CreateDirectory(strXLStoredDirectoryPath);
di.Attributes = FileAttributes.Normal;
}
string strCreateXLFileDestinationPath = strXLStoredDirectoryPath + fileName;
if (File.Exists(strCreateXLFileDestinationPath))
{
File.Delete(strCreateXLFileDestinationPath);
}
flUpldSelectFile.SaveAs(strCreateXLFileDestinationPath);
di.Attributes = FileAttributes.ReadOnly;
}
catch (Exception)
{
throw;
}
}
please guide.........
-***********************************************************************
Still problem there . it is not resolved . getting UnauthorizedAccessException. as access denied to deleting file. I m tired now . please help; I tried many things..please help
-***********************************************************************
Is may be iffect of VSS ? i am using that
UPDATE:
Part of your issue might be what is saving/creating this file. If you're using a built in "Save" or "SaveAs" feature the underlying file stream might still have a lock on the file. writing your own save logic with a FileStream wrapped in a Using statement will help dispose the stream right when you're done thus allowing you to further manipulate the file within the same context.
if flUpldSelectFile.SaveAs(strCreateXLFileDestinationPath); is the only logic that saves the file then get rid of the built in SaveAs functionality. write your own save logic using a FileStream wrapped in a Using block.
In your example i can't see what flUpldSelectFile is so i am assuming it is a System.Web.UI.WebControls.FileUpload control. Here is an example of rolling your own save logic.
using (FileStream fs = new FileStream(strCreateXLFileDestinationPath, FileMode.Create))
{
byte[] buffer = flUpldSelectFile.FileBytes;
fs.Write(buffer, 0, buffer.Length);
}
As stated previously, use this tool to find out if there is a lock on the file by another process.
ORIGINAL
Pop open this wonderful tool and search for that file to see who/what has it locked
http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx
(source: microsoft.com)
If your code is working under IIS , Note that ASPNET user doesn't have access to computer files, you should give access to it, that is not recommended, or store you files in the place where ASPNET user have access
see here
Try a combination of these 2 steps:
Set the IIS application pool to run under an account with privileges such as a domain account or local user account (not a default account like local service or local system). Instructions for IIS7.
Turn impersonation on in the web.config file, in the <system.web> section:
<identity impersonate="true"/>
<identity impersonate="true" userName="contoso\Jane" password="password"/>
I think the message is clear, you do not have authorization to delete the file or it is opened by another application. I bet 2$ you can't delete the file manually either.
As others have said, this is because IIS runs your application as a user with restricted access rights. This is a wise security precaution, so that your system is less vulnerable to malicious attacks.
What you need to do is to give the ASPNET user access to the specific folder. You do that from the security tab in the properties of a folder. The user you need to give full control to depends on the version of IIS you are using. In Windows XP it is ASPNET. In Windows Server 2003, 2008 and Windows Vista, 7 it is NETWORK_SERVICE.
See also this question for more details.
Make sure the file isn't opened or
locked by another user/process.
Make sure ASPNET user has access on the file\folder (check the file\folder's property using windows explorer and go to security tab. check if ASPNET user is added there).
One of two things are happening. Either the file is already open, or the permission of the user running IIS does not have the proper permissions.
Either way, this utility ProcMon: Proc Mon
will help you determine the issue. Run ProcMon, kick off your process to try and delete the file. Then go back to procmon. Hit Ctrl-E to turn off the capture, then Ctrl-F to find. Enter the name of the file you're trying to delete. Then once you've found the correct line with the access denied (or similar error) Double click on the the line to get further information. When you click on the Process tab, it will show you the exact user that is trying to delete the file.
So, if it is a file permission issue, you now know the exact user, and can therefore go to the file system right click on the folder that houses the file you are trying to delete, and grant that user permissions to read/write/update that folder.
Second, if the file is locked open instead of a permissions issue, you will have to find out what process is holding open the file. If you are also writing this file in another part of your code, perhaps you are not closing it properly or releasing the object reference.
Have you verified that the file does not have the read-only attribute set?
I don't think we have enough info to be helpful. What is the security context (identity) during the call to Delete? Is the application impersonating the end user? If it is, how are they authenticated? If by Windows / Active Directory, then you'll need to verify that user's access rights to the specific file. If by Forms login, then you should probably not impersonate and verify that the AppPool's security context has the appropriate access rights.

File Access Denied

I am using an FTPClient library to transfer files from a Windows share to an FTP server.
The SendFile method of the library uses the following code:
FileStream stream = new FileStream(localFileName, FileMode.Open);
This results in a System.UnauthorizedAccessException being thrown, however I am able to open, rename, and move the file using Windows Explorer under the same user account which the code is being executed.
Can anyone tell me why this is happening?
Edit:
The strange thing is that I can access other files on the share which have been granted the same NTFS permissions as the one that I can't.
This is also a Windows forms app.
Update:
Still no luck with this. I am able to read the file using a StreamReader but not a file stream. I can't understand why the two behave differently.
Are you sure it's the same user account?
Can you try something like
MessageBox.Show(WindowsIdentity.GetCurrent().Name);
?
Also, are you sure the file isn't read-only? Do you need write access to the file?
Otherwise you could try:
FileStream stream = new FileStream(localFileName, FileMode.Open, FileAccess.Read);
The process that is running your code does not have permissions on the file.
Is it part of a web application - if so you need to give access to the ASPNET account.
Give permission to 'everyone' on the file, and see if it still has problems.
Is your project being run from a network drive? If so that that will mean it runs in a restricuted priviliges mode that could cause this. Try copying the project to your C drive and running it again.
It's near FileSecurity class.
See at FileSecurity class
and try:
// Get a FileSecurity object that represents the
// current security settings.
FileSecurity fSecurity = File.GetAccessControl(localFileName);
// Add the FileSystemAccessRule to the security settings.
fSecurity.AddAccessRule(new FileSystemAccessRule("DOMAIN\USERNAME",
FileSystemRights.ReadData, AccessControlType.Allow));
// Set the new access settings.
File.SetAccessControl(localFileName, fSecurity);
1) NTFS permissions on the physical directory using explorer
2) Within the IIS MMC console FTP Site to allow read/write on the FTP folder
3) Ensure that the FTP Site or virtual directory actually exists, when checking the above step
http://www.eggheadcafe.com/forumarchives/inetserveriisftp/Jan2006/post25322215.asp

Categories