Directory security audit

First, we will have to add the proper namespaces to our project.

using System.Security.Principal;
using System.Security.AccessControl;

Next we will write a recursive function to traverse the directories in a given parent folder.

private void TraverseDirectories(string srcDir)
{
	string[] subdirEntries = Directory.GetDirectories(srcDir);

	foreach (string subDir in subdirEntries)
	{
		GetDirSecurity(subDir);
		TraverseDirectories(subDir);
	}
}

You will see that in our foreach loop, we call the GetDirSecurity function for each sub directory. Let’s take a look at what that function does.

private void GetDirSecurity(string srcDir)
{
	try
	{
		DirectorySecurity ds = Directory.GetAccessControl(srcDir, AccessControlSections.Access);
		AuthorizationRuleCollection arc = ds.GetAccessRules(true,true, typeof(NTAccount));

		foreach (FileSystemAccessRule fsar in arc)
		{
			/*
			HANDLE OUTPUT HERE
			fsar.IdentityReference.Value;
			fsar.FileSystemRights.ToString();
			fsar.AccessControlType.ToString();
			fsar.IsInherited.ToString();
			*/
		}
	}
	catch (Exception e)
	{
		//HANDLE EXCEPTION
	}
}

In the GetDirSecurity function, we pass it the directory that we wish to view the security. It creates a directory security object, then creates a collection of rules from that object. We then loop through the collection and view the rules on the directory object. Enjoy!