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