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.

125 lines
2.6 KiB

  1. /*++
  2. Copyright (c) 2001 Microsoft Corporation
  3. All rights reserved
  4. Module Name:
  5. impersonation.cxx
  6. Abstract:
  7. This file provides useful accssors and mutators.
  8. Author:
  9. Larry Zhu (LZhu) January 1, 2002 Created
  10. Environment:
  11. User Mode -Win32
  12. Revision History:
  13. --*/
  14. #include "precomp.hxx"
  15. #pragma hdrstop
  16. #include "impersonation.hxx"
  17. TImpersonation::TImpersonation(
  18. IN OPTIONAL HANDLE hToken
  19. ) : m_hTokenOld(NULL),
  20. m_bIsOldTokenValid(FALSE),
  21. m_hTokenNew(hToken),
  22. m_Status(STATUS_UNSUCCESSFUL)
  23. {
  24. m_Status DBGCHK = Initialize();
  25. }
  26. TImpersonation::~TImpersonation(
  27. VOID
  28. )
  29. {
  30. if ( m_bIsOldTokenValid && ((NULL != m_hTokenOld) || (NULL != m_hTokenNew)) )
  31. {
  32. TNtStatus Status;
  33. Status DBGCHK = NtSetInformationThread(
  34. NtCurrentThread(),
  35. ThreadImpersonationToken,
  36. &m_hTokenOld,
  37. sizeof(HANDLE)
  38. );
  39. if (NT_SUCCESS(Status))
  40. {
  41. SspiPrint(SSPI_LOG,
  42. TEXT("TImpersonation::~TImpersonation restores thread token from %p to m_hTokenOld %p\n"),
  43. m_hTokenNew, m_hTokenOld);
  44. }
  45. }
  46. if (m_hTokenOld)
  47. {
  48. NtClose(m_hTokenOld);
  49. }
  50. }
  51. NTSTATUS
  52. TImpersonation::Validate(
  53. VOID
  54. ) const
  55. {
  56. return m_Status;
  57. }
  58. /******************************************************************************
  59. Private Methods
  60. ******************************************************************************/
  61. NTSTATUS
  62. TImpersonation::Initialize(
  63. VOID
  64. )
  65. {
  66. TNtStatus Status = STATUS_SUCCESS;
  67. DBGCFG1(Status, STATUS_NO_TOKEN);
  68. Status DBGCHK = NtOpenThreadToken(
  69. NtCurrentThread(),
  70. TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE,
  71. TRUE,
  72. &m_hTokenOld
  73. );
  74. if (Status == STATUS_NO_TOKEN)
  75. {
  76. m_hTokenOld = NULL;
  77. m_bIsOldTokenValid = TRUE;
  78. Status DBGCHK = STATUS_SUCCESS;
  79. }
  80. else if (NT_SUCCESS(Status))
  81. {
  82. m_bIsOldTokenValid = TRUE;
  83. HANDLE hNullToken = NULL;
  84. Status DBGCHK = NtSetInformationThread(
  85. NtCurrentThread(),
  86. ThreadImpersonationToken,
  87. &hNullToken,
  88. sizeof(HANDLE)
  89. );
  90. }
  91. if ( NT_SUCCESS(Status) && ((NULL != m_hTokenOld) || (NULL != m_hTokenNew)) )
  92. {
  93. SspiPrint(SSPI_LOG, TEXT("TImpersonation::Initialize impersonating token new %p, old %p\n"), m_hTokenNew, m_hTokenOld);
  94. Status DBGCHK = Impersonate(m_hTokenNew);
  95. }
  96. return Status;
  97. }