Table of Contents

A webhook receiver behind NAT

An application on a laptop, a build agent or a site with no public address needs webhooks from a SaaS service. Instead of opening a port on the firewall or running a tunnelling agent, the application connects to a small public server over SSH and asks it to listen on a port of its loopback (ssh -R). The public server's reverse proxy terminates TLS and passes the webhook path to that port. Each request then arrives in the application's own code, as a stream: nothing listens on the application's machine.

flowchart LR
    saas["Webhook sender"] -- "HTTPS POST /hooks" --> proxy
    subgraph relay["relay.example.com (public)"]
        proxy["Reverse proxy (TLS)"] -- "HTTP to localhost:9000" --> sshd["sshd listener"]
    end
    sshd == "SSH connection, opened from inside<br/>(forwarded-tcpip channel per request)" ==> handler
    subgraph app["The application (behind NAT)"]
        handler["Handler: size limits, signature check"] --> queue["Queue for the application"]
    end

The approach

  • The connection goes out, the requests come in. Only an outbound SSH connection is needed. ForwardRemotePortAsync with a handler makes the server listen on localhost:9000; every connection to it becomes a channel in that SSH connection, handed to the handler.
  • Everything that arrives is untrusted. Anyone who reaches the port (the reverse proxy, but also any user or process on the relay) can connect. The handler bounds the header and body sizes and the time it waits, checks the sender's HMAC signature, and only then queues the body.
  • A cap. maxConnections bounds the requests handled at once; the server's connections above it are refused at once, which the proxy reports as a 502 and the sender retries.
  • Small handler, separate work. The handler only accepts and queues; the application processes the queue at its own pace.

The code

The receiver: one request per connection, answered with Connection: close.

/// <summary>
/// Receives webhook POSTs that arrive at a port on a public server, in this process: one request per connection, size-limited,
/// signature-checked, then queued for the application.
/// </summary>
public sealed class Receiver(byte[] signingKey, Func<byte[], CancellationToken, ValueTask> enqueue)
{
    private const int MaxHeaderBytes = 16 * 1024;
    private const int MaxBodyBytes = 1024 * 1024;

    public async Task HandleAsync(SshForwardedConnection connection, CancellationToken cancellationToken)
    {
        // Anyone who reaches the server's port can connect: bound the time and the size of everything read.
        using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
        timeout.CancelAfter(TimeSpan.FromSeconds(30));
        var stream = connection.Stream;

        var headers = await ReadHeadersAsync(stream, timeout.Token);
        if (headers is null
            || !headers.TryGetValue("content-length", out var lengthText)
            || !int.TryParse(lengthText, out var length) || length is < 0 or > MaxBodyBytes
            || !headers.TryGetValue("x-signature-sha256", out var signature))
        {
            await RespondAsync(stream, "400 Bad Request", timeout.Token);
            return;
        }

        var body = new byte[length];
        await stream.ReadExactlyAsync(body, timeout.Token);
        if (!IsSignedWith(signingKey, body, signature))
        {
            await RespondAsync(stream, "401 Unauthorized", timeout.Token);
            return;
        }

        await enqueue(body, timeout.Token);
        await RespondAsync(stream, "204 No Content", timeout.Token);
    }   // the stream is disposed when the handler returns, which closes the connection

    /// <summary>The request line and headers (names in lower case), or null when they are too long or malformed.</summary>
    private static async Task<Dictionary<string, string>?> ReadHeadersAsync(Stream stream, CancellationToken cancellationToken)
    {
        // Byte by byte, so nothing of the body is read past the blank line; a real receiver would buffer.
        var header = new List<byte>();
        var one = new byte[1];
        while (!header.EndsWith("\r\n\r\n"u8))
        {
            if (header.Count >= MaxHeaderBytes || await stream.ReadAsync(one, cancellationToken) == 0)
            {
                return null;
            }

            header.Add(one[0]);
        }

        var lines = Encoding.ASCII.GetString([.. header]).Split("\r\n", StringSplitOptions.RemoveEmptyEntries);
        if (lines.Length == 0 || !lines[0].StartsWith("POST ", StringComparison.Ordinal))
        {
            return null;
        }

        var result = new Dictionary<string, string>(StringComparer.Ordinal);
        foreach (var line in lines.Skip(1))
        {
            var colon = line.IndexOf(':', StringComparison.Ordinal);
            if (colon > 0)
            {
                result[line[..colon].Trim().ToLowerInvariant()] = line[(colon + 1)..].Trim();
            }
        }

        return result;
    }

    private static bool IsSignedWith(byte[] key, byte[] body, string signatureHex)
    {
        var expected = HMACSHA256.HashData(key, body);
        try
        {
            return CryptographicOperations.FixedTimeEquals(expected, Convert.FromHexString(signatureHex));
        }
        catch (FormatException)
        {
            return false;
        }
    }

    private static async Task RespondAsync(Stream stream, string status, CancellationToken cancellationToken) =>
        await stream.WriteAsync(Encoding.ASCII.GetBytes($"HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"), cancellationToken);
}

Starting it:

// The key the webhook sender signs with, from the environment or a secret store.
var signingKey = Convert.FromHexString(Environment.GetEnvironmentVariable("WEBHOOK_SIGNING_KEY")
    ?? throw new InvalidOperationException("WEBHOOK_SIGNING_KEY is not set."));
var queue = System.Threading.Channels.Channel.CreateBounded<byte[]>(1000);
var receiver = new Receiver(signingKey, (body, ct) => queue.Writer.WriteAsync(body, ct));

// "relay" is the public server's alias in ~/.ssh/config. Its reverse proxy (TLS) passes /hooks to its own localhost:9000.
await using var relay = await SshClient.ConnectAsync("relay", cancellationToken: cancellationToken);
await using var forwarding = await relay.ForwardRemotePortAsync("localhost", 9000, receiver.HandleAsync,
    maxConnections: 50, cancellationToken);

await foreach (var body in queue.Reader.ReadAllAsync(cancellationToken))
{
    Console.WriteLine($"Webhook received: {body.Length} bytes");
}

The relay's entry in ~/.ssh/config:

Host relay
  HostName relay.example.com
  User webhooks
  IdentityFile ~/.ssh/webhooks_ed25519
  ServerAliveInterval 30

For production

  • A dedicated account on the relay. Restrict its key in authorized_keys to forwarding only, for example restrict,port-forwarding,permitlisten="localhost:9000", so it can listen on that port and do nothing else.
  • Reconnect. When the SSH connection drops, the handlers are cancelled and the port closes on the relay. Watch relay.ConnectionClosed and connect and forward again; see Keep-alive and reconnecting. A sender's retries cover the gap.
  • A full HTTP stack. The handler above reads one small request by hand to keep the example short. For anything richer, run Kestrel on this machine's loopback and use the host-and-port overload (ForwardRemotePortAsync("localhost", 9000, "127.0.0.1", 5000)) instead.
  • Port in use. sshd refuses to listen on a port already taken on the relay (the call throws SshException); a second instance of the application needs another port.
  • Disposal. Disposing the forwarder stops the relay listening first, then cancels the handlers and gives them up to HandlerShutdownTimeout (5 seconds by default; set it on the forwarder for slower requests) to finish the request in progress.

See also