comparison common/util.c @ 505:78959fd970b0

Add is_admin and implement it for windows
author Andre Heinecke <aheinecke@intevation.de>
date Mon, 28 Apr 2014 09:19:53 +0000
parents 17e1c8f37d72
children c7a35fa302ec
comparison
equal deleted inserted replaced
504:3cf72c5282e8 505:78959fd970b0
4 * This file is Free Software under the GNU GPL (v>=2) 4 * This file is Free Software under the GNU GPL (v>=2)
5 * and comes with ABSOLUTELY NO WARRANTY! 5 * and comes with ABSOLUTELY NO WARRANTY!
6 * See LICENSE.txt for details. 6 * See LICENSE.txt for details.
7 */ 7 */
8 #include "util.h" 8 #include "util.h"
9 #include "logging.h"
10
9 #ifndef _WIN32 11 #ifndef _WIN32
10 #include <unistd.h> 12 #include <unistd.h>
11 #include <sys/types.h> 13 #include <sys/types.h>
12 #else 14 #else
13 #include <windows.h> 15 #include <windows.h>
34 if (hToken) 36 if (hToken)
35 CloseHandle (hToken); 37 CloseHandle (hToken);
36 #endif 38 #endif
37 return ret; 39 return ret;
38 } 40 }
41
42 bool is_admin()
43 {
44 #ifndef _WIN32
45 /* TODO implement */
46 return false;
47 #else
48 bool retval = false;
49 BOOL in_admin_group = FALSE;
50 HANDLE hToken = NULL;
51 HANDLE hTokenToCheck = NULL;
52 DWORD cbSize = 0;
53 TOKEN_ELEVATION_TYPE elevation;
54 BYTE admin_id[SECURITY_MAX_SID_SIZE];
55
56 if (!OpenProcessToken(GetCurrentProcess(),
57 TOKEN_QUERY | TOKEN_DUPLICATE, &hToken))
58 {
59 PRINTLASTERROR ("Failed to duplicate process token.\n");
60 return false;
61 }
62
63 if (!GetTokenInformation(hToken, TokenElevationType, &elevation,
64 sizeof(elevation), &cbSize))
65 {
66 PRINTLASTERROR ("Failed to get token information.\n");
67 goto done;
68 }
69
70 /* If limited check the the linked token instead */
71 if (TokenElevationTypeLimited == elevation)
72 {
73 if (!GetTokenInformation(hToken, TokenLinkedToken, &hTokenToCheck,
74 sizeof(hTokenToCheck), &cbSize))
75 {
76 PRINTLASTERROR ("Failed to get the linked token.\n");
77 goto done;
78 }
79 }
80
81 if (!hTokenToCheck) /* The linked token is already of the correct type */
82 {
83 if (!DuplicateToken(hToken, SecurityIdentification, &hTokenToCheck))
84 {
85 PRINTLASTERROR ("Failed to duplicate token for identification.\n");
86 goto done;
87 }
88 }
89
90 /* Do the sid dance for the adminSID */
91 cbSize = sizeof(admin_id);
92 if (!CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, &admin_id,
93 &cbSize))
94 {
95 PRINTLASTERROR ("Failed to get admin sid.\n");
96 goto done;
97 }
98
99 /* The actual check */
100 if (!CheckTokenMembership(hTokenToCheck, &admin_id, &in_admin_group))
101 {
102 PRINTLASTERROR ("Failed to check token membership.\n");
103 goto done;
104 }
105
106 if (in_admin_group)
107 {
108 /* Winbool to standard bool */
109 retval = true;
110 }
111
112 done:
113 if (hToken) CloseHandle(hToken);
114 if (hTokenToCheck) CloseHandle(hTokenToCheck);
115
116 return retval;
117 #endif
118 }
119

http://wald.intevation.org/projects/trustbridge/