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