You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

62 lines
2.5 KiB

  1. using Alphaleonis.Win32.Filesystem;
  2. using System.Collections.Generic;
  3. using System.Security.AccessControl;
  4. using System.Security.Principal;
  5. namespace Security2
  6. {
  7. public partial class FileSystemAuditRule2
  8. {
  9. public static IEnumerable<FileSystemAuditRule2> GetFileSystemAuditRules(FileSystemInfo item, bool includeExplicit, bool includeInherited, bool getInheritedFrom = false)
  10. {
  11. var sd = new FileSystemSecurity2(item);
  12. return GetFileSystemAuditRules(sd, includeExplicit, includeInherited, getInheritedFrom);
  13. }
  14. public static IEnumerable<FileSystemAuditRule2> GetFileSystemAuditRules(FileSystemSecurity2 sd, bool includeExplicit, bool includeInherited, bool getInheritedFrom = false)
  15. {
  16. List<FileSystemAuditRule2> aceList = new List<FileSystemAuditRule2>();
  17. List<string> inheritedFrom = null;
  18. if (getInheritedFrom)
  19. {
  20. inheritedFrom = Win32.GetInheritedFrom(sd.Item, sd.SecurityDescriptor);
  21. }
  22. var aceCounter = 0;
  23. var acl = !sd.IsFile ?
  24. ((DirectorySecurity)sd.SecurityDescriptor).GetAuditRules(includeExplicit, includeInherited, typeof(SecurityIdentifier)) :
  25. ((FileSecurity)sd.SecurityDescriptor).GetAuditRules(includeExplicit, includeInherited, typeof(SecurityIdentifier));
  26. foreach (FileSystemAuditRule ace in acl)
  27. {
  28. var ace2 = new FileSystemAuditRule2(ace) { FullName = sd.Item.FullName, InheritanceEnabled = !sd.SecurityDescriptor.AreAccessRulesProtected };
  29. if (getInheritedFrom)
  30. {
  31. ace2.inheritedFrom = string.IsNullOrEmpty(inheritedFrom[aceCounter]) ? "" : inheritedFrom[aceCounter].Substring(0, inheritedFrom[aceCounter].Length - 1);
  32. aceCounter++;
  33. }
  34. aceList.Add(ace2);
  35. }
  36. return aceList;
  37. }
  38. public static IEnumerable<FileSystemAuditRule2> GetFileSystemAuditRules(string path, bool includeExplicit, bool includeInherited)
  39. {
  40. if (File.Exists(path))
  41. {
  42. var item = new FileInfo(path);
  43. return GetFileSystemAuditRules(item, includeExplicit, includeInherited);
  44. }
  45. else
  46. {
  47. var item = new DirectoryInfo(path);
  48. return GetFileSystemAuditRules(item, includeExplicit, includeInherited);
  49. }
  50. }
  51. }
  52. }