Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit 46edc58

Browse files
authored
Add Mutex creation extension methods that take an ACL (#42281)
Approved API Proposal: #41662 Description We don't currently have a way to create a Mutex with a given ACL in .NET Core. We can modify the ACL, but it would be more secure to have the proper ACL on the object from the start. Customer impact Before this change, customers had to create a Mutex, then set its ACLs. This presents a few problems: Potential security hole as mutexes can be accessed between creation and modification. Porting difficulties as there isn't a 1-1 API replacement This change addresses those problems by adding a new extension method that allows creating a Mutex and ensuring the provided ACLs are set during creation.
1 parent 475778f commit 46edc58

File tree

10 files changed

+399
-10
lines changed

10 files changed

+399
-10
lines changed

src/Common/src/CoreLib/Interop/Windows/Kernel32/Interop.Mutex.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// The .NET Foundation licenses this file to you under the MIT license.
33
// See the LICENSE file in the project root for more information.
44

5+
#nullable enable
56
using Microsoft.Win32.SafeHandles;
67
using System;
78
using System.Runtime.InteropServices;
@@ -12,13 +13,13 @@ internal static partial class Kernel32
1213
{
1314
internal const uint CREATE_MUTEX_INITIAL_OWNER = 0x1;
1415

15-
[DllImport(Interop.Libraries.Kernel32, EntryPoint = "OpenMutexW", SetLastError = true, CharSet = CharSet.Unicode)]
16+
[DllImport(Libraries.Kernel32, EntryPoint = "OpenMutexW", SetLastError = true, CharSet = CharSet.Unicode)]
1617
internal static extern SafeWaitHandle OpenMutex(uint desiredAccess, bool inheritHandle, string name);
1718

18-
[DllImport(Interop.Libraries.Kernel32, EntryPoint = "CreateMutexExW", SetLastError = true, CharSet = CharSet.Unicode)]
19+
[DllImport(Libraries.Kernel32, EntryPoint = "CreateMutexExW", SetLastError = true, CharSet = CharSet.Unicode)]
1920
internal static extern SafeWaitHandle CreateMutexEx(IntPtr lpMutexAttributes, string? name, uint flags, uint desiredAccess);
2021

21-
[DllImport(Interop.Libraries.Kernel32, SetLastError = true)]
22+
[DllImport(Libraries.Kernel32, SetLastError = true)]
2223
internal static extern bool ReleaseMutex(SafeWaitHandle handle);
2324
}
2425
}

src/System.Threading.AccessControl/System.Threading.AccessControl.sln

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
Microsoft Visual Studio Solution File, Format Version 12.00
2-
# Visual Studio 15
3-
VisualStudioVersion = 15.0.27213.1
2+
# Visual Studio Version 16
3+
VisualStudioVersion = 16.0.29411.138
44
MinimumVisualStudioVersion = 10.0.40219.1
55
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Threading.AccessControl.Tests", "tests\System.Threading.AccessControl.Tests.csproj", "{458E445C-DF3C-4E4D-8E1D-F2FAC365BB40}"
66
ProjectSection(ProjectDependencies) = postProject

src/System.Threading.AccessControl/ref/System.Threading.AccessControl.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,4 +147,9 @@ public static void SetAccessControl(this System.Threading.EventWaitHandle handle
147147
public static void SetAccessControl(this System.Threading.Mutex mutex, System.Security.AccessControl.MutexSecurity mutexSecurity) { }
148148
public static void SetAccessControl(this System.Threading.Semaphore semaphore, System.Security.AccessControl.SemaphoreSecurity semaphoreSecurity) { }
149149
}
150+
151+
public static class MutexAcl
152+
{
153+
public static System.Threading.Mutex Create(bool initiallyOwned, string name, out bool createdNew, System.Security.AccessControl.MutexSecurity mutexSecurity) { throw null; }
154+
}
150155
}

src/System.Threading.AccessControl/src/Resources/Strings.resx

