2 * security.c: Security internal calls
5 * Sebastien Pouliot <sebastien@ximian.com>
7 * (C) 2004 Novell (http://www.novell.com)
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>
28 #ifndef PROTECTED_DACL_SECURITY_INFORMATION
29 #define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
39 #include <sys/types.h>
46 #ifndef HAVE_GETGRGID_R
47 #warning Non-thread safe getgrgid being used!
49 #ifndef HAVE_GETGRNAM_R
50 #warning Non-thread safe getgrnam being used!
52 #ifndef HAVE_GETPWNAM_R
53 #warning Non-thread safe getpwnam being used!
55 #ifndef HAVE_GETPWUID_R
56 #warning Non-thread safe getpwuid being used!
59 #endif /* defined(__GNUC__) */
61 #endif /* not PLATFORM_WIN32 */
64 /* internal functions - reuse driven */
68 /* ask a server to translate a SID into a textual representation */
70 GetSidName (gunichar2 *server, PSID sid, gint32 *size)
72 gunichar2 *uniname = NULL;
75 SID_NAME_USE peUse; /* out */
77 LookupAccountSid (server, sid, NULL, &cchName, NULL,
80 if ((cchName > 0) && (cchDomain > 0)) {
81 gunichar2 *user = g_malloc0 ((cchName + 1) * 2);
82 gunichar2 *domain = g_malloc0 ((cchDomain + 1) * 2);
84 LookupAccountSid (server, sid, user, &cchName, domain,
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);
98 /* no domain / machine */
104 /* nothing -> return NULL */
115 #else /* not PLATFORM_WIN32 */
117 #define MONO_SYSCONF_DEFAULT_SIZE ((size_t) 1024)
120 * Ensure we always get a valid (usable) value from sysconf.
121 * In case of error, we return the default value.
123 static size_t mono_sysconf (int name)
125 size_t size = (size_t) sysconf (name);
127 return (size == -1) ? MONO_SYSCONF_DEFAULT_SIZE : size;
132 GetTokenName (uid_t uid)
136 #ifdef HAVE_GETPWUID_R
142 struct passwd *p = NULL;
145 #ifdef HAVE_GETPWUID_R
146 #ifdef _SC_GETPW_R_SIZE_MAX
147 fbufsize = mono_sysconf (_SC_GETPW_R_SIZE_MAX);
149 fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
151 fbuf = g_malloc0 (fbufsize);
152 retval = getpwuid_r (uid, &pwd, fbuf, fbufsize, &p);
153 result = ((retval == 0) && (p == &pwd));
155 /* default to non thread-safe but posix compliant function */
157 result = (p != NULL);
161 uname = g_strdup (p->pw_name);
164 #ifdef HAVE_GETPWUID_R
173 IsMemberInList (uid_t user, struct group *g)
175 gboolean result = FALSE;
176 gchar *utf8_username = GetTokenName (user);
182 gchar **users = g->gr_mem;
186 if (strcmp (utf8_username, u) == 0) {
194 g_free (utf8_username);
200 IsDefaultGroup (uid_t user, gid_t group)
202 #ifdef HAVE_GETPWUID_R
208 struct passwd *p = NULL;
211 #ifdef HAVE_GETPWUID_R
212 #ifdef _SC_GETPW_R_SIZE_MAX
213 fbufsize = mono_sysconf (_SC_GETPW_R_SIZE_MAX);
215 fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
218 fbuf = g_malloc0 (fbufsize);
219 retval = getpwuid_r (user, &pwd, fbuf, fbufsize, &p);
220 result = ((retval == 0) && (p == &pwd));
222 /* default to non thread-safe but posix compliant function */
224 result = (p != NULL);
228 result = (p->pw_gid == group);
231 #ifdef HAVE_GETPWUID_R
240 IsMemberOf (gid_t user, struct group *g)
245 /* is it the user default group */
246 if (IsDefaultGroup (user, g->gr_gid))
249 /* is the user in the group list */
250 return IsMemberInList (user, g);
259 /* System.Environment */
263 ves_icall_System_Environment_get_UserName (void)
267 /* using glib is more portable */
268 return mono_string_new (mono_domain_get (), g_get_user_name ());
272 /* System.Security.Principal.WindowsIdentity */
276 ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken (void)
278 gpointer token = NULL;
282 #ifdef PLATFORM_WIN32
283 /* Note: This isn't a copy of the Token - we must not close it!!!
284 * http://www.develop.com/kbrown/book/html/whatis_windowsprincipal.html
287 /* thread may be impersonating somebody */
288 if (OpenThreadToken (GetCurrentThread (), TOKEN_QUERY, 1, &token) == 0) {
289 /* if not take the process identity */
290 OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &token);
293 token = GINT_TO_POINTER (geteuid ());
300 ves_icall_System_Security_Principal_WindowsIdentity_GetTokenName (gpointer token)
302 MonoString *result = NULL;
303 gunichar2 *uniname = NULL;
306 #ifdef PLATFORM_WIN32
309 GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
311 TOKEN_USER *tu = g_malloc0 (size);
312 if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
313 uniname = GetSidName (NULL, tu->User.Sid, &size);
318 gchar *uname = GetTokenName ((uid_t) GPOINTER_TO_INT (token));
323 size = strlen (uname);
324 uniname = g_utf8_to_utf16 (uname, size, NULL, NULL, NULL);
327 #endif /* PLATFORM_WIN32 */
330 result = mono_string_new_utf16 (mono_domain_get (), uniname, size);
333 result = mono_string_new (mono_domain_get (), "");
343 ves_icall_System_Security_Principal_WindowsIdentity_GetUserToken (MonoString *username)
345 #ifdef PLATFORM_WIN32
346 gpointer token = NULL;
350 /* TODO: MS has something like this working in Windows 2003 (client and
351 * server) but works only for domain accounts (so it's quite limiting).
352 * http://www.develop.com/kbrown/book/html/howto_logonuser.html
354 g_warning ("Unsupported on Win32 (anyway requires W2K3 minimum)");
356 #else /* PLATFORM_WIN32*/
358 #ifdef HAVE_GETPWNAM_R
364 gpointer token = (gpointer) -2;
371 utf8_name = mono_unicode_to_external (mono_string_chars (username));
373 #ifdef HAVE_GETPWNAM_R
374 #ifdef _SC_GETPW_R_SIZE_MAX
375 fbufsize = mono_sysconf (_SC_GETPW_R_SIZE_MAX);
377 fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
380 fbuf = g_malloc0 (fbufsize);
381 retval = getpwnam_r (utf8_name, &pwd, fbuf, fbufsize, &p);
382 result = ((retval == 0) && (p == &pwd));
384 /* default to non thread-safe but posix compliant function */
385 p = getpwnam (utf8_name);
386 result = (p != NULL);
390 token = GINT_TO_POINTER (p->pw_uid);
393 #ifdef HAVE_GETPWNAM_R
402 /* http://www.dotnet247.com/247reference/msgs/39/195403.aspx
403 // internal static string[] WindowsIdentity._GetRoles (IntPtr token)
406 ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token)
408 MonoArray *array = NULL;
409 MonoDomain *domain = mono_domain_get ();
410 #ifdef PLATFORM_WIN32
415 GetTokenInformation (token, TokenGroups, NULL, size, (PDWORD)&size);
417 TOKEN_GROUPS *tg = g_malloc0 (size);
418 if (GetTokenInformation (token, TokenGroups, tg, size, (PDWORD)&size)) {
420 int num = tg->GroupCount;
422 array = mono_array_new (domain, mono_get_string_class (), num);
424 for (i=0; i < num; i++) {
426 gunichar2 *uniname = GetSidName (NULL, tg->Groups [i].Sid, &size);
429 MonoString *str = mono_string_new_utf16 (domain, uniname, size);
430 mono_array_setref (array, i, str);
438 /* POSIX-compliant systems should use IsMemberOfGroupId or IsMemberOfGroupName */
439 g_warning ("WindowsIdentity._GetRoles should never be called on POSIX");
442 /* return empty array of string, i.e. string [0] */
443 array = mono_array_new (domain, mono_get_string_class (), 0);
449 /* System.Security.Principal.WindowsImpersonationContext */
453 ves_icall_System_Security_Principal_WindowsImpersonationContext_CloseToken (gpointer token)
455 gboolean result = TRUE;
459 #ifdef PLATFORM_WIN32
460 result = (CloseHandle (token) != 0);
467 ves_icall_System_Security_Principal_WindowsImpersonationContext_DuplicateToken (gpointer token)
469 gpointer dupe = NULL;
473 #ifdef PLATFORM_WIN32
474 if (DuplicateToken (token, SecurityImpersonation, &dupe) == 0) {
485 ves_icall_System_Security_Principal_WindowsImpersonationContext_SetCurrentToken (gpointer token)
489 /* Posix version implemented in /mono/mono/io-layer/security.c */
490 return (ImpersonateLoggedOnUser (token) != 0);
495 ves_icall_System_Security_Principal_WindowsImpersonationContext_RevertToSelf (void)
499 /* Posix version implemented in /mono/mono/io-layer/security.c */
500 return (RevertToSelf () != 0);
504 /* System.Security.Principal.WindowsPrincipal */
507 ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupId (gpointer user, gpointer group)
509 gboolean result = FALSE;
511 #ifdef PLATFORM_WIN32
514 /* The convertion from an ID to a string is done in managed code for Windows */
515 g_warning ("IsMemberOfGroupId should never be called on Win32");
517 #else /* PLATFORM_WIN32 */
519 #ifdef HAVE_GETGRGID_R
525 struct group *g = NULL;
529 #ifdef HAVE_GETGRGID_R
530 #ifdef _SC_GETGR_R_SIZE_MAX
531 fbufsize = mono_sysconf (_SC_GETGR_R_SIZE_MAX);
533 fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
535 fbuf = g_malloc0 (fbufsize);
536 retval = getgrgid_r ((gid_t) GPOINTER_TO_INT (group), &grp, fbuf, fbufsize, &g);
537 result = ((retval == 0) && (g == &grp));
539 /* default to non thread-safe but posix compliant function */
540 g = getgrgid ((gid_t) GPOINTER_TO_INT (group));
541 result = (g != NULL);
545 result = IsMemberOf ((uid_t) GPOINTER_TO_INT (user), g);
548 #ifdef HAVE_GETGRGID_R
552 #endif /* PLATFORM_WIN32 */
559 ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupName (gpointer user, MonoString *group)
561 gboolean result = FALSE;
563 #ifdef PLATFORM_WIN32
567 /* Windows version use a cache built using WindowsIdentity._GetRoles */
568 g_warning ("IsMemberOfGroupName should never be called on Win32");
570 #else /* PLATFORM_WIN32 */
571 gchar *utf8_groupname;
575 utf8_groupname = mono_unicode_to_external (mono_string_chars (group));
576 if (utf8_groupname) {
577 struct group *g = NULL;
578 #ifdef HAVE_GETGRNAM_R
582 #ifdef _SC_GETGR_R_SIZE_MAX
583 size_t fbufsize = mono_sysconf (_SC_GETGR_R_SIZE_MAX);
585 size_t fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
587 fbuf = g_malloc0 (fbufsize);
588 retval = getgrnam_r (utf8_groupname, &grp, fbuf, fbufsize, &g);
589 result = ((retval == 0) && (g == &grp));
591 /* default to non thread-safe but posix compliant function */
592 g = getgrnam (utf8_groupname);
593 result = (g != NULL);
597 result = IsMemberOf ((uid_t) GPOINTER_TO_INT (user), g);
600 #ifdef HAVE_GETGRNAM_R
603 g_free (utf8_groupname);
605 #endif /* PLATFORM_WIN32 */
611 /* Mono.Security.Cryptography IO related internal calls */
613 #ifdef PLATFORM_WIN32
616 GetAdministratorsSid (void)
618 SID_IDENTIFIER_AUTHORITY admins = SECURITY_NT_AUTHORITY;
620 if (!AllocateAndInitializeSid (&admins, 2, SECURITY_BUILTIN_DOMAIN_RID,
621 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pSid))
623 /* Note: this SID must be freed with FreeSid () */
629 GetEveryoneSid (void)
631 SID_IDENTIFIER_AUTHORITY everyone = SECURITY_WORLD_SID_AUTHORITY;
633 if (!AllocateAndInitializeSid (&everyone, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pSid))
635 /* Note: this SID must be freed with FreeSid () */
641 GetCurrentUserSid (void)
645 gpointer token = ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken ();
647 GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
649 TOKEN_USER *tu = g_malloc0 (size);
650 if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
651 DWORD length = GetLengthSid (tu->User.Sid);
652 sid = (PSID) g_malloc0 (length);
653 if (!CopySid (length, sid, tu->User.Sid)) {
660 /* Note: this SID must be freed with g_free () */
666 GetRightsFromSid (PSID sid, PACL acl)
668 ACCESS_MASK rights = 0;
671 BuildTrusteeWithSidW (&trustee, sid);
672 if (GetEffectiveRightsFromAcl (acl, &trustee, &rights) != ERROR_SUCCESS)
680 IsMachineProtected (gunichar2 *path)
682 gboolean success = FALSE;
684 PSID pEveryoneSid = NULL;
686 DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, NULL);
687 if (dwRes != ERROR_SUCCESS)
690 /* We check that Everyone is still limited to READ-ONLY -
691 but not if new entries have been added by an Administrator */
693 pEveryoneSid = GetEveryoneSid ();
695 ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
696 /* http://msdn.microsoft.com/library/en-us/security/security/generic_access_rights.asp?frame=true */
697 success = (rights == (READ_CONTROL | SYNCHRONIZE | FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES));
698 FreeSid (pEveryoneSid);
700 /* Note: we don't need to check our own access -
701 we'll know soon enough when reading the file */
711 IsUserProtected (gunichar2 *path)
713 gboolean success = FALSE;
715 PSID pEveryoneSid = NULL;
717 DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT,
718 DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, NULL);
719 if (dwRes != ERROR_SUCCESS)
722 /* We check that our original entries in the ACL are in place -
723 but not if new entries have been added by the user */
725 /* Everyone should be denied */
726 pEveryoneSid = GetEveryoneSid ();
728 ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
729 success = (rights == 0);
730 FreeSid (pEveryoneSid);
732 /* Note: we don't need to check our own access -
733 we'll know soon enough when reading the file */
743 ProtectMachine (gunichar2 *path)
745 PSID pEveryoneSid = GetEveryoneSid ();
746 PSID pAdminsSid = GetAdministratorsSid ();
749 if (pEveryoneSid && pAdminsSid) {
751 EXPLICIT_ACCESS ea [2];
752 ZeroMemory (&ea, 2 * sizeof (EXPLICIT_ACCESS));
754 /* grant all access to the BUILTIN\Administrators group */
755 BuildTrusteeWithSidW (&ea [0].Trustee, pAdminsSid);
756 ea [0].grfAccessPermissions = GENERIC_ALL;
757 ea [0].grfAccessMode = SET_ACCESS;
758 ea [0].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
759 ea [0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
760 ea [0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
762 /* read-only access everyone */
763 BuildTrusteeWithSidW (&ea [1].Trustee, pEveryoneSid);
764 ea [1].grfAccessPermissions = GENERIC_READ;
765 ea [1].grfAccessMode = SET_ACCESS;
766 ea [1].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
767 ea [1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
768 ea [1].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
770 retval = SetEntriesInAcl (2, ea, NULL, &pDACL);
771 if (retval == ERROR_SUCCESS) {
772 /* with PROTECTED_DACL_SECURITY_INFORMATION we */
773 /* remove any existing ACL (like inherited ones) */
774 retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT,
775 DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
776 NULL, NULL, pDACL, NULL);
783 FreeSid (pEveryoneSid);
785 FreeSid (pAdminsSid);
786 return (retval == ERROR_SUCCESS);
791 ProtectUser (gunichar2 *path)
795 PSID pCurrentSid = GetCurrentUserSid ();
799 ZeroMemory (&ea, sizeof (EXPLICIT_ACCESS));
801 /* grant exclusive access to the current user */
802 BuildTrusteeWithSidW (&ea.Trustee, pCurrentSid);
803 ea.grfAccessPermissions = GENERIC_ALL;
804 ea.grfAccessMode = SET_ACCESS;
805 ea.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
806 ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
807 ea.Trustee.TrusteeType = TRUSTEE_IS_USER;
809 retval = SetEntriesInAcl (1, &ea, NULL, &pDACL);
810 if (retval == ERROR_SUCCESS) {
811 /* with PROTECTED_DACL_SECURITY_INFORMATION we
812 remove any existing ACL (like inherited ones) */
813 retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT,
814 DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
815 NULL, NULL, pDACL, NULL);
820 g_free (pCurrentSid); /* g_malloc0 */
823 return (retval == ERROR_SUCCESS);
829 IsProtected (MonoString *path, gint32 protection)
831 gboolean result = FALSE;
832 gchar *utf8_name = mono_unicode_to_external (mono_string_chars (path));
835 if (stat (utf8_name, &st) == 0) {
836 result = (((st.st_mode & 0777) & protection) == 0);
845 Protect (MonoString *path, gint32 file_mode, gint32 add_dir_mode)
847 gboolean result = FALSE;
848 gchar *utf8_name = mono_unicode_to_external (mono_string_chars (path));
851 if (stat (utf8_name, &st) == 0) {
852 int mode = file_mode;
853 if (st.st_mode & S_IFDIR)
854 mode |= add_dir_mode;
855 result = (chmod (utf8_name, mode) == 0);
862 #endif /* not PLATFORM_WIN32 */
866 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_CanSecure (MonoString *root)
873 /* ACL are nice... unless you have FAT or other uncivilized filesystem */
874 if (!GetVolumeInformation (mono_string_chars (root), NULL, 0, NULL, NULL, (LPDWORD)&flags, NULL, 0))
876 return ((flags & FS_PERSISTENT_ACLS) == FS_PERSISTENT_ACLS);
879 /* we assume some kind of security is applicable outside Windows */
886 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsMachineProtected (MonoString *path)
888 gboolean ret = FALSE;
892 /* no one, but the owner, should have write access to the directory */
893 #ifdef PLATFORM_WIN32
894 ret = IsMachineProtected (mono_string_chars (path));
896 ret = IsProtected (path, (S_IWGRP | S_IWOTH));
903 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsUserProtected (MonoString *path)
905 gboolean ret = FALSE;
909 /* no one, but the user, should have access to the directory */
910 #ifdef PLATFORM_WIN32
911 ret = IsUserProtected (mono_string_chars (path));
913 ret = IsProtected (path, (S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH));
920 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectMachine (MonoString *path)
922 gboolean ret = FALSE;
926 /* read/write to owner, read to everyone else */
927 #ifdef PLATFORM_WIN32
928 ret = ProtectMachine (mono_string_chars (path));
930 ret = Protect (path, (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH), (S_IXUSR | S_IXGRP | S_IXOTH));
937 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectUser (MonoString *path)
939 gboolean ret = FALSE;
943 /* read/write to user, no access to everyone else */
944 #ifdef PLATFORM_WIN32
945 ret = ProtectUser (mono_string_chars (path));
947 ret = Protect (path, (S_IRUSR | S_IWUSR), S_IXUSR);
954 * Returns TRUE if there is "something" where the Authenticode signature is
955 * normally located. Returns FALSE is data directory is empty.
957 * Note: Neither the structure nor the signature is verified by this function.
960 ves_icall_System_Security_Policy_Evidence_IsAuthenticodePresent (MonoReflectionAssembly *refass)
962 if (refass && refass->assembly && refass->assembly->image) {
963 return mono_image_has_authenticode_entry (refass->assembly->image);