Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

take ownership of a file c#

I am trying to take ownership of a file and delete it via C#. The file is iexplorer.exe, current owner by default - TrustedInstaller. The method FileSecurity.SetOwner seems to set the specified ownership, but actually doesn't change the initial owner and throws no exception. Obviously, the next attempt to delete the file throws an exception. What should be changed in the code to take ownership of the file and delete it ?

var fileS = File.GetAccessControl(@"C:\Program Files (x86)\Internet Explorer\iexplore.exe");
fileS.SetOwner(new System.Security.Principal.NTAccount(Environment.UserDomainName, Environment.UserName));
File.Delete(@"C:\Program Files (x86)\Internet Explorer\iexplore.exe");
like image 959
alternative Avatar asked Oct 21 '12 15:10

alternative


1 Answers

You must explicitly enable SeTakeOwnershipPrivilege:

Required to take ownership of an object without being granted discretionary access. This privilege allows the owner value to be set only to those values that the holder may legitimately assign as the owner of an object. User Right: Take ownership of files or other objects.

I suggest you to read the great article written by Mark Novak: Manipulate Privileges in Managed Code Reliably, Securely, and Efficiently.

And/or take a look at his sample.

Update

Example usage:

var fileS = File.GetAccessControl(@"C:\Program Files (x86)\Internet Explorer\iexplore.exe");

Privilege p;
bool ownerChanged = false;
try
{
    p = new Privilege(Privilege.TakeOwnership);
    p.Enable();

    fileS.SetOwner(new System.Security.Principal.NTAccount(
        Environment.UserDomainName, Environment.UserName));

    ownerChanged = true;
}
catch(PrivilegeNotHeldException e)
{
   // privilege not held
   // TODO: show an error message, write logs, etc.
}
finally
{
    p.Revert();
}

if (ownerChanged)
    File.Delete(@"C:\Program Files (x86)\Internet Explorer\iexplore.exe");
like image 132
Nikolay Khil Avatar answered Sep 27 '22 23:09

Nikolay Khil