Lines changed: 109 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,64 @@
1-
<root>
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<root>
3+
<!--
4+
Microsoft ResX Schema
5+
6+
Version 2.0
7+
8+
The primary goals of this format is to allow a simple XML format
9+
that is mostly human readable. The generation and parsing of the
10+
various data types are done through the TypeConverter classes
11+
associated with the data types.
12+
13+
Example:
14+
15+
... ado.net/XML headers & schema ...
16+
<resheader name="resmimetype">text/microsoft-resx</resheader>
17+
<resheader name="version">2.0</resheader>
18+
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
19+
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
20+
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
21+
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
22+
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
23+
<value>[base64 mime encoded serialized .NET Framework object]</value>
24+
</data>
25+
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
26+
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
27+
<comment>This is a comment</comment>
28+
</data>
29+
30+
There are any number of "resheader" rows that contain simple
31+
name/value pairs.
32+
33+
Each data row contains a name, and value. The row also contains a
34+
type or mimetype. Type corresponds to a .NET class that support
35+
text/value conversion through the TypeConverter architecture.
36+
Classes that don't support this are serialized and stored with the
37+
mimetype set.
38+
39+
The mimetype is used for serialized objects, and tells the
40+
ResXResourceReader how to depersist the object. This is currently not
41+
extensible. For a given mimetype the value must be set accordingly:
42+
43+
Note - application/x-microsoft.net.object.binary.base64 is the format
44+
that the ResXResourceWriter will generate, however the reader can
45+
read any of the formats listed below.
46+
47+
mimetype: application/x-microsoft.net.object.binary.base64
48+
value : The object must be serialized with
49+
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
50+
: and then encoded with base64 encoding.
51+
52+
mimetype: application/x-microsoft.net.object.soap.base64
53+
value : The object must be serialized with
54+
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
55+
: and then encoded with base64 encoding.
56+
57+
mimetype: application/x-microsoft.net.object.bytearray.base64
58+
value : The object must be serialized into a byte array
59+
: using a System.ComponentModel.TypeConverter
60+
: and then encoded with base64 encoding.
61+
-->
262
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
363
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
464
<xsd:element name="root" msdata:IsDataSet="true">
@@ -63,4 +123,52 @@
63123
<data name="PlatformNotSupported_AccessControl" xml:space="preserve">
64124
<value>Access Control List (ACL) APIs are part of resource management on Windows and are not supported on this platform.</value>
65125
</data>
126+
<data name="Argument_WaitHandleNameTooLong" xml:space="preserve">
127+
<value>The length of the name exceeds the maximum limit.</value>
128+
</data>
129+
<data name="ArgumentOutOfRange_Enum" xml:space="preserve">
130+
<value>Enum value was out of legal range.</value>
131+
</data>
132+
<data name="IO_AlreadyExists_Name" xml:space="preserve">
133+
<value>Cannot create '{0}' because a file or directory with the same name already exists.</value>
134+
</data>
135+
<data name="IO_FileExists_Name" xml:space="preserve">
136+
<value>The file '{0}' already exists.</value>
137+
</data>
138+
<data name="IO_FileNotFound" xml:space="preserve">
139+
<value>Unable to find the specified file.</value>
140+
</data>
141+
<data name="IO_FileNotFound_FileName" xml:space="preserve">
142+
<value>Could not find file '{0}'.</value>
143+
</data>
144+
<data name="IO_PathNotFound_NoPathName" xml:space="preserve">
145+
<value>Could not find a part of the path.</value>
146+
</data>
147+
<data name="IO_PathNotFound_Path" xml:space="preserve">
148+
<value>Could not find a part of the path '{0}'.</value>
149+
</data>
150+
<data name="IO_PathTooLong" xml:space="preserve">
151+
<value>The specified file name or path is too long, or a component of the specified path is too long.</value>
152+
</data>
153+
<data name="IO_PathTooLong_Path" xml:space="preserve">
154+
<value>The path '{0}' is too long, or a component of the specified path is too long.</value>
155+
</data>
156+
<data name="IO_SharingViolation_File" xml:space="preserve">
157+
<value>The process cannot access the file '{0}' because it is being used by another process.</value>
158+
</data>
159+
<data name="IO_SharingViolation_NoFileName" xml:space="preserve">
160+
<value>The process cannot access the file because it is being used by another process.</value>
161+
</data>
162+
<data name="UnauthorizedAccess_IODenied_NoPathName" xml:space="preserve">
163+
<value>Access to the path is denied.</value>
164+
</data>
165+
<data name="UnauthorizedAccess_IODenied_Path" xml:space="preserve">
166+
<value>Access to the path '{0}' is denied.</value>
167+
</data>
168+
<data name="Argument_CannotBeNullOrEmpty" xml:space="preserve">
169+
<value>Argument cannot be null or empty.</value>
170+
</data>
171+
<data name="Threading_WaitHandleCannotBeOpenedException_InvalidHandle" xml:space="preserve">
172+
<value>A WaitHandle with system-wide name '{0}' cannot be created. A WaitHandle of a different type might have the same name.</value>
173+
</data>
66174
</root>

