Skip to content

Instantly share code, notes, and snippets.

@courtarro
Last active September 22, 2015 19:04
Show Gist options
  • Save courtarro/bd36a06673dcb3f25b58 to your computer and use it in GitHub Desktop.
Save courtarro/bd36a06673dcb3f25b58 to your computer and use it in GitHub Desktop.
Recursively reads an entire directory tree and lists any permissions that are not inherited from the parent directory.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
namespace PermCheck {
class PermChecker {
Queue<string> paths = new Queue<string>();
PermChecker() { }
void CheckPaths(string path) {
// Seed the list
path = Path.GetFullPath(path);
paths.Enqueue(path);
while (paths.Count > 0) {
path = paths.Dequeue();
Console.Error.WriteLine(path);
DirectoryInfo dirInfo = new DirectoryInfo(path);
try {
DirectorySecurity dirSec = dirInfo.GetAccessControl();
AuthorizationRuleCollection rules = dirSec.GetAccessRules(true, false, typeof(System.Security.Principal.NTAccount));
foreach (FileSystemAccessRule rule in rules) {
List<string> thisLine = new List<string>();
thisLine.Add(path);
thisLine.Add(rule.IdentityReference.ToString());
thisLine.Add(rule.AccessControlType.ToString());
thisLine.Add(rule.FileSystemRights.ToString());
Console.WriteLine(String.Join(", ", thisLine));
}
} catch (UnauthorizedAccessException) {
List<string> thisLine = new List<string>();
thisLine.Add(path);
thisLine.Add("<error: can't get permissions>");
Console.WriteLine(String.Join(", ", thisLine));
}
// Add any discovered subdirectories
try {
DirectoryInfo[] subdirs = dirInfo.GetDirectories("*", System.IO.SearchOption.TopDirectoryOnly);
foreach (var subdir in subdirs) {
paths.Enqueue(subdir.FullName);
}
} catch (UnauthorizedAccessException) {
List<string> thisLine = new List<string>();
thisLine.Add(path);
thisLine.Add("<error: can't get subdirectories>");
Console.WriteLine(String.Join(", ", thisLine));
}
}
}
static int Main(string[] args) {
// Recursively reads an entire directory tree and lists any permissions that are not inherited from the parent directory.
// Stdout contains a CSV listing of paths and their explicit (non-inherited) permissions, while stderr contains a list of
// each path as it's read. To save the output as a CSV file, just pipe the stdout to a file. Stderr will still be displayed
// to give you a sense of progress.
//
// Example: PermChecker.exe D:\Data > dataperms.csv
string path;
if (args.Length == 0) {
path = ".";
} else if (args.Length == 1) {
path = args[0];
} else {
Console.WriteLine("Usage: " + System.AppDomain.CurrentDomain.FriendlyName + " [pathname]");
return 1;
}
PermChecker pc = new PermChecker();
pc.CheckPaths(path);
return 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment