fix(config): align GatewayConfigPathRules with Secrets-005 (symlinks, drive-relative, device/loopback/local-share spellings) (scadaproj#52)
ci / nightly-windev (push) Has been skipped
ci / windows-x86 (push) Successful in 1m30s
ci / java (push) Successful in 2m17s
ci / portable (push) Failing after 4m20s

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
Joseph Doherty
2026-11-09 15:40:32 -05:00
parent 477fa55998
commit 7a7ef3b89f
2 changed files with 444 additions and 13 deletions
@@ -1,3 +1,4 @@
using System.Runtime.InteropServices;
using ZB.MOM.WW.Configuration;
namespace ZB.MOM.WW.MxGateway.Server.Configuration;
@@ -16,7 +17,7 @@ internal static class GatewayConfigPathRules
/// host running the validator</em>. Security-sensitive paths (the auth DB, the self-signed
/// private key, the Galaxy snapshot) must be absolute: a non-rooted value silently resolves
/// against the launch working directory, so the store moves with the CWD and can leak into the
/// source tree. Rooting is checked with <see cref="Path.IsPathRooted(string)"/> — the current
/// source tree. Rooting is checked with <see cref="Path.IsPathFullyQualified(string)"/> — the current
/// OS — so a Windows drive/UNC literal on a Unix host fails fast at startup rather than being
/// blessed and then written as a junk-named relative file. Reject
/// rather than auto-root; silent relocation of a credential store is worse than a boot error.
@@ -32,7 +33,9 @@ internal static class GatewayConfigPathRules
return;
}
if (!Path.IsPathRooted(value))
// Fully qualified, not merely rooted: Windows' drive-relative "C:secrets.db" and root-relative
// "\secrets.db" are rooted yet still resolve against a current directory (Secrets-005).
if (!Path.IsPathFullyQualified(value))
{
builder.Add(message);
}
@@ -101,28 +104,233 @@ internal static class GatewayConfigPathRules
return;
}
// Two readings, and the value is inside if EITHER says so (mirrors ZB.MOM.WW.Secrets
// SecretsStorePathRules, Secrets-005; mxgw pins Secrets 0.6.2 so the rules are copied, not called):
// - as SPELLED (full path, device prefix / loopback share normalised): a store configured
// through the content root moves with it on a rename even when a link inside carries it
// elsewhere today;
// - as LOCATED (symlinks, junctions and 8.3 names resolved): a store spelled through an
// alias of the content root sits in the directory the deploy replaces.
// A malformed path is AddIfInvalidPath's message to report; staying silent here keeps one
// bad value from producing two failures that say different things about the same mistake.
if (!TryGetFullPath(value, out string fullValue) || !TryGetFullPath(contentRoot, out string fullRoot))
string spelledValue, spelledRoot, locatedValue, locatedRoot;
try
{
spelledValue = Spelled(value);
spelledRoot = Spelled(contentRoot);
locatedValue = Canonicalize(value);
locatedRoot = Canonicalize(contentRoot);
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException
or PathTooLongException or IOException
or UnauthorizedAccessException)
{
return;
}
fullRoot = fullRoot.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
StringComparison comparison = OperatingSystem.IsWindows()
? StringComparison.OrdinalIgnoreCase
: StringComparison.Ordinal;
// The separator is load-bearing: a bare prefix test would also match a sibling directory
// whose name merely starts with the root's ("/srv/app" against "/srv/app-data").
if (string.Equals(fullValue, fullRoot, comparison)
|| fullValue.StartsWith(fullRoot + Path.DirectorySeparatorChar, comparison))
if (IsUnder(spelledValue, spelledRoot) || IsUnder(locatedValue, locatedRoot))
{
builder.Add(message);
}
}
private static bool IsUnder(string fullValue, string fullRoot)
{
// The separator is load-bearing, not cosmetic. Without it a bare prefix test treats
// "/srv/app-data" as inside "/srv/app" and refuses a legitimate sibling directory — and
// because this rule is fail-closed at startup, that false positive is an application that
// will not boot.
string rootWithSeparator = fullRoot.TrimEnd(
Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
// Path case sensitivity follows the OS, not a convention. Comparing case-insensitively
// everywhere would reject "/srv/App/store.db" as living under "/srv/app" on Linux, where
// those are genuinely different directories.
StringComparison comparison = OperatingSystem.IsWindows()
? StringComparison.OrdinalIgnoreCase
: StringComparison.Ordinal;
// Equal to the root counts as inside (the gateway's original rule).
return string.Equals(fullValue, fullRoot.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), comparison)
|| fullValue.StartsWith(rootWithSeparator, comparison);
}
private static string Spelled(string path) => OperatingSystem.IsWindows()
? NormalizeWindowsSpelling(Path.GetFullPath(NormalizeWindowsSpelling(path)))
: Path.GetFullPath(path);
private const int MaxLinkDepth = 40;
/// <summary>
/// Returns the location <paramref name="path"/> names, independent of how it is spelled: full
/// path, Windows device prefix stripped and loopback admin share mapped to its drive, and every
/// existing component resolved through symbolic links / junctions (and, on Windows, 8.3 short
/// names expanded). Components that do not exist yet are appended as written.
/// </summary>
/// <param name="path">The path to canonicalise.</param>
/// <returns>The canonical full path.</returns>
internal static string Canonicalize(string path) => Canonicalize(path, depth: 0);
private static string Canonicalize(string path, int depth)
{
if (depth > MaxLinkDepth)
{
throw new IOException("Too many levels of symbolic links.");
}
string full = Spelled(path);
string root = Path.GetPathRoot(full) ?? string.Empty;
string[] parts = full[root.Length..].Split(
new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar },
StringSplitOptions.RemoveEmptyEntries);
string current = root;
for (int i = 0; i < parts.Length; i++)
{
string next = Path.Combine(current, parts[i]);
FileSystemInfo? info = Directory.Exists(next) ? new DirectoryInfo(next)
: File.Exists(next) ? new FileInfo(next)
: null;
if (info is null)
{
// Not created yet (the store usually is not, at validation time): nothing on disk
// can redirect the rest, so append it as written.
return Path.Combine(new[] { current }.Concat(parts[i..]).ToArray());
}
if (info.LinkTarget is not null)
{
FileSystemInfo? target = info.ResolveLinkTarget(returnFinalTarget: true);
if (target is not null)
{
// The target's own parent directories may be links too: canonicalise it whole.
next = Canonicalize(target.FullName, depth + 1);
}
}
else if (OperatingSystem.IsWindows())
{
next = ExpandShortName(next);
}
current = next;
}
return current;
}
/// <summary>
/// Strips the Win32 device prefixes (<c>\\?\C:\…</c>, <c>\\.\C:\…</c>, <c>\\?\UNC\…</c>) and maps
/// a loopback administrative share (<c>\\localhost\C$\…</c>) back to its drive.
/// </summary>
private static string NormalizeWindowsSpelling(string path)
{
string p = path.Replace('/', '\\');
if (p.StartsWith(@"\\?\UNC\", StringComparison.OrdinalIgnoreCase))
{
p = @"\\" + p[8..];
}
else if (p.StartsWith(@"\\?\", StringComparison.Ordinal) || p.StartsWith(@"\\.\", StringComparison.Ordinal))
{
p = p[4..];
}
if (p.StartsWith(@"\\", StringComparison.Ordinal))
{
string[] segments = p[2..].Split('\\');
if (segments.Length >= 2
&& IsLoopbackHost(segments[0])
&& segments[1].Length == 2
&& char.IsAsciiLetter(segments[1][0])
&& segments[1][1] == '$')
{
p = segments[1][0] + @":\" + string.Join('\\', segments[2..]);
}
else if (segments.Length >= 2 && IsLoopbackHost(segments[0]) && TryGetLocalSharePath(segments[1]) is { } sharePath)
{
// An ordinary (non-administrative) share on THIS machine: map it to the directory it
// publishes so a store reached through a share that points back at the content root
// is compared by location.
p = sharePath.TrimEnd('\\') + (segments.Length > 2 ? @"\" + string.Join('\\', segments[2..]) : string.Empty);
}
}
return p;
}
/// <summary>
/// Returns the local directory published by share <paramref name="shareName"/> on this machine, or
/// <see langword="null"/> when it cannot be determined (no such share, or the caller lacks the
/// rights <c>NetShareGetInfo</c> level 2 demands — Administrators / Server Operators). A share on
/// ANOTHER machine is never resolved: what it points at is that server's configuration.
/// </summary>
private static string? TryGetLocalSharePath(string shareName)
{
try
{
if (NetShareGetInfo(null, shareName, 2, out IntPtr buffer) != 0)
{
return null;
}
try
{
SHARE_INFO_2 info = Marshal.PtrToStructure<SHARE_INFO_2>(buffer);
return string.IsNullOrWhiteSpace(info.shi2_path) ? null : info.shi2_path;
}
finally
{
_ = NetApiBufferFree(buffer);
}
}
catch (Exception ex) when (ex is DllNotFoundException or EntryPointNotFoundException or SEHException)
{
return null;
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct SHARE_INFO_2
{
public string shi2_netname;
public uint shi2_type;
public string shi2_remark;
public uint shi2_permissions;
public uint shi2_max_uses;
public uint shi2_current_uses;
public string shi2_path;
public string shi2_passwd;
}
[DllImport("netapi32.dll", CharSet = CharSet.Unicode)]
private static extern uint NetShareGetInfo(string? serverName, string netName, uint level, out IntPtr bufptr);
[DllImport("netapi32.dll")]
private static extern uint NetApiBufferFree(IntPtr buffer);
private static bool IsLoopbackHost(string host) =>
host.Equals("localhost", StringComparison.OrdinalIgnoreCase)
|| host.Equals("127.0.0.1", StringComparison.Ordinal)
|| host.Equals("::1", StringComparison.Ordinal)
|| host.Equals("[::1]", StringComparison.Ordinal)
|| host.Equals(Environment.MachineName, StringComparison.OrdinalIgnoreCase);
private static string ExpandShortName(string existingPath)
{
if (!existingPath.Contains('~'))
{
return existingPath;
}
char[] buffer = new char[1024];
uint length = GetLongPathNameW(existingPath, buffer, (uint)buffer.Length);
return length > 0 && length < buffer.Length ? new string(buffer, 0, (int)length) : existingPath;
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern uint GetLongPathNameW(string shortPath, [Out] char[] longPath, uint bufferLength);
private static bool TryGetFullPath(string value, out string fullPath)
{
try