src/System.Threading.AccessControl/src/System.Threading.AccessControl.csproj

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,37 @@
1-
<Project Sdk="Microsoft.NET.Sdk">
1+
<Project Sdk="Microsoft.NET.Sdk">
22
<PropertyGroup>
33
<OSGroup Condition="'$(OSGroup)' == ''">Windows_NT</OSGroup>
44
<GeneratePlatformNotSupportedAssemblyMessage Condition="'$(TargetsNetStandard)' == 'true' and '$(TargetsWindows)' != 'true'">SR.PlatformNotSupported_AccessControl</GeneratePlatformNotSupportedAssemblyMessage>
55
<IsPartialFacadeAssembly Condition="'$(TargetsNetFx)' == 'true'">true</IsPartialFacadeAssembly>
66
<Configurations>net461-Windows_NT-Debug;net461-Windows_NT-Release;netfx-Windows_NT-Debug;netfx-Windows_NT-Release;netstandard2.0-Debug;netstandard2.0-Release;netstandard2.0-Windows_NT-Debug;netstandard2.0-Windows_NT-Release</Configurations>
7+
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
78
</PropertyGroup>
9+
<ItemGroup Condition="'$(TargetsWindows)' == 'true'">
10+
<Compile Include="$(CommonPath)\CoreLib\Interop\Windows\Kernel32\Interop.MAX_PATH.cs" Link="Common\CoreLib\Interop\Windows\Kernel32\Interop.MAX_PATH.cs" />
11+
</ItemGroup>
812
<ItemGroup Condition="'$(TargetsNetStandard)' == 'true' and '$(TargetsWindows)' == 'true'">
9-
<Compile Include="$(CommonPath)\Interop\Windows\Interop.Errors.cs">
10-
<Link>Common\Interop\Windows\Interop.Errors.cs</Link>
11-
</Compile>
13+
<Compile Include="$(CommonPath)\Interop\Windows\Interop.Errors.cs" Link="Common\Interop\Windows\Interop.Errors.cs" />
14+
<Compile Include="$(CommonPath)\CoreLib\Interop\Windows\Interop.BOOL.cs" Link="Common\CoreLib\Interop\Windows\Interop.BOOL.cs" />
15+
<Compile Include="$(CommonPath)\CoreLib\Interop\Windows\Interop.Libraries.cs" Link="Common\CoreLib\Interop\Windows\Interop.Libraries.cs" />
16+
<Compile Include="$(CommonPath)\CoreLib\Interop\Windows\Kernel32\Interop.Constants.cs" Link="Common\CoreLib\Interop\Windows\Kernel32\Interop.Constants.cs" />
17+
<Compile Include="$(CommonPath)\CoreLib\Interop\Windows\Kernel32\Interop.FormatMessage.cs" Link="Common\CoreLib\Interop\Windows\Kernel32\Interop.FormatMessage.cs" />
18+
<Compile Include="$(CommonPath)\CoreLib\Interop\Windows\Kernel32\Interop.Mutex.cs" Link="Common\CoreLib\Interop\Windows\Kernel32\Interop.Mutex.cs" />
19+
<Compile Include="$(CommonPath)\CoreLib\Interop\Windows\Kernel32\Interop.SECURITY_ATTRIBUTES.cs" Link="Common\CoreLib\Interop\Windows\Kernel32\Interop.SECURITY_ATTRIBUTES.cs" />
20+
<Compile Include="$(CommonPath)\CoreLib\System\IO\Win32Marshal.cs" Link="Common\CoreLib\System\IO\Win32Marshal.cs" />
1221
<Compile Include="System\Security\AccessControl\MutexSecurity.cs" />
1322
<Compile Include="System\Security\AccessControl\EventWaitHandleSecurity.cs" />
1423
<Compile Include="System\Security\AccessControl\SemaphoreSecurity.cs" />
24+
<Compile Include="System\Threading\MutexAcl.cs" />
1525
<Compile Include="System\Threading\ThreadingAclExtensions.cs" />
1626
</ItemGroup>
1727
<ItemGroup Condition="'$(TargetsNetFx)' == 'true'">
1828
<Reference Include="mscorlib" />
1929
<Reference Include="System" />
30+
<Compile Include="System\Threading\MutexAcl.net46.cs" />
2031
<Compile Include="System\Threading\ThreadingAclExtensions.net46.cs" />
2132
</ItemGroup>
2233
<ItemGroup Condition="'$(TargetsNetFx)' != 'true'">
34+
<Reference Include="System.Memory" />
2335
<Reference Include="System.Security.AccessControl" />
2436
<Reference Include="System.Security.Principal.Windows" />
2537
</ItemGroup>
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
using System.IO;
6+
using System.Runtime.InteropServices;
7+
using System.Security.AccessControl;
8+
using Microsoft.Win32.SafeHandles;
9+
10+
namespace System.Threading
11+
{
12+
public static class MutexAcl
13+
{
14+
/// <summary>Gets or creates <see cref="Mutex" /> instance, allowing a <see cref="MutexSecurity" /> to be optionally specified to set it during the mutex creation.</summary>
15+
/// <param name="initiallyOwned"><see langword="true" /> to give the calling thread initial ownership of the named system mutex if the named system mutex is created as a result of this call; otherwise, <see langword="false" />.</param>
16+
/// <param name="name">The optional name of the system mutex. If this argument is set to <see langword="null" /> or <see cref="string.Empty" />, a local mutex is created.</param>
17+
/// <param name="createdNew">When this method returns, this argument is always set to <see langword="true" /> if a local mutex is created; that is, when <paramref name="name" /> is <see langword="null" /> or <see cref="string.Empty" />. If <paramref name="name" /> has a valid non-empty value, this argument is set to <see langword="true" /> when the system mutex is created, or it is set to <see langword="false" /> if an existing system mutex is found with that name. This parameter is passed uninitialized.</param>
18+
/// <param name="mutexSecurity">The optional mutex access control security to apply.</param>
19+
/// <returns>An object that represents a system mutex, if named, or a local mutex, if nameless.</returns>
20+
/// <exception cref="ArgumentException">.NET Framework only: The length of the name exceeds the maximum limit.</exception>
21+
/// <exception cref="WaitHandleCannotBeOpenedException">A mutex handle with system-wide <paramref name="name" /> cannot be created. A mutex handle of a different type might have the same name.</exception>
22+
public static unsafe Mutex Create(bool initiallyOwned, string name, out bool createdNew, MutexSecurity mutexSecurity)
23+
{
24+
if (mutexSecurity == null)
25+
{
26+
return new Mutex(initiallyOwned, name, out createdNew);
27+
}
28+
29+
uint mutexFlags = initiallyOwned ? Interop.Kernel32.CREATE_MUTEX_INITIAL_OWNER : 0;
30+
31+
fixed (byte* pSecurityDescriptor = mutexSecurity.GetSecurityDescriptorBinaryForm())
32+
{
33+
var secAttrs = new Interop.Kernel32.SECURITY_ATTRIBUTES
34+
{
35+
nLength = (uint)sizeof(Interop.Kernel32.SECURITY_ATTRIBUTES),
36+
lpSecurityDescriptor = (IntPtr)pSecurityDescriptor
37+
};
38+
39+
SafeWaitHandle handle = Interop.Kernel32.CreateMutexEx(
40+
(IntPtr)(&secAttrs),
41+
name,
42+
mutexFlags,
43+
(uint)MutexRights.FullControl // Equivalent to MUTEX_ALL_ACCESS
44+
);
45+
46+
ValidateMutexHandle(handle, name, out createdNew);
47+
48+
Mutex mutex = new Mutex(initiallyOwned);
49+
SafeWaitHandle old = mutex.SafeWaitHandle;
50+
mutex.SafeWaitHandle = handle;
51+
old.Dispose();
52+
53+
return mutex;
54+
}
55+
}
56+
57+
private static void ValidateMutexHandle(SafeWaitHandle mutexHandle, string name, out bool createdNew)
58+
{
59+
int errorCode = Marshal.GetLastWin32Error();
60+
61+
if (mutexHandle.IsInvalid)
62+
{
63+
mutexHandle.SetHandleAsInvalid();
64+
65+
if (errorCode == Interop.Errors.ERROR_FILENAME_EXCED_RANGE)
66+
{
67+
// On Unix, length validation is done by CoreCLR's PAL after converting to utf-8
68+
throw new ArgumentException(SR.Argument_WaitHandleNameTooLong, nameof(name));
69+
}
70+
71+
if (errorCode == Interop.Errors.ERROR_INVALID_HANDLE)
72+
{
73+
throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name));
74+
}
75+
76+
throw Win32Marshal.GetExceptionForWin32Error(errorCode, name);
77+
}
78+
79+
createdNew = (errorCode != Interop.Errors.ERROR_ALREADY_EXISTS);
80+
}
81+
}
82+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
using System.Security.AccessControl;
6+
7+
namespace System.Threading
8+
{
9+
public static class MutexAcl
10+
{
11+
public static Mutex Create(bool initiallyOwned, string name, out bool createdNew, MutexSecurity mutexSecurity)
12+
{
13+
return new Mutex(initiallyOwned, name, out createdNew, mutexSecurity);
14+
}
15+
}
16+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
namespace System.Threading.Tests
6+
{
7+
public class AclTests
8+
{
9+
protected string GetRandomName()
10+
{
11+
return Guid.NewGuid().ToString("N");
12+
}
13+
}
14+
}

0 commit comments

Comments
 (0)