Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I programmatically change the security attributes of a file so that any user can delete the file

Tags:

c#

file

security

I have a server written in C# that makes use of impersonation.

I would like to know how I can change the security attributes of a file so that any user can delete it.

My server impersonates a user and then creates a temporary file. Later on I need to delete the file but at that point, I am no longer impersonating the user that created the file and when an attempt is made to delete the file an exception is generated. My supposition is that at the time I create the file, I should be able to change the security attributes to allow any user to delete the file.

How may I accomplish this (C# preferred but p/invoke will work too).

I am currently using .NET 1.1, so a method that can be implemented in 1.1 would be appreciated.

like image 603
jmatthias Avatar asked Mar 01 '23 00:03

jmatthias


2 Answers

It sounds like you want to use the System.IO.File.SetAccessControl method to add an ACL that gives the built-in "Everyone" group the ability to delete the file. The MSDN documentation has a decent sample of adding and removing ACL records on a file.

like image 168
scwagner Avatar answered Mar 05 '23 16:03

scwagner


Instead of allowing everyone delete the file, why not add entries for just the people who need to delete the file. Based on your post, that would likely be your user account and the originating process. Allowing literally everyone to delete the file opens yourself up to security problems down the road.

public static void AllowIdentityToDelete(FileInfo file, string identity)
{
    var rule = new FileSystemAccessRule(
        identity,
        FileSystemRights.Delete | FileSystemRights.DeleteSubdirectoriesAndFiles,
        AccessControlType.Allow);

    var acls = file.GetAccessControl();
    acls.AddAccessRule(rule);
    file.SetAccessControl(acls);
}

You'll need to pass in the proper Identity for the user in question.

like image 44
JaredPar Avatar answered Mar 05 '23 16:03

JaredPar