From f2fb047f17265e7a4762343adeb6b8c06c6ffe52 Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Wed, 14 Oct 2026 10:17:12 -0700 Subject: [PATCH 1/2] Fix shared mutex privliges/permissions/defaults to be secure - Use user-scoped mutexes by default. - Use files located in system-defined user-scoped directories by default (preferring an ephemeral directory when possible) - Disallow symlinks in paths to the backing files. - Don't change permissions for folders, assume they must be correct. --- .../Unix/System.Native/Interop.MkDirAt.cs | 14 + .../Unix/System.Native/Interop.OpenAt.cs | 14 + .../Unix/System.Native/Interop.OpenFlags.cs | 1 + .../Unix/System.Native/Interop.UnlinkAt.cs | 22 + .../System.Private.CoreLib.Shared.projitems | 9 + .../src/System/IO/SharedMemoryManager.Unix.cs | 662 +++++++++++------- .../src/System/Threading/Mutex.Unix.cs | 14 +- .../src/System/Threading/NamedMutex.Unix.cs | 62 +- .../System.Threading/tests/MutexTests.cs | 75 ++ src/native/libs/System.Native/entrypoints.c | 3 + src/native/libs/System.Native/pal_io.c | 77 +- src/native/libs/System.Native/pal_io.h | 27 + 12 files changed, 698 insertions(+), 282 deletions(-) create mode 100644 src/libraries/Common/src/Interop/Unix/System.Native/Interop.MkDirAt.cs create mode 100644 src/libraries/Common/src/Interop/Unix/System.Native/Interop.OpenAt.cs create mode 100644 src/libraries/Common/src/Interop/Unix/System.Native/Interop.UnlinkAt.cs diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.MkDirAt.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.MkDirAt.cs new file mode 100644 index 00000000000000..2ba471d05f4ab7 --- /dev/null +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.MkDirAt.cs @@ -0,0 +1,14 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; + +internal static partial class Interop +{ + internal static partial class Sys + { + [LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_MkDirAt", StringMarshalling = StringMarshalling.Utf8, SetLastError = true)] + internal static partial int MkDirAt(SafeFileHandle directoryHandle, string path, int mode); + } +} diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.OpenAt.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.OpenAt.cs new file mode 100644 index 00000000000000..18f7676e56e21c --- /dev/null +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.OpenAt.cs @@ -0,0 +1,14 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; + +internal static partial class Interop +{ + internal static partial class Sys + { + [LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_OpenAt", StringMarshalling = StringMarshalling.Utf8, SetLastError = true)] + internal static partial SafeFileHandle OpenAt(SafeFileHandle directoryHandle, string path, OpenFlags flags, int mode); + } +} diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.OpenFlags.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.OpenFlags.cs index 7ab07052048f8b..6c5fa331c599e8 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.OpenFlags.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.OpenFlags.cs @@ -22,6 +22,7 @@ internal enum OpenFlags O_TRUNC = 0x0080, O_SYNC = 0x0100, O_NOFOLLOW = 0x0200, + O_DIRECTORY = 0x1000, } } } diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.UnlinkAt.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.UnlinkAt.cs new file mode 100644 index 00000000000000..59da84dc6dcf77 --- /dev/null +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.UnlinkAt.cs @@ -0,0 +1,22 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; + +internal static partial class Interop +{ + internal static partial class Sys + { + [Flags] + internal enum UnlinkAtFlags + { + None = 0, + AT_REMOVEDIR = 0x0001, + } + + [LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_UnlinkAt", StringMarshalling = StringMarshalling.Utf8, SetLastError = true)] + internal static partial int UnlinkAt(SafeFileHandle directoryHandle, string path, UnlinkAtFlags flags); + } +} diff --git a/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems b/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems index 6e7e622b64a2c8..f8df57d09d821a 100644 --- a/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems +++ b/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems @@ -2573,6 +2573,9 @@ Common\Interop\Unix\System.Native\Interop.MkDir.cs + + Common\Interop\Unix\System.Native\Interop.MkDirAt.cs + Common\Interop\Unix\System.Native\Interop.MkdTemp.cs @@ -2593,6 +2596,9 @@ Common\Interop\Unix\System.Native\Interop.Open.cs + + Common\Interop\Unix\System.Native\Interop.OpenAt.cs + Common\Interop\Unix\System.Native\Interop.OpenFlags.cs @@ -2668,6 +2674,9 @@ Common\Interop\Unix\System.Native\Interop.Unlink.cs + + Common\Interop\Unix\System.Native\Interop.UnlinkAt.cs + Common\Interop\Unix\System.Native\Interop.UTimensat.cs diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/SharedMemoryManager.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/IO/SharedMemoryManager.Unix.cs index d5c94c045da2b8..3b2a9095ad8c32 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/SharedMemoryManager.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/SharedMemoryManager.Unix.cs @@ -13,16 +13,6 @@ namespace System.IO { internal readonly unsafe struct SharedMemoryId { - private const string UserUnscopedRuntimeTempDirectoryName = ".dotnet"; - - private const string UserScopedRuntimeTempDirectoryName = ".dotnet-uid"; - - private const string SharedMemoryGlobalDirectoryName = "global"; - - private const string SharedMemorySessionDirectoryName = "session"; - - private static int SessionId { get; } = Interop.Sys.GetSid(Environment.ProcessId); - public SharedMemoryId(string name, bool isUserScope) { if (name.StartsWith("Global\\", StringComparison.Ordinal)) @@ -54,30 +44,6 @@ public SharedMemoryId(string name, bool isUserScope) public bool IsSessionScope { get; } public bool IsUserScope { get; } public uint Uid { get; } - - internal readonly string GetRuntimeTempDirectoryName() - { - if (IsUserScope) - { - return $"{UserScopedRuntimeTempDirectoryName}{Uid}"; - } - else - { - return UserUnscopedRuntimeTempDirectoryName; - } - } - - internal readonly string GetSessionDirectoryName() - { - if (IsSessionScope) - { - return $"{SharedMemorySessionDirectoryName}{SessionId}"; - } - else - { - return SharedMemoryGlobalDirectoryName; - } - } } internal enum SharedMemoryType : byte @@ -153,9 +119,11 @@ public SharedMemoryProcessDataHeader(SharedMemoryId id, SafeFileHandle fileHandl bool createIfNotExist, bool acquireLockIfCreated, out bool created, - out AutoReleaseFileLock creationDeletionLockFileHandle) + out AutoReleaseFileLock creationDeletionLockFileHandle, + out SafeFileHandle runtimeDirectoryHandle) { created = false; + runtimeDirectoryHandle = new SafeFileHandle(); // If we don't create the shared memory file, the caller won't need to hold the creation/deletion lock file handle. // Return a placeholder to simplify the caller's logic and allow them to always dispose of the handle @@ -175,24 +143,37 @@ public SharedMemoryProcessDataHeader(SharedMemoryId id, SafeFileHandle fileHandl return processDataHeader; } - using AutoReleaseFileLock creationDeletionLock = SharedMemoryManager.Instance.AcquireCreationDeletionLockForId(id); - - string sessionDirectory = Path.Combine( - SharedMemoryHelpers.SharedFilesPath, - id.GetRuntimeTempDirectoryName(), - SharedMemoryManager.SharedMemorySharedMemoryDirectoryName, - id.GetSessionDirectoryName() - ); + using AutoReleaseFileLock creationDeletionLock = + SharedMemoryManager.Instance.AcquireCreationDeletionLockForId(id, out runtimeDirectoryHandle); + + string sessionDirectoryName = SharedMemoryHelpers.GetSessionDirectoryName(id); + string sessionDirectoryPath = Path.Combine( + SharedMemoryHelpers.GetSharedFilesSystemPath(id), + SharedMemoryHelpers.GetRuntimeDirectoryName(id), + SharedMemoryHelpers.SharedMemorySharedMemoryDirectoryName, + sessionDirectoryName); + using SafeFileHandle sessionDirectoryHandle = SharedMemoryHelpers.EnsureDirectoryExists( + creationDeletionLock.FileHandle, + sessionDirectoryName, + sessionDirectoryPath, + id, + createIfNotExist); - if (!SharedMemoryHelpers.EnsureDirectoryExists(sessionDirectory, id, isGlobalLockAcquired: true, createIfNotExist)) + if (sessionDirectoryHandle.IsInvalid) { Debug.Assert(!createIfNotExist); return null; } - string sharedMemoryFilePath = Path.Combine(sessionDirectory, id.Name); + string sharedMemoryFilePath = Path.Combine(sessionDirectoryPath, id.Name); - SafeFileHandle fileHandle = SharedMemoryHelpers.CreateOrOpenFile(sharedMemoryFilePath, id, createIfNotExist, out bool createdFile); + SafeFileHandle fileHandle = SharedMemoryHelpers.CreateOrOpenFile( + sessionDirectoryHandle, + id.Name, + sharedMemoryFilePath, + id, + createIfNotExist, + out bool createdFile); if (fileHandle.IsInvalid) { return null; @@ -331,7 +312,8 @@ private void Close() SharedMemoryManager.Instance.VerifyCreationDeletionProcessLockIsLocked(); SharedMemoryManager.Instance.RemoveProcessDataHeader(this); - using AutoReleaseFileLock autoReleaseFileLock = SharedMemoryManager.Instance.AcquireCreationDeletionLockForId(_id); + using AutoReleaseFileLock autoReleaseFileLock = + SharedMemoryManager.Instance.AcquireCreationDeletionLockForId(_id, out _); bool releaseSharedData = false; @@ -357,20 +339,31 @@ private void Close() if (releaseSharedData) { - string sessionDirectoryPath = Path.Combine( - SharedMemoryHelpers.SharedFilesPath, - _id.GetRuntimeTempDirectoryName(), - SharedMemoryManager.SharedMemorySharedMemoryDirectoryName, - _id.GetSessionDirectoryName() - ); - - string sharedMemoryFilePath = Path.Combine(sessionDirectoryPath, _id.Name); - // Directly call the underlying functions here as this is best-effort. // If we fail to delete, we don't want an exception. - Interop.Sys.Unlink(sharedMemoryFilePath); + string sessionDirectoryName = SharedMemoryHelpers.GetSessionDirectoryName(_id); + string sessionDirectoryPath = Path.Combine( + SharedMemoryHelpers.GetSharedFilesSystemPath(_id), + SharedMemoryHelpers.GetRuntimeDirectoryName(_id), + SharedMemoryHelpers.SharedMemorySharedMemoryDirectoryName, + sessionDirectoryName); + using (SafeFileHandle sessionDirectoryHandle = SharedMemoryHelpers.EnsureDirectoryExists( + autoReleaseFileLock.FileHandle, + sessionDirectoryName, + sessionDirectoryPath, + _id, + createIfNotExist: false)) + { + if (!sessionDirectoryHandle.IsInvalid) + { + Interop.Sys.UnlinkAt(sessionDirectoryHandle, _id.Name, Interop.Sys.UnlinkAtFlags.None); + } + } - Interop.Sys.RmDir(sessionDirectoryPath); + Interop.Sys.UnlinkAt( + autoReleaseFileLock.FileHandle, + sessionDirectoryName, + Interop.Sys.UnlinkAtFlags.AT_REMOVEDIR); } } } @@ -386,44 +379,211 @@ internal static class SharedMemoryHelpers private const int TransientRetryCount = 10; + internal const string SharedMemorySharedMemoryDirectoryName = "shm"; + + private const string RuntimeTempDirectoryName = ".dotnet"; + + private const string UserRuntimeTempDirectoryName = ".dotnet-uid"; + + private const string SharedMemoryGlobalDirectoryName = "global"; + + private const string SharedMemorySessionDirectoryName = "session"; + // See https://developer.apple.com/documentation/Foundation/FileManager/containerURL(forSecurityApplicationGroupIdentifier:)#App-Groups-in-macOS for details on this path. - private const string ApplicationContainerBasePathSuffix = "/Library/Group Containers/"; + private const string ApplicationContainerBasePathSuffix = "Library/Group Containers/"; - public static string SharedFilesPath { get; } = InitalizeSharedFilesPath(); + private static string? ApplicationContainerPath { get; } = + OperatingSystem.IsApplePlatform() ? GetApplicationContainerPath() : null; + + private static string SharedFilesPath { get; } = InitalizeSharedFilesPath(); private static string InitalizeSharedFilesPath() { if (OperatingSystem.IsApplePlatform()) { - string? applicationGroupId = Environment.GetEnvironmentVariable("DOTNET_SHARED_MEMORY_APPLICATION_GROUP_ID"); - if (applicationGroupId is not null) + return ApplicationContainerPath ?? "/tmp/"; + } + + return "/tmp/"; + } + + private static string? GetApplicationContainerPath() + { + string? applicationGroupId = Environment.GetEnvironmentVariable("DOTNET_SANDBOX_APPLICATION_GROUP_ID"); + if (!string.IsNullOrEmpty(applicationGroupId)) + { + string sharedFilesPath = Path.Combine( + PersistedFiles.GetHomeDirectoryFromPasswd(), + ApplicationContainerBasePathSuffix, + applicationGroupId + ); + + if (File.Exists(sharedFilesPath)) { - string sharedFilesPath = Path.Combine( - PersistedFiles.GetHomeDirectoryFromPasswd(), - ApplicationContainerBasePathSuffix, - applicationGroupId - ); + // If the path exists and is a file, throw an exception. + // If it's a directory, or does not exist, callers can correctly handle it. + throw new DirectoryNotFoundException(); + } + + return sharedFilesPath; + } + return null; + } + + private static string UserSpecificSharedFilesPath { get; } = InitalizeUserSpecificSharedFilesPath(); - if (File.Exists(sharedFilesPath)) + private static string InitalizeUserSpecificSharedFilesPath() + { + if (OperatingSystem.IsApplePlatform()) + { + // On apple platforms, TMPDIR points to the user-specific temporary directory. + // For compat, we will still check the application container path first as that path + // is also user-specific. + string? path = ApplicationContainerPath ?? Environment.GetEnvironmentVariable("TMPDIR"); + if (path is not null) + { + if (ApplicationContainerPath is not null) { - // If the path exists and is a file, throw an exception. - // If it's a directory, or does not exist, callers can correctly handle it. - throw new DirectoryNotFoundException(); + // An Apple application-group container is already user-specific, so both global-scoped and + // user-scoped mutexes would otherwise use the same .dotnet directory and conflict. Give + // user-scoped mutexes a parallel directory to preserve the distinction between the scopes. +#pragma warning disable CA1416 // Validate platform compatibility. This file is only included on Unix platforms. + // The application-group container is owned by the current user, so this directory can be + // created directly without validating each component. + Directory.CreateDirectory( + Path.Combine(ApplicationContainerPath, UserRuntimeTempDirectoryName), + PermissionsMask_OwnerUser_ReadWriteExecute); +#pragma warning restore CA1416 // Validate platform compatibility } - return sharedFilesPath; + return path; + } + } + else if (OperatingSystem.IsLinux()) + { + // XDG_RUNTIME_DIR is the user-specific, cleared on reboot, runtime files directory for systems + // that follow the XDG Base Directory Specification + // https://specifications.freedesktop.org/basedir + // For Linux platforms that follow the XDG specification, we will use it. + string? xdgRuntimeDir = Environment.GetEnvironmentVariable("XDG_RUNTIME_DIR"); + if (!string.IsNullOrEmpty(xdgRuntimeDir)) + { + return xdgRuntimeDir; } } - return "/tmp/"; + // Fallback to storing data in the home directory. + // The home directory is expected to be owned by the user and only accessible by the user. + // If it is not, then that was a choice by the user. + string userFeatureDirectory = PersistedFiles.GetUserFeatureDirectory("Runtime", "SharedMemory"); + +#pragma warning disable CA1416 // Validate platform compatibility. This file is only included on Unix platforms. + // This is not a system-created directory, so we need to guarantee that it exists. + // Default permissions are fine as we are under the user's home directory. + Directory.CreateDirectory(userFeatureDirectory, PermissionsMask_OwnerUser_ReadWriteExecute); + + return userFeatureDirectory; +#pragma warning restore CA1416 // Validate platform compatibility + } + + public static SafeFileHandle OpenSharedFilesSystemDirectory(SharedMemoryId id) + { + string directoryPath = GetSharedFilesSystemPath(id); + int transientRetryCount = 0; + + while (true) + { + SafeFileHandle directoryHandle = Interop.Sys.Open( + directoryPath, + Interop.Sys.OpenFlags.O_RDONLY | Interop.Sys.OpenFlags.O_CLOEXEC | Interop.Sys.OpenFlags.O_NOFOLLOW | Interop.Sys.OpenFlags.O_DIRECTORY, + 0); + + if (!directoryHandle.IsInvalid) + { + if (Interop.Sys.FStat(directoryHandle, out Interop.Sys.FileStatus fileStatus) != 0) + { + Interop.ErrorInfo fstatError = Interop.Sys.GetLastErrorInfo(); + directoryHandle.Dispose(); + if ((fstatError.Error == Interop.Error.ENOENT || fstatError.Error == Interop.Error.EACCES) && + RetryOnTransientPermissionFailure(ref transientRetryCount)) + { + continue; + } + + throw Interop.GetExceptionForIoErrno(fstatError, directoryPath); + } + + // For system directories (such as TEMP_DIRECTORY_PATH), require sufficient permissions only for the + // owner user. For instance, "docker run --mount ..." to mount /tmp to some directory on the host mounts the + // destination directory with the same permissions as the source directory, which may not include some permissions for + // other users. In the docker container, other user permissions are typically not relevant and relaxing the permissions + // requirement allows for that scenario to work without having to work around it by first giving sufficient permissions + // for all users. + // + // If the directory is being used for user-scoped shared memory data, also ensure that either it has the sticky bit or + // it's owned by the current user and without write access for other users. + if ((fileStatus.Mode & (int)PermissionsMask_OwnerUser_ReadWriteExecute) == (int)PermissionsMask_OwnerUser_ReadWriteExecute + && ( + !id.IsUserScope || + (fileStatus.Mode & (int)PermissionsMask_Sticky) == (int)PermissionsMask_Sticky || + (fileStatus.Uid == id.Uid && (fileStatus.Mode & (int)PermissionsMask_NonOwnerUsers_Write) == 0) + )) + { + return directoryHandle; + } + + directoryHandle.Dispose(); + if (RetryOnTransientPermissionFailure(ref transientRetryCount)) + { + continue; + } + + throw new IOException(SR.Format(SR.IO_SharedMemory_DirectoryPermissionsIncorrect, directoryPath, fileStatus.Uid, Convert.ToString(fileStatus.Mode, 8))); + } + + Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo(); + directoryHandle.Dispose(); + if ((error.Error == Interop.Error.ENOENT || error.Error == Interop.Error.EACCES) && + RetryOnTransientPermissionFailure(ref transientRetryCount)) + { + continue; + } + + throw Interop.GetExceptionForIoErrno(error, directoryPath); + } + } + + internal static string GetSharedFilesSystemPath(SharedMemoryId id) + { + return id.IsUserScope ? UserSpecificSharedFilesPath : SharedFilesPath; } - internal static SafeFileHandle CreateOrOpenFile(string sharedMemoryFilePath, SharedMemoryId id, bool createIfNotExist, out bool createdFile) + internal static string GetRuntimeDirectoryName(SharedMemoryId id) + { + return id.IsUserScope && ApplicationContainerPath is not null + ? UserRuntimeTempDirectoryName + : RuntimeTempDirectoryName; + } + + private static int SessionId { get; } = Interop.Sys.GetSid(Environment.ProcessId); + + public static string GetSessionDirectoryName(SharedMemoryId id) + { + return id.IsSessionScope ? $"{SharedMemorySessionDirectoryName}{SessionId}" : SharedMemoryGlobalDirectoryName; + } + + internal static SafeFileHandle CreateOrOpenFile( + SafeFileHandle directoryHandle, + string fileName, + string filePathForError, + SharedMemoryId id, + bool createIfNotExist, + out bool createdFile) { int transientRetryCount = 0; while (true) { - SafeFileHandle fd = Interop.Sys.Open(sharedMemoryFilePath, Interop.Sys.OpenFlags.O_RDWR | Interop.Sys.OpenFlags.O_CLOEXEC, 0); + SafeFileHandle fd = Interop.Sys.OpenAt(directoryHandle, fileName, Interop.Sys.OpenFlags.O_RDWR | Interop.Sys.OpenFlags.O_NOFOLLOW | Interop.Sys.OpenFlags.O_CLOEXEC, 0); Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo(); if (!fd.IsInvalid) { @@ -433,13 +593,13 @@ internal static SafeFileHandle CreateOrOpenFile(string sharedMemoryFilePath, Sha { error = Interop.Sys.GetLastErrorInfo(); fd.Dispose(); - throw Interop.GetExceptionForIoErrno(error, sharedMemoryFilePath); + throw Interop.GetExceptionForIoErrno(error, filePathForError); } if (fileStatus.Uid != id.Uid) { fd.Dispose(); - throw new IOException(SR.Format(SR.IO_SharedMemory_FileNotOwnedByUid, sharedMemoryFilePath, id.Uid)); + throw new IOException(SR.Format(SR.IO_SharedMemory_FileNotOwnedByUid, filePathForError, id.Uid)); } if ((fileStatus.Mode & (int)PermissionsMask_AllUsers_ReadWriteExecute) != (int)PermissionsMask_OwnerUser_ReadWrite) @@ -455,7 +615,7 @@ internal static SafeFileHandle CreateOrOpenFile(string sharedMemoryFilePath, Sha continue; } - throw new IOException(SR.Format(SR.IO_SharedMemory_FilePermissionsIncorrect, sharedMemoryFilePath, PermissionsMask_OwnerUser_ReadWrite)); + throw new IOException(SR.Format(SR.IO_SharedMemory_FilePermissionsIncorrect, filePathForError, PermissionsMask_OwnerUser_ReadWrite)); } } createdFile = false; @@ -473,7 +633,7 @@ internal static SafeFileHandle CreateOrOpenFile(string sharedMemoryFilePath, Sha if (error.Error != Interop.Error.ENOENT) { - throw Interop.GetExceptionForIoErrno(error, sharedMemoryFilePath); + throw Interop.GetExceptionForIoErrno(error, filePathForError); } if (!createIfNotExist) @@ -488,9 +648,10 @@ internal static SafeFileHandle CreateOrOpenFile(string sharedMemoryFilePath, Sha ? PermissionsMask_OwnerUser_ReadWrite : PermissionsMask_AllUsers_ReadWrite; - fd = Interop.Sys.Open( - sharedMemoryFilePath, - Interop.Sys.OpenFlags.O_RDWR | Interop.Sys.OpenFlags.O_CLOEXEC | Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL, + fd = Interop.Sys.OpenAt( + directoryHandle, + fileName, + Interop.Sys.OpenFlags.O_RDWR | Interop.Sys.OpenFlags.O_NOFOLLOW | Interop.Sys.OpenFlags.O_CLOEXEC | Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL, (int)permissionsMask); if (fd.IsInvalid) @@ -504,7 +665,7 @@ internal static SafeFileHandle CreateOrOpenFile(string sharedMemoryFilePath, Sha transientRetryCount++; continue; } - throw Interop.GetExceptionForIoErrno(error, sharedMemoryFilePath); + throw Interop.GetExceptionForIoErrno(error, filePathForError); } // The mode passed to open(..., O_CREAT|O_EXCL, permissionsMask) is filtered by process umask, so the @@ -515,8 +676,8 @@ internal static SafeFileHandle CreateOrOpenFile(string sharedMemoryFilePath, Sha { error = Interop.Sys.GetLastErrorInfo(); fd.Dispose(); - Interop.Sys.Unlink(sharedMemoryFilePath); - throw Interop.GetExceptionForIoErrno(error, sharedMemoryFilePath); + Interop.Sys.UnlinkAt(directoryHandle, fileName, Interop.Sys.UnlinkAtFlags.None); + throw Interop.GetExceptionForIoErrno(error, filePathForError); } createdFile = true; @@ -524,7 +685,12 @@ internal static SafeFileHandle CreateOrOpenFile(string sharedMemoryFilePath, Sha } } - internal static bool EnsureDirectoryExists(string directoryPath, SharedMemoryId id, bool isGlobalLockAcquired, bool createIfNotExist = true, bool isSystemDirectory = false) + internal static SafeFileHandle EnsureDirectoryExists( + SafeFileHandle parentDirectoryHandle, + string directoryName, + string directoryPathForError, + SharedMemoryId id, + bool createIfNotExist = true) { int transientRetryCount = 0; while (true) @@ -533,177 +699,164 @@ internal static bool EnsureDirectoryExists(string directoryPath, SharedMemoryId ? PermissionsMask_OwnerUser_ReadWriteExecute : PermissionsMask_AllUsers_ReadWriteExecute; - int statResult = Interop.Sys.Stat(directoryPath, out Interop.Sys.FileStatus fileStatus); + SafeFileHandle directoryHandle = Interop.Sys.OpenAt( + parentDirectoryHandle, + directoryName, + Interop.Sys.OpenFlags.O_RDONLY | Interop.Sys.OpenFlags.O_CLOEXEC | Interop.Sys.OpenFlags.O_NOFOLLOW | Interop.Sys.OpenFlags.O_DIRECTORY, + 0); - if (statResult != 0 && Interop.Sys.GetLastError() == Interop.Error.ENOENT) + if (directoryHandle.IsInvalid) { - if (!createIfNotExist) - { - // The directory does not exist and we are not allowed to create it. - return false; - } + Interop.ErrorInfo openError = Interop.Sys.GetLastErrorInfo(); + directoryHandle.Dispose(); - // The path does not exist, create the directory. The permissions mask passed to mkdir() is filtered by the process' - // permissions umask, so mkdir() may not set all of the requested permissions. We need to use chmod() to set the proper - // permissions. That creates a race when there is no global lock acquired when creating the directory. Another user's - // process may create the directory and this user's process may try to use it before the other process sets the full - // permissions. The validation below tolerates that transient state while using mkdir() on the final path avoids - // rename() replacing an existing empty directory that another process may already be locking. - - if (isGlobalLockAcquired) + if (openError.Error == Interop.Error.ENOENT) { -#pragma warning disable CA1416 // Validate platform compatibility. This file is only included on Unix platforms. - Directory.CreateDirectory(directoryPath, permissionsMask); -#pragma warning restore CA1416 // Validate platform compatibility - - try + if (!createIfNotExist) { - FileSystem.SetUnixFileMode(directoryPath, permissionsMask); + // The directory does not exist and we are not allowed to create it. + return new SafeFileHandle(); } - catch + + if (Interop.Sys.MkDirAt(parentDirectoryHandle, directoryName, (int)permissionsMask) == 0) { - try { Directory.Delete(directoryPath); } catch { } - throw; - } + directoryHandle = Interop.Sys.OpenAt( + parentDirectoryHandle, + directoryName, + Interop.Sys.OpenFlags.O_RDONLY | Interop.Sys.OpenFlags.O_CLOEXEC | Interop.Sys.OpenFlags.O_NOFOLLOW | Interop.Sys.OpenFlags.O_DIRECTORY, + 0); - return true; - } + if (directoryHandle.IsInvalid) + { + Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo(); + directoryHandle.Dispose(); + Interop.Sys.UnlinkAt(parentDirectoryHandle, directoryName, Interop.Sys.UnlinkAtFlags.AT_REMOVEDIR); + throw Interop.GetExceptionForIoErrno(error, directoryPathForError); + } - if (Interop.Sys.MkDir(directoryPath, (int)permissionsMask) == 0) - { - try + if (Interop.Sys.FChMod(directoryHandle, (int)permissionsMask) != 0) + { + Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo(); + directoryHandle.Dispose(); + Interop.Sys.UnlinkAt(parentDirectoryHandle, directoryName, Interop.Sys.UnlinkAtFlags.AT_REMOVEDIR); + throw Interop.GetExceptionForIoErrno(error, directoryPathForError); + } + + return directoryHandle; + } + + Interop.ErrorInfo mkdirError = Interop.Sys.GetLastErrorInfo(); + if (mkdirError.Error != Interop.Error.EEXIST) { - FileSystem.SetUnixFileMode(directoryPath, permissionsMask); + throw Interop.GetExceptionForIoErrno(mkdirError, directoryPathForError); } - catch + + if (RetryOnTransientPermissionFailure(ref transientRetryCount)) { - try { Directory.Delete(directoryPath); } catch { } - throw; + // If we have two threads or processes racing to create this directory, + // the first one may have created it but not yet set the correct permissions. + // Retry briefly to let the other process finish setting permissions. + // We will not set permissions when we are not the creator of the directory. + continue; } - return true; + throw Interop.GetExceptionForIoErrno(mkdirError, directoryPathForError); } - Interop.ErrorInfo mkdirError = Interop.Sys.GetLastErrorInfo(); - if (mkdirError.Error != Interop.Error.EEXIST) + if ((openError.Error == Interop.Error.ENOENT || openError.Error == Interop.Error.EACCES) && + RetryOnTransientPermissionFailure(ref transientRetryCount)) { - throw Interop.GetExceptionForIoErrno(mkdirError, directoryPath); + // While another process is creating this path, openat() can temporarily fail with ENOENT before the + // directory appears, or with EACCES before the creating process has finished normalizing directory + // permissions for cross-user access. + continue; } - statResult = Interop.Sys.Stat(directoryPath, out fileStatus); - } - - if (statResult != 0) - { - Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo(); - // While another process is creating this path, stat() can temporarily fail with ENOENT before the - // directory appears, or with EACCES before the creating process has finished normalizing directory - // permissions for cross-user access. - if ((error.Error == Interop.Error.ENOENT || error.Error == Interop.Error.EACCES) && RetryOnTransientPermissionFailure()) + if (openError.Error is Interop.Error.ELOOP or Interop.Error.ENOTDIR) { - continue; + // If the path exists, check that it's a directory. + throw new IOException(SR.Format(SR.IO_SharedMemory_PathExistsButNotDirectory, directoryPathForError)); } - throw Interop.GetExceptionForIoErrno(error, directoryPath); + throw Interop.GetExceptionForIoErrno(openError, directoryPathForError); } - // If the path exists, check that it's a directory - if ((fileStatus.Mode & Interop.Sys.FileTypes.S_IFDIR) == 0) + if (ValidateDirectory(directoryHandle, directoryPathForError, id, ref transientRetryCount)) { - throw new IOException(SR.Format(SR.IO_SharedMemory_PathExistsButNotDirectory, directoryPath)); + return directoryHandle; } - if (isSystemDirectory) - { - // For system directories (such as TEMP_DIRECTORY_PATH), require sufficient permissions only for the - // owner user. For instance, "docker run --mount ..." to mount /tmp to some directory on the host mounts the - // destination directory with the same permissions as the source directory, which may not include some permissions for - // other users. In the docker container, other user permissions are typically not relevant and relaxing the permissions - // requirement allows for that scenario to work without having to work around it by first giving sufficient permissions - // for all users. - // - // If the directory is being used for user-scoped shared memory data, also ensure that either it has the sticky bit or - // it's owned by the current user and without write access for other users. - - permissionsMask = PermissionsMask_OwnerUser_ReadWriteExecute; - if ((fileStatus.Mode & (int)permissionsMask) == (int)permissionsMask - && ( - !id.IsUserScope || - (fileStatus.Mode & (int)PermissionsMask_Sticky) == (int)PermissionsMask_Sticky || - (fileStatus.Uid == id.Uid && (fileStatus.Mode & (int)PermissionsMask_NonOwnerUsers_Write) == 0) - )) - { - return true; - } - - if (RetryOnTransientPermissionFailure()) - { - continue; - } - - throw new IOException(SR.Format(SR.IO_SharedMemory_DirectoryPermissionsIncorrect, directoryPath, fileStatus.Uid, Convert.ToString(fileStatus.Mode, 8))); - } - - // For non-system directories (such as SharedFilesPath/UserUnscopedRuntimeTempDirectoryName), - // require the sufficient permissions and try to update them if requested to create the directory, so that - // shared memory files may be shared according to its scope. + directoryHandle.Dispose(); + } + } - // For user-scoped directories, verify the owner UID - if (id.IsUserScope && fileStatus.Uid != id.Uid) + private static bool ValidateDirectory( + SafeFileHandle directoryHandle, + string directoryPathForError, + SharedMemoryId id, + ref int transientRetryCount) + { + if (Interop.Sys.FStat(directoryHandle, out Interop.Sys.FileStatus fileStatus) != 0) + { + Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo(); + if ((error.Error == Interop.Error.ENOENT || error.Error == Interop.Error.EACCES) && + RetryOnTransientPermissionFailure(ref transientRetryCount)) { - if (RetryOnTransientPermissionFailure()) - { - continue; - } - - throw new IOException(SR.Format(SR.IO_SharedMemory_DirectoryNotOwnedByUid, directoryPath, id.Uid)); + return false; } - // Verify the permissions, or try to change them if possible - if ((fileStatus.Mode & (int)PermissionsMask_AllUsers_ReadWriteExecute) == (int)permissionsMask - || (createIfNotExist && Interop.Sys.ChMod(directoryPath, (int)permissionsMask) == 0)) - { - return true; - } + throw Interop.GetExceptionForIoErrno(error, directoryPathForError); + } - // We were not able to verify or set the necessary permissions. For user-scoped directories, this is treated as a failure - // since other users aren't sufficiently restricted in permissions. - if (id.IsUserScope) - { - if (RetryOnTransientPermissionFailure()) - { - continue; - } + UnixFileMode permissionsMask = id.IsUserScope + ? PermissionsMask_OwnerUser_ReadWriteExecute + : PermissionsMask_AllUsers_ReadWriteExecute; - throw new IOException(SR.Format(SR.IO_SharedMemory_DirectoryPermissionsIncorrectUserScope, directoryPath, Convert.ToString(fileStatus.Mode, 8))); - } + // For non-system directories (such as SharedFilesPath/UserUnscopedRuntimeTempDirectoryName), + // require the sufficient permissions, so that shared memory files may be shared according to its scope. - // For user-unscoped directories, as a last resort, check that at least the owner user has full access. - permissionsMask = PermissionsMask_OwnerUser_ReadWriteExecute; - if ((fileStatus.Mode & (int)permissionsMask) == (int)permissionsMask) + // For user-scoped directories, verify the owner UID. + if (id.IsUserScope && fileStatus.Uid != id.Uid) + { + if (RetryOnTransientPermissionFailure(ref transientRetryCount)) { - return true; + return false; } - if (RetryOnTransientPermissionFailure()) - { - continue; - } + throw new IOException(SR.Format(SR.IO_SharedMemory_DirectoryNotOwnedByUid, directoryPathForError, id.Uid)); + } - throw new IOException(SR.Format(SR.IO_SharedMemory_DirectoryOwnerPermissionsIncorrect, directoryPath, Convert.ToString(fileStatus.Mode, 8))); + // Verify the permissions correct. + if ((fileStatus.Mode & (int)permissionsMask) == (int)permissionsMask) + { + return true; } - bool RetryOnTransientPermissionFailure() + if (RetryOnTransientPermissionFailure(ref transientRetryCount)) { - if (transientRetryCount >= TransientRetryCount) - { - return false; - } + return false; + } - transientRetryCount++; - Thread.Sleep(1); - return true; + // We were not able to verify the necessary permissions. + // Throw an exception with a message that is specific to the scope of the shared memory data. + if (id.IsUserScope) + { + throw new IOException(SR.Format(SR.IO_SharedMemory_DirectoryPermissionsIncorrectUserScope, directoryPathForError, Convert.ToString(fileStatus.Mode, 8))); } + + throw new IOException(SR.Format(SR.IO_SharedMemory_DirectoryOwnerPermissionsIncorrect, directoryPathForError, Convert.ToString(fileStatus.Mode, 8))); + } + + private static bool RetryOnTransientPermissionFailure(ref int transientRetryCount) + { + if (transientRetryCount >= TransientRetryCount) + { + return false; + } + + transientRetryCount++; + Thread.Sleep(1); + return true; } internal static MemoryMappedFileHolder MemoryMapFile(SafeFileHandle fileHandle, nuint sharedDataTotalByteCount) @@ -794,11 +947,10 @@ internal sealed class SharedMemoryManager { internal static SharedMemoryManager Instance { get; } = new SharedMemoryManager(); - internal const string SharedMemorySharedMemoryDirectoryName = "shm"; private readonly LowLevelLock _creationDeletionProcessLock = new(); - private SafeFileHandle? _creationDeletionLockFileHandle; - private readonly Dictionary _uidToFileHandleMap = []; + private (SafeFileHandle RuntimeDirectoryHandle, SafeFileHandle SharedMemoryDirectoryHandle)? _creationDeletionDirectoryHandles; + private readonly Dictionary _uidToDirectoryHandlesMap = []; public WaitSubsystem.LockHolder AcquireCreationDeletionProcessLock() { @@ -815,55 +967,71 @@ public void VerifyCreationDeletionProcessLockIsNotLocked() _creationDeletionProcessLock.VerifyIsNotLocked(); } - public AutoReleaseFileLock AcquireCreationDeletionLockForId(SharedMemoryId id) + public AutoReleaseFileLock AcquireCreationDeletionLockForId( + SharedMemoryId id, + out SafeFileHandle runtimeDirectoryHandle) { _creationDeletionProcessLock.VerifyIsLocked(); - SafeFileHandle? fd = id.IsUserScope ? GetUserScopeCreationDeletionLockFileHandle(id.Uid) : _creationDeletionLockFileHandle; - if (fd is null) + (SafeFileHandle RuntimeDirectoryHandle, SafeFileHandle SharedMemoryDirectoryHandle)? directoryHandles = + id.IsUserScope ? GetUserScopeDirectoryHandles(id.Uid) : _creationDeletionDirectoryHandles; + if (directoryHandles is null) { - if (!SharedMemoryHelpers.EnsureDirectoryExists(SharedMemoryHelpers.SharedFilesPath, id, isGlobalLockAcquired: false, createIfNotExist: false, isSystemDirectory: true)) + using SafeFileHandle systemDirectoryHandle = SharedMemoryHelpers.OpenSharedFilesSystemDirectory(id); + string runtimeDirectoryName = SharedMemoryHelpers.GetRuntimeDirectoryName(id); + string runtimeDirectoryPath = Path.Combine( + SharedMemoryHelpers.GetSharedFilesSystemPath(id), + runtimeDirectoryName); + SafeFileHandle newRuntimeDirectoryHandle = SharedMemoryHelpers.EnsureDirectoryExists( + systemDirectoryHandle, + runtimeDirectoryName, + runtimeDirectoryPath, + id); + + SafeFileHandle sharedMemoryDirectoryHandle; + try { - Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo(); - throw Interop.GetExceptionForIoErrno(error, SharedMemoryHelpers.SharedFilesPath); + sharedMemoryDirectoryHandle = SharedMemoryHelpers.EnsureDirectoryExists( + newRuntimeDirectoryHandle, + SharedMemoryHelpers.SharedMemorySharedMemoryDirectoryName, + Path.Combine(runtimeDirectoryPath, SharedMemoryHelpers.SharedMemorySharedMemoryDirectoryName), + id); } - string runtimeTempDirectory = Path.Combine( - SharedMemoryHelpers.SharedFilesPath, - id.GetRuntimeTempDirectoryName()); - - SharedMemoryHelpers.EnsureDirectoryExists(runtimeTempDirectory, id, isGlobalLockAcquired: false); - - string sharedMemoryDirectory = Path.Combine( - runtimeTempDirectory, - SharedMemorySharedMemoryDirectoryName); - - SharedMemoryHelpers.EnsureDirectoryExists(sharedMemoryDirectory, id, isGlobalLockAcquired: false); - - fd = Interop.Sys.Open(sharedMemoryDirectory, Interop.Sys.OpenFlags.O_RDONLY, 0); - if (fd.IsInvalid) + catch { - Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo(); - fd.Dispose(); - throw Interop.GetExceptionForIoErrno(error, sharedMemoryDirectory); + newRuntimeDirectoryHandle.Dispose(); + throw; } + (SafeFileHandle RuntimeDirectoryHandle, SafeFileHandle SharedMemoryDirectoryHandle) newDirectoryHandles = + (newRuntimeDirectoryHandle, sharedMemoryDirectoryHandle); + directoryHandles = newDirectoryHandles; + if (id.IsUserScope) { - _uidToFileHandleMap.Add(id.Uid, fd); + _uidToDirectoryHandlesMap.Add(id.Uid, newDirectoryHandles); } else { - _creationDeletionLockFileHandle = fd; + _creationDeletionDirectoryHandles = newDirectoryHandles; } } - bool acquired = SharedMemoryHelpers.TryAcquireFileLock(fd, nonBlocking: false, exclusive: true); + (SafeFileHandle RuntimeDirectoryHandle, SafeFileHandle SharedMemoryDirectoryHandle) handles = directoryHandles.Value; + bool acquired = SharedMemoryHelpers.TryAcquireFileLock( + handles.SharedMemoryDirectoryHandle, + nonBlocking: false, + exclusive: true); Debug.Assert(acquired); - return new AutoReleaseFileLock(fd); + runtimeDirectoryHandle = handles.RuntimeDirectoryHandle; + return new AutoReleaseFileLock(handles.SharedMemoryDirectoryHandle); - SafeFileHandle? GetUserScopeCreationDeletionLockFileHandle(uint uid) + (SafeFileHandle RuntimeDirectoryHandle, SafeFileHandle SharedMemoryDirectoryHandle)? GetUserScopeDirectoryHandles(uint uid) { - _uidToFileHandleMap.TryGetValue(uid, out SafeFileHandle? fileHandle); - return fileHandle; + return _uidToDirectoryHandlesMap.TryGetValue( + uid, + out (SafeFileHandle RuntimeDirectoryHandle, SafeFileHandle SharedMemoryDirectoryHandle) handles) + ? handles + : null; } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Mutex.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Mutex.Unix.cs index 9ad25fa61ecf0c..518c563c93e5e2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Mutex.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Mutex.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; @@ -10,6 +11,10 @@ namespace System.Threading { public sealed partial class Mutex { + [FeatureSwitchDefinition("System.Threading.Mutex.UnsafeDefaultMutexScopeGlobal")] + private static bool UnsafeDefaultMutexScopeGlobal { get; } = + AppContext.TryGetSwitch("System.Threading.Mutex.UnsafeDefaultMutexScopeGlobal", out bool enable) ? enable : false; + private void CreateMutexCore(bool initiallyOwned) => SafeWaitHandle = WaitSubsystem.NewMutex(initiallyOwned); private void CreateMutexCore( @@ -22,7 +27,7 @@ private void CreateMutexCore( { name = BuildNameForOptions(name, options); - SafeWaitHandle? safeWaitHandle = WaitSubsystem.CreateNamedMutex(initiallyOwned, name, isUserScope: options.WasSpecified && options.CurrentUserOnly, out createdNew); + SafeWaitHandle? safeWaitHandle = WaitSubsystem.CreateNamedMutex(initiallyOwned, name, isUserScope: CalculateUserScope(options), out createdNew); if (safeWaitHandle == null) { throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); @@ -44,7 +49,7 @@ private static OpenExistingResult OpenExistingWorker( name = BuildNameForOptions(name, options); - OpenExistingResult status = WaitSubsystem.OpenNamedMutex(name, isUserScope: options.WasSpecified && options.CurrentUserOnly, out SafeWaitHandle? safeWaitHandle); + OpenExistingResult status = WaitSubsystem.OpenNamedMutex(name, isUserScope: CalculateUserScope(options), out SafeWaitHandle? safeWaitHandle); result = status == OpenExistingResult.Success ? new Mutex(safeWaitHandle!) : null; return status; } @@ -65,6 +70,11 @@ private static string BuildNameForOptions(string name, NamedWaitHandleOptionsInt return name; } + private static bool CalculateUserScope(NamedWaitHandleOptionsInternal options) + { + return options.WasSpecified ? options.CurrentUserOnly : !UnsafeDefaultMutexScopeGlobal; + } + public void ReleaseMutex() { // The field value is modifiable via the public property, save it locally diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/NamedMutex.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/NamedMutex.Unix.cs index a9cf954041077f..04fcff042e858c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/NamedMutex.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/NamedMutex.Unix.cs @@ -209,7 +209,8 @@ public void Abandon(NamedMutexOwnershipChain chain, Thread abandonedThread) createIfNotExist, acquireLockIfCreated, out created, - out AutoReleaseFileLock creationDeletionLockFileScope); + out AutoReleaseFileLock creationDeletionLockFileScope, + out SafeFileHandle runtimeDirectoryHandle); if (processDataHeader is null) { @@ -231,7 +232,10 @@ public void Abandon(NamedMutexOwnershipChain chain, Thread abandonedThread) } else { - processDataHeader._processData = new NamedMutexProcessDataNoPThreads(processDataHeader, created); + processDataHeader._processData = new NamedMutexProcessDataNoPThreads( + processDataHeader, + runtimeDirectoryHandle, + created); } if (created && acquireLockIfCreated) @@ -419,34 +423,46 @@ public override void Close(bool releaseSharedData) internal sealed unsafe class NamedMutexProcessDataNoPThreads : NamedMutexProcessDataBase { private const string SharedMemoryLockFilesDirectoryName = "lockfiles"; + private readonly Mutex _processLevelMutex = new Mutex(initiallyOwned: false); private readonly SafeFileHandle _sharedLockFileHandle; private readonly SharedData* _sharedData; - public NamedMutexProcessDataNoPThreads(SharedMemoryProcessDataHeader processDataHeader, bool created) : base(processDataHeader) + public NamedMutexProcessDataNoPThreads( + SharedMemoryProcessDataHeader processDataHeader, + SafeFileHandle runtimeDirectoryHandle, + bool created) : base(processDataHeader) { _sharedData = (SharedData*)SharedMemoryProcessDataHeader.GetDataPointer(processDataHeader); - string lockFileDirectory = Path.Combine( - SharedMemoryHelpers.SharedFilesPath, - Id.GetRuntimeTempDirectoryName(), - SharedMemoryLockFilesDirectoryName - ); - - if (created) - { - SharedMemoryHelpers.EnsureDirectoryExists(lockFileDirectory, Id, isGlobalLockAcquired: true); - } - - string sessionDirectory = Path.Combine(lockFileDirectory, Id.GetSessionDirectoryName()); - - if (created) - { - SharedMemoryHelpers.EnsureDirectoryExists(sessionDirectory, Id, isGlobalLockAcquired: true); - } - - string lockFilePath = Path.Combine(sessionDirectory, Id.Name); - _sharedLockFileHandle = SharedMemoryHelpers.CreateOrOpenFile(lockFilePath, Id, created, out _); + string lockFilesDirectoryPath = Path.Combine( + SharedMemoryHelpers.GetSharedFilesSystemPath(Id), + SharedMemoryHelpers.GetRuntimeDirectoryName(Id), + SharedMemoryLockFilesDirectoryName); + using SafeFileHandle lockFilesDirectoryHandle = SharedMemoryHelpers.EnsureDirectoryExists( + runtimeDirectoryHandle, + SharedMemoryLockFilesDirectoryName, + lockFilesDirectoryPath, + Id, + created); + + string sessionDirectoryName = SharedMemoryHelpers.GetSessionDirectoryName(Id); + using SafeFileHandle sessionDirectoryHandle = lockFilesDirectoryHandle.IsInvalid + ? new SafeFileHandle() + : SharedMemoryHelpers.EnsureDirectoryExists( + lockFilesDirectoryHandle, + sessionDirectoryName, + Path.Combine(lockFilesDirectoryPath, sessionDirectoryName), + Id, + created); + + _sharedLockFileHandle = SharedMemoryHelpers.CreateOrOpenFile( + sessionDirectoryHandle, + Id.Name, + Path.Combine(lockFilesDirectoryPath, sessionDirectoryName, Id.Name), + Id, + created, + out _); } protected override bool IsLockOwnedByThreadInThisProcess(Thread thread) diff --git a/src/libraries/System.Threading/tests/MutexTests.cs b/src/libraries/System.Threading/tests/MutexTests.cs index b96dd1ad763827..d78281ad997dcc 100644 --- a/src/libraries/System.Threading/tests/MutexTests.cs +++ b/src/libraries/System.Threading/tests/MutexTests.cs @@ -1095,6 +1095,81 @@ public void NamedMutex_OtherEvent_NotCompatible() | UnixFileMode.OtherRead | UnixFileMode.OtherWrite | UnixFileMode.OtherExecute; + private const UnixFileMode OwnerUserRwx = + UnixFileMode.UserRead + | UnixFileMode.UserWrite + | UnixFileMode.UserExecute; + + [ConditionalFact(nameof(IsRemoteExecutorAndCrossProcessNamedMutexSupported))] + [PlatformSpecific(TestPlatforms.Linux)] + [UnsupportedOSPlatform("windows")] + public void NamedMutex_UserScopedSharedMemoryFallbackPathIsCreated() + { + string homeDirectory = GetTestFilePath(); + Directory.CreateDirectory(homeDirectory); + + RemoteInvokeOptions remoteInvokeOptions = new(); + remoteInvokeOptions.StartInfo.EnvironmentVariables["HOME"] = homeDirectory; + remoteInvokeOptions.StartInfo.EnvironmentVariables["XDG_RUNTIME_DIR"] = string.Empty; + + RemoteExecutor.Invoke( + homeDirectory => + { + string sharedMemoryBaseDirectory = Path.Combine( + homeDirectory, + ".dotnet", + "corefx", + "Runtime", + "SharedMemory"); + string name = Guid.NewGuid().ToString("N"); + string sharedMemoryDirectory = Path.Combine(sharedMemoryBaseDirectory, ".dotnet", "shm", "global"); + NamedWaitHandleOptions options = + new() { CurrentUserOnly = true, CurrentSessionOnly = false }; + using Mutex mutex = new($"Global\\{name}", options); + Assert.True(File.Exists(Path.Combine(sharedMemoryDirectory, name))); + Assert.Equal(OwnerUserRwx, File.GetUnixFileMode(Path.Combine(sharedMemoryBaseDirectory, ".dotnet"))); + Assert.Equal(OwnerUserRwx, File.GetUnixFileMode(Path.Combine(sharedMemoryBaseDirectory, ".dotnet", "shm"))); + Assert.Equal(OwnerUserRwx, File.GetUnixFileMode(sharedMemoryDirectory)); + }, + homeDirectory, + remoteInvokeOptions).Dispose(); + } + + [ConditionalFact(nameof(IsRemoteExecutorAndCrossProcessNamedMutexSupported))] + [PlatformSpecific(TestPlatforms.Linux)] + [UnsupportedOSPlatform("windows")] + public void NamedMutex_SharedMemoryDirectoryReplacementDoesNotRedirectFileAccess() + { + string userRuntimeDirectory = GetTestFilePath(); + Directory.CreateDirectory(userRuntimeDirectory); + + RemoteInvokeOptions remoteInvokeOptions = new(); + remoteInvokeOptions.StartInfo.EnvironmentVariables["XDG_RUNTIME_DIR"] = userRuntimeDirectory; + + RemoteExecutor.Invoke( + userRuntimeDirectory => + { + NamedWaitHandleOptions options = + new() { CurrentUserOnly = true, CurrentSessionOnly = false }; + string firstName = Guid.NewGuid().ToString("N"); + + using Mutex firstMutex = new($"Global\\{firstName}", options); + + string runtimeDirectory = Path.Combine(userRuntimeDirectory, ".dotnet"); + string sharedMemoryDirectory = Path.Combine(runtimeDirectory, "shm"); + string originalSharedMemoryDirectory = Path.Combine(runtimeDirectory, "shm-original"); + Directory.Move(sharedMemoryDirectory, originalSharedMemoryDirectory); + Directory.CreateDirectory(Path.Combine(sharedMemoryDirectory, "global"), OwnerUserRwx); + + string secondName = Guid.NewGuid().ToString("N"); + using Mutex secondMutex = new($"Global\\{secondName}", options); + + Assert.True(File.Exists(Path.Combine(originalSharedMemoryDirectory, "global", secondName))); + Assert.False(File.Exists(Path.Combine(sharedMemoryDirectory, "global", secondName))); + }, + userRuntimeDirectory, + remoteInvokeOptions).Dispose(); + } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotMobile))] [PlatformSpecific(TestPlatforms.AnyUnix)] diff --git a/src/native/libs/System.Native/entrypoints.c b/src/native/libs/System.Native/entrypoints.c index 08e1b2de315c88..1ac7b8ab49dc3e 100644 --- a/src/native/libs/System.Native/entrypoints.c +++ b/src/native/libs/System.Native/entrypoints.c @@ -61,9 +61,11 @@ static const Entry s_sysNative[] = DllImportEntry(SystemNative_Stat) DllImportEntry(SystemNative_LStat) DllImportEntry(SystemNative_Open) + DllImportEntry(SystemNative_OpenAt) DllImportEntry(SystemNative_Close) DllImportEntry(SystemNative_Dup) DllImportEntry(SystemNative_Unlink) + DllImportEntry(SystemNative_UnlinkAt) DllImportEntry(SystemNative_IsMemfdSupported) DllImportEntry(SystemNative_MemfdCreate) DllImportEntry(SystemNative_ShmOpen) @@ -81,6 +83,7 @@ static const Entry s_sysNative[] = DllImportEntry(SystemNative_FcntlSetIsNonBlocking) DllImportEntry(SystemNative_FcntlGetIsNonBlocking) DllImportEntry(SystemNative_MkDir) + DllImportEntry(SystemNative_MkDirAt) DllImportEntry(SystemNative_ChMod) DllImportEntry(SystemNative_FChMod) DllImportEntry(SystemNative_FSync) diff --git a/src/native/libs/System.Native/pal_io.c b/src/native/libs/System.Native/pal_io.c index 38134a115f5b95..6ab0a4eb2e4557 100644 --- a/src/native/libs/System.Native/pal_io.c +++ b/src/native/libs/System.Native/pal_io.c @@ -315,7 +315,7 @@ static int32_t ConvertOpenFlags(int32_t flags) return -1; } - if (flags & ~(PAL_O_ACCESS_MODE_MASK | PAL_O_CLOEXEC | PAL_O_CREAT | PAL_O_EXCL | PAL_O_TRUNC | PAL_O_SYNC | PAL_O_NOFOLLOW)) + if (flags & ~(PAL_O_ACCESS_MODE_MASK | PAL_O_CLOEXEC | PAL_O_CREAT | PAL_O_EXCL | PAL_O_TRUNC | PAL_O_SYNC | PAL_O_NOFOLLOW | PAL_O_DIRECTORY)) { assert_msg(false, "Unknown Open flag", (int)flags); return -1; @@ -335,18 +335,15 @@ static int32_t ConvertOpenFlags(int32_t flags) ret |= O_SYNC; if (flags & PAL_O_NOFOLLOW) ret |= O_NOFOLLOW; + if (flags & PAL_O_DIRECTORY) + ret |= O_DIRECTORY; assert(ret != -1); return ret; } -intptr_t SystemNative_Open(const char* path, int32_t flags, int32_t mode) +static int32_t ConvertOpenFlagsAndAddDefaults(int32_t flags) { -// these two ifdefs are for platforms where we dont have the open version of CLOEXEC and thus -// must simulate it by doing a fcntl with the SETFFD version after the open instead -#if !HAVE_O_CLOEXEC - int32_t old_flags = flags; -#endif flags = ConvertOpenFlags(flags); if (flags == -1) { @@ -360,15 +357,47 @@ intptr_t SystemNative_Open(const char* path, int32_t flags, int32_t mode) #ifndef TARGET_WASM flags |= O_NOCTTY; #endif + return flags; +} - int result; - while ((result = open(path, flags, (mode_t)mode)) < 0 && errno == EINTR); +static void SetCloseOnExecIfNeeded(int result, int32_t flags) +{ #if !HAVE_O_CLOEXEC - if (old_flags & PAL_O_CLOEXEC) + if (result >= 0 && (flags & PAL_O_CLOEXEC)) { fcntl(result, F_SETFD, FD_CLOEXEC); } +#else + (void)result; + (void)flags; #endif +} + +intptr_t SystemNative_Open(const char* path, int32_t flags, int32_t mode) +{ + int32_t nativeFlags = ConvertOpenFlagsAndAddDefaults(flags); + if (nativeFlags == -1) + { + return -1; + } + + int result; + while ((result = open(path, nativeFlags, (mode_t)mode)) < 0 && errno == EINTR); + SetCloseOnExecIfNeeded(result, flags); + return result; +} + +intptr_t SystemNative_OpenAt(intptr_t dirfd, const char* path, int32_t flags, int32_t mode) +{ + int32_t nativeFlags = ConvertOpenFlagsAndAddDefaults(flags); + if (nativeFlags == -1) + { + return -1; + } + + int result; + while ((result = openat(ToFileDescriptor(dirfd), path, nativeFlags, (mode_t)mode)) < 0 && errno == EINTR); + SetCloseOnExecIfNeeded(result, flags); return result; } @@ -403,6 +432,27 @@ int32_t SystemNative_Unlink(const char* path) return result; } +int32_t SystemNative_UnlinkAt(intptr_t dirfd, const char* path, int32_t flags) +{ + int nativeFlags; + switch (flags) + { + case 0: + nativeFlags = 0; + break; + case PAL_AT_REMOVEDIR: + nativeFlags = AT_REMOVEDIR; + break; + default: + errno = EINVAL; + return -1; + } + + int32_t result; + while ((result = unlinkat(ToFileDescriptor(dirfd), path, nativeFlags)) < 0 && errno == EINTR); + return result; +} + #ifdef __NR_memfd_create #ifndef MFD_CLOEXEC #define MFD_CLOEXEC 0x0001U @@ -770,6 +820,13 @@ int32_t SystemNative_MkDir(const char* path, int32_t mode) return result; } +int32_t SystemNative_MkDirAt(intptr_t dirfd, const char* path, int32_t mode) +{ + int32_t result; + while ((result = mkdirat(ToFileDescriptor(dirfd), path, (mode_t)mode)) < 0 && errno == EINTR); + return result; +} + int32_t SystemNative_ChMod(const char* path, int32_t mode) { #if HAVE_CHMOD diff --git a/src/native/libs/System.Native/pal_io.h b/src/native/libs/System.Native/pal_io.h index d9bcc826792277..3b0d675489a867 100644 --- a/src/native/libs/System.Native/pal_io.h +++ b/src/native/libs/System.Native/pal_io.h @@ -183,6 +183,12 @@ enum PAL_O_NOFOLLOW = 0x0200, // Fails to open the target if it's a symlink, parent symlinks are allowed PAL_O_NONBLOCK_READ = 0x0400, // Set O_NONBLOCK on the read end of a pipe PAL_O_NONBLOCK_WRITE = 0x0800, // Set O_NONBLOCK on the write end of a pipe + PAL_O_DIRECTORY = 0x1000, // Fails to open the target if it's not a directory +}; + +enum +{ + PAL_AT_REMOVEDIR = 0x0001, // Remove the entry as a directory }; /** @@ -375,6 +381,13 @@ PALEXPORT int32_t SystemNative_LStat(const char* path, FileStatus* output); */ PALEXPORT intptr_t SystemNative_Open(const char* path, int32_t flags, int32_t mode); +/** + * Open or create a file or device relative to a directory descriptor. Implemented as shim to openat(2). + * + * Returns file descriptor or -1 for failure. Sets errno on failure. + */ +PALEXPORT intptr_t SystemNative_OpenAt(intptr_t dirfd, const char* path, int32_t flags, int32_t mode); + /** * Close a file descriptor. Implemented as shim to open(2). * @@ -396,6 +409,13 @@ PALEXPORT intptr_t SystemNative_Dup(intptr_t oldfd); */ PALEXPORT int32_t SystemNative_Unlink(const char* path); +/** + * Delete an entry relative to a directory descriptor. Implemented as shim to unlinkat(2). + * + * Returns 0 for success, -1 for failure. Sets errno on failure. + */ +PALEXPORT int32_t SystemNative_UnlinkAt(intptr_t dirfd, const char* path, int32_t flags); + /** * Check if the system supports memfd_create(2). * @@ -520,6 +540,13 @@ PALEXPORT int32_t SystemNative_FcntlGetIsNonBlocking(intptr_t fd, int32_t* isNon */ PALEXPORT int32_t SystemNative_MkDir(const char* path, int32_t mode); +/** + * Create a directory relative to a directory descriptor. Implemented as a shim to mkdirat(2). + * + * Returns 0 for success, -1 for failure. Sets errno for failure. + */ +PALEXPORT int32_t SystemNative_MkDirAt(intptr_t dirfd, const char* path, int32_t mode); + /** * Change permissions of a file. Implemented as a shim to chmod(2). * From 4c416c7a9250c1bd9c6f4b84f523a92acbcd45f1 Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Wed, 14 Oct 2026 13:15:02 -0700 Subject: [PATCH 2/2] Add a test for the feature switch to opt back into global scope mutexes. --- .../System.Threading/tests/MutexTests.cs | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/libraries/System.Threading/tests/MutexTests.cs b/src/libraries/System.Threading/tests/MutexTests.cs index d78281ad997dcc..e96008513d7bee 100644 --- a/src/libraries/System.Threading/tests/MutexTests.cs +++ b/src/libraries/System.Threading/tests/MutexTests.cs @@ -1100,6 +1100,47 @@ public void NamedMutex_OtherEvent_NotCompatible() | UnixFileMode.UserWrite | UnixFileMode.UserExecute; + [ConditionalTheory(nameof(IsRemoteExecutorAndCrossProcessNamedMutexSupported))] + [InlineData(null)] + [InlineData(false)] + [InlineData(true)] + [PlatformSpecific(TestPlatforms.Linux)] + public void NamedMutex_DefaultScope_UsesExpectedSharedMemoryPath(bool? unsafeDefaultMutexScopeGlobal) + { + string userRuntimeDirectory = GetTestFilePath(); + Directory.CreateDirectory(userRuntimeDirectory); + + RemoteInvokeOptions remoteInvokeOptions = new(); + remoteInvokeOptions.StartInfo.EnvironmentVariables["XDG_RUNTIME_DIR"] = userRuntimeDirectory; + if (unsafeDefaultMutexScopeGlobal.HasValue) + { + remoteInvokeOptions.RuntimeConfigurationOptions["System.Threading.Mutex.UnsafeDefaultMutexScopeGlobal"] = + unsafeDefaultMutexScopeGlobal.Value; + } + + RemoteExecutor.Invoke( + (userRuntimeDirectory, useGlobalScope) => + { + string name = Guid.NewGuid().ToString("N"); + string mutexName = $"Global\\{name}"; + string userPath = Path.Combine(userRuntimeDirectory, ".dotnet", "shm", "global", name); + string globalPath = Path.Combine(GlobalSharedMemoryDirectory, name); + bool isGlobalScope = bool.Parse(useGlobalScope); + + using Mutex mutex = new(false, mutexName, out bool createdNew); + Assert.True(createdNew); + Assert.Equal(!isGlobalScope, File.Exists(userPath)); + Assert.Equal(isGlobalScope, File.Exists(globalPath)); + + using Mutex openedMutex = Mutex.OpenExisting(mutexName); + Assert.True(Mutex.TryOpenExisting(mutexName, out Mutex existingMutex)); + existingMutex.Dispose(); + }, + userRuntimeDirectory, + (unsafeDefaultMutexScopeGlobal == true).ToString(), + remoteInvokeOptions).Dispose(); + } + [ConditionalFact(nameof(IsRemoteExecutorAndCrossProcessNamedMutexSupported))] [PlatformSpecific(TestPlatforms.Linux)] [UnsupportedOSPlatform("windows")]