]> asedeno.scripts.mit.edu Git - PuTTY_svn.git/blob - windows/winsecur.c
Move the dynamic loading of advapi into its own module.
[PuTTY_svn.git] / windows / winsecur.c
1 /*
2  * winsecur.c: implementation of winsecur.h.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7
8 #include "putty.h"
9
10 #if !defined NO_SECURITY
11
12 #define WINSECUR_GLOBAL
13 #include "winsecur.h"
14
15 int got_advapi(void)
16 {
17     static int attempted = FALSE;
18     static int successful;
19     static HMODULE advapi;
20
21     if (!attempted) {
22         attempted = TRUE;
23         advapi = load_system32_dll("advapi32.dll");
24         successful = advapi &&
25             GET_WINDOWS_FUNCTION(advapi, GetSecurityInfo) &&
26             GET_WINDOWS_FUNCTION(advapi, OpenProcessToken) &&
27             GET_WINDOWS_FUNCTION(advapi, GetTokenInformation) &&
28             GET_WINDOWS_FUNCTION(advapi, InitializeSecurityDescriptor) &&
29             GET_WINDOWS_FUNCTION(advapi, SetSecurityDescriptorOwner);
30     }
31     return successful;
32 }
33
34 PSID get_user_sid(void)
35 {
36     HANDLE proc = NULL, tok = NULL;
37     TOKEN_USER *user = NULL;
38     DWORD toklen, sidlen;
39     PSID sid = NULL, ret = NULL;
40
41     if (!got_advapi())
42         goto cleanup;
43
44     if ((proc = OpenProcess(MAXIMUM_ALLOWED, FALSE,
45                             GetCurrentProcessId())) == NULL)
46         goto cleanup;
47
48     if (!p_OpenProcessToken(proc, TOKEN_QUERY, &tok))
49         goto cleanup;
50
51     if (!p_GetTokenInformation(tok, TokenUser, NULL, 0, &toklen) &&
52         GetLastError() != ERROR_INSUFFICIENT_BUFFER)
53         goto cleanup;
54
55     if ((user = (TOKEN_USER *)LocalAlloc(LPTR, toklen)) == NULL)
56         goto cleanup;
57
58     if (!p_GetTokenInformation(tok, TokenUser, user, toklen, &toklen))
59         goto cleanup;
60
61     sidlen = GetLengthSid(user->User.Sid);
62
63     sid = (PSID)smalloc(sidlen);
64
65     if (!CopySid(sidlen, sid, user->User.Sid))
66         goto cleanup;
67
68     /* Success. Move sid into the return value slot, and null it out
69      * to stop the cleanup code freeing it. */
70     ret = sid;
71     sid = NULL;
72
73   cleanup:
74     if (proc != NULL)
75         CloseHandle(proc);
76     if (tok != NULL)
77         CloseHandle(tok);
78     if (user != NULL)
79         LocalFree(user);
80     if (sid != NULL)
81         sfree(sid);
82
83     return ret;
84 }
85
86 #endif /* !defined NO_SECURITY */