using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text.Json; using Grpc.Core; using Grpc.Net.Client; using GrpcDataProbe; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; var failurePhase = ProbeFailurePhase.WireSetup; string? failureTarget = null; string? failureOutput = null; var results = new List(); try { var arguments = args.Chunk(2).ToDictionary(pair => pair[0], pair => pair.Length == 2 ? pair[1] : throw new ArgumentException()); failureOutput = arguments.GetValueOrDefault("--output"); var manifestPath = Path.GetFullPath(arguments["--manifest"]); Restricted(manifestPath); using var manifest = JsonDocument.Parse(await File.ReadAllTextAsync(manifestPath)); var root = manifest.RootElement; var scenario = arguments.GetValueOrDefault("--scenario", "all"); if (scenario is not ("all" or "D13" or "wire")) throw new ArgumentException("Unsupported wire scenario."); var nodes = root.GetProperty("nodes"); var endpoints = root.GetProperty("endpoints"); var keyPath = root.GetProperty("credentials").GetProperty("data_key_files").GetProperty("source").GetString()!; Restricted(keyPath); var key = (await File.ReadAllTextAsync(keyPath)).Trim(); var caPath = root.GetProperty("tls").GetProperty("ca_file").GetString()!; using var ca = X509Certificate2.CreateFromPem(File.ReadAllText(caPath)); var sourceNodes = nodes.EnumerateObject().Where(item => item.Value.GetProperty("cluster_id").GetString() == "SOURCE").ToArray(); if (sourceNodes.Length != 2) throw new InvalidOperationException(); var routes = sourceNodes.ToDictionary(item => item.Name, item => endpoints.GetProperty(item.Name + ".data").GetProperty("host_port").GetInt32()); foreach (var port in routes.Values) if (port is < 1 or > 65535) throw new InvalidOperationException(); using var security = new ProbeSecurity(routes, ca, key); if (scenario is "all" or "D13") { foreach (var node in sourceNodes) { var name = node.Name; failureTarget = name is "source-1" or "source-2" ? name : null; var nodeId = node.Value.GetProperty("node_id").GetString()!; async Task Reject(string id, string credential, bool correctCa, bool correctName, bool useUi = false, bool plainData = false) { failurePhase = id switch { "bad-key" => ProbeFailurePhase.WireBadKey, "wrong-ca" => ProbeFailurePhase.WireWrongCa, "wrong-san" => ProbeFailurePhase.WireWrongSan, "wrong-listener" => ProbeFailurePhase.WireWrongListener, "h2c-data-listener" => ProbeFailurePhase.WireH2c, _ => ProbeFailurePhase.Other }; using var handler = security.Handler(name, correctCa, correctName, useUi ? endpoints.GetProperty(name + ".admin").GetProperty("host_port").GetInt32() : null); using var channel = GrpcChannel.ForAddress($"{(useUi || plainData ? "http" : "https")}://{name}:{(useUi ? 9000 : 4057)}", new() { HttpHandler = handler }); var client = new W.DataConnectionService.DataConnectionServiceClient(channel); var headers = Headers(credential, "Node", nodeId); var denied = false; try { await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, headers, DateTime.UtcNow.AddSeconds(5)); } catch (RpcException error) when (error.StatusCode is StatusCode.Unauthenticated or StatusCode.PermissionDenied or StatusCode.Unavailable or StatusCode.Unimplemented or StatusCode.Internal) { denied = true; } results.Add(new(id + "-" + name, "wire-rejection", denied, 1, new() { ["target"] = nodeId, ["rejected"] = denied })); } // Each negative changes only one admission input after a positive TLS call. using (var handler = security.Handler(name)) using (var channel = GrpcChannel.ForAddress($"https://{name}:4057", new() { HttpHandler = handler })) { failurePhase = ProbeFailurePhase.WirePositiveCapabilities; var client = new W.DataConnectionService.DataConnectionServiceClient(channel); var caps = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, Headers(key, "Node", nodeId), DateTime.UtcNow.AddSeconds(5)); var valid = caps.ProtocolMajor == 1 && caps.ClusterId == "SOURCE" && caps.Serving.NodeId == nodeId; results.Add(new("positive-" + name, "wire-capabilities", valid, 3, new() { ["serving"] = caps.Serving.ToString() })); var incompatible = false; failurePhase = ProbeFailurePhase.WireProtocolMajor; try { await client.GetCapabilitiesAsync(new() { ProtocolMajor = 99 }, Headers(key, "Node", nodeId), DateTime.UtcNow.AddSeconds(5)); } catch (RpcException error) when (error.StatusCode == StatusCode.Unimplemented) { incompatible = true; } results.Add(new("protocol-major-" + name, "wire-negotiation", incompatible, 1, new() { ["rejectedIncompatibleMajor"] = incompatible })); if (arguments.TryGetValue("--previous-key-state", out var previousState)) { failurePhase = ProbeFailurePhase.WirePreviousKey; if (previousState is not ("enabled" or "revoked")) throw new ArgumentException(); var previousPath = Path.Combine(Path.GetDirectoryName(keyPath)!, "source-previous.key"); Restricted(previousPath); var previousKey = (await File.ReadAllTextAsync(previousPath)).Trim(); var accepted = false; var explicitlyDenied = false; try { var oldCaps = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, Headers(previousKey, "Node", nodeId), DateTime.UtcNow.AddSeconds(5)); accepted = oldCaps.Serving.NodeId == nodeId; } catch (RpcException error) when (error.StatusCode is StatusCode.Unauthenticated or StatusCode.PermissionDenied) { explicitlyDenied = true; } results.Add(new("previous-key-" + name, "wire-credential-rotation", previousState == "enabled" ? accepted : explicitlyDenied, 1, new() { ["expectedState"] = previousState, ["accepted"] = accepted, ["explicitlyDenied"] = explicitlyDenied })); } } await Reject("bad-key", "invalid-presented-key", true, true); await Reject("wrong-ca", key, false, true); await Reject("wrong-san", key, true, false); await Reject("wrong-listener", key, true, true, useUi: true); await Reject("h2c-data-listener", key, true, true, plainData: true); if (root.GetProperty("tls").TryGetProperty("rotation", out var rotation) && rotation.GetString() == "retired") { failurePhase = ProbeFailurePhase.WireRetiredCa; using var oldCa = X509Certificate2.CreateFromPem(File.ReadAllText(Path.Combine(Path.GetDirectoryName(caPath)!, "ca-original.pem"))); using var oldSecurity = new ProbeSecurity(routes, oldCa, key); using var handler = oldSecurity.Handler(name); using var channel = GrpcChannel.ForAddress($"https://{name}:4057", new() { HttpHandler = handler }); var rejected = false; ProbeFailureEvidence? tlsRejection = null; try { await new W.DataConnectionService.DataConnectionServiceClient(channel).GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, Headers(key, "Node", nodeId), DateTime.UtcNow.AddSeconds(5)); } catch (RpcException error) when (ProbeFailureClassifier.IsRetiredCaTlsRejection( ProbeFailureClassifier.Capture(error, ProbeFailurePhase.WireRetiredCa))) { rejected = true; tlsRejection = ProbeFailureClassifier.Capture(error, ProbeFailurePhase.WireRetiredCa); } results.Add(new("retired-ca-" + name, "wire-trust-retirement", rejected, 1, new() { ["oldCaRejected"] = rejected, ["failureEvidence"] = tlsRejection })); } } } if (scenario != "D13") { var fixture = root.GetProperty("fixture"); var rawUri = fixture.GetProperty("namespace_uris").GetProperty("raw").GetString()!; var unsUri = fixture.GetProperty("namespace_uris").GetProperty("uns").GetString()!; foreach (var mode in new[] { DataTargetMode.Node, DataTargetMode.Cluster }) { foreach (var source in mode == DataTargetMode.Node ? sourceNodes : sourceNodes.Take(1)) { failurePhase = ProbeFailurePhase.WireOperation; failureTarget = source.Name is "source-1" or "source-2" ? source.Name : null; var target = new DataTarget(mode, "SOURCE", mode == DataTargetMode.Node ? source.Value.GetProperty("node_id").GetString() : null, mode == DataTargetMode.Node ? DataConsistency.ReadyReplica : DataConsistency.Primary); using var scope = new DataConnectionScopeLease(1, CancellationToken.None, () => { }); await using var connection = new GrpcDataConnection("wire-probe", target, (mode == DataTargetMode.Node ? [source] : sourceNodes).Select(item => new Uri($"https://{item.Name}:4057")), security, scope, 1024 * 1024, 2, eligibleNodeIds: sourceNodes.Select(item => item.Value.GetProperty("node_id").GetString()!).ToHashSet()); foreach (var realm in new[] { "raw", "uns" }) { var path = fixture.GetProperty("origin_paths").GetProperty(realm).GetString()!; foreach (var operation in new[] { "capabilities", "metadata", "read", "browse" }) { var command = new ProbeCommand($"{mode}-{source.Name}-{realm}-{operation}", "wire-probe", operation, realm, "SOURCE", realm == "raw" ? rawUri : unsUri, operation == "browse" ? fixture.GetProperty("browse_roots").GetProperty(realm).GetString()! : path, ExpectedNodeId: mode == DataTargetMode.Node ? source.Value.GetProperty("node_id").GetString() : null); results.Add(await ProbeEngine.RunAsync(connection, command, CancellationToken.None)); } } } } } var output = JsonSerializer.Serialize(new { schemaVersion = 1, scenario, passed = results.Count > 0 && results.All(result => result.Passed && result.Assertions > 0), results }, ProbeEngine.Json); if (arguments.TryGetValue("--output", out var outputPath)) { await File.WriteAllTextAsync(outputPath, output); if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(outputPath, UnixFileMode.UserRead | UnixFileMode.UserWrite); } Console.WriteLine(output); return results.Count > 0 && results.All(result => result.Passed && result.Assertions > 0) ? 0 : 1; } catch (Exception error) when (error is not OutOfMemoryException) { var failure = ProbeFailureClassifier.Capture(error, failurePhase); var output = JsonSerializer.Serialize(new { passed = false, failure = failure.Category, failurePhase = failure.Phase, targetNode = failureTarget, failureEvidence = failure, results = results.Take(128).ToArray(), partialResultsTruncated = results.Count > 128 }, ProbeEngine.Json); if (failureOutput is not null && Path.IsPathFullyQualified(failureOutput)) { try { if (new FileInfo(failureOutput).LinkTarget is null) { await File.WriteAllTextAsync(failureOutput, output); if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(failureOutput, UnixFileMode.UserRead | UnixFileMode.UserWrite); } } catch (Exception) { /* Preserve the original wire failure and exit status. */ } } Console.Error.WriteLine(output); return 2; } static void Restricted(string path) { var file = new FileInfo(path); if (!file.Exists || file.LinkTarget is not null || !Path.IsPathFullyQualified(path) || file.Length > 1024 * 1024) throw new InvalidOperationException(); if (!OperatingSystem.IsWindows() && (File.GetUnixFileMode(path) & (UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherWrite | UnixFileMode.OtherExecute)) != 0) throw new InvalidOperationException(); } static Metadata Headers(string key, string mode, string nodeId) => new() { { "authorization", "Bearer " + key }, { "x-data-target-mode", mode }, { "x-data-cluster-id", "SOURCE" }, { "x-data-node-id", nodeId }, { "x-data-consistency", "ReadyReplica" } }; sealed class ProbeSecurity(Dictionary routes, X509Certificate2 root, string key) : IDataConnectionSecurityProvider, IDisposable { private readonly X509Certificate2 _untrustedRoot = UntrustedRoot(); private static X509Certificate2 UntrustedRoot() { using var signingKey = ECDsa.Create(ECCurve.NamedCurves.nistP256); var request = new CertificateRequest("CN=unrelated-grpc-data-probe-ca", signingKey, HashAlgorithmName.SHA256); request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); return request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-1), DateTimeOffset.UtcNow.AddHours(1)); } public void Dispose() => _untrustedRoot.Dispose(); public event Action? Changed { add { } remove { } } public ValueTask ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) => ValueTask.FromResult(new("fixture-key-v1", Convert.ToHexString(SHA256.HashData(root.RawData)), key, () => Handler(endpoint.Host))); public HttpMessageHandler Handler(string host, bool correctCa = true, bool correctName = true, int? overridePort = null) { if (!routes.TryGetValue(host, out var port)) throw new InvalidOperationException(); return new SocketsHttpHandler { UseProxy = false, ConnectTimeout = TimeSpan.FromSeconds(5), ConnectCallback = async (_, token) => { var socket = new Socket(SocketType.Stream, ProtocolType.Tcp); try { await socket.ConnectAsync(IPAddress.Loopback, overridePort ?? port, token); return new NetworkStream(socket, ownsSocket: true); } catch { socket.Dispose(); throw; } }, SslOptions = new SslClientAuthenticationOptions { EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13, RemoteCertificateValidationCallback = (_, certificate, _, _) => { if (certificate is null) return false; using var leaf = X509CertificateLoader.LoadCertificate(certificate.GetRawCertData()); if (!leaf.MatchesHostname(correctName ? host : "wrong-san.grpc-data.invalid", allowWildcards: false, allowCommonName: false)) return false; using var chain = new X509Chain(); chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; chain.ChainPolicy.CustomTrustStore.Add(correctCa ? root : _untrustedRoot); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.1")); return chain.Build(leaf); } } }; } }