Skip to content

Commit 0232cf7

Browse files
authored
Use performant way to enforce handle inheritance restrictions, fail wth error if not available (dotnet#135753)
1 parent 1439901 commit 0232cf7

3 files changed

Lines changed: 141 additions & 56 deletions

File tree

‎src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessStartInfo.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,8 @@ public string Arguments
258258
/// Only <see cref="SafeFileHandle"/> and <see cref="SafePipeHandle"/> are supported in this list.
259259
/// </para>
260260
/// <para>
261-
/// Setting this property on Unix systems that do not have native support for controlling handle inheritance can severely degrade process start performance.
261+
/// Setting this property on Unix systems that do not have native support for controlling handle inheritance
262+
/// causes <see cref="Process.Start(ProcessStartInfo)"/> to throw <see cref="PlatformNotSupportedException"/>.
262263
/// </para>
263264
/// <para>
264265
/// Handles in this list should not have inheritance enabled beforehand.

‎src/libraries/System.Diagnostics.Process/tests/ProcessHandlesTests.Unix.cs‎

Lines changed: 112 additions & 0 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

44
using System.ComponentModel;
5+
using System.IO;
56
using System.Runtime.InteropServices;
67
using Microsoft.DotNet.RemoteExecutor;
78
using Microsoft.DotNet.XUnitExtensions;
@@ -12,6 +13,117 @@ namespace System.Diagnostics.Tests
1213
{
1314
public partial class ProcessHandlesTests
1415
{
16+
// RLIMIT_NOFILE's numeric value is Linux-specific (7); other Unix platforms use different values.
17+
private const int RLIMIT_NOFILE = 7;
18+
private static readonly nuint RLIM_INFINITY = nuint.MaxValue;
19+
20+
// struct rlimit uses native rlim_t fields, which are pointer-sized (32-bit on 32-bit Linux).
21+
[StructLayout(LayoutKind.Sequential)]
22+
private struct RLimit
23+
{
24+
public nuint rlim_cur;
25+
public nuint rlim_max;
26+
}
27+
28+
[DllImport("libc", SetLastError = true)]
29+
private static extern int dup2(int oldfd, int newfd);
30+
31+
[DllImport("libc", SetLastError = true)]
32+
private static extern int close(int fd);
33+
34+
[DllImport("libc", SetLastError = true)]
35+
private static extern int getrlimit(int resource, out RLimit rlim);
36+
37+
[DllImport("libc", SetLastError = true)]
38+
private static extern int setrlimit(int resource, ref RLimit rlim);
39+
40+
// Regression test for a bug where SetCloexecForAllFdsFallback() (the fallback used when
41+
// close_range()/fdwalk() are unavailable, in pal_process.c) bounded its cleanup loop by the
42+
// *current* RLIMIT_NOFILE soft limit. If a high-numbered fd was opened and RLIMIT_NOFILE was
43+
// subsequently lowered below it (which does not close the already-open fd, only future opens),
44+
// the loop would stop short of that fd, leaving FD_CLOEXEC unset on it and leaking it into
45+
// child processes even though it wasn't in the InheritedHandles allow-list.
46+
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
47+
[PlatformSpecific(TestPlatforms.Linux)]
48+
public void HighNumberedFd_NotLeakedAfterLoweringRLimit()
49+
{
50+
// Everything below -- including the RLIMIT_NOFILE change -- runs inside a RemoteExecutor-invoked
51+
// process, so that lowering the fd limit does not affect other tests running concurrently
52+
// in this test process.
53+
using RemoteInvokeHandle remoteHandle = RemoteExecutor.Invoke(static () =>
54+
{
55+
Assert.Equal(0, getrlimit(RLIMIT_NOFILE, out RLimit limit));
56+
57+
// Need enough headroom to safely carve out a high fd and then lower the limit below it,
58+
// while leaving plenty of room for fds this process (and Process.Start machinery) still need.
59+
const nuint MinRequiredLimit = 512;
60+
if (limit.rlim_cur == RLIM_INFINITY || limit.rlim_cur < MinRequiredLimit)
61+
{
62+
return; // Cannot safely construct the scenario on this machine; skip.
63+
}
64+
65+
string path = Path.GetTempFileName();
66+
try
67+
{
68+
using SafeFileHandle fileHandle = File.OpenHandle(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None, FileOptions.None);
69+
string id = GetSafeFileHandleId(fileHandle);
70+
71+
// Duplicate the handle to a high fd number, just below the current soft limit.
72+
// dup2() always clears FD_CLOEXEC on the new fd, so it starts out inheritable,
73+
// exactly like a raw fd a user opened and wants to keep alive across the limit change.
74+
int highFd = (int)(limit.rlim_cur - 10);
75+
if (dup2((int)fileHandle.DangerousGetHandle(), highFd) < 0)
76+
{
77+
throw new Win32Exception(Marshal.GetLastWin32Error());
78+
}
79+
80+
try
81+
{
82+
// Lower RLIMIT_NOFILE below highFd. This does not close the already-open highFd,
83+
// it only restricts future opens above the new limit.
84+
RLimit newLimit = limit;
85+
newLimit.rlim_cur = (nuint)highFd - 5;
86+
Assert.Equal(0, setrlimit(RLIMIT_NOFILE, ref newLimit));
87+
88+
RemoteInvokeOptions options = new() { CheckExitCode = true };
89+
options.StartInfo.InheritedHandles = []; // restrict all handle inheritance
90+
91+
using RemoteInvokeHandle grandchildHandle = RemoteExecutor.Invoke(
92+
static (string fdStr, string fileId) =>
93+
{
94+
int fd = int.Parse(fdStr);
95+
using SafeFileHandle handle = new SafeFileHandle((nint)fd, ownsHandle: false);
96+
97+
string? childId;
98+
try
99+
{
100+
childId = GetSafeFileHandleId(handle);
101+
}
102+
catch (Win32Exception)
103+
{
104+
// Not a valid fd in the grandchild process: not leaked, as expected.
105+
return RemoteExecutor.SuccessExitCode;
106+
}
107+
108+
Assert.NotEqual(fileId, childId);
109+
return RemoteExecutor.SuccessExitCode;
110+
},
111+
highFd.ToString(),
112+
id,
113+
options);
114+
}
115+
finally
116+
{
117+
close(highFd);
118+
}
119+
}
120+
finally
121+
{
122+
File.Delete(path);
123+
}
124+
});
125+
}
126+
15127
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
16128
public unsafe void StartWithCallback_PosixSpawn_CanRedirectOutput()
17129
{

‎src/native/libs/System.Native/pal_process.c‎

Lines changed: 27 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
#include <fcntl.h>
2525

2626
#if defined(__linux__)
27-
#if !defined(HAVE_CLOSE_RANGE)
27+
#if !HAVE_CLOSE_RANGE
2828
#include <sys/syscall.h>
2929
#if !defined(__NR_close_range)
3030
// close_range was added in Linux 5.9. The syscall number is 436 for all
@@ -37,7 +37,7 @@
3737
# define __NR_close_range 436
3838
# endif
3939
#endif // !defined(__NR_close_range)
40-
#endif // !defined(HAVE_CLOSE_RANGE)
40+
#endif // !HAVE_CLOSE_RANGE
4141
#endif // defined(__linux__)
4242
#if (HAVE_CLOSE_RANGE || defined(__NR_close_range)) && !defined(CLOSE_RANGE_CLOEXEC)
4343
#define CLOSE_RANGE_CLOEXEC (1U << 2)
@@ -246,74 +246,44 @@ static int SetCloexecForFd(void* context, int fd)
246246
}
247247
#endif
248248

249-
// Used when OS-specific bulk methods (close_range, fdwalk) are unavailable or fail.
250-
// Always sets FD_CLOEXEC rather than closing fds directly. Closing fds directly would close
251-
// waitForChildToExecPipe[WRITE_END_OF_PIPE] (which has O_CLOEXEC), making it impossible to
252-
// report exec() failures back to the parent when execve() fails after RestrictHandleInheritance.
253-
static void SetCloexecForAllFdsFallback(void)
254-
{
255-
struct rlimit rl;
256-
int maxFd;
257-
if (getrlimit(RLIMIT_NOFILE, &rl) == 0 && rl.rlim_cur != RLIM_INFINITY)
258-
{
259-
maxFd = (int)rl.rlim_cur;
260-
}
261-
else
262-
{
263-
maxFd = (int)sysconf(_SC_OPEN_MAX);
264-
if (maxFd <= 0)
265-
{
266-
maxFd = 65536; // reasonable upper bound
267-
}
268-
}
269-
270-
// Fallback: iterate over all file descriptors and set FD_CLOEXEC on each open one >= 3.
271-
for (int fd = 3; fd < maxFd; fd++)
272-
{
273-
int flags = fcntl(fd, F_GETFD);
274-
if (flags == -1)
275-
{
276-
continue; // fd not open
277-
}
278-
279-
if ((flags & FD_CLOEXEC) == 0)
280-
{
281-
fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
282-
}
283-
}
284-
}
285-
286-
static void RestrictHandleInheritance(int32_t* inheritedFds, int32_t inheritedFdCount)
249+
// Returns 0 on success, or -1 (with errno set to ENOTSUP) if this platform/kernel doesn't provide
250+
// a performant native way (close_range()/fdwalk()) to restrict which fds a child process inherits.
251+
//
252+
// We intentionally do NOT fall back to manually scanning every possible fd via fcntl() in that
253+
// case: without close_range()/fdwalk(), there is no reliable way to learn only the fds that are
254+
// actually open, so such a scan would need to cover the entire valid fd range (up to INT_MAX) to
255+
// be correct -- something that has been measured to take multiple minutes of CPU time per
256+
// Process.Start call. That's not an acceptable cost, so we report failure instead and let the
257+
// managed layer surface a clear, actionable error.
258+
static int32_t RestrictHandleInheritance(int32_t* inheritedFds, int32_t inheritedFdCount)
287259
{
288260
// FDs 0-2 are stdin/stdout/stderr; this method must be called AFTER the dup2 calls.
289261
// We always set FD_CLOEXEC rather than closing fds directly. This is critical because
290262
// waitForChildToExecPipe[WRITE_END_OF_PIPE] (which has O_CLOEXEC) must remain open
291263
// until execve() is called so that exec failures can be reported back to the parent.
292264
// Using closefrom() or close_range() with flag 0 (direct close) would destroy this pipe.
293265

266+
int result;
294267
#if HAVE_CLOSE_RANGE
295268
// On systems where close_range() is available as a function (FreeBSD 12.2+, Linux glibc >= 2.34).
296-
if (close_range(3, UINT_MAX, CLOSE_RANGE_CLOEXEC) != 0)
297-
{
298-
SetCloexecForAllFdsFallback();
299-
}
269+
result = close_range(3, UINT_MAX, CLOSE_RANGE_CLOEXEC);
300270
#elif defined(__NR_close_range)
301271
// On Linux with older glibc that doesn't expose close_range() as a function,
302272
// use the raw syscall number if the kernel supports it (kernel >= 5.9).
303-
if (syscall(__NR_close_range, 3, UINT_MAX, CLOSE_RANGE_CLOEXEC) != 0)
304-
{
305-
SetCloexecForAllFdsFallback();
306-
}
273+
result = (int)syscall(__NR_close_range, 3, UINT_MAX, CLOSE_RANGE_CLOEXEC);
307274
#elif HAVE_FDWALK
308275
// On Illumos/Solaris, use fdwalk() to set FD_CLOEXEC on all open fds >= 3.
309-
if (fdwalk(SetCloexecForFd, NULL) != 0)
310-
{
311-
SetCloexecForAllFdsFallback();
312-
}
276+
result = fdwalk(SetCloexecForFd, NULL);
313277
#else
314-
SetCloexecForAllFdsFallback();
278+
result = -1;
315279
#endif
316280

281+
if (result != 0)
282+
{
283+
errno = ENOTSUP;
284+
return -1;
285+
}
286+
317287
// Remove CLOEXEC from user-provided inherited file descriptors so they survive execve.
318288
for (int i = 0; i < inheritedFdCount; i++)
319289
{
@@ -327,6 +297,8 @@ static void RestrictHandleInheritance(int32_t* inheritedFds, int32_t inheritedFd
327297
}
328298
}
329299
}
300+
301+
return 0;
330302
}
331303

332304
// Forward declaration of the internal fork+exec function
@@ -907,9 +879,9 @@ static int32_t ForkAndExecProcessInternal(
907879
}
908880
}
909881

910-
if (inheritedFdCount >= 0)
882+
if (inheritedFdCount >= 0 && RestrictHandleInheritance(inheritedFds, inheritedFdCount) != 0)
911883
{
912-
RestrictHandleInheritance(inheritedFds, inheritedFdCount);
884+
ExitChild(waitForChildToExecPipe[WRITE_END_OF_PIPE], errno);
913885
}
914886

915887
#if HAVE_PR_SET_PDEATHSIG

0 commit comments

Comments
 (0)