透過 System.Management 命名空間存取 WMI Win32_LogicalFileSecuritySetting 類別,可讀取任意檔案/目錄的 DACL(自主存取控制清單)與擁有者資訊。本文提供完整可執行範例。
using System;
using System.Management;
using System.Collections;
class Tester
{
public static void Main()
{
try
{
ManagementPath path = new ManagementPath();
path.Server = ".";
path.NamespacePath = @"root\cimv2";
path.RelativePath = @"Win32_LogicalFileSecuritySetting.Path='c:\\test'"; // 雙反斜線跳脫
ManagementObject lfs = new ManagementObject(path);
// 列出所有 Trustee (含擁有者)
foreach (ManagementBaseObject b in lfs.GetRelated())
Console.WriteLine("Trustee: {0} SID [{1}]", b["AccountName"], b["SID"]);
// 取得 Security Descriptor
ManagementBaseObject outParams = lfs.InvokeMethod("GetSecurityDescriptor", null, null);
if ((uint)outParams.Properties["ReturnValue"].Value == 0)
{
ManagementBaseObject sd = (ManagementBaseObject)outParams.Properties["Descriptor"].Value;
DumpACEs((ManagementBaseObject[])sd.Properties["Dacl"].Value);
DumpOwner((ManagementBaseObject)sd.Properties["Owner"].Value);
}
}
catch (Exception ex) { Console.WriteLine(ex); }
Console.ReadLine();
}
static void DumpACEs(ManagementBaseObject[] dacl)
{
string[] maskNames = { "FILE_READ_DATA", "FILE_WRITE_DATA", "FILE_APPEND_DATA", "FILE_READ_EA",
"FILE_WRITE_EA", "FILE_EXECUTE", "FILE_DELETE_CHILD", "FILE_READ_ATTRIBUTES",
"FILE_WRITE_ATTRIBUTES", "", "", "", "", "", "", "",
"DELETE", "READ_CONTROL", "WRITE_DAC", "WRITE_OWNER",
"SYNCHRONIZE", "", "", "", "ACCESS_SYSTEM_SECURITY", "MAXIMUM_ALLOWED", "", "",
"GENERIC_ALL", "GENERIC_EXECUTE", "GENERIC_WRITE", "GENERIC_READ" };
foreach (ManagementBaseObject ace in dacl)
{
Console.WriteLine("-------------------------------------------------");
Console.WriteLine("Mask: 0x{0:X} AceFlags: {1} AceType: {2}",
ace["AccessMask"], ace["AceFlags"], ace["AceType"]);
Console.WriteLine(ace["AceType"].ToString() == "1" ? "DENIED ACE" : "ALLOWED ACE");
ManagementBaseObject trustee = (ManagementBaseObject)ace["Trustee"];
Console.WriteLine("Name: {0} Domain: {1} SID: {2}",
trustee["Name"], trustee["Domain"], trustee["SIDString"]);
uint mask = (uint)ace["AccessMask"];
BitArray bits = new BitArray(new int[] { (int)mask });
int i = 0;
foreach (bool bit in bits)
{
if (bit && i < maskNames.Length)
Console.WriteLine(" [{0}]", maskNames[i]);
i++;
}
}
}
static void DumpOwner(ManagementBaseObject owner)
{
Console.WriteLine("=============== Owner ===============");
Console.WriteLine("Domain: {0} Name: {1} SID: {2}",
owner["Domain"], owner["Name"], owner["SidString"]);
}
}
| 類別/方法 | 用途 |
|---|---|
Win32_LogicalFileSecuritySetting | 代表檔案/目錄安全性設定 |
GetSecurityDescriptor() | 取得包含 Owner、Group、DACL、SACL 的描述子 |
GetRelated() | 列舉關聯的 Trustee (SID、帳號名稱) |
AceType = 0:Access AllowedAceType = 1:Access DeniedAceType = 2:System AuditSystem.Management.dll