static void EnumRights()
{
uint length = 0;
bool res;
// first call gets lenght of TokenInformation
res = GetTokenInformation(WindowsIdentity.GetCurrent().Token, TOKEN_INFORMATION_CLASS.TokenPrivileges, IntPtr.Zero, length, out length);
IntPtr tokenInformation = Marshal.AllocHGlobal(unchecked((int)length));
res = GetTokenInformation(WindowsIdentity.GetCurrent().Token, TOKEN_INFORMATION_CLASS.TokenPrivileges, tokenInformation, length, out length);
if (res)
{
TOKEN_PRIVILEGES privs = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(tokenInformation, typeof(TOKEN_PRIVILEGES));
for (int i = 0; i < privs.Count; i++)
{
IntPtr ptr = new IntPtr(tokenInformation.ToInt64() + sizeof(uint) + i * Marshal.SizeOf(typeof(LUID_AND_ATTRIBUTES)));
LUID_AND_ATTRIBUTES privInfo = (LUID_AND_ATTRIBUTES)Marshal.PtrToStructure(ptr, typeof(LUID_AND_ATTRIBUTES));
StringBuilder name = new StringBuilder();
IntPtr luidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LUID)));
Marshal.StructureToPtr(privInfo.Luid, luidPtr, false);
int size = 0;
LookupPrivilegeName(null, luidPtr, null, ref size);
name.EnsureCapacity(size);
LookupPrivilegeName(null, luidPtr, name, ref size);
Marshal.FreeHGlobal(luidPtr);
Console.WriteLine(name.ToString());
}
}
Marshal.FreeHGlobal(tokenInformation);
}
#region Interop
[StructLayout(LayoutKind.Sequential)]
struct LUID
{
public uint LowPart;
public int HighPart;
}
[StructLayout(LayoutKind.Sequential)]
struct LUID_AND_ATTRIBUTES
{
public LUID Luid;
public uint Attributes;
}
[StructLayout(LayoutKind.Sequential)]
struct TOKEN_PRIVILEGES
{
public uint Count;
//public IntPtr Privileges; //array of LUID_AND_ATTRIBUTES
}
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool GetTokenInformation(
IntPtr TokenHandle,
TOKEN_INFORMATION_CLASS TokenInformationClass,
IntPtr TokenInformation,
uint TokenInformationLength,
out uint ReturnLength);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool LookupPrivilegeName(
string lpSystemName,
IntPtr lpLuid,
System.Text.StringBuilder lpName,
ref int cchName);
#endregion