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.
 
 

256 lines
14 KiB

  1. /* Copyright (C) 2008-2016 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
  2. *
  3. * Permission is hereby granted, free of charge, to any person obtaining a copy
  4. * of this software and associated documentation files (the "Software"), to deal
  5. * in the Software without restriction, including without limitation the rights
  6. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. * copies of the Software, and to permit persons to whom the Software is
  8. * furnished to do so, subject to the following conditions:
  9. *
  10. * The above copyright notice and this permission notice shall be included in
  11. * all copies or substantial portions of the Software.
  12. *
  13. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. * THE SOFTWARE.
  20. */
  21. using System;
  22. using System.Diagnostics.CodeAnalysis;
  23. using System.IO;
  24. using System.Runtime.InteropServices;
  25. using System.Security;
  26. using System.Security.AccessControl;
  27. using Alphaleonis.Win32.Security;
  28. using Microsoft.Win32.SafeHandles;
  29. namespace Alphaleonis.Win32.Filesystem
  30. {
  31. partial class File
  32. {
  33. /// <summary>Gets a <see cref="FileSecurity"/> object that encapsulates the access control list (ACL) entries for a specified file.</summary>
  34. /// <returns>A <see cref="FileSecurity"/> object that encapsulates the access control rules for the file described by the <paramref name="path"/> parameter.</returns>
  35. /// <exception cref="IOException"/>
  36. /// <exception cref="ArgumentException"/>
  37. /// <exception cref="ArgumentNullException"/>
  38. /// <param name="path">The path to a file containing a <see cref="FileSecurity"/> object that describes the file's access control list (ACL) information.</param>
  39. [SecurityCritical]
  40. public static FileSecurity GetAccessControl(string path)
  41. {
  42. return GetAccessControlCore<FileSecurity>(false, path, AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner, PathFormat.RelativePath);
  43. }
  44. /// <summary>Gets a <see cref="FileSecurity"/> object that encapsulates the access control list (ACL) entries for a specified file.</summary>
  45. /// <returns>A <see cref="FileSecurity"/> object that encapsulates the access control rules for the file described by the <paramref name="path"/> parameter.</returns>
  46. /// <exception cref="IOException"/>
  47. /// <exception cref="ArgumentException"/>
  48. /// <exception cref="ArgumentNullException"/>
  49. /// <param name="path">The path to a file containing a <see cref="FileSecurity"/> object that describes the file's access control list (ACL) information.</param>
  50. /// <param name="includeSections">One (or more) of the <see cref="AccessControlSections"/> values that specifies the type of access control list (ACL) information to receive.</param>
  51. [SecurityCritical]
  52. public static FileSecurity GetAccessControl(string path, AccessControlSections includeSections)
  53. {
  54. return GetAccessControlCore<FileSecurity>(false, path, includeSections, PathFormat.RelativePath);
  55. }
  56. /// <summary>[AlphaFS] Gets a <see cref="FileSecurity"/> object that encapsulates the access control list (ACL) entries for a specified file.</summary>
  57. /// <returns>A <see cref="FileSecurity"/> object that encapsulates the access control rules for the file described by the <paramref name="path"/> parameter.</returns>
  58. /// <exception cref="IOException"/>
  59. /// <exception cref="ArgumentException"/>
  60. /// <exception cref="ArgumentNullException"/>
  61. /// <param name="path">The path to a file containing a <see cref="FileSecurity"/> object that describes the file's access control list (ACL) information.</param>
  62. /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
  63. [SecurityCritical]
  64. public static FileSecurity GetAccessControl(string path, PathFormat pathFormat)
  65. {
  66. return GetAccessControlCore<FileSecurity>(false, path, AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner, pathFormat);
  67. }
  68. /// <summary>[AlphaFS] Gets a <see cref="FileSecurity"/> object that encapsulates the access control list (ACL) entries for a specified file.</summary>
  69. /// <returns>A <see cref="FileSecurity"/> object that encapsulates the access control rules for the file described by the <paramref name="path"/> parameter.</returns>
  70. /// <exception cref="IOException"/>
  71. /// <exception cref="ArgumentException"/>
  72. /// <exception cref="ArgumentNullException"/>
  73. /// <param name="path">The path to a file containing a <see cref="FileSecurity"/> object that describes the file's access control list (ACL) information.</param>
  74. /// <param name="includeSections">One (or more) of the <see cref="AccessControlSections"/> values that specifies the type of access control list (ACL) information to receive.</param>
  75. /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
  76. [SecurityCritical]
  77. public static FileSecurity GetAccessControl(string path, AccessControlSections includeSections, PathFormat pathFormat)
  78. {
  79. return GetAccessControlCore<FileSecurity>(false, path, includeSections, pathFormat);
  80. }
  81. /// <summary>[AlphaFS] Gets a <see cref="FileSecurity"/> object that encapsulates the access control list (ACL) entries for a specified file handle.</summary>
  82. /// <returns>A <see cref="FileSecurity"/> object that encapsulates the access control rules for the file described by the <paramref name="handle"/> parameter.</returns>
  83. /// <exception cref="IOException"/>
  84. /// <exception cref="ArgumentException"/>
  85. /// <exception cref="ArgumentNullException"/>
  86. /// <param name="handle">A <see cref="SafeHandle"/> to a file containing a <see cref="FileSecurity"/> object that describes the file's access control list (ACL) information.</param>
  87. [SecurityCritical]
  88. public static FileSecurity GetAccessControl(SafeFileHandle handle)
  89. {
  90. return GetAccessControlHandleCore<FileSecurity>(false, false, handle, AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner, SecurityInformation.None);
  91. }
  92. /// <summary>[AlphaFS] Gets a <see cref="FileSecurity"/> object that encapsulates the access control list (ACL) entries for a specified file handle.</summary>
  93. /// <returns>A <see cref="FileSecurity"/> object that encapsulates the access control rules for the file described by the <paramref name="handle"/> parameter.</returns>
  94. /// <exception cref="IOException"/>
  95. /// <exception cref="ArgumentException"/>
  96. /// <exception cref="ArgumentNullException"/>
  97. /// <param name="handle">A <see cref="SafeHandle"/> to a file containing a <see cref="FileSecurity"/> object that describes the file's access control list (ACL) information.</param>
  98. /// <param name="includeSections">One (or more) of the <see cref="AccessControlSections"/> values that specifies the type of access control list (ACL) information to receive.</param>
  99. [SecurityCritical]
  100. public static FileSecurity GetAccessControl(SafeFileHandle handle, AccessControlSections includeSections)
  101. {
  102. return GetAccessControlHandleCore<FileSecurity>(false, false, handle, includeSections, SecurityInformation.None);
  103. }
  104. /// <summary>[AlphaFS] Gets an <see cref="ObjectSecurity"/> object for a particular file or directory.</summary>
  105. /// <returns>An <see cref="ObjectSecurity"/> object that encapsulates the access control rules for the file or directory described by the <paramref name="path"/> parameter.</returns>
  106. /// <exception cref="IOException"/>
  107. /// <exception cref="ArgumentException"/>
  108. /// <exception cref="ArgumentNullException"/>
  109. /// <typeparam name="T">Generic type parameter.</typeparam>
  110. /// <param name="isFolder">Specifies that <paramref name="path"/> is a file or directory.</param>
  111. /// <param name="path">The path to a file/directory containing a <see cref="FileSecurity"/>/<see cref="DirectorySecurity"/> object that describes the file's/directory's access control list (ACL) information.</param>
  112. /// <param name="includeSections">One (or more) of the <see cref="AccessControlSections"/> values that specifies the type of access control list (ACL) information to receive.</param>
  113. /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
  114. [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Disposing is controlled.")]
  115. [SecurityCritical]
  116. internal static T GetAccessControlCore<T>(bool isFolder, string path, AccessControlSections includeSections, PathFormat pathFormat)
  117. {
  118. SecurityInformation securityInfo = CreateSecurityInformation(includeSections);
  119. // We need the SE_SECURITY_NAME privilege enabled to be able to get the SACL descriptor.
  120. // So we enable it here for the remainder of this function.
  121. PrivilegeEnabler privilege = null;
  122. if ((includeSections & AccessControlSections.Audit) != 0)
  123. privilege = new PrivilegeEnabler(Privilege.Security);
  124. using (privilege)
  125. {
  126. IntPtr pSidOwner, pSidGroup, pDacl, pSacl;
  127. SafeGlobalMemoryBufferHandle pSecurityDescriptor;
  128. string pathLp = Path.GetExtendedLengthPathCore(null, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);
  129. // Get/SetNamedSecurityInfo does not work with a handle but with a path, hence does not honor the privileges.
  130. // It magically does since Windows Server 2012 / 8 but not in previous OS versions.
  131. uint lastError = Security.NativeMethods.GetNamedSecurityInfo(pathLp, ObjectType.FileObject, securityInfo,
  132. out pSidOwner, out pSidGroup, out pDacl, out pSacl, out pSecurityDescriptor);
  133. // When GetNamedSecurityInfo() fails with ACCESS_DENIED, try again using GetSecurityInfo().
  134. if (lastError == Win32Errors.ERROR_ACCESS_DENIED)
  135. using (SafeFileHandle handle = CreateFileCore(null, pathLp, ExtendedFileAttributes.BackupSemantics, null, FileMode.Open, FileSystemRights.Read, FileShare.Read, false, PathFormat.LongFullPath))
  136. return GetAccessControlHandleCore<T>(true, isFolder, handle, includeSections, securityInfo);
  137. return GetSecurityDescriptor<T>(lastError, isFolder, pathLp, pSecurityDescriptor);
  138. }
  139. }
  140. internal static T GetAccessControlHandleCore<T>(bool internalCall, bool isFolder, SafeFileHandle handle, AccessControlSections includeSections, SecurityInformation securityInfo)
  141. {
  142. if (!internalCall)
  143. securityInfo = CreateSecurityInformation(includeSections);
  144. // We need the SE_SECURITY_NAME privilege enabled to be able to get the SACL descriptor.
  145. // So we enable it here for the remainder of this function.
  146. PrivilegeEnabler privilege = null;
  147. if (!internalCall && (includeSections & AccessControlSections.Audit) != 0)
  148. privilege = new PrivilegeEnabler(Privilege.Security);
  149. using (privilege)
  150. {
  151. IntPtr pSidOwner, pSidGroup, pDacl, pSacl;
  152. SafeGlobalMemoryBufferHandle pSecurityDescriptor;
  153. uint lastError = Security.NativeMethods.GetSecurityInfo(handle, ObjectType.FileObject, securityInfo,
  154. out pSidOwner, out pSidGroup, out pDacl, out pSacl, out pSecurityDescriptor);
  155. return GetSecurityDescriptor<T>(lastError, isFolder, null, pSecurityDescriptor);
  156. }
  157. }
  158. private static SecurityInformation CreateSecurityInformation(AccessControlSections includeSections)
  159. {
  160. var securityInfo = SecurityInformation.None;
  161. if ((includeSections & AccessControlSections.Access) != 0)
  162. securityInfo |= SecurityInformation.Dacl;
  163. if ((includeSections & AccessControlSections.Audit) != 0)
  164. securityInfo |= SecurityInformation.Sacl;
  165. if ((includeSections & AccessControlSections.Group) != 0)
  166. securityInfo |= SecurityInformation.Group;
  167. if ((includeSections & AccessControlSections.Owner) != 0)
  168. securityInfo |= SecurityInformation.Owner;
  169. return securityInfo;
  170. }
  171. private static T GetSecurityDescriptor<T>(uint lastError, bool isFolder, string path, SafeGlobalMemoryBufferHandle securityDescriptor)
  172. {
  173. ObjectSecurity objectSecurity;
  174. using (securityDescriptor)
  175. {
  176. if (lastError == Win32Errors.ERROR_FILE_NOT_FOUND || lastError == Win32Errors.ERROR_PATH_NOT_FOUND)
  177. lastError = isFolder ? Win32Errors.ERROR_PATH_NOT_FOUND : Win32Errors.ERROR_FILE_NOT_FOUND;
  178. // If the function fails, the return value is zero.
  179. if (lastError != Win32Errors.ERROR_SUCCESS)
  180. {
  181. if (!Utils.IsNullOrWhiteSpace(path))
  182. NativeError.ThrowException(lastError, path);
  183. else
  184. NativeError.ThrowException((int) lastError);
  185. }
  186. if (!NativeMethods.IsValidHandle(securityDescriptor, false))
  187. throw new IOException(Resources.Returned_Invalid_Security_Descriptor);
  188. uint length = Security.NativeMethods.GetSecurityDescriptorLength(securityDescriptor);
  189. // Seems not to work: Method .CopyTo: length > Capacity, so an Exception is thrown.
  190. //byte[] managedBuffer = new byte[length];
  191. //pSecurityDescriptor.CopyTo(managedBuffer, 0, (int) length);
  192. byte[] managedBuffer = securityDescriptor.ToByteArray(0, (int) length);
  193. objectSecurity = isFolder ? (ObjectSecurity) new DirectorySecurity() : new FileSecurity();
  194. objectSecurity.SetSecurityDescriptorBinaryForm(managedBuffer);
  195. }
  196. return (T) (object) objectSecurity;
  197. }
  198. }
  199. }