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/exception.h>
16 #include <mono/metadata/security.h>
17 #include <mono/io-layer/io-layer.h>
18 #include <mono/utils/strenc.h>
25 #ifndef PROTECTED_DACL_SECURITY_INFORMATION
26 #define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
36 #include <sys/types.h>
43 #ifndef HAVE_GETGRGID_R
44 #warning Non-thread safe getgrgid being used!
46 #ifndef HAVE_GETGRNAM_R
47 #warning Non-thread safe getgrnam being used!
49 #ifndef HAVE_GETPWNAM_R
50 #warning Non-thread safe getpwnam being used!
52 #ifndef HAVE_GETPWUID_R
53 #warning Non-thread safe getpwuid being used!
56 #endif /* defined(__GNUC__) */
58 #endif /* not PLATFORM_WIN32 */
61 /* internal functions - reuse driven */
65 /* ask a server to translate a SID into a textual representation */
67 GetSidName (gunichar2 *server, PSID sid, gint32 *size)
69 gunichar2 *uniname = NULL;
72 SID_NAME_USE peUse; /* out */
74 LookupAccountSid (server, sid, NULL, &cchName, NULL,
77 if ((cchName > 0) && (cchDomain > 0)) {
78 gunichar2 *user = g_malloc0 ((cchName + 1) * 2);
79 gunichar2 *domain = g_malloc0 ((cchDomain + 1) * 2);
81 LookupAccountSid (server, sid, user, &cchName, domain,
86 /* domain/machine name included (+ sepearator) */
87 *size = cchName + cchDomain + 1;
88 uniname = g_malloc0 ((*size + 1) * 2);
89 memcpy (uniname, domain, cchDomain * 2);
90 *(uniname + cchDomain) = '\\';
91 memcpy (uniname + cchDomain + 1, user, cchName * 2);
95 /* no domain / machine */
101 // nothing -> return NULL
112 #else /* not PLATFORM_WIN32 */
116 GetTokenName (uid_t uid)
120 #ifdef HAVE_GETPWUID_R
126 struct passwd *p = NULL;
129 #ifdef HAVE_GETPWUID_R
130 #ifdef _SC_GETPW_R_SIZE_MAX
131 fbufsize = (size_t) sysconf (_SC_GETPW_R_SIZE_MAX);
133 fbufsize = (size_t) 1024;
135 fbuf = g_malloc0 (fbufsize);
136 retval = getpwuid_r (uid, &pwd, fbuf, fbufsize, &p);
137 result = ((retval == 0) && (p == &pwd));
139 /* default to non thread-safe but posix compliant function */
141 result = (p != NULL);
145 uname = g_strdup (p->pw_name);
148 #ifdef HAVE_GETPWUID_R
157 IsMemberInList (uid_t user, struct group *g)
159 gboolean result = FALSE;
160 gchar *utf8_username = GetTokenName (user);
166 gchar **users = g->gr_mem;
170 if (strcmp (utf8_username, u) == 0) {
178 g_free (utf8_username);
184 IsDefaultGroup (uid_t user, gid_t group)
186 #ifdef HAVE_GETPWUID_R
192 struct passwd *p = NULL;
195 #ifdef HAVE_GETPWUID_R
196 #ifdef _SC_GETPW_R_SIZE_MAX
197 fbufsize = (size_t) sysconf (_SC_GETPW_R_SIZE_MAX);
199 fbufsize = (size_t) 1024;
202 fbuf = g_malloc0 (fbufsize);
203 retval = getpwuid_r (user, &pwd, fbuf, fbufsize, &p);
204 result = ((retval == 0) && (p == &pwd));
206 /* default to non thread-safe but posix compliant function */
208 result = (p != NULL);
212 result = (p->pw_gid == group);
215 #ifdef HAVE_GETPWUID_R
224 IsMemberOf (gid_t user, struct group *g)
229 /* is it the user default group */
230 if (IsDefaultGroup (user, g->gr_gid))
233 /* is the user in the group list */
234 return IsMemberInList (user, g);
243 /* System.Environment */
247 ves_icall_System_Environment_get_UserName (void)
251 /* using glib is more portable */
252 return mono_string_new (mono_domain_get (), g_get_user_name ());
256 /* System.Security.Principal.WindowsIdentity */
260 ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken (void)
262 gpointer token = NULL;
266 #ifdef PLATFORM_WIN32
267 /* Note: This isn't a copy of the Token - we must not close it!!!
268 * http://www.develop.com/kbrown/book/html/whatis_windowsprincipal.html
271 /* thread may be impersonating somebody */
272 if (OpenThreadToken (GetCurrentThread (), TOKEN_QUERY, 1, &token) == 0) {
273 /* if not take the process identity */
274 OpenProcessToken (GetCurrentProcess (), TOKEN_QUERY, &token);
277 token = (gpointer) geteuid ();
284 ves_icall_System_Security_Principal_WindowsIdentity_GetTokenName (gpointer token)
286 MonoString *result = NULL;
287 gunichar2 *uniname = NULL;
290 #ifdef PLATFORM_WIN32
293 GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
295 TOKEN_USER *tu = g_malloc0 (size);
296 if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
297 uniname = GetSidName (NULL, tu->User.Sid, &size);
302 gchar *uname = GetTokenName ((uid_t) token);
307 size = strlen (uname);
308 uniname = g_utf8_to_utf16 (uname, size, NULL, NULL, NULL);
311 #endif /* PLATFORM_WIN32 */
314 result = mono_string_new_utf16 (mono_domain_get (), uniname, size);
317 result = mono_string_new (mono_domain_get (), "");
327 ves_icall_System_Security_Principal_WindowsIdentity_GetUserToken (MonoString *username)
329 #ifdef PLATFORM_WIN32
330 gpointer token = NULL;
334 /* TODO: MS has something like this working in Windows 2003 (client and
335 * server) but works only for domain accounts (so it's quite limiting).
336 * http://www.develop.com/kbrown/book/html/howto_logonuser.html
338 g_warning ("Unsupported on Win32 (anyway requires W2K3 minimum)");
340 #else /* PLATFORM_WIN32*/
342 #ifdef HAVE_GETPWNAM_R
348 gpointer token = (gpointer) -2;
355 utf8_name = mono_unicode_to_external (mono_string_chars (username));
357 #ifdef HAVE_GETPWNAM_R
358 #ifdef _SC_GETPW_R_SIZE_MAX
359 fbufsize = (size_t) sysconf (_SC_GETPW_R_SIZE_MAX);
361 fbufsize = (size_t) 1024;
364 fbuf = g_malloc0 (fbufsize);
365 retval = getpwnam_r (utf8_name, &pwd, fbuf, fbufsize, &p);
366 result = ((retval == 0) && (p == &pwd));
368 /* default to non thread-safe but posix compliant function */
369 p = getpwnam (utf8_name);
370 result = (p != NULL);
374 token = (gpointer) p->pw_uid;
377 #ifdef HAVE_GETPWNAM_R
386 // http://www.dotnet247.com/247reference/msgs/39/195403.aspx
387 // internal static string[] WindowsIdentity._GetRoles (IntPtr token)
389 ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token)
391 MonoArray *array = NULL;
392 MonoDomain *domain = mono_domain_get ();
393 #ifdef PLATFORM_WIN32
398 GetTokenInformation (token, TokenGroups, NULL, size, (PDWORD)&size);
400 TOKEN_GROUPS *tg = g_malloc0 (size);
401 if (GetTokenInformation (token, TokenGroups, tg, size, (PDWORD)&size)) {
403 int num = tg->GroupCount;
405 array = mono_array_new (domain, mono_defaults.string_class, num);
407 for (i=0; i < num; i++) {
409 gunichar2 *uniname = GetSidName (NULL, tg->Groups [i].Sid, &size);
412 MonoString *str = mono_string_new_utf16 (domain, uniname, size);
413 mono_array_set (array, MonoString *, i, str);
421 /* POSIX-compliant systems should use IsMemberOfGroupId or IsMemberOfGroupName */
422 g_warning ("WindowsIdentity._GetRoles should never be called on POSIX");
425 /* return empty array of string, i.e. string [0] */
426 array = mono_array_new (domain, mono_defaults.string_class, 0);
432 /* System.Security.Principal.WindowsImpersonationContext */
436 ves_icall_System_Security_Principal_WindowsImpersonationContext_CloseToken (gpointer token)
438 gboolean result = TRUE;
442 #ifdef PLATFORM_WIN32
443 result = (CloseHandle (token) != 0);
450 ves_icall_System_Security_Principal_WindowsImpersonationContext_DuplicateToken (gpointer token)
452 gpointer dupe = NULL;
456 #ifdef PLATFORM_WIN32
457 if (DuplicateToken (token, SecurityImpersonation, &dupe) == 0) {
468 ves_icall_System_Security_Principal_WindowsImpersonationContext_SetCurrentToken (gpointer token)
472 /* Posix version implemented in /mono/mono/io-layer/security.c */
473 return (ImpersonateLoggedOnUser (token) != 0);
478 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;
494 #ifdef PLATFORM_WIN32
497 /* The convertion from an ID to a string is done in managed code for Windows */
498 g_warning ("IsMemberOfGroupId should never be called on Win32");
500 #else /* PLATFORM_WIN32 */
502 #ifdef HAVE_GETGRGID_R
508 struct group *g = NULL;
512 #ifdef HAVE_GETGRGID_R
513 #ifdef _SC_GETGR_R_SIZE_MAX
514 fbufsize = (size_t) sysconf (_SC_GETGR_R_SIZE_MAX);
516 fbufsize = (size_t) 1024;
518 fbuf = g_malloc0 (fbufsize);
519 retval = getgrgid_r ((gid_t) group, &grp, fbuf, fbufsize, &g);
520 result = ((retval == 0) && (g == &grp));
522 /* default to non thread-safe but posix compliant function */
523 g = getgrgid ((gid_t) group);
524 result = (g != NULL);
528 result = IsMemberOf ((uid_t) user, g);
531 #ifdef HAVE_GETGRGID_R
535 #endif /* PLATFORM_WIN32 */
542 ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupName (gpointer user, MonoString *group)
544 gboolean result = FALSE;
546 #ifdef PLATFORM_WIN32
550 /* Windows version use a cache built using WindowsIdentity._GetRoles */
551 g_warning ("IsMemberOfGroupName should never be called on Win32");
553 #else /* PLATFORM_WIN32 */
554 gchar *utf8_groupname;
558 utf8_groupname = mono_unicode_to_external (mono_string_chars (group));
559 if (utf8_groupname) {
560 struct group *g = NULL;
561 #ifdef HAVE_GETGRNAM_R
565 #ifdef _SC_GETGR_R_SIZE_MAX
566 size_t fbufsize = (size_t) sysconf (_SC_GETGR_R_SIZE_MAX);
568 size_t fbufsize = (size_t) 1024;
570 fbuf = g_malloc0 (fbufsize);
571 retval = getgrnam_r (utf8_groupname, &grp, fbuf, fbufsize, &g);
572 result = ((retval == 0) && (g == &grp));
574 /* default to non thread-safe but posix compliant function */
575 g = getgrnam (utf8_groupname);
576 result = (g != NULL);
580 result = IsMemberOf ((uid_t) user, g);
583 #ifdef HAVE_GETGRNAM_R
586 g_free (utf8_groupname);
588 #endif /* PLATFORM_WIN32 */
594 /* Mono.Security.Cryptography IO related internal calls */
596 #ifdef PLATFORM_WIN32
599 GetAdministratorsSid (void)
601 SID_IDENTIFIER_AUTHORITY admins = SECURITY_NT_AUTHORITY;
603 if (!AllocateAndInitializeSid (&admins, 2, SECURITY_BUILTIN_DOMAIN_RID,
604 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pSid))
606 /* Note: this SID must be freed with FreeSid () */
612 GetEveryoneSid (void)
614 SID_IDENTIFIER_AUTHORITY everyone = SECURITY_WORLD_SID_AUTHORITY;
616 if (!AllocateAndInitializeSid (&everyone, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pSid))
618 /* Note: this SID must be freed with FreeSid () */
624 GetCurrentUserSid (void)
628 gpointer token = ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken ();
630 GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
632 TOKEN_USER *tu = g_malloc0 (size);
633 if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
634 DWORD length = GetLengthSid (tu->User.Sid);
635 sid = (PSID) g_malloc0 (length);
636 if (!CopySid (length, sid, tu->User.Sid)) {
643 /* Note: this SID must be freed with g_free () */
649 GetRightsFromSid (PSID sid, PACL acl)
651 ACCESS_MASK rights = 0;
654 BuildTrusteeWithSidW (&trustee, sid);
655 if (GetEffectiveRightsFromAcl (acl, &trustee, &rights) != ERROR_SUCCESS)
663 IsMachineProtected (gunichar2 *path)
665 gboolean success = FALSE;
667 PSID pEveryoneSid = NULL;
669 DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, NULL);
670 if (dwRes != ERROR_SUCCESS)
673 /* We check that Everyone is still limited to READ-ONLY -
674 but not if new entries have been added by an Administrator */
676 pEveryoneSid = GetEveryoneSid ();
678 ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
679 // http://msdn.microsoft.com/library/en-us/security/security/generic_access_rights.asp?frame=true
680 success = (rights == (READ_CONTROL | SYNCHRONIZE | FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES));
681 FreeSid (pEveryoneSid);
683 /* Note: we don't need to check our own access -
684 we'll know soon enough when reading the file */
694 IsUserProtected (gunichar2 *path)
696 gboolean success = FALSE;
698 PSID pEveryoneSid = NULL;
700 DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT,
701 DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, NULL);
702 if (dwRes != ERROR_SUCCESS)
705 /* We check that our original entries in the ACL are in place -
706 but not if new entries have been added by the user */
708 /* Everyone should be denied */
709 pEveryoneSid = GetEveryoneSid ();
711 ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
712 success = (rights == 0);
713 FreeSid (pEveryoneSid);
715 /* Note: we don't need to check our own access -
716 we'll know soon enough when reading the file */
726 ProtectMachine (gunichar2 *path)
728 PSID pEveryoneSid = GetEveryoneSid ();
729 PSID pAdminsSid = GetAdministratorsSid ();
732 if (pEveryoneSid && pAdminsSid) {
734 EXPLICIT_ACCESS ea [2];
735 ZeroMemory (&ea, 2 * sizeof (EXPLICIT_ACCESS));
737 // grant all access to the BUILTIN\Administrators group
738 BuildTrusteeWithSidW (&ea [0].Trustee, pAdminsSid);
739 ea [0].grfAccessPermissions = GENERIC_ALL;
740 ea [0].grfAccessMode = SET_ACCESS;
741 ea [0].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
742 ea [0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
743 ea [0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
745 // read-only access everyone
746 BuildTrusteeWithSidW (&ea [1].Trustee, pEveryoneSid);
747 ea [1].grfAccessPermissions = GENERIC_READ;
748 ea [1].grfAccessMode = SET_ACCESS;
749 ea [1].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
750 ea [1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
751 ea [1].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
753 retval = SetEntriesInAcl (2, ea, NULL, &pDACL);
754 if (retval == ERROR_SUCCESS) {
755 // with PROTECTED_DACL_SECURITY_INFORMATION we
756 // remove any existing ACL (like inherited ones)
757 retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT,
758 DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
759 NULL, NULL, pDACL, NULL);
766 FreeSid (pEveryoneSid);
768 FreeSid (pAdminsSid);
769 return (retval == ERROR_SUCCESS);
774 ProtectUser (gunichar2 *path)
778 PSID pCurrentSid = GetCurrentUserSid ();
782 ZeroMemory (&ea, sizeof (EXPLICIT_ACCESS));
784 // grant exclusive access to the current user
785 BuildTrusteeWithSidW (&ea.Trustee, pCurrentSid);
786 ea.grfAccessPermissions = GENERIC_ALL;
787 ea.grfAccessMode = SET_ACCESS;
788 ea.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
789 ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
790 ea.Trustee.TrusteeType = TRUSTEE_IS_USER;
792 retval = SetEntriesInAcl (1, &ea, NULL, &pDACL);
793 if (retval == ERROR_SUCCESS) {
794 // with PROTECTED_DACL_SECURITY_INFORMATION we
795 // remove any existing ACL (like inherited ones)
796 retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT,
797 DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
798 NULL, NULL, pDACL, NULL);
803 g_free (pCurrentSid); /* g_malloc0 */
806 return (retval == ERROR_SUCCESS);
812 IsProtected (MonoString *path, gint32 protection)
814 gboolean result = FALSE;
815 gchar *utf8_name = mono_unicode_to_external (mono_string_chars (path));
818 if (stat (utf8_name, &st) == 0) {
819 result = (((st.st_mode & 0777) & protection) == 0);
828 Protect (MonoString *path, gint32 file_mode, gint32 add_dir_mode)
830 gboolean result = FALSE;
831 gchar *utf8_name = mono_unicode_to_external (mono_string_chars (path));
834 if (stat (utf8_name, &st) == 0) {
835 int mode = file_mode;
836 if (st.st_mode & S_IFDIR)
837 mode |= add_dir_mode;
838 result = (chmod (utf8_name, mode) == 0);
845 #endif /* not PLATFORM_WIN32 */
849 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_CanSecure (MonoString *root)
856 /* ACL are nice... unless you have FAT or other uncivilized filesystem */
857 if (!GetVolumeInformation (mono_string_chars (root), NULL, 0, NULL, NULL, (LPDWORD)&flags, NULL, 0))
859 return ((flags & FS_PERSISTENT_ACLS) == FS_PERSISTENT_ACLS);
862 /* we assume some kind of security is applicable outside Windows */
869 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsMachineProtected (MonoString *path)
871 gboolean ret = FALSE;
875 /* no one, but the owner, should have write access to the directory */
876 #ifdef PLATFORM_WIN32
877 ret = IsMachineProtected (mono_string_chars (path));
879 ret = IsProtected (path, (S_IWGRP | S_IWOTH));
886 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsUserProtected (MonoString *path)
888 gboolean ret = FALSE;
892 /* no one, but the user, should have access to the directory */
893 #ifdef PLATFORM_WIN32
894 ret = IsUserProtected (mono_string_chars (path));
896 ret = IsProtected (path, (S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH));
903 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectMachine (MonoString *path)
905 gboolean ret = FALSE;
909 /* read/write to owner, read to everyone else */
910 #ifdef PLATFORM_WIN32
911 ret = ProtectMachine (mono_string_chars (path));
913 ret = Protect (path, (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH), (S_IXUSR | S_IXGRP | S_IXOTH));
920 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectUser (MonoString *path)
922 gboolean ret = FALSE;
926 /* read/write to user, no access to everyone else */
927 #ifdef PLATFORM_WIN32
928 ret = ProtectUser (mono_string_chars (path));
930 ret = Protect (path, (S_IRUSR | S_IWUSR), S_IXUSR);