Merge pull request #1439 from BrzVlad/feature-managed-allocator
[mono.git] / mono / metadata / mono-security.c
1 /*
2  * security.c:  Security internal calls
3  *
4  * Author:
5  *      Sebastien Pouliot  <sebastien@ximian.com>
6  *
7  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
8  */
9
10 #ifdef HAVE_CONFIG_H
11 #include <config.h>
12 #endif
13
14 #include <mono/metadata/assembly.h>
15 #include <mono/metadata/appdomain.h>
16 #include <mono/metadata/image.h>
17 #include <mono/metadata/exception.h>
18 #include <mono/metadata/object-internals.h>
19 #include <mono/metadata/metadata-internals.h>
20 #include <mono/metadata/security.h>
21 #include <mono/io-layer/io-layer.h>
22 #include <mono/utils/strenc.h>
23
24 #ifdef HOST_WIN32
25
26 #include <aclapi.h>
27 #include <accctrl.h>
28
29 #ifndef PROTECTED_DACL_SECURITY_INFORMATION
30 #define PROTECTED_DACL_SECURITY_INFORMATION     0x80000000L
31 #endif
32
33 #else
34
35 #include <config.h>
36 #ifdef HAVE_GRP_H
37 #include <grp.h>
38 #endif
39 #ifdef HAVE_PWD_H
40 #include <pwd.h>
41 #endif
42 #include <string.h>
43 #include <sys/stat.h>
44 #include <sys/types.h>
45 #include <unistd.h>
46
47 /* Disclaimers */
48
49 #if defined(__GNUC__)
50
51 #ifndef HAVE_GETGRGID_R
52         #warning Non-thread safe getgrgid being used!
53 #endif
54 #ifndef HAVE_GETGRNAM_R
55         #warning Non-thread safe getgrnam being used!
56 #endif
57 #ifndef HAVE_GETPWNAM_R
58         #warning Non-thread safe getpwnam being used!
59 #endif
60 #ifndef HAVE_GETPWUID_R
61         #warning Non-thread safe getpwuid being used!
62 #endif
63
64 #endif /* defined(__GNUC__) */
65
66 #endif /* not HOST_WIN32 */
67
68
69 /* internal functions - reuse driven */
70
71 #ifdef HOST_WIN32
72
73 /* ask a server to translate a SID into a textual representation */
74 static gunichar2*
75 GetSidName (gunichar2 *server, PSID sid, gint32 *size) 
76 {
77         gunichar2 *uniname = NULL;
78         DWORD cchName = 0;
79         DWORD cchDomain = 0;
80         SID_NAME_USE peUse; /* out */
81
82         LookupAccountSid (server, sid, NULL, &cchName, NULL, 
83                 &cchDomain, &peUse); 
84         
85         if ((cchName > 0) && (cchDomain > 0)) {
86                 gunichar2 *user = g_malloc0 ((cchName + 1) * 2);
87                 gunichar2 *domain = g_malloc0 ((cchDomain + 1) * 2);
88
89                 LookupAccountSid (server, sid, user, &cchName, domain,
90                         &cchDomain, &peUse);
91
92                 if (cchName > 0) {
93                         if (cchDomain > 0) {
94                                 /* domain/machine name included (+ sepearator) */
95                                 *size = cchName + cchDomain + 1;
96                                 uniname = g_malloc0 ((*size + 1) * 2);
97                                 memcpy (uniname, domain, cchDomain * 2);
98                                 *(uniname + cchDomain) = '\\';
99                                 memcpy (uniname + cchDomain + 1, user, cchName * 2);
100                                 g_free (user);
101                         }
102                         else {
103                                 /* no domain / machine */
104                                 *size = cchName;
105                                 uniname = user;
106                         }
107                 }
108                 else {
109                         /* nothing -> return NULL */
110                         g_free (user);
111                 }
112
113                 g_free (domain);
114         }
115
116         return uniname;
117 }
118
119
120 #else /* not HOST_WIN32 */
121
122 #define MONO_SYSCONF_DEFAULT_SIZE       ((size_t) 1024)
123
124 /*
125  * Ensure we always get a valid (usable) value from sysconf.
126  * In case of error, we return the default value.
127  */
128 static size_t mono_sysconf (int name)
129 {
130         size_t size = (size_t) sysconf (name);
131         /* default value */
132         return (size == -1) ? MONO_SYSCONF_DEFAULT_SIZE : size;
133 }
134
135
136 static gchar*
137 GetTokenName (uid_t uid)
138 {
139         gchar *uname = NULL;
140
141 #ifdef HAVE_GETPWUID_R
142         struct passwd pwd;
143         size_t fbufsize;
144         gchar *fbuf;
145         gint32 retval;
146 #endif
147         struct passwd *p = NULL;
148         gboolean result;
149
150 #ifdef HAVE_GETPWUID_R
151 #ifdef _SC_GETPW_R_SIZE_MAX
152         fbufsize = mono_sysconf (_SC_GETPW_R_SIZE_MAX);
153 #else
154         fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
155 #endif
156         fbuf = g_malloc0 (fbufsize);
157         retval = getpwuid_r (uid, &pwd, fbuf, fbufsize, &p);
158         result = ((retval == 0) && (p == &pwd));
159 #else
160         /* default to non thread-safe but posix compliant function */
161         p = getpwuid (uid);
162         result = (p != NULL);
163 #endif
164
165         if (result) {
166                 uname = g_strdup (p->pw_name);
167         }
168
169 #ifdef HAVE_GETPWUID_R
170         g_free (fbuf);
171 #endif
172
173         return uname;
174 }
175
176
177 static gboolean
178 IsMemberInList (uid_t user, struct group *g) 
179 {
180         gboolean result = FALSE;
181         gchar *utf8_username = GetTokenName (user);
182
183         if (!utf8_username)
184                 return FALSE;
185
186         if (g) {
187                 gchar **users = g->gr_mem;
188
189                 while (*users) {
190                         gchar *u = *(users);
191                         if (strcmp (utf8_username, u) == 0) {
192                                 result = TRUE;
193                                 break;
194                         }
195                         users++;
196                 }
197         }               
198
199         g_free (utf8_username);
200         return result;
201 }
202
203
204 static gboolean
205 IsDefaultGroup (uid_t user, gid_t group)
206 {
207 #ifdef HAVE_GETPWUID_R
208         struct passwd pwd;
209         size_t fbufsize;
210         gchar *fbuf;
211         gint32 retval;
212 #endif
213         struct passwd *p = NULL;
214         gboolean result;
215
216 #ifdef HAVE_GETPWUID_R
217 #ifdef _SC_GETPW_R_SIZE_MAX
218         fbufsize = mono_sysconf (_SC_GETPW_R_SIZE_MAX);
219 #else
220         fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
221 #endif
222
223         fbuf = g_malloc0 (fbufsize);
224         retval = getpwuid_r (user, &pwd, fbuf, fbufsize, &p);
225         result = ((retval == 0) && (p == &pwd));
226 #else
227         /* default to non thread-safe but posix compliant function */
228         p = getpwuid (user);
229         result = (p != NULL);
230 #endif
231
232         if (result) {
233                 result = (p->pw_gid == group);
234         }
235
236 #ifdef HAVE_GETPWUID_R
237         g_free (fbuf);
238 #endif
239
240         return result;
241 }
242
243
244 static gboolean
245 IsMemberOf (gid_t user, struct group *g) 
246 {
247         if (!g)
248                 return FALSE;
249
250         /* is it the user default group */
251         if (IsDefaultGroup (user, g->gr_gid))
252                 return TRUE;
253
254         /* is the user in the group list */
255         return IsMemberInList (user, g);
256 }
257
258 #endif
259
260
261 /* ICALLS */
262
263
264 /* System.Security.Principal.WindowsIdentity */
265
266
267 gpointer
268 ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken (void)
269 {
270         gpointer token = NULL;
271
272 #ifdef HOST_WIN32
273         /* Note: This isn't a copy of the Token - we must not close it!!!
274          * http://www.develop.com/kbrown/book/html/whatis_windowsprincipal.html
275          */
276
277         /* thread may be impersonating somebody */
278         if (OpenThreadToken (GetCurrentThread (), TOKEN_QUERY, 1, &token) == 0) {
279                 /* if not take the process identity */
280                 OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &token);
281         }
282 #else
283         token = GINT_TO_POINTER (geteuid ());
284 #endif
285         return token;
286 }
287
288
289 MonoString*
290 ves_icall_System_Security_Principal_WindowsIdentity_GetTokenName (gpointer token)
291 {
292         MonoString *result = NULL;
293         gunichar2 *uniname = NULL;
294         gint32 size = 0;
295
296 #ifdef HOST_WIN32
297         GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
298         if (size > 0) {
299                 TOKEN_USER *tu = g_malloc0 (size);
300                 if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
301                         uniname = GetSidName (NULL, tu->User.Sid, &size);
302                 }
303                 g_free (tu);
304         }
305 #else 
306         gchar *uname = GetTokenName ((uid_t) GPOINTER_TO_INT (token));
307
308         if (uname) {
309                 size = strlen (uname);
310                 uniname = g_utf8_to_utf16 (uname, size, NULL, NULL, NULL);
311                 g_free (uname);
312         }
313 #endif /* HOST_WIN32 */
314
315         if (size > 0) {
316                 result = mono_string_new_utf16 (mono_domain_get (), uniname, size);
317         }
318         else
319                 result = mono_string_new (mono_domain_get (), "");
320
321         if (uniname)
322                 g_free (uniname);
323
324         return result;
325 }
326
327
328 gpointer
329 ves_icall_System_Security_Principal_WindowsIdentity_GetUserToken (MonoString *username)
330 {
331 #ifdef HOST_WIN32
332         gpointer token = NULL;
333
334         /* TODO: MS has something like this working in Windows 2003 (client and
335          * server) but works only for domain accounts (so it's quite limiting).
336          * http://www.develop.com/kbrown/book/html/howto_logonuser.html
337          */
338         g_warning ("Unsupported on Win32 (anyway requires W2K3 minimum)");
339
340 #else /* HOST_WIN32*/
341
342 #ifdef HAVE_GETPWNAM_R
343         struct passwd pwd;
344         size_t fbufsize;
345         gchar *fbuf;
346         gint32 retval;
347 #endif
348         gpointer token = (gpointer) -2;
349         struct passwd *p;
350         gchar *utf8_name;
351         gboolean result;
352
353         utf8_name = mono_unicode_to_external (mono_string_chars (username));
354
355 #ifdef HAVE_GETPWNAM_R
356 #ifdef _SC_GETPW_R_SIZE_MAX
357         fbufsize = mono_sysconf (_SC_GETPW_R_SIZE_MAX);
358 #else
359         fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
360 #endif
361
362         fbuf = g_malloc0 (fbufsize);
363         retval = getpwnam_r (utf8_name, &pwd, fbuf, fbufsize, &p);
364         result = ((retval == 0) && (p == &pwd));
365 #else
366         /* default to non thread-safe but posix compliant function */
367         p = getpwnam (utf8_name);
368         result = (p != NULL);
369 #endif
370
371         if (result) {
372                 token = GINT_TO_POINTER (p->pw_uid);
373         }
374
375 #ifdef HAVE_GETPWNAM_R
376         g_free (fbuf);
377 #endif
378         g_free (utf8_name);
379 #endif
380         return token;
381 }
382
383
384 /* http://www.dotnet247.com/247reference/msgs/39/195403.aspx
385 // internal static string[] WindowsIdentity._GetRoles (IntPtr token)
386 */
387 MonoArray*
388 ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token) 
389 {
390         MonoArray *array = NULL;
391         MonoDomain *domain = mono_domain_get (); 
392 #ifdef HOST_WIN32
393         gint32 size = 0;
394
395         GetTokenInformation (token, TokenGroups, NULL, size, (PDWORD)&size);
396         if (size > 0) {
397                 TOKEN_GROUPS *tg = g_malloc0 (size);
398                 if (GetTokenInformation (token, TokenGroups, tg, size, (PDWORD)&size)) {
399                         int i=0;
400                         int num = tg->GroupCount;
401
402                         array = mono_array_new (domain, mono_get_string_class (), num);
403
404                         for (i=0; i < num; i++) {
405                                 gint32 size = 0;
406                                 gunichar2 *uniname = GetSidName (NULL, tg->Groups [i].Sid, &size);
407
408                                 if (uniname) {
409                                         MonoString *str = mono_string_new_utf16 (domain, uniname, size);
410                                         mono_array_setref (array, i, str);
411                                         g_free (uniname);
412                                 }
413                         }
414                 }
415                 g_free (tg);
416         }
417 #else
418         /* POSIX-compliant systems should use IsMemberOfGroupId or IsMemberOfGroupName */
419         g_warning ("WindowsIdentity._GetRoles should never be called on POSIX");
420 #endif
421         if (!array) {
422                 /* return empty array of string, i.e. string [0] */
423                 array = mono_array_new (domain, mono_get_string_class (), 0);
424         }
425         return array;
426 }
427
428
429 /* System.Security.Principal.WindowsImpersonationContext */
430
431
432 gboolean
433 ves_icall_System_Security_Principal_WindowsImpersonationContext_CloseToken (gpointer token)
434 {
435         gboolean result = TRUE;
436
437 #ifdef HOST_WIN32
438         result = (CloseHandle (token) != 0);
439 #endif
440         return result;
441 }
442
443
444 gpointer
445 ves_icall_System_Security_Principal_WindowsImpersonationContext_DuplicateToken (gpointer token)
446 {
447         gpointer dupe = NULL;
448
449 #ifdef HOST_WIN32
450         if (DuplicateToken (token, SecurityImpersonation, &dupe) == 0) {
451                 dupe = NULL;
452         }
453 #else
454         dupe = token;
455 #endif
456         return dupe;
457 }
458
459
460 gboolean
461 ves_icall_System_Security_Principal_WindowsImpersonationContext_SetCurrentToken (gpointer token)
462 {
463         /* Posix version implemented in /mono/mono/io-layer/security.c */
464         return (ImpersonateLoggedOnUser (token) != 0);
465 }
466
467
468 gboolean
469 ves_icall_System_Security_Principal_WindowsImpersonationContext_RevertToSelf (void)
470 {
471         /* Posix version implemented in /mono/mono/io-layer/security.c */
472         return (RevertToSelf () != 0);
473 }
474
475
476 /* System.Security.Principal.WindowsPrincipal */
477
478 gboolean
479 ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupId (gpointer user, gpointer group)
480 {
481         gboolean result = FALSE;
482
483 #ifdef HOST_WIN32
484         /* The convertion from an ID to a string is done in managed code for Windows */
485         g_warning ("IsMemberOfGroupId should never be called on Win32");
486
487 #else /* HOST_WIN32 */
488
489 #ifdef HAVE_GETGRGID_R
490         struct group grp;
491         size_t fbufsize;
492         gchar *fbuf;
493         gint32 retval;
494 #endif
495         struct group *g = NULL;
496
497 #ifdef HAVE_GETGRGID_R
498 #ifdef _SC_GETGR_R_SIZE_MAX
499         fbufsize = mono_sysconf (_SC_GETGR_R_SIZE_MAX);
500 #else
501         fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
502 #endif
503         fbuf = g_malloc0 (fbufsize);
504         retval = getgrgid_r ((gid_t) GPOINTER_TO_INT (group), &grp, fbuf, fbufsize, &g);
505         result = ((retval == 0) && (g == &grp));
506 #else
507         /* default to non thread-safe but posix compliant function */
508         g = getgrgid ((gid_t) GPOINTER_TO_INT (group));
509         result = (g != NULL);
510 #endif
511
512         if (result) {
513                 result = IsMemberOf ((uid_t) GPOINTER_TO_INT (user), g);
514         }
515
516 #ifdef HAVE_GETGRGID_R
517         g_free (fbuf);
518 #endif
519
520 #endif /* HOST_WIN32 */
521
522         return result;
523 }
524
525
526 gboolean
527 ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupName (gpointer user, MonoString *group)
528 {
529         gboolean result = FALSE;
530
531 #ifdef HOST_WIN32
532         /* Windows version use a cache built using WindowsIdentity._GetRoles */
533         g_warning ("IsMemberOfGroupName should never be called on Win32");
534
535 #else /* HOST_WIN32 */
536         gchar *utf8_groupname;
537
538         utf8_groupname = mono_unicode_to_external (mono_string_chars (group));
539         if (utf8_groupname) {
540                 struct group *g = NULL;
541 #ifdef HAVE_GETGRNAM_R
542                 struct group grp;
543                 gchar *fbuf;
544                 gint32 retval;
545 #ifdef _SC_GETGR_R_SIZE_MAX
546                 size_t fbufsize = mono_sysconf (_SC_GETGR_R_SIZE_MAX);
547 #else
548                 size_t fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
549 #endif
550                 fbuf = g_malloc0 (fbufsize);
551                 retval = getgrnam_r (utf8_groupname, &grp, fbuf, fbufsize, &g);
552                 result = ((retval == 0) && (g == &grp));
553 #else
554                 /* default to non thread-safe but posix compliant function */
555                 g = getgrnam (utf8_groupname);
556                 result = (g != NULL);
557 #endif
558
559                 if (result) {
560                         result = IsMemberOf ((uid_t) GPOINTER_TO_INT (user), g);
561                 }
562
563 #ifdef HAVE_GETGRNAM_R
564                 g_free (fbuf);
565 #endif
566                 g_free (utf8_groupname);
567         }
568 #endif /* HOST_WIN32 */
569
570         return result;
571 }
572
573
574 /* Mono.Security.Cryptography IO related internal calls */
575
576 #ifdef HOST_WIN32
577
578 static PSID
579 GetAdministratorsSid (void) 
580 {
581         SID_IDENTIFIER_AUTHORITY admins = SECURITY_NT_AUTHORITY;
582         PSID pSid = NULL;
583         if (!AllocateAndInitializeSid (&admins, 2, SECURITY_BUILTIN_DOMAIN_RID, 
584                 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pSid)) 
585                 return NULL;
586         /* Note: this SID must be freed with FreeSid () */
587         return pSid;
588 }
589
590
591 static PSID
592 GetEveryoneSid (void)
593 {
594         SID_IDENTIFIER_AUTHORITY everyone = SECURITY_WORLD_SID_AUTHORITY;
595         PSID pSid = NULL;
596         if (!AllocateAndInitializeSid (&everyone, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pSid))
597                 return NULL;
598         /* Note: this SID must be freed with FreeSid () */
599         return pSid;
600 }
601
602
603 static PSID
604 GetCurrentUserSid (void) 
605 {
606         PSID sid = NULL;
607         guint32 size = 0;
608         gpointer token = ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken ();
609
610         GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
611         if (size > 0) {
612                 TOKEN_USER *tu = g_malloc0 (size);
613                 if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
614                         DWORD length = GetLengthSid (tu->User.Sid);
615                         sid = (PSID) g_malloc0 (length);
616                         if (!CopySid (length, sid, tu->User.Sid)) {
617                                 g_free (sid);
618                                 sid = NULL;
619                         }
620                 }
621                 g_free (tu);
622         }
623         /* Note: this SID must be freed with g_free () */
624         return sid;
625 }
626
627
628 static ACCESS_MASK
629 GetRightsFromSid (PSID sid, PACL acl) 
630 {
631         ACCESS_MASK rights = 0;
632         TRUSTEE trustee;
633
634         BuildTrusteeWithSidW (&trustee, sid);
635         if (GetEffectiveRightsFromAcl (acl, &trustee, &rights) != ERROR_SUCCESS)
636                 return 0;
637
638         return rights;
639 }
640
641
642 static gboolean 
643 IsMachineProtected (gunichar2 *path)
644 {
645         gboolean success = FALSE;
646         PACL pDACL = NULL;
647         PSID pEveryoneSid = NULL;
648
649         DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, NULL);
650         if (dwRes != ERROR_SUCCESS)
651                 return FALSE;
652
653         /* We check that Everyone is still limited to READ-ONLY -
654         but not if new entries have been added by an Administrator */
655
656         pEveryoneSid = GetEveryoneSid ();
657         if (pEveryoneSid) {
658                 ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
659                 /* http://msdn.microsoft.com/library/en-us/security/security/generic_access_rights.asp?frame=true */
660                 success = (rights == (READ_CONTROL | SYNCHRONIZE | FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES));
661                 FreeSid (pEveryoneSid);
662         }
663         /* Note: we don't need to check our own access - 
664         we'll know soon enough when reading the file */
665
666         if (pDACL)
667                 LocalFree (pDACL);
668
669         return success;
670 }
671
672
673 static gboolean 
674 IsUserProtected (gunichar2 *path)
675 {
676         gboolean success = FALSE;
677         PACL pDACL = NULL;
678         PSID pEveryoneSid = NULL;
679         PSECURITY_DESCRIPTOR pSecurityDescriptor = NULL;
680
681         DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT, 
682                 DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, &pSecurityDescriptor);
683         if (dwRes != ERROR_SUCCESS)
684                 return FALSE;
685
686         /* We check that our original entries in the ACL are in place -
687         but not if new entries have been added by the user */
688
689         /* Everyone should be denied */
690         pEveryoneSid = GetEveryoneSid ();
691         if (pEveryoneSid) {
692                 ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
693                 success = (rights == 0);
694                 FreeSid (pEveryoneSid);
695         }
696         /* Note: we don't need to check our own access - 
697         we'll know soon enough when reading the file */
698
699         if (pSecurityDescriptor)
700                 LocalFree (pSecurityDescriptor);
701
702         return success;
703 }
704
705
706 static gboolean 
707 ProtectMachine (gunichar2 *path)
708 {
709         PSID pEveryoneSid = GetEveryoneSid ();
710         PSID pAdminsSid = GetAdministratorsSid ();
711         DWORD retval = -1;
712
713         if (pEveryoneSid && pAdminsSid) {
714                 PACL pDACL = NULL;
715                 EXPLICIT_ACCESS ea [2];
716                 ZeroMemory (&ea, 2 * sizeof (EXPLICIT_ACCESS));
717
718                 /* grant all access to the BUILTIN\Administrators group */
719                 BuildTrusteeWithSidW (&ea [0].Trustee, pAdminsSid);
720                 ea [0].grfAccessPermissions = GENERIC_ALL;
721                 ea [0].grfAccessMode = SET_ACCESS;
722                 ea [0].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
723                 ea [0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
724                 ea [0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
725
726                 /* read-only access everyone */
727                 BuildTrusteeWithSidW (&ea [1].Trustee, pEveryoneSid);
728                 ea [1].grfAccessPermissions = GENERIC_READ;
729                 ea [1].grfAccessMode = SET_ACCESS;
730                 ea [1].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
731                 ea [1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
732                 ea [1].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
733
734                 retval = SetEntriesInAcl (2, ea, NULL, &pDACL);
735                 if (retval == ERROR_SUCCESS) {
736                         /* with PROTECTED_DACL_SECURITY_INFORMATION we */
737                         /* remove any existing ACL (like inherited ones) */
738                         retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT, 
739                                 DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
740                                 NULL, NULL, pDACL, NULL);
741                 }
742                 if (pDACL)
743                         LocalFree (pDACL);
744         }
745
746         if (pEveryoneSid)
747                 FreeSid (pEveryoneSid);
748         if (pAdminsSid)
749                 FreeSid (pAdminsSid);
750         return (retval == ERROR_SUCCESS);
751 }
752
753
754 static gboolean 
755 ProtectUser (gunichar2 *path)
756 {
757         DWORD retval = -1;
758
759         PSID pCurrentSid = GetCurrentUserSid ();
760         if (pCurrentSid) {
761                 PACL pDACL = NULL;
762                 EXPLICIT_ACCESS ea;
763                 ZeroMemory (&ea, sizeof (EXPLICIT_ACCESS));
764
765                 /* grant exclusive access to the current user */
766                 BuildTrusteeWithSidW (&ea.Trustee, pCurrentSid);
767                 ea.grfAccessPermissions = GENERIC_ALL;
768                 ea.grfAccessMode = SET_ACCESS;
769                 ea.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
770                 ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
771                 ea.Trustee.TrusteeType = TRUSTEE_IS_USER;
772
773                 retval = SetEntriesInAcl (1, &ea, NULL, &pDACL);
774                 if (retval == ERROR_SUCCESS) {
775                         /* with PROTECTED_DACL_SECURITY_INFORMATION we
776                            remove any existing ACL (like inherited ones) */
777                         retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT, 
778                                 DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
779                                 NULL, NULL, pDACL, NULL);
780                 }
781
782                 if (pDACL)
783                         LocalFree (pDACL);
784                 g_free (pCurrentSid); /* g_malloc0 */
785         }
786
787         return (retval == ERROR_SUCCESS);
788 }
789
790 #else
791
792 static gboolean 
793 IsProtected (MonoString *path, gint32 protection) 
794 {
795         gboolean result = FALSE;
796         gchar *utf8_name = mono_unicode_to_external (mono_string_chars (path));
797         if (utf8_name) {
798                 struct stat st;
799                 if (stat (utf8_name, &st) == 0) {
800                         result = (((st.st_mode & 0777) & protection) == 0);
801                 }
802                 g_free (utf8_name);
803         }
804         return result;
805 }
806
807
808 static gboolean 
809 Protect (MonoString *path, gint32 file_mode, gint32 add_dir_mode)
810 {
811         gboolean result = FALSE;
812         gchar *utf8_name = mono_unicode_to_external (mono_string_chars (path));
813         if (utf8_name) {
814                 struct stat st;
815                 if (stat (utf8_name, &st) == 0) {
816                         int mode = file_mode;
817                         if (st.st_mode & S_IFDIR)
818                                 mode |= add_dir_mode;
819                         result = (chmod (utf8_name, mode) == 0);
820                 }
821                 g_free (utf8_name);
822         }
823         return result;
824 }
825
826 #endif /* not HOST_WIN32 */
827
828
829 MonoBoolean
830 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_CanSecure (MonoString *root)
831 {
832 #if HOST_WIN32
833         gint32 flags;
834
835         /* ACL are nice... unless you have FAT or other uncivilized filesystem */
836         if (!GetVolumeInformation (mono_string_chars (root), NULL, 0, NULL, NULL, (LPDWORD)&flags, NULL, 0))
837                 return FALSE;
838         return ((flags & FS_PERSISTENT_ACLS) == FS_PERSISTENT_ACLS);
839 #else
840         /* we assume some kind of security is applicable outside Windows */
841         return TRUE;
842 #endif
843 }
844
845
846 MonoBoolean
847 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsMachineProtected (MonoString *path)
848 {
849         gboolean ret = FALSE;
850
851         /* no one, but the owner, should have write access to the directory */
852 #ifdef HOST_WIN32
853         ret = IsMachineProtected (mono_string_chars (path));
854 #else
855         ret = IsProtected (path, (S_IWGRP | S_IWOTH));
856 #endif
857         return ret;
858 }
859
860
861 MonoBoolean
862 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsUserProtected (MonoString *path)
863 {
864         gboolean ret = FALSE;
865
866         /* no one, but the user, should have access to the directory */
867 #ifdef HOST_WIN32
868         ret = IsUserProtected (mono_string_chars (path));
869 #else
870         ret = IsProtected (path, (S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH));
871 #endif
872         return ret;
873 }
874
875
876 MonoBoolean
877 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectMachine (MonoString *path)
878 {
879         gboolean ret = FALSE;
880
881         /* read/write to owner, read to everyone else */
882 #ifdef HOST_WIN32
883         ret = ProtectMachine (mono_string_chars (path));
884 #else
885         ret = Protect (path, (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH), (S_IXUSR | S_IXGRP | S_IXOTH));
886 #endif
887         return ret;
888 }
889
890
891 MonoBoolean
892 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectUser (MonoString *path)
893 {
894         gboolean ret = FALSE;
895         
896         /* read/write to user, no access to everyone else */
897 #ifdef HOST_WIN32
898         ret = ProtectUser (mono_string_chars (path));
899 #else
900         ret = Protect (path, (S_IRUSR | S_IWUSR), S_IXUSR);
901 #endif
902         return ret;
903 }
904
905
906 /*
907  * Returns TRUE if there is "something" where the Authenticode signature is 
908  * normally located. Returns FALSE is data directory is empty.
909  *
910  * Note: Neither the structure nor the signature is verified by this function.
911  */
912 MonoBoolean
913 ves_icall_System_Security_Policy_Evidence_IsAuthenticodePresent (MonoReflectionAssembly *refass)
914 {
915         if (refass && refass->assembly && refass->assembly->image) {
916                 return mono_image_has_authenticode_entry (refass->assembly->image);
917         }
918         return FALSE;
919 }
920
921
922 /* System.Security.SecureString related internal calls */
923
924 static MonoImage *system_security_assembly = NULL;
925
926 void
927 ves_icall_System_Security_SecureString_DecryptInternal (MonoArray *data, MonoObject *scope)
928 {
929         invoke_protected_memory_method (data, scope, FALSE);
930 }
931 void
932 ves_icall_System_Security_SecureString_EncryptInternal (MonoArray* data, MonoObject *scope)
933 {
934         invoke_protected_memory_method (data, scope, TRUE);
935 }
936
937 void invoke_protected_memory_method (MonoArray *data, MonoObject *scope, gboolean encrypt)
938 {
939         MonoClass *klass;
940         MonoMethod *method;
941         void *params [2];
942
943         if (system_security_assembly == NULL) {
944                 system_security_assembly = mono_image_loaded ("System.Security");
945                 if (!system_security_assembly) {
946                         MonoAssembly *sa = mono_assembly_open ("System.Security.dll", NULL);
947                         if (!sa)
948                                 g_assert_not_reached ();
949                         system_security_assembly = mono_assembly_get_image (sa);
950                 }
951         }
952
953         klass = mono_class_from_name (system_security_assembly,
954                                                                   "System.Security.Cryptography", "ProtectedMemory");
955         method = mono_class_get_method_from_name (klass, encrypt ? "Protect" : "Unprotect", 2);
956         params [0] = data;
957         params [1] = scope; /* MemoryProtectionScope.SameProcess */
958         mono_runtime_invoke (method, NULL, params, NULL);
959 }