[runtime] Call error_init instead of mono_error_init (#4425)
[mono.git] / mono / metadata / mono-security-windows.c
1 /*
2  * mono-security-windows.c: Windows security support.
3  *
4  * Copyright 2016 Microsoft
5  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
6  */
7 #include <config.h>
8 #include <glib.h>
9
10 #if defined(HOST_WIN32)
11 #include <winsock2.h>
12 #include <windows.h>
13 #include "mono/metadata/mono-security-windows-internals.h"
14
15 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
16 #include <aclapi.h>
17 #include <accctrl.h>
18 #endif
19
20 #ifndef PROTECTED_DACL_SECURITY_INFORMATION
21 #define PROTECTED_DACL_SECURITY_INFORMATION     0x80000000L
22 #endif
23
24 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
25 static gunichar2*
26 GetSidName (gunichar2 *server, PSID sid, gint32 *size)
27 {
28         gunichar2 *uniname = NULL;
29         DWORD cchName = 0;
30         DWORD cchDomain = 0;
31         SID_NAME_USE peUse; /* out */
32
33         LookupAccountSid (server, sid, NULL, &cchName, NULL,
34                 &cchDomain, &peUse);
35
36         if ((cchName > 0) && (cchDomain > 0)) {
37                 gunichar2 *user = g_malloc0 ((cchName + 1) * 2);
38                 gunichar2 *domain = g_malloc0 ((cchDomain + 1) * 2);
39
40                 LookupAccountSid (server, sid, user, &cchName, domain,
41                         &cchDomain, &peUse);
42
43                 if (cchName > 0) {
44                         if (cchDomain > 0) {
45                                 /* domain/machine name included (+ sepearator) */
46                                 *size = cchName + cchDomain + 1;
47                                 uniname = g_malloc0 ((*size + 1) * 2);
48                                 memcpy (uniname, domain, cchDomain * 2);
49                                 *(uniname + cchDomain) = '\\';
50                                 memcpy (uniname + cchDomain + 1, user, cchName * 2);
51                                 g_free (user);
52                         }
53                         else {
54                                 /* no domain / machine */
55                                 *size = cchName;
56                                 uniname = user;
57                         }
58                 }
59                 else {
60                         /* nothing -> return NULL */
61                         g_free (user);
62                 }
63
64                 g_free (domain);
65         }
66
67         return uniname;
68 }
69
70 gpointer
71 ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken (void)
72 {
73         gpointer token = NULL;
74
75         /* Note: This isn't a copy of the Token - we must not close it!!!
76          * http://www.develop.com/kbrown/book/html/whatis_windowsprincipal.html
77          */
78
79         /* thread may be impersonating somebody */
80         if (OpenThreadToken (GetCurrentThread (), MAXIMUM_ALLOWED, 1, &token) == 0) {
81                 /* if not take the process identity */
82                 OpenProcessToken (GetCurrentProcess (), MAXIMUM_ALLOWED, &token);
83         }
84
85         return token;
86 }
87
88 gint32
89 mono_security_win_get_token_name (gpointer token, gunichar2 ** uniname)
90 {
91         gint32 size = 0;
92
93         GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
94         if (size > 0) {
95                 TOKEN_USER *tu = g_malloc0 (size);
96                 if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
97                         *uniname = GetSidName (NULL, tu->User.Sid, &size);
98                 }
99                 g_free (tu);
100         }
101
102         return size;
103 }
104 #endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
105
106 MonoString*
107 ves_icall_System_Security_Principal_WindowsIdentity_GetTokenName (gpointer token)
108 {
109         MonoError error;
110         MonoString *result = NULL;
111         gunichar2 *uniname = NULL;
112         gint32 size = 0;
113
114         error_init (&error);
115
116         size = mono_security_win_get_token_name (token, &uniname);
117
118         if (size > 0) {
119                 result = mono_string_new_utf16_checked (mono_domain_get (), uniname, size, &error);
120         }
121         else
122                 result = mono_string_new (mono_domain_get (), "");
123
124         if (uniname)
125                 g_free (uniname);
126
127         mono_error_set_pending_exception (&error);
128         return result;
129 }
130
131 gpointer
132 ves_icall_System_Security_Principal_WindowsIdentity_GetUserToken (MonoString *username)
133 {
134         gpointer token = NULL;
135
136         /* TODO: MS has something like this working in Windows 2003 (client and
137          * server) but works only for domain accounts (so it's quite limiting).
138          * http://www.develop.com/kbrown/book/html/howto_logonuser.html
139          */
140         g_warning ("Unsupported on Win32 (anyway requires W2K3 minimum)");
141         return token;
142 }
143
144 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
145 MonoArray*
146 ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token)
147 {
148         MonoError error;
149         MonoArray *array = NULL;
150         MonoDomain *domain = mono_domain_get ();
151
152         gint32 size = 0;
153
154         GetTokenInformation (token, TokenGroups, NULL, size, (PDWORD)&size);
155         if (size > 0) {
156                 TOKEN_GROUPS *tg = g_malloc0 (size);
157                 if (GetTokenInformation (token, TokenGroups, tg, size, (PDWORD)&size)) {
158                         int i=0;
159                         int num = tg->GroupCount;
160
161                         array = mono_array_new_checked (domain, mono_get_string_class (), num, &error);
162                         if (mono_error_set_pending_exception (&error)) {
163                                 g_free (tg);
164                                 return NULL;
165                         }
166
167                         for (i=0; i < num; i++) {
168                                 gint32 size = 0;
169                                 gunichar2 *uniname = GetSidName (NULL, tg->Groups [i].Sid, &size);
170
171                                 if (uniname) {
172                                         MonoString *str = mono_string_new_utf16_checked (domain, uniname, size, &error);
173                                         if (!is_ok (&error)) {
174                                                 g_free (uniname);
175                                                 g_free (tg);
176                                                 mono_error_set_pending_exception (&error);
177                                                 return NULL;
178                                         }
179                                         mono_array_setref (array, i, str);
180                                         g_free (uniname);
181                                 }
182                         }
183                 }
184                 g_free (tg);
185         }
186
187         if (!array) {
188                 /* return empty array of string, i.e. string [0] */
189                 array = mono_array_new_checked (domain, mono_get_string_class (), 0, &error);
190                 mono_error_set_pending_exception (&error);
191         }
192         return array;
193 }
194 #endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
195
196 gboolean
197 ves_icall_System_Security_Principal_WindowsImpersonationContext_CloseToken (gpointer token)
198 {
199         gboolean result = TRUE;
200         result = (CloseHandle (token) != 0);
201         return result;
202 }
203
204 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
205 gpointer
206 ves_icall_System_Security_Principal_WindowsImpersonationContext_DuplicateToken (gpointer token)
207 {
208         gpointer dupe = NULL;
209
210         if (DuplicateToken (token, SecurityImpersonation, &dupe) == 0) {
211                 dupe = NULL;
212         }
213         return dupe;
214 }
215 #endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
216
217 gboolean
218 ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupId (gpointer user, gpointer group)
219 {
220         gboolean result = FALSE;
221
222         /* The convertion from an ID to a string is done in managed code for Windows */
223         g_warning ("IsMemberOfGroupId should never be called on Win32");
224         return result;
225 }
226
227 gboolean
228 ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupName (gpointer user, MonoString *group)
229 {
230         gboolean result = FALSE;
231
232         /* Windows version use a cache built using WindowsIdentity._GetRoles */
233         g_warning ("IsMemberOfGroupName should never be called on Win32");
234         return result;
235 }
236
237 #if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT)
238 static PSID
239 GetAdministratorsSid (void)
240 {
241         SID_IDENTIFIER_AUTHORITY admins = { SECURITY_NT_AUTHORITY };
242         PSID pSid = NULL;
243         if (!AllocateAndInitializeSid (&admins, 2, SECURITY_BUILTIN_DOMAIN_RID,
244                 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pSid))
245                 return NULL;
246         /* Note: this SID must be freed with FreeSid () */
247         return pSid;
248 }
249
250 static PSID
251 GetEveryoneSid (void)
252 {
253         SID_IDENTIFIER_AUTHORITY everyone = { SECURITY_WORLD_SID_AUTHORITY };
254         PSID pSid = NULL;
255         if (!AllocateAndInitializeSid (&everyone, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pSid))
256                 return NULL;
257         /* Note: this SID must be freed with FreeSid () */
258         return pSid;
259 }
260
261 static PSID
262 GetCurrentUserSid (void)
263 {
264         PSID sid = NULL;
265         guint32 size = 0;
266         gpointer token = ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken ();
267
268         GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
269         if (size > 0) {
270                 TOKEN_USER *tu = g_malloc0 (size);
271                 if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
272                         DWORD length = GetLengthSid (tu->User.Sid);
273                         sid = (PSID) g_malloc0 (length);
274                         if (!CopySid (length, sid, tu->User.Sid)) {
275                                 g_free (sid);
276                                 sid = NULL;
277                         }
278                 }
279                 g_free (tu);
280         }
281         /* Note: this SID must be freed with g_free () */
282         return sid;
283 }
284
285 static ACCESS_MASK
286 GetRightsFromSid (PSID sid, PACL acl)
287 {
288         ACCESS_MASK rights = 0;
289         TRUSTEE trustee;
290
291         BuildTrusteeWithSidW (&trustee, sid);
292         if (GetEffectiveRightsFromAcl (acl, &trustee, &rights) != ERROR_SUCCESS)
293                 return 0;
294
295         return rights;
296 }
297
298 gboolean
299 mono_security_win_is_machine_protected (gunichar2 *path)
300 {
301         gboolean success = FALSE;
302         PACL pDACL = NULL;
303         PSECURITY_DESCRIPTOR pSD = NULL;
304         PSID pEveryoneSid = NULL;
305
306         DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, &pSD);
307         if (dwRes != ERROR_SUCCESS)
308                 return FALSE;
309
310         /* We check that Everyone is still limited to READ-ONLY -
311         but not if new entries have been added by an Administrator */
312
313         pEveryoneSid = GetEveryoneSid ();
314         if (pEveryoneSid) {
315                 ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
316                 /* http://msdn.microsoft.com/library/en-us/security/security/generic_access_rights.asp?frame=true */
317                 success = (rights == (READ_CONTROL | SYNCHRONIZE | FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES));
318                 FreeSid (pEveryoneSid);
319         }
320         /* Note: we don't need to check our own access -
321         we'll know soon enough when reading the file */
322
323         if (pSD)
324                 LocalFree (pSD);
325
326         return success;
327 }
328
329 gboolean
330 mono_security_win_is_user_protected (gunichar2 *path)
331 {
332         gboolean success = FALSE;
333         PACL pDACL = NULL;
334         PSID pEveryoneSid = NULL;
335         PSECURITY_DESCRIPTOR pSecurityDescriptor = NULL;
336
337         DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT,
338                 DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, &pSecurityDescriptor);
339         if (dwRes != ERROR_SUCCESS)
340                 return FALSE;
341
342         /* We check that our original entries in the ACL are in place -
343         but not if new entries have been added by the user */
344
345         /* Everyone should be denied */
346         pEveryoneSid = GetEveryoneSid ();
347         if (pEveryoneSid) {
348                 ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
349                 success = (rights == 0);
350                 FreeSid (pEveryoneSid);
351         }
352         /* Note: we don't need to check our own access -
353         we'll know soon enough when reading the file */
354
355         if (pSecurityDescriptor)
356                 LocalFree (pSecurityDescriptor);
357
358         return success;
359 }
360
361 gboolean
362 mono_security_win_protect_machine (gunichar2 *path)
363 {
364         PSID pEveryoneSid = GetEveryoneSid ();
365         PSID pAdminsSid = GetAdministratorsSid ();
366         DWORD retval = -1;
367
368         if (pEveryoneSid && pAdminsSid) {
369                 PACL pDACL = NULL;
370                 EXPLICIT_ACCESS ea [2];
371                 ZeroMemory (&ea, 2 * sizeof (EXPLICIT_ACCESS));
372
373                 /* grant all access to the BUILTIN\Administrators group */
374                 BuildTrusteeWithSidW (&ea [0].Trustee, pAdminsSid);
375                 ea [0].grfAccessPermissions = GENERIC_ALL;
376                 ea [0].grfAccessMode = SET_ACCESS;
377                 ea [0].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
378                 ea [0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
379                 ea [0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
380
381                 /* read-only access everyone */
382                 BuildTrusteeWithSidW (&ea [1].Trustee, pEveryoneSid);
383                 ea [1].grfAccessPermissions = GENERIC_READ;
384                 ea [1].grfAccessMode = SET_ACCESS;
385                 ea [1].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
386                 ea [1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
387                 ea [1].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
388
389                 retval = SetEntriesInAcl (2, ea, NULL, &pDACL);
390                 if (retval == ERROR_SUCCESS) {
391                         /* with PROTECTED_DACL_SECURITY_INFORMATION we */
392                         /* remove any existing ACL (like inherited ones) */
393                         retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT,
394                                 DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
395                                 NULL, NULL, pDACL, NULL);
396                 }
397                 if (pDACL)
398                         LocalFree (pDACL);
399         }
400
401         if (pEveryoneSid)
402                 FreeSid (pEveryoneSid);
403         if (pAdminsSid)
404                 FreeSid (pAdminsSid);
405         return (retval == ERROR_SUCCESS);
406 }
407
408 gboolean
409 mono_security_win_protect_user (gunichar2 *path)
410 {
411         DWORD retval = -1;
412
413         PSID pCurrentSid = GetCurrentUserSid ();
414         if (pCurrentSid) {
415                 PACL pDACL = NULL;
416                 EXPLICIT_ACCESS ea;
417                 ZeroMemory (&ea, sizeof (EXPLICIT_ACCESS));
418
419                 /* grant exclusive access to the current user */
420                 BuildTrusteeWithSidW (&ea.Trustee, pCurrentSid);
421                 ea.grfAccessPermissions = GENERIC_ALL;
422                 ea.grfAccessMode = SET_ACCESS;
423                 ea.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
424                 ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
425                 ea.Trustee.TrusteeType = TRUSTEE_IS_USER;
426
427                 retval = SetEntriesInAcl (1, &ea, NULL, &pDACL);
428                 if (retval == ERROR_SUCCESS) {
429                         /* with PROTECTED_DACL_SECURITY_INFORMATION we
430                            remove any existing ACL (like inherited ones) */
431                         retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT,
432                                 DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
433                                 NULL, NULL, pDACL, NULL);
434                 }
435
436                 if (pDACL)
437                         LocalFree (pDACL);
438                 g_free (pCurrentSid); /* g_malloc0 */
439         }
440
441         return (retval == ERROR_SUCCESS);
442 }
443 #endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT) */
444
445 MonoBoolean
446 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_CanSecure (MonoString *root)
447 {
448         gint32 flags;
449
450         /* ACL are nice... unless you have FAT or other uncivilized filesystem */
451         if (!GetVolumeInformation (mono_string_chars (root), NULL, 0, NULL, NULL, (LPDWORD)&flags, NULL, 0))
452                 return FALSE;
453         return ((flags & FS_PERSISTENT_ACLS) == FS_PERSISTENT_ACLS);
454 }
455
456 MonoBoolean
457 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsMachineProtected (MonoString *path)
458 {
459         gboolean ret = FALSE;
460
461         /* no one, but the owner, should have write access to the directory */
462         ret = mono_security_win_is_machine_protected (mono_string_chars (path));
463         return (MonoBoolean)ret;
464 }
465
466 MonoBoolean
467 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsUserProtected (MonoString *path)
468 {
469         gboolean ret = FALSE;
470
471         /* no one, but the user, should have access to the directory */
472         ret = mono_security_win_is_user_protected (mono_string_chars (path));
473         return (MonoBoolean)ret;
474 }
475
476 MonoBoolean
477 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectMachine (MonoString *path)
478 {
479         gboolean ret = FALSE;
480
481         /* read/write to owner, read to everyone else */
482         ret = mono_security_win_protect_machine (mono_string_chars (path));
483         return (MonoBoolean)ret;
484 }
485
486 MonoBoolean
487 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectUser (MonoString *path)
488 {
489         gboolean ret = FALSE;
490
491         /* read/write to user, no access to everyone else */
492         ret = mono_security_win_protect_user (mono_string_chars (path));
493         return (MonoBoolean)ret;
494 }
495 #endif /* HOST_WIN32 */