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