Impartunate.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Runtime.InteropServices;
  3. using System.Security.Principal;
  4. namespace LAPS_XMLQC_Service.App_Data
  5. {
  6. public class Impartunate : IDisposable
  7. {
  8. private IntPtr tokenHandle;
  9. private WindowsIdentity newId;
  10. private readonly string impersUsername;
  11. private readonly string impersPwd;
  12. private readonly string impersDomain;
  13. [DllImport("advapi32.dll", SetLastError = true)]
  14. private static extern bool LogonUser(
  15. string sUsername,
  16. string sDomain,
  17. string sPassword,
  18. int iLogonType,
  19. int iLogonProvider,
  20. ref IntPtr oToken);
  21. [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  22. private static extern bool CloseHandle(IntPtr oHandle);
  23. public Impartunate(string username, string password, string domain)
  24. {
  25. impersUsername = username;
  26. impersPwd = password;
  27. impersDomain = domain;
  28. }
  29. public WindowsIdentity AllowAccesstoServer()
  30. {
  31. try
  32. {
  33. tokenHandle = IntPtr.Zero;
  34. bool result = LogonUser(impersUsername, impersDomain, impersPwd, 2, 0, ref tokenHandle);
  35. if (!result)
  36. {
  37. int errorCode = Marshal.GetLastWin32Error();
  38. throw new UnauthorizedAccessException($"LogonUser failed with error code {errorCode}");
  39. }
  40. newId = new WindowsIdentity(tokenHandle);
  41. return newId;
  42. }
  43. catch (Exception ex)
  44. {
  45. throw new InvalidOperationException("Failed to impersonate user", ex);
  46. }
  47. }
  48. public void RemoveServerAccess()
  49. {
  50. if (tokenHandle != IntPtr.Zero)
  51. {
  52. CloseHandle(tokenHandle);
  53. tokenHandle = IntPtr.Zero;
  54. }
  55. }
  56. public void Dispose()
  57. {
  58. RemoveServerAccess();
  59. GC.SuppressFinalize(this);
  60. }
  61. ~Impartunate()
  62. {
  63. RemoveServerAccess();
  64. }
  65. }
  66. }