OdeToCode IC Logo

What's Wrong With This Code? (#9)

Tuesday, December 5, 2006

Jill Developer has a new assignment. She needs code that will overwrite data in a sensitive file. Only the local machine administrator has access to the file, but Jill plans to impersonate the admin account to gain access to the file.

Jill first builds a static class to PInvoke LogonUser and start the impersonation. This class (Utility), and it's method (ImpersonateAdministrator) work well. Jill's next step is to write the following code:

public void WriteToSensitiveFile(string path, byte[] data)
{
    
WindowsImpersonationContext impersonationContext = null;
    impersonationContext =
Utility.ImpersonateAdministrator();

    
try
    {
        
using (FileStream fs = File.OpenWrite(path))
        {
            fs.Write(data, 0, data.Length);
        }

    }
    
finally
    {
        
if (impersonationContext != null)
        {
            impersonationContext.Undo();
        }
    }

}

Of course, Jill still has some work ahead to verify the path, the data, and the user who is calling this method. At this early point, however, Jill has one worry she wants to put to rest before moving on - is it possible for a malicious caller to take advantage of the impersonation context and do something other than write to a file?