2 * security.c: Security internal calls
5 * Sebastien Pouliot <sebastien@ximian.com>
7 * (C) 2004 Novell (http://www.novell.com)
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>
29 #ifndef PROTECTED_DACL_SECURITY_INFORMATION
30 #define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
40 #include <sys/types.h>
47 #ifndef HAVE_GETGRGID_R
48 #warning Non-thread safe getgrgid being used!
50 #ifndef HAVE_GETGRNAM_R
51 #warning Non-thread safe getgrnam being used!
53 #ifndef HAVE_GETPWNAM_R
54 #warning Non-thread safe getpwnam being used!
56 #ifndef HAVE_GETPWUID_R
57 #warning Non-thread safe getpwuid being used!
60 #endif /* defined(__GNUC__) */
62 #endif /* not PLATFORM_WIN32 */
65 /* internal functions - reuse driven */
69 /* ask a server to translate a SID into a textual representation */
71 GetSidName (gunichar2 *server, PSID sid, gint32 *size)
73 gunichar2 *uniname = NULL;
76 SID_NAME_USE peUse; /* out */
78 LookupAccountSid (server, sid, NULL, &cchName, NULL,
81 if ((cchName > 0) && (cchDomain > 0)) {
82 gunichar2 *user = g_malloc0 ((cchName + 1) * 2);
83 gunichar2 *domain = g_malloc0 ((cchDomain + 1) * 2);
85 LookupAccountSid (server, sid, user, &cchName, domain,
90 /* domain/machine name included (+ sepearator) */
91 *size = cchName + cchDomain + 1;
92 uniname = g_malloc0 ((*size + 1) * 2);
93 memcpy (uniname, domain, cchDomain * 2);
94 *(uniname + cchDomain) = '\\';
95 memcpy (uniname + cchDomain + 1, user, cchName * 2);
99 /* no domain / machine */
105 /* nothing -> return NULL */
116 #else /* not PLATFORM_WIN32 */
118 #define MONO_SYSCONF_DEFAULT_SIZE ((size_t) 1024)
121 * Ensure we always get a valid (usable) value from sysconf.
122 * In case of error, we return the default value.
124 static size_t mono_sysconf (int name)
126 size_t size = (size_t) sysconf (name);
128 return (size == -1) ? MONO_SYSCONF_DEFAULT_SIZE : size;
133 GetTokenName (uid_t uid)
137 #ifdef HAVE_GETPWUID_R
143 struct passwd *p = NULL;
146 #ifdef HAVE_GETPWUID_R
147 #ifdef _SC_GETPW_R_SIZE_MAX
148 fbufsize = mono_sysconf (_SC_GETPW_R_SIZE_MAX);
150 fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
152 fbuf = g_malloc0 (fbufsize);
153 retval = getpwuid_r (uid, &pwd, fbuf, fbufsize, &p);
154 result = ((retval == 0) && (p == &pwd));
156 /* default to non thread-safe but posix compliant function */
158 result = (p != NULL);
162 uname = g_strdup (p->pw_name);
165 #ifdef HAVE_GETPWUID_R
174 IsMemberInList (uid_t user, struct group *g)
176 gboolean result = FALSE;
177 gchar *utf8_username = GetTokenName (user);
183 gchar **users = g->gr_mem;
187 if (strcmp (utf8_username, u) == 0) {
195 g_free (utf8_username);
201 IsDefaultGroup (uid_t user, gid_t group)
203 #ifdef HAVE_GETPWUID_R
209 struct passwd *p = NULL;
212 #ifdef HAVE_GETPWUID_R
213 #ifdef _SC_GETPW_R_SIZE_MAX
214 fbufsize = mono_sysconf (_SC_GETPW_R_SIZE_MAX);
216 fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
219 fbuf = g_malloc0 (fbufsize);
220 retval = getpwuid_r (user, &pwd, fbuf, fbufsize, &p);
221 result = ((retval == 0) && (p == &pwd));
223 /* default to non thread-safe but posix compliant function */
225 result = (p != NULL);
229 result = (p->pw_gid == group);
232 #ifdef HAVE_GETPWUID_R
241 IsMemberOf (gid_t user, struct group *g)
246 /* is it the user default group */
247 if (IsDefaultGroup (user, g->gr_gid))
250 /* is the user in the group list */
251 return IsMemberInList (user, g);
260 /* System.Environment */
264 ves_icall_System_Environment_get_UserName (void)
268 /* using glib is more portable */
269 return mono_string_new (mono_domain_get (), g_get_user_name ());
273 /* System.Security.Principal.WindowsIdentity */
277 ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken (void)
279 gpointer token = NULL;
283 #ifdef PLATFORM_WIN32
284 /* Note: This isn't a copy of the Token - we must not close it!!!
285 * http://www.develop.com/kbrown/book/html/whatis_windowsprincipal.html
288 /* thread may be impersonating somebody */
289 if (OpenThreadToken (GetCurrentThread (), TOKEN_QUERY, 1, &token) == 0) {
290 /* if not take the process identity */
291 OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &token);
294 token = GINT_TO_POINTER (geteuid ());
301 ves_icall_System_Security_Principal_WindowsIdentity_GetTokenName (gpointer token)
303 MonoString *result = NULL;
304 gunichar2 *uniname = NULL;
307 #ifdef PLATFORM_WIN32
310 GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
312 TOKEN_USER *tu = g_malloc0 (size);
313 if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
314 uniname = GetSidName (NULL, tu->User.Sid, &size);
319 gchar *uname = GetTokenName ((uid_t) GPOINTER_TO_INT (token));
324 size = strlen (uname);
325 uniname = g_utf8_to_utf16 (uname, size, NULL, NULL, NULL);
328 #endif /* PLATFORM_WIN32 */
331 result = mono_string_new_utf16 (mono_domain_get (), uniname, size);
334 result = mono_string_new (mono_domain_get (), "");
344 ves_icall_System_Security_Principal_WindowsIdentity_GetUserToken (MonoString *username)
346 #ifdef PLATFORM_WIN32
347 gpointer token = NULL;
351 /* TODO: MS has something like this working in Windows 2003 (client and
352 * server) but works only for domain accounts (so it's quite limiting).
353 * http://www.develop.com/kbrown/book/html/howto_logonuser.html
355 g_warning ("Unsupported on Win32 (anyway requires W2K3 minimum)");
357 #else /* PLATFORM_WIN32*/
359 #ifdef HAVE_GETPWNAM_R
365 gpointer token = (gpointer) -2;
372 utf8_name = mono_unicode_to_external (mono_string_chars (username));
374 #ifdef HAVE_GETPWNAM_R
375 #ifdef _SC_GETPW_R_SIZE_MAX
376 fbufsize = mono_sysconf (_SC_GETPW_R_SIZE_MAX);
378 fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
381 fbuf = g_malloc0 (fbufsize);
382 retval = getpwnam_r (utf8_name, &pwd, fbuf, fbufsize, &p);
383 result = ((retval == 0) && (p == &pwd));
385 /* default to non thread-safe but posix compliant function */
386 p = getpwnam (utf8_name);
387 result = (p != NULL);
391 token = GINT_TO_POINTER (p->pw_uid);
394 #ifdef HAVE_GETPWNAM_R
403 /* http://www.dotnet247.com/247reference/msgs/39/195403.aspx
404 // internal static string[] WindowsIdentity._GetRoles (IntPtr token)
407 ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token)
409 MonoArray *array = NULL;
410 MonoDomain *domain = mono_domain_get ();
411 #ifdef PLATFORM_WIN32
416 GetTokenInformation (token, TokenGroups, NULL, size, (PDWORD)&size);
418 TOKEN_GROUPS *tg = g_malloc0 (size);
419 if (GetTokenInformation (token, TokenGroups, tg, size, (PDWORD)&size)) {
421 int num = tg->GroupCount;
423 array = mono_array_new (domain, mono_get_string_class (), num);
425 for (i=0; i < num; i++) {
427 gunichar2 *uniname = GetSidName (NULL, tg->Groups [i].Sid, &size);
430 MonoString *str = mono_string_new_utf16 (domain, uniname, size);
431 mono_array_setref (array, i, str);
439 /* POSIX-compliant systems should use IsMemberOfGroupId or IsMemberOfGroupName */
440 g_warning ("WindowsIdentity._GetRoles should never be called on POSIX");
443 /* return empty array of string, i.e. string [0] */
444 array = mono_array_new (domain, mono_get_string_class (), 0);
450 /* System.Security.Principal.WindowsImpersonationContext */
454 ves_icall_System_Security_Principal_WindowsImpersonationContext_CloseToken (gpointer token)
456 gboolean result = TRUE;
460 #ifdef PLATFORM_WIN32
461 result = (CloseHandle (token) != 0);
468 ves_icall_System_Security_Principal_WindowsImpersonationContext_DuplicateToken (gpointer token)
470 gpointer dupe = NULL;
474 #ifdef PLATFORM_WIN32
475 if (DuplicateToken (token, SecurityImpersonation, &dupe) == 0) {
486 ves_icall_System_Security_Principal_WindowsImpersonationContext_SetCurrentToken (gpointer token)
490 /* Posix version implemented in /mono/mono/io-layer/security.c */
491 return (ImpersonateLoggedOnUser (token) != 0);
496 ves_icall_System_Security_Principal_WindowsImpersonationContext_RevertToSelf (void)
500 /* Posix version implemented in /mono/mono/io-layer/security.c */
501 return (RevertToSelf () != 0);
505 /* System.Security.Principal.WindowsPrincipal */
508 ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupId (gpointer user, gpointer group)
510 gboolean result = FALSE;
512 #ifdef PLATFORM_WIN32
515 /* The convertion from an ID to a string is done in managed code for Windows */
516 g_warning ("IsMemberOfGroupId should never be called on Win32");
518 #else /* PLATFORM_WIN32 */
520 #ifdef HAVE_GETGRGID_R
526 struct group *g = NULL;
530 #ifdef HAVE_GETGRGID_R
531 #ifdef _SC_GETGR_R_SIZE_MAX
532 fbufsize = mono_sysconf (_SC_GETGR_R_SIZE_MAX);
534 fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
536 fbuf = g_malloc0 (fbufsize);
537 retval = getgrgid_r ((gid_t) GPOINTER_TO_INT (group), &grp, fbuf, fbufsize, &g);
538 result = ((retval == 0) && (g == &grp));
540 /* default to non thread-safe but posix compliant function */
541 g = getgrgid ((gid_t) GPOINTER_TO_INT (group));
542 result = (g != NULL);
546 result = IsMemberOf ((uid_t) GPOINTER_TO_INT (user), g);
549 #ifdef HAVE_GETGRGID_R
553 #endif /* PLATFORM_WIN32 */
560 ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupName (gpointer user, MonoString *group)
562 gboolean result = FALSE;
564 #ifdef PLATFORM_WIN32
568 /* Windows version use a cache built using WindowsIdentity._GetRoles */
569 g_warning ("IsMemberOfGroupName should never be called on Win32");
571 #else /* PLATFORM_WIN32 */
572 gchar *utf8_groupname;
576 utf8_groupname = mono_unicode_to_external (mono_string_chars (group));
577 if (utf8_groupname) {
578 struct group *g = NULL;
579 #ifdef HAVE_GETGRNAM_R
583 #ifdef _SC_GETGR_R_SIZE_MAX
584 size_t fbufsize = mono_sysconf (_SC_GETGR_R_SIZE_MAX);
586 size_t fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
588 fbuf = g_malloc0 (fbufsize);
589 retval = getgrnam_r (utf8_groupname, &grp, fbuf, fbufsize, &g);
590 result = ((retval == 0) && (g == &grp));
592 /* default to non thread-safe but posix compliant function */
593 g = getgrnam (utf8_groupname);
594 result = (g != NULL);
598 result = IsMemberOf ((uid_t) GPOINTER_TO_INT (user), g);
601 #ifdef HAVE_GETGRNAM_R
604 g_free (utf8_groupname);
606 #endif /* PLATFORM_WIN32 */
612 /* Mono.Security.Cryptography IO related internal calls */
614 #ifdef PLATFORM_WIN32
617 GetAdministratorsSid (void)
619 SID_IDENTIFIER_AUTHORITY admins = SECURITY_NT_AUTHORITY;
621 if (!AllocateAndInitializeSid (&admins, 2, SECURITY_BUILTIN_DOMAIN_RID,
622 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pSid))
624 /* Note: this SID must be freed with FreeSid () */
630 GetEveryoneSid (void)
632 SID_IDENTIFIER_AUTHORITY everyone = SECURITY_WORLD_SID_AUTHORITY;
634 if (!AllocateAndInitializeSid (&everyone, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pSid))
636 /* Note: this SID must be freed with FreeSid () */
642 GetCurrentUserSid (void)
646 gpointer token = ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken ();
648 GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
650 TOKEN_USER *tu = g_malloc0 (size);
651 if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
652 DWORD length = GetLengthSid (tu->User.Sid);
653 sid = (PSID) g_malloc0 (length);
654 if (!CopySid (length, sid, tu->User.Sid)) {
661 /* Note: this SID must be freed with g_free () */
667 GetRightsFromSid (PSID sid, PACL acl)
669 ACCESS_MASK rights = 0;
672 BuildTrusteeWithSidW (&trustee, sid);
673 if (GetEffectiveRightsFromAcl (acl, &trustee, &rights) != ERROR_SUCCESS)
681 IsMachineProtected (gunichar2 *path)
683 gboolean success = FALSE;
685 PSID pEveryoneSid = NULL;
687 DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, NULL);
688 if (dwRes != ERROR_SUCCESS)
691 /* We check that Everyone is still limited to READ-ONLY -
692 but not if new entries have been added by an Administrator */
694 pEveryoneSid = GetEveryoneSid ();
696 ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
697 /* http://msdn.microsoft.com/library/en-us/security/security/generic_access_rights.asp?frame=true */
698 success = (rights == (READ_CONTROL | SYNCHRONIZE | FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES));
699 FreeSid (pEveryoneSid);
701 /* Note: we don't need to check our own access -
702 we'll know soon enough when reading the file */
712 IsUserProtected (gunichar2 *path)
714 gboolean success = FALSE;
716 PSID pEveryoneSid = NULL;
718 DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT,
719 DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, NULL);
720 if (dwRes != ERROR_SUCCESS)
723 /* We check that our original entries in the ACL are in place -
724 but not if new entries have been added by the user */
726 /* Everyone should be denied */
727 pEveryoneSid = GetEveryoneSid ();
729 ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
730 success = (rights == 0);
731 FreeSid (pEveryoneSid);
733 /* Note: we don't need to check our own access -
734 we'll know soon enough when reading the file */
744 ProtectMachine (gunichar2 *path)
746 PSID pEveryoneSid = GetEveryoneSid ();
747 PSID pAdminsSid = GetAdministratorsSid ();
750 if (pEveryoneSid && pAdminsSid) {
752 EXPLICIT_ACCESS ea [2];
753 ZeroMemory (&ea, 2 * sizeof (EXPLICIT_ACCESS));
755 /* grant all access to the BUILTIN\Administrators group */
756 BuildTrusteeWithSidW (&ea [0].Trustee, pAdminsSid);
757 ea [0].grfAccessPermissions = GENERIC_ALL;
758 ea [0].grfAccessMode = SET_ACCESS;
759 ea [0].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
760 ea [0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
761 ea [0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
763 /* read-only access everyone */
764 BuildTrusteeWithSidW (&ea [1].Trustee, pEveryoneSid);
765 ea [1].grfAccessPermissions = GENERIC_READ;
766 ea [1].grfAccessMode = SET_ACCESS;
767 ea [1].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
768 ea [1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
769 ea [1].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
771 retval = SetEntriesInAcl (2, ea, NULL, &pDACL);
772 if (retval == ERROR_SUCCESS) {
773 /* with PROTECTED_DACL_SECURITY_INFORMATION we */
774 /* remove any existing ACL (like inherited ones) */
775 retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT,
776 DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
777 NULL, NULL, pDACL, NULL);
784 FreeSid (pEveryoneSid);
786 FreeSid (pAdminsSid);
787 return (retval == ERROR_SUCCESS);
792 ProtectUser (gunichar2 *path)
796 PSID pCurrentSid = GetCurrentUserSid ();
800 ZeroMemory (&ea, sizeof (EXPLICIT_ACCESS));
802 /* grant exclusive access to the current user */
803 BuildTrusteeWithSidW (&ea.Trustee, pCurrentSid);
804 ea.grfAccessPermissions = GENERIC_ALL;
805 ea.grfAccessMode = SET_ACCESS;
806 ea.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
807 ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
808 ea.Trustee.TrusteeType = TRUSTEE_IS_USER;
810 retval = SetEntriesInAcl (1, &ea, NULL, &pDACL);
811 if (retval == ERROR_SUCCESS) {
812 /* with PROTECTED_DACL_SECURITY_INFORMATION we
813 remove any existing ACL (like inherited ones) */
814 retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT,
815 DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
816 NULL, NULL, pDACL, NULL);
821 g_free (pCurrentSid); /* g_malloc0 */
824 return (retval == ERROR_SUCCESS);
830 IsProtected (MonoString *path, gint32 protection)
832 gboolean result = FALSE;
833 gchar *utf8_name = mono_unicode_to_external (mono_string_chars (path));
836 if (stat (utf8_name, &st) == 0) {
837 result = (((st.st_mode & 0777) & protection) == 0);
846 Protect (MonoString *path, gint32 file_mode, gint32 add_dir_mode)
848 gboolean result = FALSE;
849 gchar *utf8_name = mono_unicode_to_external (mono_string_chars (path));
852 if (stat (utf8_name, &st) == 0) {
853 int mode = file_mode;
854 if (st.st_mode & S_IFDIR)
855 mode |= add_dir_mode;
856 result = (chmod (utf8_name, mode) == 0);
863 #endif /* not PLATFORM_WIN32 */
867 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_CanSecure (MonoString *root)
874 /* ACL are nice... unless you have FAT or other uncivilized filesystem */
875 if (!GetVolumeInformation (mono_string_chars (root), NULL, 0, NULL, NULL, (LPDWORD)&flags, NULL, 0))
877 return ((flags & FS_PERSISTENT_ACLS) == FS_PERSISTENT_ACLS);
880 /* we assume some kind of security is applicable outside Windows */
887 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsMachineProtected (MonoString *path)
889 gboolean ret = FALSE;
893 /* no one, but the owner, should have write access to the directory */
894 #ifdef PLATFORM_WIN32
895 ret = IsMachineProtected (mono_string_chars (path));
897 ret = IsProtected (path, (S_IWGRP | S_IWOTH));
904 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsUserProtected (MonoString *path)
906 gboolean ret = FALSE;
910 /* no one, but the user, should have access to the directory */
911 #ifdef PLATFORM_WIN32
912 ret = IsUserProtected (mono_string_chars (path));
914 ret = IsProtected (path, (S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH));
921 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectMachine (MonoString *path)
923 gboolean ret = FALSE;
927 /* read/write to owner, read to everyone else */
928 #ifdef PLATFORM_WIN32
929 ret = ProtectMachine (mono_string_chars (path));
931 ret = Protect (path, (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH), (S_IXUSR | S_IXGRP | S_IXOTH));
938 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectUser (MonoString *path)
940 gboolean ret = FALSE;
944 /* read/write to user, no access to everyone else */
945 #ifdef PLATFORM_WIN32
946 ret = ProtectUser (mono_string_chars (path));
948 ret = Protect (path, (S_IRUSR | S_IWUSR), S_IXUSR);
955 * Returns TRUE if there is "something" where the Authenticode signature is
956 * normally located. Returns FALSE is data directory is empty.
958 * Note: Neither the structure nor the signature is verified by this function.
961 ves_icall_System_Security_Policy_Evidence_IsAuthenticodePresent (MonoReflectionAssembly *refass)
963 if (refass && refass->assembly && refass->assembly->image) {
964 return mono_image_has_authenticode_entry (refass->assembly->image);
970 /* System.Security.SecureString related internal calls */
972 static MonoImage *system_security_assembly = NULL;
975 ves_icall_System_Security_SecureString_DecryptInternal (MonoArray *data, MonoObject *scope)
977 invoke_protected_memory_method (data, scope, FALSE);
980 ves_icall_System_Security_SecureString_EncryptInternal (MonoArray* data, MonoObject *scope)
982 invoke_protected_memory_method (data, scope, TRUE);
985 void invoke_protected_memory_method (MonoArray *data, MonoObject *scope, gboolean encrypt)
993 if (system_security_assembly == NULL) {
994 system_security_assembly = mono_image_loaded ("System.Security");
995 if (!system_security_assembly) {
996 MonoAssembly *sa = mono_assembly_open ("System.Security.dll", NULL);
998 g_assert_not_reached ();
999 system_security_assembly = mono_assembly_get_image (sa);
1003 klass = mono_class_from_name (system_security_assembly,
1004 "System.Security.Cryptography", "ProtectedMemory");
1005 method = mono_class_get_method_from_name (klass, encrypt ? "Protect" : "Unprotect", 2);
1007 params [1] = scope; /* MemoryProtectionScope.SameProcess */
1008 mono_runtime_invoke (method, NULL, params, NULL);