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:
@@ -11,7 +11,19 @@ public sealed record CredentialField(string Name, CredentialLiteralPolicy Litera
|
||||
/// <param name="DriverType">The <see cref="DriverTypeNames"/> value.</param>
|
||||
/// <param name="Scope">The namespace its references are confined to.</param>
|
||||
/// <param name="Fields">The credential fields its DriverConfig/DeviceConfig may carry.</param>
|
||||
public sealed record DriverCredentialRules(string DriverType, CredentialScope Scope, IReadOnlyList<CredentialField> Fields);
|
||||
/// <param name="PathFields">Fields naming a node-local key-material file, confined to a node directory (lmxopcua#836).</param>
|
||||
public sealed record DriverCredentialRules(
|
||||
string DriverType, CredentialScope Scope, IReadOnlyList<CredentialField> Fields, IReadOnlyList<CredentialPathField>? PathFields = null)
|
||||
{
|
||||
/// <summary>The path fields (never null).</summary>
|
||||
public IReadOnlyList<CredentialPathField> PathFieldList => PathFields ?? [];
|
||||
}
|
||||
|
||||
/// <summary>The identity of one driver instance, as the cross-instance rule (lmxopcua#835) matches it.</summary>
|
||||
/// <param name="DriverInstanceId">The instance id.</param>
|
||||
/// <param name="Name">The instance's display name.</param>
|
||||
/// <param name="DriverType">The instance's driver type.</param>
|
||||
public sealed record DriverInstanceIdentity(string DriverInstanceId, string Name, string DriverType);
|
||||
|
||||
/// <summary>
|
||||
/// The per-driver credential namespaces (lmxopcua#815) — the single table the AdminUI save path, the deploy gate,
|
||||
@@ -39,6 +51,14 @@ public static class DriverCredentialPolicy
|
||||
/// <summary>OPC UA Client user / certificate passwords: <c>secret:opcuaclient/…</c> / <c>env:OTOPCUA_OPCUACLIENT_…</c>.</summary>
|
||||
public static readonly CredentialScope OpcUaClientScope = new("OpcUaClient", ["opcuaclient/"], ["OTOPCUA_OPCUACLIENT_"]);
|
||||
|
||||
/// <summary>The node config key of the OpcUaClient user-certificate directory (lmxopcua#836).</summary>
|
||||
public const string OpcUaClientUserCertificateDirectoryKey = "Drivers:OpcUaClient:UserCertificateDirectory";
|
||||
|
||||
/// <summary>OpcUaClient <c>UserCertificatePath</c>: a relative path inside the node's user-certificate directory (#836).</summary>
|
||||
public static readonly CredentialPathField OpcUaClientUserCertificatePathField = new(
|
||||
"UserCertificatePath",
|
||||
OpcUaClientUserCertificateDirectoryKey + ", default <LocalAppData>/OtOpcUa/pki/user-certificates");
|
||||
|
||||
/// <summary>Galaxy <c>Gateway.ApiKeySecretRef</c> (literal accepted for back-compat, with a warning at resolve).</summary>
|
||||
public static readonly CredentialField GalaxyApiKeyField = new("ApiKeySecretRef", CredentialLiteralPolicy.Allowed);
|
||||
|
||||
@@ -59,7 +79,7 @@ public static class DriverCredentialPolicy
|
||||
[
|
||||
new("Password", CredentialLiteralPolicy.Allowed),
|
||||
new("UserCertificatePassword", CredentialLiteralPolicy.Allowed),
|
||||
]),
|
||||
], [OpcUaClientUserCertificatePathField]),
|
||||
};
|
||||
|
||||
/// <summary>The rules for a driver type, if it resolves credential references.</summary>
|
||||
@@ -110,7 +130,35 @@ public static class DriverCredentialPolicy
|
||||
return problems;
|
||||
}
|
||||
|
||||
private static void Scan(JsonElement element, string path, DriverCredentialRules rules, List<string> problems, int depth)
|
||||
private static void Scan(JsonElement element, string path, DriverCredentialRules rules, List<string> problems, int depth) =>
|
||||
Visit(element, path, rules, depth, (fieldPath, value, field, pathField) =>
|
||||
{
|
||||
if (field is not null)
|
||||
{
|
||||
var ok = value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.Null => true,
|
||||
JsonValueKind.String => CredentialReferences.IsAcceptable(value.GetString(), rules.Scope, field.Literals),
|
||||
_ => false,
|
||||
};
|
||||
if (!ok) problems.Add(CredentialReferences.RuleMessage(fieldPath, rules.Scope, field.Literals));
|
||||
}
|
||||
else if (pathField is not null)
|
||||
{
|
||||
var ok = value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.Null => true,
|
||||
JsonValueKind.String => CredentialFilePaths.IsAcceptable(value.GetString()),
|
||||
_ => false,
|
||||
};
|
||||
if (!ok) problems.Add(CredentialFilePaths.RuleMessage(fieldPath, pathField.DirectoryDescription));
|
||||
}
|
||||
});
|
||||
|
||||
/// <summary>Walks every credential / path field of <paramref name="rules"/> at any depth, keys matched case-insensitively.</summary>
|
||||
private static void Visit(
|
||||
JsonElement element, string path, DriverCredentialRules rules, int depth,
|
||||
Action<string, JsonElement, CredentialField?, CredentialPathField?> onField)
|
||||
{
|
||||
if (depth > 32) return;
|
||||
if (element.ValueKind == JsonValueKind.Array)
|
||||
@@ -118,7 +166,7 @@ public static class DriverCredentialPolicy
|
||||
var i = 0;
|
||||
foreach (var item in element.EnumerateArray())
|
||||
{
|
||||
Scan(item, $"{path}[{i}]", rules, problems, depth + 1);
|
||||
Visit(item, $"{path}[{i}]", rules, depth + 1, onField);
|
||||
i++;
|
||||
}
|
||||
|
||||
@@ -130,19 +178,141 @@ public static class DriverCredentialPolicy
|
||||
{
|
||||
var fieldPath = path.Length == 0 ? p.Name : $"{path}.{p.Name}";
|
||||
var field = rules.Fields.FirstOrDefault(f => string.Equals(f.Name, p.Name, StringComparison.OrdinalIgnoreCase));
|
||||
if (field is null)
|
||||
var pathField = field is null
|
||||
? rules.PathFieldList.FirstOrDefault(f => string.Equals(f.Name, p.Name, StringComparison.OrdinalIgnoreCase))
|
||||
: null;
|
||||
if (field is null && pathField is null)
|
||||
{
|
||||
Scan(p.Value, fieldPath, rules, problems, depth + 1);
|
||||
Visit(p.Value, fieldPath, rules, depth + 1, onField);
|
||||
continue;
|
||||
}
|
||||
|
||||
var ok = p.Value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.Null => true,
|
||||
JsonValueKind.String => CredentialReferences.IsAcceptable(p.Value.GetString(), rules.Scope, field.Literals),
|
||||
_ => false,
|
||||
};
|
||||
if (!ok) problems.Add(CredentialReferences.RuleMessage(fieldPath, rules.Scope, field.Literals));
|
||||
onField(fieldPath, p.Value, field, pathField);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------
|
||||
// lmxopcua#835 — cross-instance references inside one namespace
|
||||
// ---------------------------------------------------------------------------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// The instance-identifying segment of an in-scope <c>secret:</c> reference: the first path segment after the
|
||||
/// matched namespace (<c>secret:galaxy/<X>/apikey</c> ⇒ <c>X</c>; <c>secret:otopcua/galaxy/<X></c> ⇒
|
||||
/// <c>X</c>). Null for anything else — <c>env:</c> references carry no instance convention, and literals and
|
||||
/// out-of-scope references are the #815 rule's business.
|
||||
/// </summary>
|
||||
/// <param name="value">The authored field value.</param>
|
||||
/// <param name="scope">The driver's scope.</param>
|
||||
/// <returns>The segment, or null.</returns>
|
||||
public static string? InstanceSegment(string? value, CredentialScope scope)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(scope);
|
||||
if (CredentialReferences.Parse(value, scope, out var name) != CredentialReferenceKind.Secret) return null;
|
||||
var ns = scope.SecretNamespaces
|
||||
.Where(n => name.StartsWith(n, StringComparison.Ordinal))
|
||||
.OrderByDescending(n => n.Length)
|
||||
.FirstOrDefault();
|
||||
if (ns is null) return null;
|
||||
var rest = name[ns.Length..];
|
||||
var slash = rest.IndexOf('/');
|
||||
return slash < 0 ? rest : rest[..slash];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when the config carries at least one in-scope <c>secret:</c> reference — i.e. the cross-instance rule
|
||||
/// (<see cref="DescribeOtherInstanceProblems"/>) has something to check, so a seam must load the instance list.
|
||||
/// Lets seams skip the ConfigDb read otherwise.
|
||||
/// </summary>
|
||||
/// <param name="driverType">The owning driver's type.</param>
|
||||
/// <param name="json">The config JSON.</param>
|
||||
/// <returns>Whether any instance segment is present.</returns>
|
||||
public static bool HasInstanceSegments(string? driverType, string? json) =>
|
||||
CollectSegments(driverType, json).Count > 0;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#835: inside one namespace, a reference whose instance-identifying segment (see
|
||||
/// <see cref="InstanceSegment"/>) names a DIFFERENT existing instance of the same driver type — by its
|
||||
/// <see cref="DriverInstanceIdentity.DriverInstanceId"/> or its <see cref="DriverInstanceIdentity.Name"/>,
|
||||
/// case-insensitively — is refused: otherwise a Designer could create (or Test Connect / browse) a driver that
|
||||
/// points at their own endpoint with <c>secret:galaxy/<other-instance>/apikey</c> and capture that
|
||||
/// instance's key. Shared names that are no other instance's id or name (<c>secret:galaxy/gw/apikey</c>,
|
||||
/// <c>secret:galaxy/apikey</c>) stay valid, as does a reference naming the instance itself.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A match against ANOTHER instance wins over a match against the owner — names are not unique, and renaming
|
||||
/// one's own driver after a victim's must not unlock the victim's secret. <paramref name="ownDriverInstanceId"/>
|
||||
/// is null for a driver that does not exist yet (every listed instance is then "another").
|
||||
/// </remarks>
|
||||
/// <param name="driverType">The owning driver's type.</param>
|
||||
/// <param name="json">The DriverConfig / DeviceConfig / merged config JSON.</param>
|
||||
/// <param name="ownDriverInstanceId">The driver the config belongs to; null when it is being created.</param>
|
||||
/// <param name="instances">The known driver instances (any type; the owner may be included).</param>
|
||||
/// <returns>The problems; empty when acceptable, unreadable, or the type has no rules.</returns>
|
||||
public static IReadOnlyList<string> DescribeOtherInstanceProblems(
|
||||
string? driverType, string? json, string? ownDriverInstanceId, IEnumerable<DriverInstanceIdentity> instances)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(instances);
|
||||
var problems = new List<string>();
|
||||
if (!TryGet(driverType, out var rules)) return problems;
|
||||
var segments = CollectSegments(driverType, json);
|
||||
if (segments.Count == 0) return problems;
|
||||
|
||||
var others = instances
|
||||
.Where(i => string.Equals(i.DriverType, rules.DriverType, StringComparison.OrdinalIgnoreCase)
|
||||
&& !string.Equals(i.DriverInstanceId, ownDriverInstanceId, StringComparison.Ordinal))
|
||||
.ToList();
|
||||
foreach (var (fieldPath, segment) in segments)
|
||||
{
|
||||
var other = others.FirstOrDefault(o =>
|
||||
string.Equals(o.DriverInstanceId, segment, StringComparison.OrdinalIgnoreCase)
|
||||
|| string.Equals(o.Name, segment, StringComparison.OrdinalIgnoreCase));
|
||||
if (other is null) continue;
|
||||
problems.Add(
|
||||
$"{fieldPath} names a secret under '{segment}/', which is another {rules.Scope.Label} driver instance "
|
||||
+ $"('{other.Name}', {other.DriverInstanceId}) — a driver may reference only its own secrets "
|
||||
+ $"(secret:{rules.Scope.SecretNamespaces[0]}<this-driver-id>/…) or a shared name that is no other "
|
||||
+ "instance's id or name (lmxopcua#835).");
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Both rules at once — <see cref="DescribeProblems(string?, string?)"/> (namespace, literals, path fields) followed
|
||||
/// by <see cref="DescribeOtherInstanceProblems"/> — as every seam that knows the owner and the instance list applies them.
|
||||
/// </summary>
|
||||
/// <param name="driverType">The owning driver's type.</param>
|
||||
/// <param name="json">The config JSON.</param>
|
||||
/// <param name="ownDriverInstanceId">The owning driver; null when it is being created.</param>
|
||||
/// <param name="instances">The known driver instances.</param>
|
||||
/// <returns>The problems.</returns>
|
||||
public static IReadOnlyList<string> DescribeProblems(
|
||||
string? driverType, string? json, string? ownDriverInstanceId, IEnumerable<DriverInstanceIdentity> instances) =>
|
||||
[.. DescribeProblems(driverType, json), .. DescribeOtherInstanceProblems(driverType, json, ownDriverInstanceId, instances)];
|
||||
|
||||
private static List<(string FieldPath, string Segment)> CollectSegments(string? driverType, string? json)
|
||||
{
|
||||
var found = new List<(string, string)>();
|
||||
if (!TryGet(driverType, out var rules) || string.IsNullOrWhiteSpace(json)) return found;
|
||||
JsonDocument doc;
|
||||
try
|
||||
{
|
||||
doc = JsonDocument.Parse(json, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return found; // DescribeProblems reports unreadable JSON.
|
||||
}
|
||||
|
||||
using (doc)
|
||||
{
|
||||
Visit(doc.RootElement, "", rules, 0, (fieldPath, value, field, _) =>
|
||||
{
|
||||
if (field is null || value.ValueKind != JsonValueKind.String) return;
|
||||
if (InstanceSegment(value.GetString(), rules.Scope) is { Length: > 0 } segment) found.Add((fieldPath, segment));
|
||||
});
|
||||
}
|
||||
|
||||
return found;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user