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