summaryrefslogtreecommitdiff
path: root/vdagent/as_user.cpp
diff options
context:
space:
mode:
authorUri Lublin <uril@redhat.com>2013-11-03 11:28:57 +0200
committerUri Lublin <uril@redhat.com>2013-11-13 10:24:59 +0200
commit750a8bab405588d91c41f84c458d9cda0f7189bf (patch)
treeb715ad4116e40be857217d03dd9ca1463f575270 /vdagent/as_user.cpp
parentfac9e8d3bf3d3b90d4c20e5c114430ea1781b2f7 (diff)
vdagent: add as_user to run tasks with user privileges
The class calls Impersonate upon begin(), and Revert upon end() or destruction. The user is the current user that is logged in. create mode 100644 vdagent/as_user.cpp create mode 100644 vdagent/as_user.h
Diffstat (limited to 'vdagent/as_user.cpp')
-rw-r--r--vdagent/as_user.cpp73
1 files changed, 73 insertions, 0 deletions
diff --git a/vdagent/as_user.cpp b/vdagent/as_user.cpp
new file mode 100644
index 0000000..d2d6c58
--- /dev/null
+++ b/vdagent/as_user.cpp
@@ -0,0 +1,73 @@
+/*
+ Copyright (C) 2013 Red Hat, Inc.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of
+ the License, or (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "vdcommon.h"
+#include "as_user.h"
+
+#include <wtsapi32.h>
+
+AsUser::AsUser(DWORD session_id):
+ _started(false),
+ _session_id(session_id),
+ _token(INVALID_HANDLE_VALUE)
+{
+}
+
+bool AsUser::begin()
+{
+ BOOL ret;
+
+ if (_session_id == (DWORD)-1) {
+ ret = ProcessIdToSessionId(GetCurrentProcessId(), &_session_id);
+ if (!ret) {
+ vd_printf("ProcessIdToSessionId failed %lu", GetLastError());
+ return false;
+ }
+ }
+ if (_token == INVALID_HANDLE_VALUE) {
+ ret = WTSQueryUserToken(_session_id, &_token);
+ if (!ret) {
+ vd_printf("WTSQueryUserToken failed -- %lu", GetLastError());
+ return false;
+ }
+ }
+
+ ret = ImpersonateLoggedOnUser(_token);
+ if (!ret) {
+ vd_printf("ImpersonateLoggedOnUser failed: %lu", GetLastError());
+ return false;
+ }
+
+ _started = true;
+ return true;
+}
+
+void AsUser::end()
+{
+ if (_started) {
+ RevertToSelf();
+ _started = false;
+ }
+}
+
+AsUser::~AsUser()
+{
+ end();
+ if (_token != INVALID_HANDLE_VALUE) {
+ CloseHandle(_token);
+ }
+}