Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

111 lines
2.3 KiB

  1. //
  2. // Copyright � Microsoft Corporation. All rights reserved.
  3. //
  4. // CImpersonate class implementation
  5. // Created: 6/3/2000
  6. // Author: khughes
  7. #include <precomp.h>
  8. #include <chstring.h>
  9. #include "AutoImpRevert.h"
  10. CAutoImpRevert::CAutoImpRevert(
  11. BOOL fOpenAsSelf)
  12. : m_hOriginalUser(INVALID_HANDLE_VALUE),
  13. m_dwLastError(ERROR_SUCCESS)
  14. {
  15. GetCurrentImpersonation(fOpenAsSelf);
  16. }
  17. CAutoImpRevert::~CAutoImpRevert()
  18. {
  19. if(m_hOriginalUser != INVALID_HANDLE_VALUE)
  20. {
  21. Revert();
  22. }
  23. }
  24. bool CAutoImpRevert::GetCurrentImpersonation(
  25. BOOL fOpenAsSelf)
  26. {
  27. bool fRet = false;
  28. ::SetLastError(ERROR_SUCCESS);
  29. m_dwLastError = ERROR_SUCCESS;
  30. // Store the current user's handle...
  31. if(::OpenThreadToken(
  32. ::GetCurrentThread(),
  33. TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE,
  34. fOpenAsSelf,
  35. &m_hOriginalUser))
  36. {
  37. fRet = true;
  38. }
  39. else
  40. {
  41. m_dwLastError = ::GetLastError();
  42. if(m_dwLastError == ERROR_NO_TOKEN)
  43. {
  44. ::SetLastError(ERROR_SUCCESS);
  45. if(::ImpersonateSelf(SecurityImpersonation))
  46. {
  47. if(::OpenThreadToken(
  48. ::GetCurrentThread(),
  49. TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE,
  50. fOpenAsSelf,
  51. &m_hOriginalUser))
  52. {
  53. fRet = true;
  54. m_dwLastError = ERROR_SUCCESS;
  55. }
  56. else
  57. {
  58. m_dwLastError = ::GetLastError();
  59. }
  60. }
  61. else
  62. {
  63. m_dwLastError = ::GetLastError();
  64. }
  65. }
  66. }
  67. return fRet;
  68. }
  69. bool CAutoImpRevert::Revert()
  70. {
  71. bool fRet = false;
  72. if(m_hOriginalUser != INVALID_HANDLE_VALUE)
  73. {
  74. if(::ImpersonateLoggedOnUser(m_hOriginalUser))
  75. {
  76. CloseHandle(m_hOriginalUser);
  77. m_hOriginalUser = INVALID_HANDLE_VALUE;
  78. fRet = true;
  79. }
  80. else
  81. {
  82. m_dwLastError = ::GetLastError();
  83. }
  84. }
  85. return fRet;
  86. }
  87. DWORD CAutoImpRevert::LastError() const
  88. {
  89. return m_dwLastError;
  90. }