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)
390 ves_icall_System_Security_Principal_WindowsIdentity_GetRoles (gpointer token)
392 MonoArray *array = NULL;
393 MonoDomain *domain = mono_domain_get ();
394 #ifdef PLATFORM_WIN32
399 GetTokenInformation (token, TokenGroups, NULL, size, (PDWORD)&size);
401 TOKEN_GROUPS *tg = g_malloc0 (size);
402 if (GetTokenInformation (token, TokenGroups, tg, size, (PDWORD)&size)) {
404 int num = tg->GroupCount;
406 array = mono_array_new (domain, mono_get_string_class (), num);
408 for (i=0; i < num; i++) {
410 gunichar2 *uniname = GetSidName (NULL, tg->Groups [i].Sid, &size);
413 MonoString *str = mono_string_new_utf16 (domain, uniname, size);
414 mono_array_set (array, MonoString *, i, str);
422 /* POSIX-compliant systems should use IsMemberOfGroupId or IsMemberOfGroupName */
423 g_warning ("WindowsIdentity._GetRoles should never be called on POSIX");
426 /* return empty array of string, i.e. string [0] */
427 array = mono_array_new (domain, mono_get_string_class (), 0);
433 /* System.Security.Principal.WindowsImpersonationContext */
437 ves_icall_System_Security_Principal_WindowsImpersonationContext_CloseToken (gpointer token)
439 gboolean result = TRUE;
443 #ifdef PLATFORM_WIN32
444 result = (CloseHandle (token) != 0);
451 ves_icall_System_Security_Principal_WindowsImpersonationContext_DuplicateToken (gpointer token)
453 gpointer dupe = NULL;
457 #ifdef PLATFORM_WIN32
458 if (DuplicateToken (token, SecurityImpersonation, &dupe) == 0) {
469 ves_icall_System_Security_Principal_WindowsImpersonationContext_SetCurrentToken (gpointer token)
473 /* Posix version implemented in /mono/mono/io-layer/security.c */
474 return (ImpersonateLoggedOnUser (token) != 0);
479 ves_icall_System_Security_Principal_WindowsImpersonationContext_RevertToSelf (void)
483 /* Posix version implemented in /mono/mono/io-layer/security.c */
484 return (RevertToSelf () != 0);
488 /* System.Security.Principal.WindowsPrincipal */
491 ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupId (gpointer user, gpointer group)
493 gboolean result = FALSE;
495 #ifdef PLATFORM_WIN32
498 /* The convertion from an ID to a string is done in managed code for Windows */
499 g_warning ("IsMemberOfGroupId should never be called on Win32");
501 #else /* PLATFORM_WIN32 */
503 #ifdef HAVE_GETGRGID_R
509 struct group *g = NULL;
513 #ifdef HAVE_GETGRGID_R
514 #ifdef _SC_GETGR_R_SIZE_MAX
515 fbufsize = (size_t) sysconf (_SC_GETGR_R_SIZE_MAX);
517 fbufsize = (size_t) 1024;
519 fbuf = g_malloc0 (fbufsize);
520 retval = getgrgid_r ((gid_t) group, &grp, fbuf, fbufsize, &g);
521 result = ((retval == 0) && (g == &grp));
523 /* default to non thread-safe but posix compliant function */
524 g = getgrgid ((gid_t) group);
525 result = (g != NULL);
529 result = IsMemberOf ((uid_t) user, g);
532 #ifdef HAVE_GETGRGID_R
536 #endif /* PLATFORM_WIN32 */
543 ves_icall_System_Security_Principal_WindowsPrincipal_IsMemberOfGroupName (gpointer user, MonoString *group)
545 gboolean result = FALSE;
547 #ifdef PLATFORM_WIN32
551 /* Windows version use a cache built using WindowsIdentity._GetRoles */
552 g_warning ("IsMemberOfGroupName should never be called on Win32");
554 #else /* PLATFORM_WIN32 */
555 gchar *utf8_groupname;
559 utf8_groupname = mono_unicode_to_external (mono_string_chars (group));
560 if (utf8_groupname) {
561 struct group *g = NULL;
562 #ifdef HAVE_GETGRNAM_R
566 #ifdef _SC_GETGR_R_SIZE_MAX
567 size_t fbufsize = (size_t) sysconf (_SC_GETGR_R_SIZE_MAX);
569 size_t fbufsize = (size_t) 1024;
571 fbuf = g_malloc0 (fbufsize);
572 retval = getgrnam_r (utf8_groupname, &grp, fbuf, fbufsize, &g);
573 result = ((retval == 0) && (g == &grp));
575 /* default to non thread-safe but posix compliant function */
576 g = getgrnam (utf8_groupname);
577 result = (g != NULL);
581 result = IsMemberOf ((uid_t) user, g);
584 #ifdef HAVE_GETGRNAM_R
587 g_free (utf8_groupname);
589 #endif /* PLATFORM_WIN32 */
595 /* Mono.Security.Cryptography IO related internal calls */
597 #ifdef PLATFORM_WIN32
600 GetAdministratorsSid (void)
602 SID_IDENTIFIER_AUTHORITY admins = SECURITY_NT_AUTHORITY;
604 if (!AllocateAndInitializeSid (&admins, 2, SECURITY_BUILTIN_DOMAIN_RID,
605 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pSid))
607 /* Note: this SID must be freed with FreeSid () */
613 GetEveryoneSid (void)
615 SID_IDENTIFIER_AUTHORITY everyone = SECURITY_WORLD_SID_AUTHORITY;
617 if (!AllocateAndInitializeSid (&everyone, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pSid))
619 /* Note: this SID must be freed with FreeSid () */
625 GetCurrentUserSid (void)
629 gpointer token = ves_icall_System_Security_Principal_WindowsIdentity_GetCurrentToken ();
631 GetTokenInformation (token, TokenUser, NULL, size, (PDWORD)&size);
633 TOKEN_USER *tu = g_malloc0 (size);
634 if (GetTokenInformation (token, TokenUser, tu, size, (PDWORD)&size)) {
635 DWORD length = GetLengthSid (tu->User.Sid);
636 sid = (PSID) g_malloc0 (length);
637 if (!CopySid (length, sid, tu->User.Sid)) {
644 /* Note: this SID must be freed with g_free () */
650 GetRightsFromSid (PSID sid, PACL acl)
652 ACCESS_MASK rights = 0;
655 BuildTrusteeWithSidW (&trustee, sid);
656 if (GetEffectiveRightsFromAcl (acl, &trustee, &rights) != ERROR_SUCCESS)
664 IsMachineProtected (gunichar2 *path)
666 gboolean success = FALSE;
668 PSID pEveryoneSid = NULL;
670 DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, NULL);
671 if (dwRes != ERROR_SUCCESS)
674 /* We check that Everyone is still limited to READ-ONLY -
675 but not if new entries have been added by an Administrator */
677 pEveryoneSid = GetEveryoneSid ();
679 ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
680 /* http://msdn.microsoft.com/library/en-us/security/security/generic_access_rights.asp?frame=true */
681 success = (rights == (READ_CONTROL | SYNCHRONIZE | FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES));
682 FreeSid (pEveryoneSid);
684 /* Note: we don't need to check our own access -
685 we'll know soon enough when reading the file */
695 IsUserProtected (gunichar2 *path)
697 gboolean success = FALSE;
699 PSID pEveryoneSid = NULL;
701 DWORD dwRes = GetNamedSecurityInfoW (path, SE_FILE_OBJECT,
702 DACL_SECURITY_INFORMATION, NULL, NULL, &pDACL, NULL, NULL);
703 if (dwRes != ERROR_SUCCESS)
706 /* We check that our original entries in the ACL are in place -
707 but not if new entries have been added by the user */
709 /* Everyone should be denied */
710 pEveryoneSid = GetEveryoneSid ();
712 ACCESS_MASK rights = GetRightsFromSid (pEveryoneSid, pDACL);
713 success = (rights == 0);
714 FreeSid (pEveryoneSid);
716 /* Note: we don't need to check our own access -
717 we'll know soon enough when reading the file */
727 ProtectMachine (gunichar2 *path)
729 PSID pEveryoneSid = GetEveryoneSid ();
730 PSID pAdminsSid = GetAdministratorsSid ();
733 if (pEveryoneSid && pAdminsSid) {
735 EXPLICIT_ACCESS ea [2];
736 ZeroMemory (&ea, 2 * sizeof (EXPLICIT_ACCESS));
738 /* grant all access to the BUILTIN\Administrators group */
739 BuildTrusteeWithSidW (&ea [0].Trustee, pAdminsSid);
740 ea [0].grfAccessPermissions = GENERIC_ALL;
741 ea [0].grfAccessMode = SET_ACCESS;
742 ea [0].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
743 ea [0].Trustee.TrusteeForm = TRUSTEE_IS_SID;
744 ea [0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
746 /* read-only access everyone */
747 BuildTrusteeWithSidW (&ea [1].Trustee, pEveryoneSid);
748 ea [1].grfAccessPermissions = GENERIC_READ;
749 ea [1].grfAccessMode = SET_ACCESS;
750 ea [1].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
751 ea [1].Trustee.TrusteeForm = TRUSTEE_IS_SID;
752 ea [1].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
754 retval = SetEntriesInAcl (2, ea, NULL, &pDACL);
755 if (retval == ERROR_SUCCESS) {
756 /* with PROTECTED_DACL_SECURITY_INFORMATION we */
757 /* remove any existing ACL (like inherited ones) */
758 retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT,
759 DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
760 NULL, NULL, pDACL, NULL);
767 FreeSid (pEveryoneSid);
769 FreeSid (pAdminsSid);
770 return (retval == ERROR_SUCCESS);
775 ProtectUser (gunichar2 *path)
779 PSID pCurrentSid = GetCurrentUserSid ();
783 ZeroMemory (&ea, sizeof (EXPLICIT_ACCESS));
785 /* grant exclusive access to the current user */
786 BuildTrusteeWithSidW (&ea.Trustee, pCurrentSid);
787 ea.grfAccessPermissions = GENERIC_ALL;
788 ea.grfAccessMode = SET_ACCESS;
789 ea.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT;
790 ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
791 ea.Trustee.TrusteeType = TRUSTEE_IS_USER;
793 retval = SetEntriesInAcl (1, &ea, NULL, &pDACL);
794 if (retval == ERROR_SUCCESS) {
795 /* with PROTECTED_DACL_SECURITY_INFORMATION we
796 remove any existing ACL (like inherited ones) */
797 retval = SetNamedSecurityInfo (path, SE_FILE_OBJECT,
798 DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
799 NULL, NULL, pDACL, NULL);
804 g_free (pCurrentSid); /* g_malloc0 */
807 return (retval == ERROR_SUCCESS);
813 IsProtected (MonoString *path, gint32 protection)
815 gboolean result = FALSE;
816 gchar *utf8_name = mono_unicode_to_external (mono_string_chars (path));
819 if (stat (utf8_name, &st) == 0) {
820 result = (((st.st_mode & 0777) & protection) == 0);
829 Protect (MonoString *path, gint32 file_mode, gint32 add_dir_mode)
831 gboolean result = FALSE;
832 gchar *utf8_name = mono_unicode_to_external (mono_string_chars (path));
835 if (stat (utf8_name, &st) == 0) {
836 int mode = file_mode;
837 if (st.st_mode & S_IFDIR)
838 mode |= add_dir_mode;
839 result = (chmod (utf8_name, mode) == 0);
846 #endif /* not PLATFORM_WIN32 */
850 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_CanSecure (MonoString *root)
857 /* ACL are nice... unless you have FAT or other uncivilized filesystem */
858 if (!GetVolumeInformation (mono_string_chars (root), NULL, 0, NULL, NULL, (LPDWORD)&flags, NULL, 0))
860 return ((flags & FS_PERSISTENT_ACLS) == FS_PERSISTENT_ACLS);
863 /* we assume some kind of security is applicable outside Windows */
870 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsMachineProtected (MonoString *path)
872 gboolean ret = FALSE;
876 /* no one, but the owner, should have write access to the directory */
877 #ifdef PLATFORM_WIN32
878 ret = IsMachineProtected (mono_string_chars (path));
880 ret = IsProtected (path, (S_IWGRP | S_IWOTH));
887 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_IsUserProtected (MonoString *path)
889 gboolean ret = FALSE;
893 /* no one, but the user, should have access to the directory */
894 #ifdef PLATFORM_WIN32
895 ret = IsUserProtected (mono_string_chars (path));
897 ret = IsProtected (path, (S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH));
904 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectMachine (MonoString *path)
906 gboolean ret = FALSE;
910 /* read/write to owner, read to everyone else */
911 #ifdef PLATFORM_WIN32
912 ret = ProtectMachine (mono_string_chars (path));
914 ret = Protect (path, (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH), (S_IXUSR | S_IXGRP | S_IXOTH));
921 ves_icall_Mono_Security_Cryptography_KeyPairPersistence_ProtectUser (MonoString *path)
923 gboolean ret = FALSE;
927 /* read/write to user, no access to everyone else */
928 #ifdef PLATFORM_WIN32
929 ret = ProtectUser (mono_string_chars (path));
931 ret = Protect (path, (S_IRUSR | S_IWUSR), S_IXUSR);