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.

67 rivejä
2.4 KiB

  1. using Alphaleonis.Win32.Filesystem;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6. using System.Security.AccessControl;
  7. using System.Text;
  8. namespace Security2
  9. {
  10. internal partial class Win32
  11. {
  12. public static List<string> GetInheritedFrom(string path, ObjectSecurity sd, bool isContainer)
  13. {
  14. var inheritedFrom = new List<string>();
  15. path = Path.GetLongPath(path);
  16. uint returnValue = 0;
  17. GENERIC_MAPPING genericMap = new GENERIC_MAPPING();
  18. genericMap.GenericRead = (uint)MappedGenericRights.FILE_GENERIC_READ;
  19. genericMap.GenericWrite = (uint)MappedGenericRights.FILE_GENERIC_WRITE;
  20. genericMap.GenericExecute = (uint)MappedGenericRights.FILE_GENERIC_EXECUTE;
  21. genericMap.GenericAll = (uint)MappedGenericRights.FILE_GENERIC_ALL;
  22. var sdBytes = sd.GetSecurityDescriptorBinaryForm();
  23. var commonSd = new CommonSecurityDescriptor(isContainer, false, sdBytes, 0);
  24. var aclBytes = new byte[commonSd.DiscretionaryAcl.BinaryLength];
  25. commonSd.DiscretionaryAcl.GetBinaryForm(aclBytes, 0);
  26. var pInheritInfo = Marshal.AllocHGlobal(commonSd.DiscretionaryAcl.Count * Marshal.SizeOf(typeof(PINHERITED_FROM)));
  27. returnValue = GetInheritanceSource(
  28. path,
  29. ResourceType.FileObject,
  30. SECURITY_INFORMATION.DACL_SECURITY_INFORMATION,
  31. isContainer,
  32. IntPtr.Zero,
  33. 0,
  34. aclBytes,
  35. IntPtr.Zero,
  36. ref genericMap,
  37. pInheritInfo
  38. );
  39. if (returnValue != 0)
  40. {
  41. throw new System.ComponentModel.Win32Exception((int)returnValue);
  42. }
  43. for (int i = 0; i < commonSd.DiscretionaryAcl.Count; i++)
  44. {
  45. var inheritInfo = pInheritInfo.ElementAt<PINHERITED_FROM>(i);
  46. inheritedFrom.Add(
  47. !string.IsNullOrEmpty(inheritInfo.AncestorName) && inheritInfo.AncestorName.StartsWith(@"\\?\") ? inheritInfo.AncestorName.Substring(4) : inheritInfo.AncestorName
  48. );
  49. }
  50. FreeInheritedFromArray(pInheritInfo, (ushort)commonSd.DiscretionaryAcl.Count, IntPtr.Zero);
  51. Marshal.FreeHGlobal(pInheritInfo);
  52. return inheritedFrom;
  53. }
  54. }
  55. }