Friday, October 22, 2004

Programatically changing file permissions

I'm back to implementing some permission related unit tests that I balked at earlier.

It took me a bit of time to find how to remove all permissions from a file. Since I don't want to have to go through this again I'll post it here.

Basically I'm pulling what I found in Keith Brown's absolute must read wiki: The .NET Developer's Guide to Windows Security in How to program with SIDs into a class.

I implemented it in a typical Resource Acquisition Is Initialization manner using IDispose so that I know I'll restore the permissions to their original after my tests are done.

Here's the class (a little light on error checking for brevity):

class ApplySecuritySettingsToFile : IDisposable

{
#region Private Members
private FileSystemAccessRule m_AccessRule = null;
private FileInfo m_FileInfo = null;
#endregion


#region Constructor
public ApplySecuritySettingsToFile (string fileName,
FileSystemAccessRule accessRule)
{
if (fileName == null && accessRule == null)
return;


m_FileInfo = new FileInfo (fileName);
m_AccessRule = accessRule;


FileSecurity sd = m_FileInfo.GetAccessControl ();
sd.AddAccessRule (m_AccessRule);
m_FileInfo.SetAccessControl (sd);
}
#endregion


#region Dispose pattern
private bool m_bIsDisposed = false;


~ApplySecuritySettingsToFile ()
{
Dispose ();
}


public void Dispose ()
{
if (!m_bIsDisposed)
{
if (m_FileInfo != null && m_AccessRule != null)
{
FileSecurity sd =
m_FileInfo.GetAccessControl ();
sd.RemoveAccessRule (m_AccessRule);
m_FileInfo.SetAccessControl (sd);
}


GC.SuppressFinalize (this);
m_bIsDisposed = true;
}
}
#endregion
}
And here's how you use it to Deny FullControl (i.e. remove all permissions) to file C:\temp\temp.txt for the BUILTIN\users group:
using (new ApplySecuritySettingsToFile (@"C:\temp\temp.txt",

new FileSystemAccessRule (
new SecurityIdentifier (
WellKnownSidType.BuiltinUsersSid,
null),
FileSystemRights.FullControl,
AccessControlType.Deny)
)
)
{
// You (and everyone else for that matter) now have
// no permissions whatsoever to C:\temp\temp.txt

}
You could just as easily add permissions using AccessControlType.Allow.

Hope it helps.

[Listening to: Marilyn Manson - Mother Inferior Got Her Gunn]

No comments: