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