Advertisement
Guest User

Untitled

a guest
Oct 26th, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. using System;
  2. using System.Runtime.ConstrainedExecution;
  3. using System.Runtime.InteropServices;
  4. using System.Security;
  5. using System.Security.Permissions;
  6. using System.Security.Principal;
  7. using Microsoft.Win32.SafeHandles;
  8.  
  9. namespace Impersonator
  10. {
  11. [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
  12. public class Impersonation : IDisposable
  13. {
  14. private readonly SafeTokenHandle _handle;
  15. private readonly WindowsImpersonationContext _context;
  16.  
  17. const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
  18.  
  19. public Impersonation(string domain, string username, string password)
  20. {
  21. var ok = LogonUser(username, domain, password,
  22. LOGON32_LOGON_NEW_CREDENTIALS, 0, out this._handle);
  23. if (!ok)
  24. {
  25. var errorCode = Marshal.GetLastWin32Error();
  26. throw new ApplicationException(string.Format("Could not impersonate the elevated user. LogonUser returned error code {0}.", errorCode));
  27. }
  28.  
  29. this._context = WindowsIdentity.Impersonate(this._handle.DangerousGetHandle());
  30. }
  31.  
  32. public void Dispose()
  33. {
  34. this._context.Dispose();
  35. this._handle.Dispose();
  36. }
  37.  
  38. [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
  39. private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
  40.  
  41. public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
  42. {
  43. private SafeTokenHandle()
  44. : base(true) { }
  45.  
  46. [DllImport("kernel32.dll")]
  47. [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  48. [SuppressUnmanagedCodeSecurity]
  49. [return: MarshalAs(UnmanagedType.Bool)]
  50. private static extern bool CloseHandle(IntPtr handle);
  51.  
  52. protected override bool ReleaseHandle()
  53. {
  54. return CloseHandle(handle);
  55. }
  56. }
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement