fix(security): per-instance credential references (#835) and confined OpcUaClient user-certificate path (#836)
#835: inside one driver namespace, a secret:<ns>/<X>/... reference whose first segment names ANOTHER existing same-type driver instance (id or name, case-insensitive; another-instance match beats an own-name match, so renaming one's driver after a victim's unlocks nothing) is refused at save (DriverConfigSaveGate.ValidateAsync), deploy (CredentialReferenceOtherInstance, Heidenhain included), Test Connect (TestDriverConnect.DriverInstanceId, ConfigDb read off the mailbox) and live browse (BrowserSessionService, fail-closed without a ConfigDb). One rule: DriverCredentialPolicy.DescribeOtherInstanceProblems + DriverInstanceIdentities. Shared names and the driver's own id stay valid; env: is not instance-scoped. Running drivers are unchanged (warn-only window: the deploy gate and the upgrade preflight / /raw banner list them). #836: OpcUaClient UserCertificatePath is a relative path inside Drivers:OpcUaClient:UserCertificateDirectory (default <LocalAppData>/OtOpcUa/pki/user-certificates). Syntactic rule (CredentialFilePaths, a DriverCredentialPolicy path field) at every #815 seam; at load time ResolveSecretRefsAsync joins, canonicalises and requires lexical AND link-resolved containment before the PFX password is resolved, and LoadCertificate refuses an unresolved path. A running driver's pre-#836 absolute path keeps loading with a rate-limited warning (LegacyCredentialReferenceTracker.ReportPath). Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,121 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// A driver-config field naming a node-local file that holds key material (lmxopcua#836 — OpcUaClient
|
||||
/// <c>UserCertificatePath</c>). The node loads the file and USES its private key against the author-chosen endpoint,
|
||||
/// so an unrestricted path lets a Designer make the node sign a hostile server's nonce with any PFX the service
|
||||
/// account can read. The field is therefore confined to one node-configured directory.
|
||||
/// </summary>
|
||||
/// <param name="Name">The JSON property name (matched case-insensitively, as the driver binds it).</param>
|
||||
/// <param name="DirectoryDescription">How the operator configures the directory (for messages).</param>
|
||||
public sealed record CredentialPathField(string Name, string DirectoryDescription);
|
||||
|
||||
/// <summary>
|
||||
/// The one rule for <see cref="CredentialPathField"/> values (lmxopcua#836): authored as a RELATIVE path inside a
|
||||
/// node-configured directory, checked syntactically at every admin seam (save, deploy gate, Test Connect, browse) and
|
||||
/// canonicalised — including symbolic links / junctions — at load time by <see cref="ResolveWithin"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The admin seams cannot see the driver node's directory, so the authored form carries no directory at all: an
|
||||
/// absolute, rooted, drive-qualified or UNC path is refused there, as is any <c>.</c> / <c>..</c> / empty segment or a
|
||||
/// character outside <c>[A-Za-z0-9._-]</c>. Resolution re-checks the syntax (fail-closed), joins it to the node's
|
||||
/// directory, and requires both the lexical result and the real (link-resolved) result to stay inside the real
|
||||
/// directory.
|
||||
/// </remarks>
|
||||
public static class CredentialFilePaths
|
||||
{
|
||||
private const int MaxLength = 260;
|
||||
|
||||
/// <summary>True when <paramref name="value"/> is blank or an acceptable relative path.</summary>
|
||||
/// <param name="value">The authored value.</param>
|
||||
/// <returns>Whether it may be stored / deployed.</returns>
|
||||
public static bool IsAcceptable(string? value) => string.IsNullOrEmpty(value) || IsAcceptableRelative(value);
|
||||
|
||||
/// <summary>True when <paramref name="value"/> is a non-empty relative path of plain segments.</summary>
|
||||
/// <param name="value">The authored value.</param>
|
||||
/// <returns>Whether it is a relative path the resolver will accept.</returns>
|
||||
public static bool IsAcceptableRelative(string? value)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value) || value.Length > MaxLength) return false;
|
||||
if (value[0] is '/' or '\\') return false;
|
||||
var segments = value.Split('/', '\\');
|
||||
foreach (var seg in segments)
|
||||
{
|
||||
if (seg.Length == 0 || seg is "." or "..") return false;
|
||||
if (!seg.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_' or '.')) return false;
|
||||
}
|
||||
|
||||
return !Path.IsPathRooted(value);
|
||||
}
|
||||
|
||||
/// <summary>The one wording of the rule — names the field and the directory setting, never the value.</summary>
|
||||
/// <param name="field">The field path.</param>
|
||||
/// <param name="directoryDescription">How the directory is configured.</param>
|
||||
/// <returns>The message.</returns>
|
||||
public static string RuleMessage(string field, string directoryDescription) =>
|
||||
$"{field} must be blank or a relative path (e.g. 'plant1/user.pfx') inside the node's certificate directory "
|
||||
+ $"({directoryDescription}) — an absolute, drive or UNC path, a '.'/'..' segment, or a character outside "
|
||||
+ "[A-Za-z0-9._-] is refused (lmxopcua#836).";
|
||||
|
||||
/// <summary>
|
||||
/// Resolves an authored relative path inside <paramref name="directory"/>, fail-closed: throws
|
||||
/// <see cref="CredentialReferenceException"/> when the value is not an acceptable relative path, or when the
|
||||
/// result — lexically or after resolving every symbolic link / junction on the way — leaves the directory.
|
||||
/// </summary>
|
||||
/// <param name="value">The authored relative path.</param>
|
||||
/// <param name="directory">The node's configured directory.</param>
|
||||
/// <param name="field">Field label for messages.</param>
|
||||
/// <param name="directoryDescription">How the directory is configured (for messages).</param>
|
||||
/// <returns>The full path to load (the lexical path inside the directory).</returns>
|
||||
public static string ResolveWithin(string? value, string directory, string field, string directoryDescription)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(directory);
|
||||
if (!IsAcceptableRelative(value))
|
||||
throw new CredentialReferenceException(RuleMessage(field, directoryDescription) + " (fail-closed)");
|
||||
|
||||
var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(directory));
|
||||
var full = Path.GetFullPath(Path.Combine(root, value!));
|
||||
if (!IsUnder(full, root))
|
||||
throw new CredentialReferenceException($"{field} resolves outside the certificate directory (fail-closed).");
|
||||
|
||||
var realRoot = RealPath(root);
|
||||
var realFull = RealPath(full);
|
||||
if (!IsUnder(realFull, realRoot))
|
||||
throw new CredentialReferenceException(
|
||||
$"{field} resolves (through a symbolic link or junction) outside the certificate directory (fail-closed).");
|
||||
return full;
|
||||
}
|
||||
|
||||
private static StringComparison PathComparison =>
|
||||
OperatingSystem.IsWindows() || OperatingSystem.IsMacOS() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
||||
|
||||
private static bool IsUnder(string path, string root)
|
||||
{
|
||||
var prefix = root.EndsWith(Path.DirectorySeparatorChar) ? root : root + Path.DirectorySeparatorChar;
|
||||
return path.StartsWith(prefix, PathComparison);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The path with every existing symbolic link / junction component replaced by its final target, walked from the
|
||||
/// root (a link's target may itself sit under another link). Components that do not exist are kept verbatim.
|
||||
/// </summary>
|
||||
private static string RealPath(string fullPath)
|
||||
{
|
||||
var root = Path.GetPathRoot(fullPath) ?? "";
|
||||
var current = root;
|
||||
var rest = fullPath[root.Length..].Split(
|
||||
[Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar], StringSplitOptions.RemoveEmptyEntries);
|
||||
for (var i = 0; i < rest.Length; i++)
|
||||
{
|
||||
current = Path.Combine(current, rest[i]);
|
||||
FileSystemInfo info = Directory.Exists(current) ? new DirectoryInfo(current) : new FileInfo(current);
|
||||
if (!info.Exists || info.LinkTarget is null) continue;
|
||||
var target = info.ResolveLinkTarget(returnFinalTarget: true);
|
||||
if (target is null) continue;
|
||||
// Re-walk the target itself: its own parents may be links too.
|
||||
current = RealPath(Path.GetFullPath(target.FullName));
|
||||
}
|
||||
|
||||
return current;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user