| 1 |
using Microsoft.Win32.SafeHandles; |
| 2 |
using System; |
| 3 |
using System.Collections.Generic; |
| 4 |
using System.Linq; |
| 5 |
using System.Runtime.InteropServices; |
| 6 |
using System.Security.Principal; |
| 7 |
using System.Text; |
| 8 |
|
| 9 |
namespace Ansible.AccessToken |
| 10 |
{ |
| 11 |
internal class NativeHelpers |
| 12 |
{ |
| 13 |
[StructLayout(LayoutKind.Sequential)] |
| 14 |
public struct LUID_AND_ATTRIBUTES |
| 15 |
{ |
| 16 |
public Luid Luid; |
| 17 |
public UInt32 Attributes; |
| 18 |
} |
| 19 |
|
| 20 |
[StructLayout(LayoutKind.Sequential)] |
| 21 |
public struct SID_AND_ATTRIBUTES |
| 22 |
{ |
| 23 |
public IntPtr Sid; |
| 24 |
public int Attributes; |
| 25 |
} |
| 26 |
|
| 27 |
[StructLayout(LayoutKind.Sequential)] |
| 28 |
public struct TOKEN_PRIVILEGES |
| 29 |
{ |
| 30 |
public UInt32 PrivilegeCount; |
| 31 |
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] |
| 32 |
public LUID_AND_ATTRIBUTES[] Privileges; |
| 33 |
} |
| 34 |
|
| 35 |
[StructLayout(LayoutKind.Sequential)] |
| 36 |
public struct TOKEN_USER |
| 37 |
{ |
| 38 |
public SID_AND_ATTRIBUTES User; |
| 39 |
} |
| 40 |
|
| 41 |
public enum TokenInformationClass : uint |
| 42 |
{ |
| 43 |
TokenUser = 1, |
| 44 |
TokenPrivileges = 3, |
| 45 |
TokenStatistics = 10, |
| 46 |
TokenElevationType = 18, |
| 47 |
TokenLinkedToken = 19, |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
internal class NativeMethods |
| 52 |
{ |
| 53 |
[DllImport("kernel32.dll", SetLastError = true)] |
| 54 |
public static extern bool CloseHandle( |
| 55 |
IntPtr hObject); |
| 56 |
|
| 57 |
[DllImport("advapi32.dll", SetLastError = true)] |
| 58 |
public static extern bool DuplicateTokenEx( |
| 59 |
SafeNativeHandle hExistingToken, |
| 60 |
TokenAccessLevels dwDesiredAccess, |
| 61 |
IntPtr lpTokenAttributes, |
| 62 |
SecurityImpersonationLevel ImpersonationLevel, |
| 63 |
TokenType TokenType, |
| 64 |
out SafeNativeHandle phNewToken); |
| 65 |
|
| 66 |
[DllImport("kernel32.dll")] |
| 67 |
public static extern SafeNativeHandle GetCurrentProcess(); |
| 68 |
|
| 69 |
[DllImport("advapi32.dll", SetLastError = true)] |
| 70 |
public static extern bool GetTokenInformation( |
| 71 |
SafeNativeHandle TokenHandle, |
| 72 |
NativeHelpers.TokenInformationClass TokenInformationClass, |
| 73 |
SafeMemoryBuffer TokenInformation, |
| 74 |
UInt32 TokenInformationLength, |
| 75 |
out UInt32 ReturnLength); |
| 76 |
|
| 77 |
[DllImport("advapi32.dll", SetLastError = true)] |
| 78 |
public static extern bool ImpersonateLoggedOnUser( |
| 79 |
SafeNativeHandle hToken); |
| 80 |
|
| 81 |
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] |
| 82 |
public static extern bool LogonUserW( |
| 83 |
string lpszUsername, |
| 84 |
string lpszDomain, |
| 85 |
string lpszPassword, |
| 86 |
LogonType dwLogonType, |
| 87 |
LogonProvider dwLogonProvider, |
| 88 |
out SafeNativeHandle phToken); |
| 89 |
|
| 90 |
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] |
| 91 |
public static extern bool LookupPrivilegeNameW( |
| 92 |
string lpSystemName, |
| 93 |
ref Luid lpLuid, |
| 94 |
StringBuilder lpName, |
| 95 |
ref UInt32 cchName); |
| 96 |
|
| 97 |
[DllImport("kernel32.dll", SetLastError = true)] |
| 98 |
public static extern SafeNativeHandle OpenProcess( |
| 99 |
ProcessAccessFlags dwDesiredAccess, |
| 100 |
bool bInheritHandle, |
| 101 |
UInt32 dwProcessId); |
| 102 |
|
| 103 |
[DllImport("advapi32.dll", SetLastError = true)] |
| 104 |
public static extern bool OpenProcessToken( |
| 105 |
SafeNativeHandle ProcessHandle, |
| 106 |
TokenAccessLevels DesiredAccess, |
| 107 |
out SafeNativeHandle TokenHandle); |
| 108 |
|
| 109 |
[DllImport("advapi32.dll", SetLastError = true)] |
| 110 |
public static extern bool RevertToSelf(); |
| 111 |
} |
| 112 |
|
| 113 |
internal class SafeMemoryBuffer : SafeHandleZeroOrMinusOneIsInvalid |
| 114 |
{ |
| 115 |
public SafeMemoryBuffer() : base(true) { } |
| 116 |
public SafeMemoryBuffer(int cb) : base(true) |
| 117 |
{ |
| 118 |
base.SetHandle(Marshal.AllocHGlobal(cb)); |
| 119 |
} |
| 120 |
public SafeMemoryBuffer(IntPtr handle) : base(true) |
| 121 |
{ |
| 122 |
base.SetHandle(handle); |
| 123 |
} |
| 124 |
|
| 125 |
protected override bool ReleaseHandle() |
| 126 |
{ |
| 127 |
Marshal.FreeHGlobal(handle); |
| 128 |
return true; |
| 129 |
} |
| 130 |
} |
| 131 |
|
| 132 |
public enum LogonProvider |
| 133 |
{ |
| 134 |
Default, |
| 135 |
WinNT35, |
| 136 |
WinNT40, |
| 137 |
WinNT50, |
| 138 |
} |
| 139 |
|
| 140 |
public enum LogonType |
| 141 |
{ |
| 142 |
Interactive = 2, |
| 143 |
Network = 3, |
| 144 |
Batch = 4, |
| 145 |
Service = 5, |
| 146 |
Unlock = 7, |
| 147 |
NetworkCleartext = 8, |
| 148 |
NewCredentials = 9, |
| 149 |
} |
| 150 |
|
| 151 |
[Flags] |
| 152 |
public enum PrivilegeAttributes : uint |
| 153 |
{ |
| 154 |
Disabled = 0x00000000, |
| 155 |
EnabledByDefault = 0x00000001, |
| 156 |
Enabled = 0x00000002, |
| 157 |
Removed = 0x00000004, |
| 158 |
UsedForAccess = 0x80000000, |
| 159 |
} |
| 160 |
|
| 161 |
[Flags] |
| 162 |
public enum ProcessAccessFlags : uint |
| 163 |
{ |
| 164 |
Terminate = 0x00000001, |
| 165 |
CreateThread = 0x00000002, |
| 166 |
VmOperation = 0x00000008, |
| 167 |
VmRead = 0x00000010, |
| 168 |
VmWrite = 0x00000020, |
| 169 |
DupHandle = 0x00000040, |
| 170 |
CreateProcess = 0x00000080, |
| 171 |
SetQuota = 0x00000100, |
| 172 |
SetInformation = 0x00000200, |
| 173 |
QueryInformation = 0x00000400, |
| 174 |
SuspendResume = 0x00000800, |
| 175 |
QueryLimitedInformation = 0x00001000, |
| 176 |
Delete = 0x00010000, |
| 177 |
ReadControl = 0x00020000, |
| 178 |
WriteDac = 0x00040000, |
| 179 |
WriteOwner = 0x00080000, |
| 180 |
Synchronize = 0x00100000, |
| 181 |
} |
| 182 |
|
| 183 |
public enum SecurityImpersonationLevel |
| 184 |
{ |
| 185 |
Anonymous, |
| 186 |
Identification, |
| 187 |
Impersonation, |
| 188 |
Delegation, |
| 189 |
} |
| 190 |
|
| 191 |
public enum TokenElevationType |
| 192 |
{ |
| 193 |
Default = 1, |
| 194 |
Full, |
| 195 |
Limited, |
| 196 |
} |
| 197 |
|
| 198 |
public enum TokenType |
| 199 |
{ |
| 200 |
Primary = 1, |
| 201 |
Impersonation, |
| 202 |
} |
| 203 |
|
| 204 |
[StructLayout(LayoutKind.Sequential)] |
| 205 |
public struct Luid |
| 206 |
{ |
| 207 |
public UInt32 LowPart; |
| 208 |
public Int32 HighPart; |
| 209 |
|
| 210 |
public static explicit operator UInt64(Luid l) |
| 211 |
{ |
| 212 |
return (UInt64)((UInt64)l.HighPart << 32) | (UInt64)l.LowPart; |
| 213 |
} |
| 214 |
} |
| 215 |
|
| 216 |
[StructLayout(LayoutKind.Sequential)] |
| 217 |
public struct TokenStatistics |
| 218 |
{ |
| 219 |
public Luid TokenId; |
| 220 |
public Luid AuthenticationId; |
| 221 |
public Int64 ExpirationTime; |
| 222 |
public TokenType TokenType; |
| 223 |
public SecurityImpersonationLevel ImpersonationLevel; |
| 224 |
public UInt32 DynamicCharged; |
| 225 |
public UInt32 DynamicAvailable; |
| 226 |
public UInt32 GroupCount; |
| 227 |
public UInt32 PrivilegeCount; |
| 228 |
public Luid ModifiedId; |
| 229 |
} |
| 230 |
|
| 231 |
public class PrivilegeInfo |
| 232 |
{ |
| 233 |
public string Name; |
| 234 |
public PrivilegeAttributes Attributes; |
| 235 |
|
| 236 |
internal PrivilegeInfo(NativeHelpers.LUID_AND_ATTRIBUTES la) |
| 237 |
{ |
| 238 |
Name = TokenUtil.GetPrivilegeName(la.Luid); |
| 239 |
Attributes = (PrivilegeAttributes)la.Attributes; |
| 240 |
} |
| 241 |
} |
| 242 |
|
| 243 |
public class SafeNativeHandle : SafeHandleZeroOrMinusOneIsInvalid |
| 244 |
{ |
| 245 |
public SafeNativeHandle() : base(true) { } |
| 246 |
public SafeNativeHandle(IntPtr handle) : base(true) { this.handle = handle; } |
| 247 |
|
| 248 |
protected override bool ReleaseHandle() |
| 249 |
{ |
| 250 |
return NativeMethods.CloseHandle(handle); |
| 251 |
} |
| 252 |
} |
| 253 |
|
| 254 |
public class Win32Exception : System.ComponentModel.Win32Exception |
| 255 |
{ |
| 256 |
private string _msg; |
| 257 |
|
| 258 |
public Win32Exception(string message) : this(Marshal.GetLastWin32Error(), message) { } |
| 259 |
public Win32Exception(int errorCode, string message) : base(errorCode) |
| 260 |
{ |
| 261 |
_msg = String.Format("{0} ({1}, Win32ErrorCode {2} - 0x{2:X8})", message, base.Message, errorCode); |
| 262 |
} |
| 263 |
|
| 264 |
public override string Message { get { return _msg; } } |
| 265 |
public static explicit operator Win32Exception(string message) { return new Win32Exception(message); } |
| 266 |
} |
| 267 |
|
| 268 |
public class TokenUtil |
| 269 |
{ |
| 270 |
public static SafeNativeHandle DuplicateToken(SafeNativeHandle hToken, TokenAccessLevels access, |
| 271 |
SecurityImpersonationLevel impersonationLevel, TokenType tokenType) |
| 272 |
{ |
| 273 |
SafeNativeHandle dupToken; |
| 274 |
if (!NativeMethods.DuplicateTokenEx(hToken, access, IntPtr.Zero, impersonationLevel, tokenType, out dupToken)) |
| 275 |
throw new Win32Exception("Failed to duplicate token"); |
| 276 |
return dupToken; |
| 277 |
} |
| 278 |
|
| 279 |
public static SecurityIdentifier GetTokenUser(SafeNativeHandle hToken) |
| 280 |
{ |
| 281 |
using (SafeMemoryBuffer tokenInfo = GetTokenInformation(hToken, |
| 282 |
NativeHelpers.TokenInformationClass.TokenUser)) |
| 283 |
{ |
| 284 |
NativeHelpers.TOKEN_USER tokenUser = (NativeHelpers.TOKEN_USER)Marshal.PtrToStructure( |
| 285 |
tokenInfo.DangerousGetHandle(), |
| 286 |
typeof(NativeHelpers.TOKEN_USER)); |
| 287 |
return new SecurityIdentifier(tokenUser.User.Sid); |
| 288 |
} |
| 289 |
} |
| 290 |
|
| 291 |
public static List<PrivilegeInfo> GetTokenPrivileges(SafeNativeHandle hToken) |
| 292 |
{ |
| 293 |
using (SafeMemoryBuffer tokenInfo = GetTokenInformation(hToken, |
| 294 |
NativeHelpers.TokenInformationClass.TokenPrivileges)) |
| 295 |
{ |
| 296 |
NativeHelpers.TOKEN_PRIVILEGES tokenPrivs = (NativeHelpers.TOKEN_PRIVILEGES)Marshal.PtrToStructure( |
| 297 |
tokenInfo.DangerousGetHandle(), |
| 298 |
typeof(NativeHelpers.TOKEN_PRIVILEGES)); |
| 299 |
|
| 300 |
NativeHelpers.LUID_AND_ATTRIBUTES[] luidAttrs = |
| 301 |
new NativeHelpers.LUID_AND_ATTRIBUTES[tokenPrivs.PrivilegeCount]; |
| 302 |
PtrToStructureArray(luidAttrs, IntPtr.Add(tokenInfo.DangerousGetHandle(), |
| 303 |
Marshal.SizeOf(tokenPrivs.PrivilegeCount))); |
| 304 |
|
| 305 |
return luidAttrs.Select(la => new PrivilegeInfo(la)).ToList(); |
| 306 |
} |
| 307 |
} |
| 308 |
|
| 309 |
public static TokenStatistics GetTokenStatistics(SafeNativeHandle hToken) |
| 310 |
{ |
| 311 |
using (SafeMemoryBuffer tokenInfo = GetTokenInformation(hToken, |
| 312 |
NativeHelpers.TokenInformationClass.TokenStatistics)) |
| 313 |
{ |
| 314 |
TokenStatistics tokenStats = (TokenStatistics)Marshal.PtrToStructure( |
| 315 |
tokenInfo.DangerousGetHandle(), |
| 316 |
typeof(TokenStatistics)); |
| 317 |
return tokenStats; |
| 318 |
} |
| 319 |
} |
| 320 |
|
| 321 |
public static TokenElevationType GetTokenElevationType(SafeNativeHandle hToken) |
| 322 |
{ |
| 323 |
using (SafeMemoryBuffer tokenInfo = GetTokenInformation(hToken, |
| 324 |
NativeHelpers.TokenInformationClass.TokenElevationType)) |
| 325 |
{ |
| 326 |
return (TokenElevationType)Marshal.ReadInt32(tokenInfo.DangerousGetHandle()); |
| 327 |
} |
| 328 |
} |
| 329 |
|
| 330 |
public static SafeNativeHandle GetTokenLinkedToken(SafeNativeHandle hToken) |
| 331 |
{ |
| 332 |
using (SafeMemoryBuffer tokenInfo = GetTokenInformation(hToken, |
| 333 |
NativeHelpers.TokenInformationClass.TokenLinkedToken)) |
| 334 |
{ |
| 335 |
return new SafeNativeHandle(Marshal.ReadIntPtr(tokenInfo.DangerousGetHandle())); |
| 336 |
} |
| 337 |
} |
| 338 |
|
| 339 |
public static IEnumerable<SafeNativeHandle> EnumerateUserTokens(SecurityIdentifier sid, |
| 340 |
TokenAccessLevels access = TokenAccessLevels.Query) |
| 341 |
{ |
| 342 |
return EnumerateUserTokens(sid, access, (p, h) => true); |
| 343 |
} |
| 344 |
|
| 345 |
public static IEnumerable<SafeNativeHandle> EnumerateUserTokens( |
| 346 |
SecurityIdentifier sid, |
| 347 |
TokenAccessLevels access, |
| 348 |
Func<System.Diagnostics.Process, SafeNativeHandle, bool> processFilter) |
| 349 |
{ |
| 350 |
// We always need the Query access level so we can query the TokenUser |
| 351 |
access |= TokenAccessLevels.Query; |
| 352 |
|
| 353 |
foreach (System.Diagnostics.Process process in System.Diagnostics.Process.GetProcesses()) |
| 354 |
{ |
| 355 |
using (process) |
| 356 |
using (SafeNativeHandle processHandle = NativeMethods.OpenProcess(ProcessAccessFlags.QueryInformation, false, (UInt32)process.Id)) |
| 357 |
{ |
| 358 |
if (processHandle.IsInvalid) |
| 359 |
{ |
| 360 |
continue; |
| 361 |
} |
| 362 |
|
| 363 |
if (!processFilter(process, processHandle)) |
| 364 |
{ |
| 365 |
continue; |
| 366 |
} |
| 367 |
|
| 368 |
SafeNativeHandle accessToken; |
| 369 |
if (!NativeMethods.OpenProcessToken(processHandle, access, out accessToken)) |
| 370 |
{ |
| 371 |
continue; |
| 372 |
} |
| 373 |
|
| 374 |
using (accessToken) |
| 375 |
{ |
| 376 |
if (!sid.Equals(GetTokenUser(accessToken))) |
| 377 |
{ |
| 378 |
continue; |
| 379 |
} |
| 380 |
|
| 381 |
yield return accessToken; |
| 382 |
} |
| 383 |
} |
| 384 |
} |
| 385 |
} |
| 386 |
|
| 387 |
public static void ImpersonateToken(SafeNativeHandle hToken) |
| 388 |
{ |
| 389 |
if (!NativeMethods.ImpersonateLoggedOnUser(hToken)) |
| 390 |
throw new Win32Exception("Failed to impersonate token"); |
| 391 |
} |
| 392 |
|
| 393 |
public static SafeNativeHandle LogonUser(string username, string domain, string password, LogonType logonType, |
| 394 |
LogonProvider logonProvider) |
| 395 |
{ |
| 396 |
SafeNativeHandle hToken; |
| 397 |
if (!NativeMethods.LogonUserW(username, domain, password, logonType, logonProvider, out hToken)) |
| 398 |
throw new Win32Exception(String.Format("Failed to logon {0}", |
| 399 |
String.IsNullOrEmpty(domain) ? username : domain + "\\" + username)); |
| 400 |
|
| 401 |
return hToken; |
| 402 |
} |
| 403 |
|
| 404 |
public static SafeNativeHandle OpenProcess() |
| 405 |
{ |
| 406 |
return NativeMethods.GetCurrentProcess(); |
| 407 |
} |
| 408 |
|
| 409 |
public static SafeNativeHandle OpenProcess(Int32 pid, ProcessAccessFlags access, bool inherit) |
| 410 |
{ |
| 411 |
SafeNativeHandle hProcess = NativeMethods.OpenProcess(access, inherit, (UInt32)pid); |
| 412 |
if (hProcess.IsInvalid) |
| 413 |
throw new Win32Exception(String.Format("Failed to open process {0} with access {1}", |
| 414 |
pid, access.ToString())); |
| 415 |
|
| 416 |
return hProcess; |
| 417 |
} |
| 418 |
|
| 419 |
public static SafeNativeHandle OpenProcessToken(SafeNativeHandle hProcess, TokenAccessLevels access) |
| 420 |
{ |
| 421 |
SafeNativeHandle hToken; |
| 422 |
if (!NativeMethods.OpenProcessToken(hProcess, access, out hToken)) |
| 423 |
throw new Win32Exception(String.Format("Failed to open process token with access {0}", |
| 424 |
access.ToString())); |
| 425 |
|
| 426 |
return hToken; |
| 427 |
} |
| 428 |
|
| 429 |
public static void RevertToSelf() |
| 430 |
{ |
| 431 |
if (!NativeMethods.RevertToSelf()) |
| 432 |
throw new Win32Exception("Failed to revert thread impersonation"); |
| 433 |
} |
| 434 |
|
| 435 |
internal static string GetPrivilegeName(Luid luid) |
| 436 |
{ |
| 437 |
UInt32 nameLen = 0; |
| 438 |
NativeMethods.LookupPrivilegeNameW(null, ref luid, null, ref nameLen); |
| 439 |
|
| 440 |
StringBuilder name = new StringBuilder((int)(nameLen + 1)); |
| 441 |
if (!NativeMethods.LookupPrivilegeNameW(null, ref luid, name, ref nameLen)) |
| 442 |
throw new Win32Exception("LookupPrivilegeName() failed"); |
| 443 |
|
| 444 |
return name.ToString(); |
| 445 |
} |
| 446 |
|
| 447 |
private static SafeMemoryBuffer GetTokenInformation(SafeNativeHandle hToken, |
| 448 |
NativeHelpers.TokenInformationClass infoClass) |
| 449 |
{ |
| 450 |
UInt32 tokenLength; |
| 451 |
bool res = NativeMethods.GetTokenInformation(hToken, infoClass, new SafeMemoryBuffer(IntPtr.Zero), 0, |
| 452 |
out tokenLength); |
| 453 |
int errCode = Marshal.GetLastWin32Error(); |
| 454 |
if (!res && errCode != 24 && errCode != 122) // ERROR_INSUFFICIENT_BUFFER, ERROR_BAD_LENGTH |
| 455 |
throw new Win32Exception(errCode, String.Format("GetTokenInformation({0}) failed to get buffer length", |
| 456 |
infoClass.ToString())); |
| 457 |
|
| 458 |
SafeMemoryBuffer tokenInfo = new SafeMemoryBuffer((int)tokenLength); |
| 459 |
if (!NativeMethods.GetTokenInformation(hToken, infoClass, tokenInfo, tokenLength, out tokenLength)) |
| 460 |
throw new Win32Exception(String.Format("GetTokenInformation({0}) failed", infoClass.ToString())); |
| 461 |
|
| 462 |
return tokenInfo; |
| 463 |
} |
| 464 |
|
| 465 |
private static void PtrToStructureArray<T>(T[] array, IntPtr ptr) |
| 466 |
{ |
| 467 |
IntPtr ptrOffset = ptr; |
| 468 |
for (int i = 0; i < array.Length; i++, ptrOffset = IntPtr.Add(ptrOffset, Marshal.SizeOf(typeof(T)))) |
| 469 |
array[i] = (T)Marshal.PtrToStructure(ptrOffset, typeof(T)); |
| 470 |
} |
| 471 |
} |
| 472 |
} |