25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

81 lines
2.8 KiB

  1. using Alphaleonis.Win32.Filesystem;
  2. using Security2;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Management.Automation;
  7. namespace NTFSSecurity
  8. {
  9. [Cmdlet(VerbsCommon.Get, "NTFSOrphanedAccess")]
  10. [OutputType(typeof(FileSystemAccessRule2))]
  11. public class GetOrphanedAccess : GetAccess
  12. {
  13. int orphanedSidCount = 0;
  14. protected override void ProcessRecord()
  15. {
  16. IEnumerable<FileSystemAccessRule2> acl = null;
  17. FileSystemInfo item = null;
  18. foreach (var path in paths)
  19. {
  20. try
  21. {
  22. item = this.GetFileSystemInfo2(path);
  23. }
  24. catch (Exception ex)
  25. {
  26. this.WriteError(new ErrorRecord(ex, "ReadFileError", ErrorCategory.OpenError, path));
  27. continue;
  28. }
  29. try
  30. {
  31. acl = FileSystemAccessRule2.GetFileSystemAccessRules(item, !ExcludeExplicit, !ExcludeInherited, getInheritedFrom);
  32. }
  33. catch (UnauthorizedAccessException)
  34. {
  35. try
  36. {
  37. var ownerInfo = FileSystemOwner.GetOwner(item);
  38. var previousOwner = ownerInfo.Owner;
  39. FileSystemOwner.SetOwner(item, System.Security.Principal.WindowsIdentity.GetCurrent().User);
  40. acl = FileSystemAccessRule2.GetFileSystemAccessRules(item, !ExcludeExplicit, !ExcludeInherited, getInheritedFrom);
  41. FileSystemOwner.SetOwner(item, previousOwner);
  42. }
  43. catch (Exception ex2)
  44. {
  45. this.WriteError(new ErrorRecord(ex2, "AddAceError", ErrorCategory.WriteError, path));
  46. }
  47. }
  48. catch (Exception ex)
  49. {
  50. this.WriteWarning(string.Format("Could not read item {0}. The error was: {1}", path, ex.Message));
  51. }
  52. finally
  53. {
  54. if (acl != null)
  55. {
  56. var orphanedAces = acl.Where(ace => string.IsNullOrEmpty(ace.Account.AccountName));
  57. orphanedSidCount += orphanedAces.Count();
  58. WriteVerbose(string.Format("Item {0} knows about {1} orphaned SIDs in its ACL", path, orphanedAces.Count()));
  59. orphanedAces.ForEach(ace => WriteObject(ace));
  60. }
  61. }
  62. }
  63. }
  64. protected override void EndProcessing()
  65. {
  66. WriteVerbose(string.Format("Total orphaned Access Control Enties: {0}", orphanedSidCount));
  67. base.EndProcessing();
  68. }
  69. }
  70. }