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.

100 lines
2.3 KiB

  1. // Copyright (C) 2002 Microsoft Corporation
  2. //
  3. // AutoTokenPrivileges class - for enabling and automatically restoring
  4. // process token privileges
  5. //
  6. // 29 April 2002 sburns
  7. #ifndef AUTOTOKENPRIVILEGES_HPP_INCLUDED
  8. #define AUTOTOKENPRIVILEGES_HPP_INCLUDED
  9. // class AutoTokenPrivileges is a convenient way to scope a process token
  10. // privilege elevation to just the piece of code that requires the elevation,
  11. // and restore it again when the scope exits.
  12. //
  13. // It is generally a good idea to only enable the privileges that are
  14. // absolutely required, and only for as long as they are required. See
  15. // Howard, Michael. Writing Secure Code. Ch. 5. Microsoft Press. ISBN
  16. // 0-7356-1588-8
  17. //
  18. // Example:
  19. //
  20. // { // open scope
  21. // // enable the SE_RESTORE_NAME priv, required to set owers in an sd.
  22. //
  23. // AutoTokenPrivileges autoPrivs(SE_RESTORE_NAME);
  24. // hr = autoPrivs.Enable();
  25. // if (SUCCEEDED(hr))
  26. // {
  27. // // make the calls that require the priv.
  28. // }
  29. // } // close scope -- the old state of the enabled privs will be restored
  30. class
  31. AutoTokenPrivileges
  32. {
  33. public:
  34. // Create a new instance that will enable the named privilege in the
  35. // process token when Enable is called, and restore the prior state of the
  36. // privilege when either Restore is called, or the instance is destroyed.
  37. //
  38. // privName - an SE_ privilege name string, like SE_SHUTDOWN_NAME.
  39. explicit
  40. AutoTokenPrivileges(const String& privName);
  41. // CODEWORK: another ctor that takes a vector of priv names
  42. // Restores the privileges to their state prior to calling Enable, unless
  43. // Restore has been called, in which case the privileges are untouched.
  44. ~AutoTokenPrivileges();
  45. // Enable the privileges that were identified in the ctor. May return
  46. // Win32ToHresult(ERROR_NOT_ALL_ASSIGNED)
  47. HRESULT
  48. Enable();
  49. // Restore the privileges that were enabled to their prior state.
  50. HRESULT
  51. Restore();
  52. private:
  53. HRESULT
  54. InternalRestore();
  55. StringList privNames;
  56. // cached data:
  57. mutable HANDLE processToken;
  58. mutable TOKEN_PRIVILEGES* newPrivs;
  59. mutable TOKEN_PRIVILEGES* oldPrivs;
  60. };
  61. #endif // AUTOTOKENPRIVILEGES_HPP_INCLUDED