2 * security.c: Security internal calls
5 * Sebastien Pouliot <sebastien@ximian.com>
7 * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
8 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
15 #include <mono/metadata/assembly.h>
16 #include <mono/metadata/appdomain.h>
17 #include <mono/metadata/image.h>
18 #include <mono/metadata/exception.h>
19 #include <mono/metadata/object-internals.h>
20 #include <mono/metadata/metadata-internals.h>
21 #include <mono/metadata/security.h>
22 #include <mono/io-layer/io-layer.h>
23 #include <mono/utils/strenc.h>
30 #ifndef PROTECTED_DACL_SECURITY_INFORMATION
31 #define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
45 #include <sys/types.h>
52 #ifndef HAVE_GETGRGID_R
53 #warning Non-thread safe getgrgid being used!
55 #ifndef HAVE_GETGRNAM_R
56 #warning Non-thread safe getgrnam being used!
58 #ifndef HAVE_GETPWNAM_R
59 #warning Non-thread safe getpwnam being used!
61 #ifndef HAVE_GETPWUID_R
62 #warning Non-thread safe getpwuid being used!
65 #endif /* defined(__GNUC__) */
67 #endif /* not HOST_WIN32 */
70 /* internal functions - reuse driven */
74 /* ask a server to translate a SID into a textual representation */
76 GetSidName (gunichar2 *server, PSID sid, gint32 *size)
78 gunichar2 *uniname = NULL;
81 SID_NAME_USE peUse; /* out */
83 LookupAccountSid (server, sid, NULL, &cchName, NULL,
86 if ((cchName > 0) && (cchDomain > 0)) {
87 gunichar2 *user = g_malloc0 ((cchName + 1) * 2);
88 gunichar2 *domain = g_malloc0 ((cchDomain + 1) * 2);
90 LookupAccountSid (server, sid, user, &cchName, domain,
95 /* domain/machine name included (+ sepearator) */
96 *size = cchName + cchDomain + 1;
97 uniname = g_malloc0 ((*size + 1) * 2);
98 memcpy (uniname, domain, cchDomain * 2);
99 *(uniname + cchDomain) = '\\';
100 memcpy (uniname + cchDomain + 1, user, cchName * 2);
104 /* no domain / machine */
110 /* nothing -> return NULL */
121 #else /* not HOST_WIN32 */
123 #define MONO_SYSCONF_DEFAULT_SIZE ((size_t) 1024)
126 * Ensure we always get a valid (usable) value from sysconf.
127 * In case of error, we return the default value.
129 static size_t mono_sysconf (int name)
131 size_t size = (size_t) sysconf (name);
133 return (size == -1) ? MONO_SYSCONF_DEFAULT_SIZE : size;
138 GetTokenName (uid_t uid)
142 #ifdef HAVE_GETPWUID_R
148 struct passwd *p = NULL;
151 #ifdef HAVE_GETPWUID_R
152 #ifdef _SC_GETPW_R_SIZE_MAX
153 fbufsize = mono_sysconf (_SC_GETPW_R_SIZE_MAX);
155 fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
157 fbuf = (gchar *)g_malloc0 (fbufsize);
158 retval = getpwuid_r (uid, &pwd, fbuf, fbufsize, &p);
159 result = ((retval == 0) && (p == &pwd));
161 /* default to non thread-safe but posix compliant function */
163 result = (p != NULL);
167 uname = g_strdup (p->pw_name);
170 #ifdef HAVE_GETPWUID_R
179 IsMemberInList (uid_t user, struct group *g)
181 gboolean result = FALSE;
182 gchar *utf8_username = GetTokenName (user);
188 gchar **users = g->gr_mem;
192 if (strcmp (utf8_username, u) == 0) {
200 g_free (utf8_username);
206 IsDefaultGroup (uid_t user, gid_t group)
208 #ifdef HAVE_GETPWUID_R
214 struct passwd *p = NULL;
217 #ifdef HAVE_GETPWUID_R
218 #ifdef _SC_GETPW_R_SIZE_MAX
219 fbufsize = mono_sysconf (_SC_GETPW_R_SIZE_MAX);
221 fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
224 fbuf = (gchar *)g_malloc0 (fbufsize);
225 retval = getpwuid_r (user, &pwd, fbuf, fbufsize, &p);
226 result = ((retval == 0) && (p == &pwd));
228 /* default to non thread-safe but posix compliant function */
230 result = (p != NULL);
234 result = (p->pw_gid == group);
237 #ifdef HAVE_GETPWUID_R
246 IsMemberOf (gid_t user, struct group *g)
251 /* is it the user default group */
252 if (IsDefaultGroup (user, g->gr_gid))
255 /* is the user in the group list */
256 return IsMemberInList (user, g);
265 /* System.Security.Principal.WindowsIdentity */
269 ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken (void)
271 gpointer token = NULL;
274 /* Note: This isn't a copy of the Token - we must not close it!!!
275 * http://www.develop.com/kbrown/book/html/whatis_windowsprincipal.html
278 /* thread may be impersonating somebody */
279 if (OpenThreadToken (GetCurrentThread (), TOKEN_QUERY, 1, &token) == 0) {
280 /* if not take the process identity */
281 OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &token);
284 token = GINT_TO_POINTER (geteuid ());
291 ves_icall_System_Security_Principal_WindowsIdentity_GetTokenName (gpointer token)
294 MonoString *result = NULL;
295 gunichar2 *uniname = NULL;
298 mono_error_init (&error);
300 GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
302 TOKEN_USER *tu = g_malloc0 (size);
303 if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
304 uniname = GetSidName (NULL, tu->User.Sid, &size);
309 gchar *uname = GetTokenName ((uid_t) GPOINTER_TO_INT (token));
312 size = strlen (uname);
313 uniname = g_utf8_to_utf16 (uname, size, NULL, NULL, NULL);
316 #endif /* HOST_WIN32 */
319 result = mono_string_new_utf16_checked (mono_domain_get (), uniname, size, &error);
322 result = mono_string_new (mono_domain_get (), "");
327 mono_error_set_pending_exception (&error);
333 ves_icall_System_Security_Principal_WindowsIdentity_GetUserToken (MonoString *username)
336 gpointer token = NULL;
338 /* TODO: MS has something like this working in Windows 2003 (client and
339 * server) but works only for domain accounts (so it's quite limiting).
340 * http://www.develop.com/kbrown/book/html/howto_logonuser.html
342 g_warning ("Unsupported on Win32 (anyway requires W2K3 minimum)");
344 #else /* HOST_WIN32*/
346 #ifdef HAVE_GETPWNAM_R
352 gpointer token = (gpointer) -2;
357 utf8_name = mono_unicode_to_external (mono_string_chars (username));
359 #ifdef HAVE_GETPWNAM_R
360 #ifdef _SC_GETPW_R_SIZE_MAX
361 fbufsize = mono_sysconf (_SC_GETPW_R_SIZE_MAX);
363 fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
366 fbuf = (gchar *)g_malloc0 (fbufsize);
367 retval = getpwnam_r (utf8_name, &pwd, fbuf, fbufsize, &p);
368 result = ((retval == 0) && (p == &pwd));
370 /* default to non thread-safe but posix compliant function */
371 p = getpwnam (utf8_name);
372 result = (p != NULL);
376 token = GINT_TO_POINTER (p->pw_uid);
379 #ifdef HAVE_GETPWNAM_R
388 /* http://www.dotnet247.com/247reference/msgs/39/195403.aspx
389 // internal static string[] WindowsIdentity._GetRoles (IntPtr token)
392 ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token)
394 MonoArray *array = NULL;
395 MonoDomain *domain = mono_domain_get ();
400 GetTokenInformation (token, TokenGroups, NULL, size, (PDWORD)&size);
402 TOKEN_GROUPS *tg = g_malloc0 (size);
403 if (GetTokenInformation (token, TokenGroups, tg, size, (PDWORD)&size)) {
405 int num = tg->GroupCount;
407 array = mono_array_new (domain, mono_get_string_class (), num);
409 for (i=0; i < num; i++) {
411 gunichar2 *uniname = GetSidName (NULL, tg->Groups [i].Sid, &size);
414 MonoString *str = mono_string_new_utf16_checked (domain, uniname, size, &error);
415 if (!is_ok (&error)) {
418 mono_error_set_pending_exception (&error);
421 mono_array_setref (array, i, str);
429 /* POSIX-compliant systems should use IsMemberOfGroupId or IsMemberOfGroupName */
430 g_warning ("WindowsIdentity._GetRoles should never be called on POSIX");
433 /* return empty array of string, i.e. string [0] */
434 array = mono_array_new (domain, mono_get_string_class (), 0);
440 /* System.Security.Principal.WindowsImpersonationContext */
444 ves_icall_System_Security_Principal_WindowsImpersonationContext_CloseToken (gpointer token)
446 gboolean result = TRUE;
449 result = (CloseHandle (token) != 0);
456 ves_icall_System_Security_Principal_WindowsImpersonationContext_DuplicateToken (gpointer token)
458 gpointer dupe = NULL;
461 if (DuplicateToken (token, SecurityImpersonation, &dupe) == 0) {
472 ves_icall_System_Security_Principal_WindowsImpersonationContext_SetCurrentToken (gpointer token)
474 /* Posix version implemented in /mono/mono/io-layer/security.c */
475 return (ImpersonateLoggedOnUser (token) != 0);
480 ves_icall_System_Security_Principal_WindowsImpersonationContext_RevertToSelf (void)
482 /* Posix version implemented in /mono/mono/io-layer/security.c */
483 return (RevertToSelf () != 0);
487 /* System.Security.Principal.WindowsPrincipal */
490 ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupId (gpointer user, gpointer group)
492 gboolean result = FALSE;
495 /* The convertion from an ID to a string is done in managed code for Windows */
496 g_warning ("IsMemberOfGroupId should never be called on Win32");
498 #else /* HOST_WIN32 */
500 #ifdef HAVE_GETGRGID_R
506 struct group *g = NULL;
508 #ifdef HAVE_GETGRGID_R
509 #ifdef _SC_GETGR_R_SIZE_MAX
510 fbufsize = mono_sysconf (_SC_GETGR_R_SIZE_MAX);
512 fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
514 fbuf = (gchar *)g_malloc0 (fbufsize);
515 retval = getgrgid_r ((gid_t) GPOINTER_TO_INT (group), &grp, fbuf, fbufsize, &g);
516 result = ((retval == 0) && (g == &grp));
518 /* default to non thread-safe but posix compliant function */
519 g = getgrgid ((gid_t) GPOINTER_TO_INT (group));
520 result = (g != NULL);
524 result = IsMemberOf ((uid_t) GPOINTER_TO_INT (user), g);
527 #ifdef HAVE_GETGRGID_R
531 #endif /* HOST_WIN32 */
538 ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupName (gpointer user, MonoString *group)
540 gboolean result = FALSE;
543 /* Windows version use a cache built using WindowsIdentity._GetRoles */
544 g_warning ("IsMemberOfGroupName should never be called on Win32");
546 #else /* HOST_WIN32 */
547 gchar *utf8_groupname;
549 utf8_groupname = mono_unicode_to_external (mono_string_chars (group));
550 if (utf8_groupname) {
551 struct group *g = NULL;
552 #ifdef HAVE_GETGRNAM_R
556 #ifdef _SC_GETGR_R_SIZE_MAX
557 size_t fbufsize = mono_sysconf (_SC_GETGR_R_SIZE_MAX);
559 size_t fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
561 fbuf = (gchar *)g_malloc0 (fbufsize);
562 retval = getgrnam_r (utf8_groupname, &grp, fbuf, fbufsize, &g);
563 result = ((retval == 0) && (g == &grp));
565 /* default to non thread-safe but posix compliant function */
566 g = getgrnam (utf8_groupname);
567 result = (g != NULL);
571 result = IsMemberOf ((uid_t) GPOINTER_TO_INT (user), g);
574 #ifdef HAVE_GETGRNAM_R
577 g_free (utf8_groupname);
579 #endif /* HOST_WIN32 */
585 /* Mono.Security.Cryptography IO related internal calls */
590 GetAdministratorsSid (void)
592 SID_IDENTIFIER_AUTHORITY admins = SECURITY_NT_AUTHORITY;
594 if (!AllocateAndInitializeSid (&admins, 2, SECURITY_BUILTIN_DOMAIN_RID,
595 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pSid))
597 /* Note: this SID must be freed with FreeSid () */
603 GetEveryoneSid (void)
605 SID_IDENTIFIER_AUTHORITY everyone = SECURITY_WORLD_SID_AUTHORITY;
607 if (!AllocateAndInitializeSid (&everyone, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pSid))
609 /* Note: this SID must be freed with FreeSid () */
615 GetCurrentUserSid (void)
619 gpointer token = ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken ();
621 GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
623 TOKEN_USER *tu = g_malloc0 (size);
624 if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
625 DWORD length = GetLengthSid (tu->User.Sid);
626 sid = (PSID) g_malloc0 (length);
627 if (!CopySid (length, sid, tu->User.Sid)) {
634 /* Note: this SID must be freed with g_free () */
640 GetRightsFromSid (PSID sid, PACL acl)
642 ACCESS_MASK rights = 0;
645 BuildTrusteeWithSidW (&trustee, sid);
646 if (GetEffectiveRightsFromAcl (acl, &trustee, &rights) != ERROR_SUCCESS)
654 IsMachineProtected (gunichar2 *path)
656 gboolean success = FALSE;
658 PSID pEveryoneSid = NULL;
660 DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, NULL);
661 if (dwRes != ERROR_SUCCESS)
664 /* We check that Everyone is still limited to READ-ONLY -
665 but not if new entries have been added by an Administrator */
667 pEveryoneSid = GetEveryoneSid ();
669 ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
670 /* http://msdn.microsoft.com/library/en-us/security/security/generic_access_rights.asp?frame=true */
671 success = (rights == (READ_CONTROL | SYNCHRONIZE | FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES));
672 FreeSid (pEveryoneSid);
674 /* Note: we don't need to check our own access -
675 we'll know soon enough when reading the file */
685 IsUserProtected (gunichar2 *path)
687 gboolean success = FALSE;
689 PSID pEveryoneSid = NULL;
690 PSECURITY_DESCRIPTOR pSecurityDescriptor = NULL;
692 DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT,
693 DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, &pSecurityDescriptor);
694 if (dwRes != ERROR_SUCCESS)
697 /* We check that our original entries in the ACL are in place -
698 but not if new entries have been added by the user */
700 /* Everyone should be denied */
701 pEveryoneSid = GetEveryoneSid ();
703 ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
704 success = (rights == 0);
705 FreeSid (pEveryoneSid);
707 /* Note: we don't need to check our own access -
708 we'll know soon enough when reading the file */
710 if (pSecurityDescriptor)
711 LocalFree (pSecurityDescriptor);
718 ProtectMachine (gunichar2 *path)
720 PSID pEveryoneSid = GetEveryoneSid ();
721 PSID pAdminsSid = GetAdministratorsSid ();
724 if (pEveryoneSid && pAdminsSid) {
726 EXPLICIT_ACCESS ea [2];
727 ZeroMemory (&ea, 2 * sizeof (EXPLICIT_ACCESS));
729 /* grant all access to the BUILTIN\Administrators group */
730 BuildTrusteeWithSidW (&ea [0].Trustee, pAdminsSid);
731 ea [0].grfAccessPermissions = GENERIC_ALL;
732 ea [0].grfAccessMode = SET_ACCESS;
733 ea [0].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
734 ea [0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
735 ea [0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
737 /* read-only access everyone */
738 BuildTrusteeWithSidW (&ea [1].Trustee, pEveryoneSid);
739 ea [1].grfAccessPermissions = GENERIC_READ;
740 ea [1].grfAccessMode = SET_ACCESS;
741 ea [1].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
742 ea [1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
743 ea [1].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
745 retval = SetEntriesInAcl (2, ea, NULL, &pDACL);
746 if (retval == ERROR_SUCCESS) {
747 /* with PROTECTED_DACL_SECURITY_INFORMATION we */
748 /* remove any existing ACL (like inherited ones) */
749 retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT,
750 DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
751 NULL, NULL, pDACL, NULL);
758 FreeSid (pEveryoneSid);
760 FreeSid (pAdminsSid);
761 return (retval == ERROR_SUCCESS);
766 ProtectUser (gunichar2 *path)
770 PSID pCurrentSid = GetCurrentUserSid ();
774 ZeroMemory (&ea, sizeof (EXPLICIT_ACCESS));
776 /* grant exclusive access to the current user */
777 BuildTrusteeWithSidW (&ea.Trustee, pCurrentSid);
778 ea.grfAccessPermissions = GENERIC_ALL;
779 ea.grfAccessMode = SET_ACCESS;
780 ea.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
781 ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
782 ea.Trustee.TrusteeType = TRUSTEE_IS_USER;
784 retval = SetEntriesInAcl (1, &ea, NULL, &pDACL);
785 if (retval == ERROR_SUCCESS) {
786 /* with PROTECTED_DACL_SECURITY_INFORMATION we
787 remove any existing ACL (like inherited ones) */
788 retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT,
789 DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
790 NULL, NULL, pDACL, NULL);
795 g_free (pCurrentSid); /* g_malloc0 */
798 return (retval == ERROR_SUCCESS);
804 IsProtected (MonoString *path, gint32 protection)
806 gboolean result = FALSE;
807 gchar *utf8_name = mono_unicode_to_external (mono_string_chars (path));
810 if (stat (utf8_name, &st) == 0) {
811 result = (((st.st_mode & 0777) & protection) == 0);
820 Protect (MonoString *path, gint32 file_mode, gint32 add_dir_mode)
822 gboolean result = FALSE;
823 gchar *utf8_name = mono_unicode_to_external (mono_string_chars (path));
826 if (stat (utf8_name, &st) == 0) {
827 int mode = file_mode;
828 if (st.st_mode & S_IFDIR)
829 mode |= add_dir_mode;
830 result = (chmod (utf8_name, mode) == 0);
837 #endif /* not HOST_WIN32 */
841 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_CanSecure (MonoString *root)
846 /* ACL are nice... unless you have FAT or other uncivilized filesystem */
847 if (!GetVolumeInformation (mono_string_chars (root), NULL, 0, NULL, NULL, (LPDWORD)&flags, NULL, 0))
849 return ((flags & FS_PERSISTENT_ACLS) == FS_PERSISTENT_ACLS);
851 /* we assume some kind of security is applicable outside Windows */
858 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsMachineProtected (MonoString *path)
860 gboolean ret = FALSE;
862 /* no one, but the owner, should have write access to the directory */
864 ret = IsMachineProtected (mono_string_chars (path));
866 ret = IsProtected (path, (S_IWGRP | S_IWOTH));
873 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsUserProtected (MonoString *path)
875 gboolean ret = FALSE;
877 /* no one, but the user, should have access to the directory */
879 ret = IsUserProtected (mono_string_chars (path));
881 ret = IsProtected (path, (S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH));
888 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectMachine (MonoString *path)
890 gboolean ret = FALSE;
892 /* read/write to owner, read to everyone else */
894 ret = ProtectMachine (mono_string_chars (path));
896 ret = Protect (path, (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH), (S_IXUSR | S_IXGRP | S_IXOTH));
903 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectUser (MonoString *path)
905 gboolean ret = FALSE;
907 /* read/write to user, no access to everyone else */
909 ret = ProtectUser (mono_string_chars (path));
911 ret = Protect (path, (S_IRUSR | S_IWUSR), S_IXUSR);
918 * Returns TRUE if there is "something" where the Authenticode signature is
919 * normally located. Returns FALSE is data directory is empty.
921 * Note: Neither the structure nor the signature is verified by this function.
924 ves_icall_System_Security_Policy_Evidence_IsAuthenticodePresent (MonoReflectionAssembly *refass)
926 if (refass && refass->assembly && refass->assembly->image) {
927 return mono_image_has_authenticode_entry (refass->assembly->image);
933 /* System.Security.SecureString related internal calls */
935 static MonoImage *system_security_assembly = NULL;
938 ves_icall_System_Security_SecureString_DecryptInternal (MonoArray *data, MonoObject *scope)
941 invoke_protected_memory_method (data, scope, FALSE, &error);
942 mono_error_set_pending_exception (&error);
945 ves_icall_System_Security_SecureString_EncryptInternal (MonoArray* data, MonoObject *scope)
948 invoke_protected_memory_method (data, scope, TRUE, &error);
949 mono_error_set_pending_exception (&error);
952 void invoke_protected_memory_method (MonoArray *data, MonoObject *scope, gboolean encrypt, MonoError *error)
958 mono_error_init (error);
960 if (system_security_assembly == NULL) {
961 system_security_assembly = mono_image_loaded ("System.Security");
962 if (!system_security_assembly) {
963 MonoAssembly *sa = mono_assembly_open ("System.Security.dll", NULL);
965 g_assert_not_reached ();
966 system_security_assembly = mono_assembly_get_image (sa);
970 klass = mono_class_load_from_name (system_security_assembly,
971 "System.Security.Cryptography", "ProtectedMemory");
972 method = mono_class_get_method_from_name (klass, encrypt ? "Protect" : "Unprotect", 2);
974 params [1] = scope; /* MemoryProtectionScope.SameProcess */
976 mono_runtime_invoke_checked (method, NULL, params, error);