2 * security.c: Security internal calls
5 * Sebastien Pouliot <sebastien@ximian.com>
7 * Copyright 2004-2009 Novell, Inc (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
44 #include <sys/types.h>
51 #ifndef HAVE_GETGRGID_R
52 #warning Non-thread safe getgrgid being used!
54 #ifndef HAVE_GETGRNAM_R
55 #warning Non-thread safe getgrnam being used!
57 #ifndef HAVE_GETPWNAM_R
58 #warning Non-thread safe getpwnam being used!
60 #ifndef HAVE_GETPWUID_R
61 #warning Non-thread safe getpwuid being used!
64 #endif /* defined(__GNUC__) */
66 #endif /* not HOST_WIN32 */
69 /* internal functions - reuse driven */
73 /* ask a server to translate a SID into a textual representation */
75 GetSidName (gunichar2 *server, PSID sid, gint32 *size)
77 gunichar2 *uniname = NULL;
80 SID_NAME_USE peUse; /* out */
82 LookupAccountSid (server, sid, NULL, &cchName, NULL,
85 if ((cchName > 0) && (cchDomain > 0)) {
86 gunichar2 *user = g_malloc0 ((cchName + 1) * 2);
87 gunichar2 *domain = g_malloc0 ((cchDomain + 1) * 2);
89 LookupAccountSid (server, sid, user, &cchName, domain,
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);
103 /* no domain / machine */
109 /* nothing -> return NULL */
120 #else /* not HOST_WIN32 */
122 #define MONO_SYSCONF_DEFAULT_SIZE ((size_t) 1024)
125 * Ensure we always get a valid (usable) value from sysconf.
126 * In case of error, we return the default value.
128 static size_t mono_sysconf (int name)
130 size_t size = (size_t) sysconf (name);
132 return (size == -1) ? MONO_SYSCONF_DEFAULT_SIZE : size;
137 GetTokenName (uid_t uid)
141 #ifdef HAVE_GETPWUID_R
147 struct passwd *p = NULL;
150 #ifdef HAVE_GETPWUID_R
151 #ifdef _SC_GETPW_R_SIZE_MAX
152 fbufsize = mono_sysconf (_SC_GETPW_R_SIZE_MAX);
154 fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
156 fbuf = g_malloc0 (fbufsize);
157 retval = getpwuid_r (uid, &pwd, fbuf, fbufsize, &p);
158 result = ((retval == 0) && (p == &pwd));
160 /* default to non thread-safe but posix compliant function */
162 result = (p != NULL);
166 uname = g_strdup (p->pw_name);
169 #ifdef HAVE_GETPWUID_R
178 IsMemberInList (uid_t user, struct group *g)
180 gboolean result = FALSE;
181 gchar *utf8_username = GetTokenName (user);
187 gchar **users = g->gr_mem;
191 if (strcmp (utf8_username, u) == 0) {
199 g_free (utf8_username);
205 IsDefaultGroup (uid_t user, gid_t group)
207 #ifdef HAVE_GETPWUID_R
213 struct passwd *p = NULL;
216 #ifdef HAVE_GETPWUID_R
217 #ifdef _SC_GETPW_R_SIZE_MAX
218 fbufsize = mono_sysconf (_SC_GETPW_R_SIZE_MAX);
220 fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
223 fbuf = g_malloc0 (fbufsize);
224 retval = getpwuid_r (user, &pwd, fbuf, fbufsize, &p);
225 result = ((retval == 0) && (p == &pwd));
227 /* default to non thread-safe but posix compliant function */
229 result = (p != NULL);
233 result = (p->pw_gid == group);
236 #ifdef HAVE_GETPWUID_R
245 IsMemberOf (gid_t user, struct group *g)
250 /* is it the user default group */
251 if (IsDefaultGroup (user, g->gr_gid))
254 /* is the user in the group list */
255 return IsMemberInList (user, g);
264 /* System.Security.Principal.WindowsIdentity */
268 ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken (void)
270 gpointer token = NULL;
275 /* Note: This isn't a copy of the Token - we must not close it!!!
276 * http://www.develop.com/kbrown/book/html/whatis_windowsprincipal.html
279 /* thread may be impersonating somebody */
280 if (OpenThreadToken (GetCurrentThread (), TOKEN_QUERY, 1, &token) == 0) {
281 /* if not take the process identity */
282 OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &token);
285 token = GINT_TO_POINTER (geteuid ());
292 ves_icall_System_Security_Principal_WindowsIdentity_GetTokenName (gpointer token)
294 MonoString *result = NULL;
295 gunichar2 *uniname = NULL;
301 GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
303 TOKEN_USER *tu = g_malloc0 (size);
304 if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
305 uniname = GetSidName (NULL, tu->User.Sid, &size);
310 gchar *uname = GetTokenName ((uid_t) GPOINTER_TO_INT (token));
315 size = strlen (uname);
316 uniname = g_utf8_to_utf16 (uname, size, NULL, NULL, NULL);
319 #endif /* HOST_WIN32 */
322 result = mono_string_new_utf16 (mono_domain_get (), uniname, size);
325 result = mono_string_new (mono_domain_get (), "");
335 ves_icall_System_Security_Principal_WindowsIdentity_GetUserToken (MonoString *username)
338 gpointer token = NULL;
342 /* TODO: MS has something like this working in Windows 2003 (client and
343 * server) but works only for domain accounts (so it's quite limiting).
344 * http://www.develop.com/kbrown/book/html/howto_logonuser.html
346 g_warning ("Unsupported on Win32 (anyway requires W2K3 minimum)");
348 #else /* HOST_WIN32*/
350 #ifdef HAVE_GETPWNAM_R
356 gpointer token = (gpointer) -2;
363 utf8_name = mono_unicode_to_external (mono_string_chars (username));
365 #ifdef HAVE_GETPWNAM_R
366 #ifdef _SC_GETPW_R_SIZE_MAX
367 fbufsize = mono_sysconf (_SC_GETPW_R_SIZE_MAX);
369 fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
372 fbuf = g_malloc0 (fbufsize);
373 retval = getpwnam_r (utf8_name, &pwd, fbuf, fbufsize, &p);
374 result = ((retval == 0) && (p == &pwd));
376 /* default to non thread-safe but posix compliant function */
377 p = getpwnam (utf8_name);
378 result = (p != NULL);
382 token = GINT_TO_POINTER (p->pw_uid);
385 #ifdef HAVE_GETPWNAM_R
394 /* http://www.dotnet247.com/247reference/msgs/39/195403.aspx
395 // internal static string[] WindowsIdentity._GetRoles (IntPtr token)
398 ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token)
400 MonoArray *array = NULL;
401 MonoDomain *domain = mono_domain_get ();
407 GetTokenInformation (token, TokenGroups, NULL, size, (PDWORD)&size);
409 TOKEN_GROUPS *tg = g_malloc0 (size);
410 if (GetTokenInformation (token, TokenGroups, tg, size, (PDWORD)&size)) {
412 int num = tg->GroupCount;
414 array = mono_array_new (domain, mono_get_string_class (), num);
416 for (i=0; i < num; i++) {
418 gunichar2 *uniname = GetSidName (NULL, tg->Groups [i].Sid, &size);
421 MonoString *str = mono_string_new_utf16 (domain, uniname, size);
422 mono_array_setref (array, i, str);
430 /* POSIX-compliant systems should use IsMemberOfGroupId or IsMemberOfGroupName */
431 g_warning ("WindowsIdentity._GetRoles should never be called on POSIX");
434 /* return empty array of string, i.e. string [0] */
435 array = mono_array_new (domain, mono_get_string_class (), 0);
441 /* System.Security.Principal.WindowsImpersonationContext */
445 ves_icall_System_Security_Principal_WindowsImpersonationContext_CloseToken (gpointer token)
447 gboolean result = TRUE;
452 result = (CloseHandle (token) != 0);
459 ves_icall_System_Security_Principal_WindowsImpersonationContext_DuplicateToken (gpointer token)
461 gpointer dupe = NULL;
466 if (DuplicateToken (token, SecurityImpersonation, &dupe) == 0) {
477 ves_icall_System_Security_Principal_WindowsImpersonationContext_SetCurrentToken (gpointer token)
481 /* Posix version implemented in /mono/mono/io-layer/security.c */
482 return (ImpersonateLoggedOnUser (token) != 0);
487 ves_icall_System_Security_Principal_WindowsImpersonationContext_RevertToSelf (void)
491 /* Posix version implemented in /mono/mono/io-layer/security.c */
492 return (RevertToSelf () != 0);
496 /* System.Security.Principal.WindowsPrincipal */
499 ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupId (gpointer user, gpointer group)
501 gboolean result = FALSE;
506 /* The convertion from an ID to a string is done in managed code for Windows */
507 g_warning ("IsMemberOfGroupId should never be called on Win32");
509 #else /* HOST_WIN32 */
511 #ifdef HAVE_GETGRGID_R
517 struct group *g = NULL;
521 #ifdef HAVE_GETGRGID_R
522 #ifdef _SC_GETGR_R_SIZE_MAX
523 fbufsize = mono_sysconf (_SC_GETGR_R_SIZE_MAX);
525 fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
527 fbuf = g_malloc0 (fbufsize);
528 retval = getgrgid_r ((gid_t) GPOINTER_TO_INT (group), &grp, fbuf, fbufsize, &g);
529 result = ((retval == 0) && (g == &grp));
531 /* default to non thread-safe but posix compliant function */
532 g = getgrgid ((gid_t) GPOINTER_TO_INT (group));
533 result = (g != NULL);
537 result = IsMemberOf ((uid_t) GPOINTER_TO_INT (user), g);
540 #ifdef HAVE_GETGRGID_R
544 #endif /* HOST_WIN32 */
551 ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupName (gpointer user, MonoString *group)
553 gboolean result = FALSE;
559 /* Windows version use a cache built using WindowsIdentity._GetRoles */
560 g_warning ("IsMemberOfGroupName should never be called on Win32");
562 #else /* HOST_WIN32 */
563 gchar *utf8_groupname;
567 utf8_groupname = mono_unicode_to_external (mono_string_chars (group));
568 if (utf8_groupname) {
569 struct group *g = NULL;
570 #ifdef HAVE_GETGRNAM_R
574 #ifdef _SC_GETGR_R_SIZE_MAX
575 size_t fbufsize = mono_sysconf (_SC_GETGR_R_SIZE_MAX);
577 size_t fbufsize = MONO_SYSCONF_DEFAULT_SIZE;
579 fbuf = g_malloc0 (fbufsize);
580 retval = getgrnam_r (utf8_groupname, &grp, fbuf, fbufsize, &g);
581 result = ((retval == 0) && (g == &grp));
583 /* default to non thread-safe but posix compliant function */
584 g = getgrnam (utf8_groupname);
585 result = (g != NULL);
589 result = IsMemberOf ((uid_t) GPOINTER_TO_INT (user), g);
592 #ifdef HAVE_GETGRNAM_R
595 g_free (utf8_groupname);
597 #endif /* HOST_WIN32 */
603 /* Mono.Security.Cryptography IO related internal calls */
608 GetAdministratorsSid (void)
610 SID_IDENTIFIER_AUTHORITY admins = SECURITY_NT_AUTHORITY;
612 if (!AllocateAndInitializeSid (&admins, 2, SECURITY_BUILTIN_DOMAIN_RID,
613 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pSid))
615 /* Note: this SID must be freed with FreeSid () */
621 GetEveryoneSid (void)
623 SID_IDENTIFIER_AUTHORITY everyone = SECURITY_WORLD_SID_AUTHORITY;
625 if (!AllocateAndInitializeSid (&everyone, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pSid))
627 /* Note: this SID must be freed with FreeSid () */
633 GetCurrentUserSid (void)
637 gpointer token = ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken ();
639 GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
641 TOKEN_USER *tu = g_malloc0 (size);
642 if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
643 DWORD length = GetLengthSid (tu->User.Sid);
644 sid = (PSID) g_malloc0 (length);
645 if (!CopySid (length, sid, tu->User.Sid)) {
652 /* Note: this SID must be freed with g_free () */
658 GetRightsFromSid (PSID sid, PACL acl)
660 ACCESS_MASK rights = 0;
663 BuildTrusteeWithSidW (&trustee, sid);
664 if (GetEffectiveRightsFromAcl (acl, &trustee, &rights) != ERROR_SUCCESS)
672 IsMachineProtected (gunichar2 *path)
674 gboolean success = FALSE;
676 PSID pEveryoneSid = NULL;
678 DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, NULL);
679 if (dwRes != ERROR_SUCCESS)
682 /* We check that Everyone is still limited to READ-ONLY -
683 but not if new entries have been added by an Administrator */
685 pEveryoneSid = GetEveryoneSid ();
687 ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
688 /* http://msdn.microsoft.com/library/en-us/security/security/generic_access_rights.asp?frame=true */
689 success = (rights == (READ_CONTROL | SYNCHRONIZE | FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES));
690 FreeSid (pEveryoneSid);
692 /* Note: we don't need to check our own access -
693 we'll know soon enough when reading the file */
703 IsUserProtected (gunichar2 *path)
705 gboolean success = FALSE;
707 PSID pEveryoneSid = NULL;
708 PSECURITY_DESCRIPTOR pSecurityDescriptor = NULL;
710 DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT,
711 DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, &pSecurityDescriptor);
712 if (dwRes != ERROR_SUCCESS)
715 /* We check that our original entries in the ACL are in place -
716 but not if new entries have been added by the user */
718 /* Everyone should be denied */
719 pEveryoneSid = GetEveryoneSid ();
721 ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
722 success = (rights == 0);
723 FreeSid (pEveryoneSid);
725 /* Note: we don't need to check our own access -
726 we'll know soon enough when reading the file */
728 if (pSecurityDescriptor)
729 LocalFree (pSecurityDescriptor);
736 ProtectMachine (gunichar2 *path)
738 PSID pEveryoneSid = GetEveryoneSid ();
739 PSID pAdminsSid = GetAdministratorsSid ();
742 if (pEveryoneSid && pAdminsSid) {
744 EXPLICIT_ACCESS ea [2];
745 ZeroMemory (&ea, 2 * sizeof (EXPLICIT_ACCESS));
747 /* grant all access to the BUILTIN\Administrators group */
748 BuildTrusteeWithSidW (&ea [0].Trustee, pAdminsSid);
749 ea [0].grfAccessPermissions = GENERIC_ALL;
750 ea [0].grfAccessMode = SET_ACCESS;
751 ea [0].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
752 ea [0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
753 ea [0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
755 /* read-only access everyone */
756 BuildTrusteeWithSidW (&ea [1].Trustee, pEveryoneSid);
757 ea [1].grfAccessPermissions = GENERIC_READ;
758 ea [1].grfAccessMode = SET_ACCESS;
759 ea [1].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
760 ea [1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
761 ea [1].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
763 retval = SetEntriesInAcl (2, ea, NULL, &pDACL);
764 if (retval == ERROR_SUCCESS) {
765 /* with PROTECTED_DACL_SECURITY_INFORMATION we */
766 /* remove any existing ACL (like inherited ones) */
767 retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT,
768 DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
769 NULL, NULL, pDACL, NULL);
776 FreeSid (pEveryoneSid);
778 FreeSid (pAdminsSid);
779 return (retval == ERROR_SUCCESS);
784 ProtectUser (gunichar2 *path)
788 PSID pCurrentSid = GetCurrentUserSid ();
792 ZeroMemory (&ea, sizeof (EXPLICIT_ACCESS));
794 /* grant exclusive access to the current user */
795 BuildTrusteeWithSidW (&ea.Trustee, pCurrentSid);
796 ea.grfAccessPermissions = GENERIC_ALL;
797 ea.grfAccessMode = SET_ACCESS;
798 ea.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
799 ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
800 ea.Trustee.TrusteeType = TRUSTEE_IS_USER;
802 retval = SetEntriesInAcl (1, &ea, NULL, &pDACL);
803 if (retval == ERROR_SUCCESS) {
804 /* with PROTECTED_DACL_SECURITY_INFORMATION we
805 remove any existing ACL (like inherited ones) */
806 retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT,
807 DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
808 NULL, NULL, pDACL, NULL);
813 g_free (pCurrentSid); /* g_malloc0 */
816 return (retval == ERROR_SUCCESS);
822 IsProtected (MonoString *path, gint32 protection)
824 gboolean result = FALSE;
825 gchar *utf8_name = mono_unicode_to_external (mono_string_chars (path));
828 if (stat (utf8_name, &st) == 0) {
829 result = (((st.st_mode & 0777) & protection) == 0);
838 Protect (MonoString *path, gint32 file_mode, gint32 add_dir_mode)
840 gboolean result = FALSE;
841 gchar *utf8_name = mono_unicode_to_external (mono_string_chars (path));
844 if (stat (utf8_name, &st) == 0) {
845 int mode = file_mode;
846 if (st.st_mode & S_IFDIR)
847 mode |= add_dir_mode;
848 result = (chmod (utf8_name, mode) == 0);
855 #endif /* not HOST_WIN32 */
859 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_CanSecure (MonoString *root)
866 /* ACL are nice... unless you have FAT or other uncivilized filesystem */
867 if (!GetVolumeInformation (mono_string_chars (root), NULL, 0, NULL, NULL, (LPDWORD)&flags, NULL, 0))
869 return ((flags & FS_PERSISTENT_ACLS) == FS_PERSISTENT_ACLS);
872 /* we assume some kind of security is applicable outside Windows */
879 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsMachineProtected (MonoString *path)
881 gboolean ret = FALSE;
885 /* no one, but the owner, should have write access to the directory */
887 ret = IsMachineProtected (mono_string_chars (path));
889 ret = IsProtected (path, (S_IWGRP | S_IWOTH));
896 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsUserProtected (MonoString *path)
898 gboolean ret = FALSE;
902 /* no one, but the user, should have access to the directory */
904 ret = IsUserProtected (mono_string_chars (path));
906 ret = IsProtected (path, (S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH));
913 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectMachine (MonoString *path)
915 gboolean ret = FALSE;
919 /* read/write to owner, read to everyone else */
921 ret = ProtectMachine (mono_string_chars (path));
923 ret = Protect (path, (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH), (S_IXUSR | S_IXGRP | S_IXOTH));
930 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectUser (MonoString *path)
932 gboolean ret = FALSE;
936 /* read/write to user, no access to everyone else */
938 ret = ProtectUser (mono_string_chars (path));
940 ret = Protect (path, (S_IRUSR | S_IWUSR), S_IXUSR);
947 * Returns TRUE if there is "something" where the Authenticode signature is
948 * normally located. Returns FALSE is data directory is empty.
950 * Note: Neither the structure nor the signature is verified by this function.
953 ves_icall_System_Security_Policy_Evidence_IsAuthenticodePresent (MonoReflectionAssembly *refass)
955 if (refass && refass->assembly && refass->assembly->image) {
956 return mono_image_has_authenticode_entry (refass->assembly->image);
962 /* System.Security.SecureString related internal calls */
964 static MonoImage *system_security_assembly = NULL;
967 ves_icall_System_Security_SecureString_DecryptInternal (MonoArray *data, MonoObject *scope)
969 invoke_protected_memory_method (data, scope, FALSE);
972 ves_icall_System_Security_SecureString_EncryptInternal (MonoArray* data, MonoObject *scope)
974 invoke_protected_memory_method (data, scope, TRUE);
977 void invoke_protected_memory_method (MonoArray *data, MonoObject *scope, gboolean encrypt)
985 if (system_security_assembly == NULL) {
986 system_security_assembly = mono_image_loaded ("System.Security");
987 if (!system_security_assembly) {
988 MonoAssembly *sa = mono_assembly_open ("System.Security.dll", NULL);
990 g_assert_not_reached ();
991 system_security_assembly = mono_assembly_get_image (sa);
995 klass = mono_class_from_name (system_security_assembly,
996 "System.Security.Cryptography", "ProtectedMemory");
997 method = mono_class_get_method_from_name (klass, encrypt ? "Protect" : "Unprotect", 2);
999 params [1] = scope; /* MemoryProtectionScope.SameProcess */
1000 mono_runtime_invoke (method, NULL, params, NULL);