mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-20 00:31:32 +08:00
e8afa4237b
Addresses 25 of 39 findings from a branch security review (assessment 5). CRITICAL: F1 gate MCP key-disclosure tools, F2 0600 keylog/pcap files, F3 per-user BaseFolder, F16 ChannelKeyMaterial IDisposable + ZeroMemory, F17 PcapFileReader MaxPacketBytes (64MB) bound, F18 FlowBuffer MaxBufferBytes (256MB) cap, F19 NodeSet export path validation, F20 ReplaySession listenPort range. HIGH: F4 IPcapAuditSink + LoggerPcapAuditSink + rate-limited frame-capture audit, F5 AES-256-GCM EncryptedKeyLogStream + SessionKeyManager (sibling .key file 0600), F14 IKeyEscrowProvider abstraction + DiskKeyEscrowProvider default (DI TryAddSingleton so consumers can route to KMS), F21 ChannelManagerOptions.MaxChannels (256) cap, F22 CaptureSessionManager.SessionFolder path-traversal guard, F23 PacketDecodeTools pcapPath/keyLogPath validation, F24 replay_pcap speed validation (NaN/Inf/<=0), F25 explicit permissions blocks on .github/workflows. MEDIUM: F6 OnTokenActivated [EditorBrowsable(Never)] + key-disclosure doc, F7 IDiagnosticsChannelMutation accessor + stack-walk caller guard (replaces internal OfflineLoadTokens), F8 PcapOptions.AllowMockClientReplay + AllowedReplayEndpoints, F9 PcapFileWriter / UaKeyLog*Writer rotation (.NNN suffix) with MaxBytes / MaxArtifactsPerSession, F13 keylog-isolation gap acknowledgment doc, F15 HashChainedAuditFileSink (HMAC-chained JSONL ledger, VerifyChain), F11 replay URL scheme allow-list (opc.tcp/opc.tcps/opc.https). LOW/INFO: F10 SBOM/CVE governance comments on PacketDotNet/SharpPcap + Docs/PacketCapture.md, F12 Security model section at top of PacketCapture.md. Tests: 100+ new NUnit tests across Audit/, Capture/, Frame/, KeyLog/, McpServerTools/, Replay/, Stack/Tcp/, DependencyInjection/. All file-mode/HMAC-chain/encryption tests are [Platform(Linux,MacOSX)]-gated where Unix-specific. Build: 0 warnings / 0 errors on Stack/Opc.Ua.Bindings.Pcap for net8.0 and net9.0. net10.0 build is environmentally blocked by a corrupted local SDK 10.0.300 workload manifest (microsoft.net.workload.mono.toolchain.net6 10.0.108 requires Emscripten.net6 >=10.0.108, only 9.0.17 installed); requires 'dotnet workload repair' from an elevated shell to validate the third TFM. No tests were run pending the SDK fix. 5 CA1508/CA2000 false positives suppressed with documented #pragma blocks (ownership transfer in escrow factory / IAsyncEnumerable iterator / unreachable catch path). Deferred to follow-up GitHub issues: 9 MEDIUM (M-SEC-07/09/10/11/12/13/16/22/31 — exception sanitization, reconnect defaults, cert-rotation races, nonce-suppress deprecation, parser hardening) and 10 LOW/INFO (L-SEC-14/15/17/23/24/33/34/35/36/37 — handler cleanup, EventSource endpoint masking, key-log schema validation, EOL deps, SAST). Full reasoning in session plan.md Round 10.
413 lines
15 KiB
C#
413 lines
15 KiB
C#
/* ========================================================================
|
|
* Copyright (c) 2005-2026 The OPC Foundation, Inc. All rights reserved.
|
|
*
|
|
* OPC Foundation MIT License 1.00
|
|
*
|
|
* Permission is hereby granted, free of charge, to any person
|
|
* obtaining a copy of this software and associated documentation
|
|
* files (the "Software"), to deal in the Software without
|
|
* restriction, including without limitation the rights to use,
|
|
* copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
* copies of the Software, and to permit persons to whom the
|
|
* Software is furnished to do so, subject to the following
|
|
* conditions:
|
|
*
|
|
* The above copyright notice and this permission notice shall be
|
|
* included in all copies or substantial portions of the Software.
|
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
|
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
|
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
|
* OTHER DEALINGS IN THE SOFTWARE.
|
|
*
|
|
* The complete license agreement can be found here:
|
|
* http://opcfoundation.org/License/MIT/1.00/
|
|
* ======================================================================*/
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Opc.Ua.Bindings.Pcap.Capture;
|
|
|
|
namespace Opc.Ua.Bindings.Pcap.KeyLog
|
|
{
|
|
/// <summary>
|
|
/// Writes OPC UA channel key material as JSON-lines records.
|
|
/// </summary>
|
|
public sealed class UaKeyLogJsonWriter : IKeyLogWriter
|
|
{
|
|
/// <summary>
|
|
/// Default maximum bytes per keylog file.
|
|
/// </summary>
|
|
public const long DefaultMaxBytesPerKeylog = 8L * 1024 * 1024;
|
|
|
|
/// <summary>
|
|
/// Default maximum number of retained artifacts per session.
|
|
/// </summary>
|
|
public const int DefaultMaxArtifactsPerSession = 16;
|
|
|
|
/// <summary>
|
|
/// Constructs a JSON-lines key-log writer for the supplied file.
|
|
/// </summary>
|
|
public UaKeyLogJsonWriter(string filePath)
|
|
: this(filePath, sessionKey: null, DefaultMaxBytesPerKeylog, DefaultMaxArtifactsPerSession)
|
|
{
|
|
}
|
|
|
|
/// <summary>
|
|
/// Constructs a JSON-lines key-log writer for the supplied file.
|
|
/// </summary>
|
|
public UaKeyLogJsonWriter(string filePath, byte[]? sessionKey)
|
|
: this(filePath, sessionKey, DefaultMaxBytesPerKeylog, DefaultMaxArtifactsPerSession)
|
|
{
|
|
}
|
|
|
|
/// <summary>
|
|
/// Constructs a JSON-lines key-log writer for the supplied file.
|
|
/// </summary>
|
|
public UaKeyLogJsonWriter(string filePath, long maxBytes, int maxArtifacts)
|
|
: this(filePath, sessionKey: null, maxBytes, maxArtifacts)
|
|
{
|
|
}
|
|
|
|
/// <summary>
|
|
/// Constructs a JSON-lines key-log writer for the supplied file.
|
|
/// </summary>
|
|
public UaKeyLogJsonWriter(string filePath, byte[]? sessionKey, long maxBytes, int maxArtifacts)
|
|
{
|
|
ArgumentException.ThrowIfNullOrWhiteSpace(filePath);
|
|
ArgumentOutOfRangeException.ThrowIfNegative(maxBytes);
|
|
ArgumentOutOfRangeException.ThrowIfNegative(maxArtifacts);
|
|
|
|
FilePath = filePath;
|
|
m_maxBytes = maxBytes;
|
|
m_maxArtifacts = maxArtifacts;
|
|
m_sessionKey = sessionKey is null ? null : (byte[])sessionKey.Clone();
|
|
OpenCurrentFile(FileMode.OpenOrCreate);
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
public string FilePath { get; }
|
|
|
|
/// <inheritdoc/>
|
|
public async ValueTask AppendAsync(ChannelKeyMaterial material, CancellationToken ct)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(material);
|
|
await m_gate.WaitAsync(ct).ConfigureAwait(false);
|
|
try
|
|
{
|
|
string json = JsonSerializer.Serialize(
|
|
KeyLogRecord.From(material),
|
|
UaKeyLogJsonContext.Default.KeyLogRecord);
|
|
await m_writer.WriteLineAsync(json.AsMemory(), ct).ConfigureAwait(false);
|
|
await m_writer.FlushAsync(ct).ConfigureAwait(false);
|
|
await m_stream.FlushAsync(ct).ConfigureAwait(false);
|
|
m_bytesWritten = m_fileStream.Length;
|
|
if (m_bytesWritten >= m_maxBytes && m_maxBytes > 0)
|
|
{
|
|
await RotateAsync(ct).ConfigureAwait(false);
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
m_gate.Release();
|
|
}
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
public async ValueTask FlushAsync(CancellationToken ct)
|
|
{
|
|
await m_gate.WaitAsync(ct).ConfigureAwait(false);
|
|
try
|
|
{
|
|
await FlushCoreAsync(ct).ConfigureAwait(false);
|
|
}
|
|
finally
|
|
{
|
|
m_gate.Release();
|
|
}
|
|
}
|
|
|
|
/// <inheritdoc/>
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
if (m_disposed)
|
|
{
|
|
return;
|
|
}
|
|
|
|
await m_gate.WaitAsync(CancellationToken.None).ConfigureAwait(false);
|
|
try
|
|
{
|
|
if (m_disposed)
|
|
{
|
|
return;
|
|
}
|
|
|
|
await FlushCoreAsync(CancellationToken.None).ConfigureAwait(false);
|
|
m_disposed = true;
|
|
await m_writer.DisposeAsync().ConfigureAwait(false);
|
|
await m_stream.DisposeAsync().ConfigureAwait(false);
|
|
await m_fileStream.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
finally
|
|
{
|
|
m_gate.Release();
|
|
m_gate.Dispose();
|
|
}
|
|
}
|
|
|
|
private void OpenCurrentFile(FileMode fileMode)
|
|
{
|
|
string currentPath = GetCurrentFilePath();
|
|
m_fileStream = new FileStream(
|
|
currentPath,
|
|
fileMode,
|
|
FileAccess.Write,
|
|
FileShare.Read,
|
|
bufferSize: 4096,
|
|
FileOptions.Asynchronous | FileOptions.SequentialScan);
|
|
if (!OperatingSystem.IsWindows())
|
|
{
|
|
File.SetUnixFileMode(currentPath, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
|
}
|
|
|
|
m_fileStream.Seek(0, SeekOrigin.End);
|
|
m_bytesWritten = m_fileStream.Length;
|
|
m_stream = m_sessionKey is null
|
|
? m_fileStream
|
|
: new EncryptedKeyLogStream(m_fileStream, m_sessionKey, leaveOpen: false);
|
|
m_writer = new StreamWriter(m_stream, Encoding.UTF8, bufferSize: 1024, leaveOpen: true);
|
|
}
|
|
|
|
private async ValueTask FlushCoreAsync(CancellationToken ct)
|
|
{
|
|
await m_writer.FlushAsync(ct).ConfigureAwait(false);
|
|
await m_stream.FlushAsync(ct).ConfigureAwait(false);
|
|
}
|
|
|
|
private async ValueTask RotateAsync(CancellationToken ct)
|
|
{
|
|
await FlushCoreAsync(ct).ConfigureAwait(false);
|
|
await m_writer.DisposeAsync().ConfigureAwait(false);
|
|
await m_stream.DisposeAsync().ConfigureAwait(false);
|
|
await m_fileStream.DisposeAsync().ConfigureAwait(false);
|
|
m_currentSuffix++;
|
|
OpenCurrentFile(FileMode.Create);
|
|
PruneArtifacts();
|
|
}
|
|
|
|
private void PruneArtifacts()
|
|
{
|
|
if (m_maxArtifacts == 0)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var artifacts = new List<ArtifactFile>();
|
|
if (File.Exists(FilePath))
|
|
{
|
|
artifacts.Add(new ArtifactFile(0, FilePath));
|
|
}
|
|
|
|
string? directory = Path.GetDirectoryName(FilePath);
|
|
string searchDirectory = string.IsNullOrEmpty(directory) ? "." : directory;
|
|
string baseName = Path.GetFileNameWithoutExtension(FilePath);
|
|
string extension = Path.GetExtension(FilePath);
|
|
foreach (string filePath in Directory.GetFiles(searchDirectory, baseName + ".*" + extension))
|
|
{
|
|
if (TryGetSuffix(filePath, out int suffix))
|
|
{
|
|
artifacts.Add(new ArtifactFile(suffix, filePath));
|
|
}
|
|
}
|
|
|
|
artifacts.Sort(static (left, right) => right.Suffix.CompareTo(left.Suffix));
|
|
int retainedArtifacts = 0;
|
|
foreach (ArtifactFile artifact in artifacts)
|
|
{
|
|
if (artifact.Suffix == m_currentSuffix)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
retainedArtifacts++;
|
|
if (retainedArtifacts >= m_maxArtifacts)
|
|
{
|
|
File.Delete(artifact.FilePath);
|
|
}
|
|
}
|
|
}
|
|
|
|
private bool TryGetSuffix(string filePath, out int suffix)
|
|
{
|
|
suffix = 0;
|
|
string fileName = Path.GetFileName(filePath);
|
|
string baseName = Path.GetFileNameWithoutExtension(FilePath);
|
|
string extension = Path.GetExtension(FilePath);
|
|
if (!fileName.StartsWith(baseName + ".", StringComparison.Ordinal) ||
|
|
!fileName.EndsWith(extension, StringComparison.Ordinal))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
string suffixText = fileName.Substring(
|
|
baseName.Length + 1,
|
|
fileName.Length - baseName.Length - extension.Length - 1);
|
|
return int.TryParse(suffixText, out suffix);
|
|
}
|
|
|
|
private string GetCurrentFilePath()
|
|
{
|
|
if (m_currentSuffix == 0)
|
|
{
|
|
return FilePath;
|
|
}
|
|
|
|
string? directory = Path.GetDirectoryName(FilePath);
|
|
string fileName = Path.GetFileNameWithoutExtension(FilePath);
|
|
string extension = Path.GetExtension(FilePath);
|
|
string suffix = m_currentSuffix.ToString("000", System.Globalization.CultureInfo.InvariantCulture);
|
|
return Path.Combine(string.IsNullOrEmpty(directory) ? "." : directory, fileName + "." + suffix + extension);
|
|
}
|
|
|
|
private readonly struct ArtifactFile
|
|
{
|
|
public ArtifactFile(int suffix, string filePath)
|
|
{
|
|
Suffix = suffix;
|
|
FilePath = filePath;
|
|
}
|
|
|
|
public int Suffix { get; }
|
|
|
|
public string FilePath { get; }
|
|
}
|
|
|
|
private FileStream m_fileStream = null!;
|
|
private Stream m_stream = null!;
|
|
private StreamWriter m_writer = null!;
|
|
private readonly SemaphoreSlim m_gate = new(1, 1);
|
|
private readonly byte[]? m_sessionKey;
|
|
private readonly long m_maxBytes;
|
|
private readonly int m_maxArtifacts;
|
|
private int m_currentSuffix;
|
|
private long m_bytesWritten;
|
|
private bool m_disposed;
|
|
}
|
|
|
|
[JsonSourceGenerationOptions(
|
|
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
|
GenerationMode = JsonSourceGenerationMode.Metadata)]
|
|
[JsonSerializable(typeof(KeyLogRecord))]
|
|
internal sealed partial class UaKeyLogJsonContext : JsonSerializerContext;
|
|
|
|
internal sealed class KeyLogRecord
|
|
{
|
|
[JsonPropertyName("channelId")]
|
|
public uint ChannelId { get; init; }
|
|
|
|
[JsonPropertyName("tokenId")]
|
|
public uint TokenId { get; init; }
|
|
|
|
[JsonPropertyName("securityPolicyUri")]
|
|
public string SecurityPolicyUri { get; init; } = string.Empty;
|
|
|
|
[JsonPropertyName("securityMode")]
|
|
public string SecurityMode { get; init; } = nameof(MessageSecurityMode.None);
|
|
|
|
[JsonPropertyName("createdAt")]
|
|
public DateTimeOffset CreatedAt { get; init; }
|
|
|
|
[JsonPropertyName("lifetimeMs")]
|
|
public int LifetimeMs { get; init; }
|
|
|
|
[JsonPropertyName("clientNonce")]
|
|
public string? ClientNonce { get; init; }
|
|
|
|
[JsonPropertyName("serverNonce")]
|
|
public string? ServerNonce { get; init; }
|
|
|
|
[JsonPropertyName("clientSigningKey")]
|
|
public string? ClientSigningKey { get; init; }
|
|
|
|
[JsonPropertyName("clientEncryptingKey")]
|
|
public string? ClientEncryptingKey { get; init; }
|
|
|
|
[JsonPropertyName("clientInitializationVector")]
|
|
public string? ClientInitializationVector { get; init; }
|
|
|
|
[JsonPropertyName("serverSigningKey")]
|
|
public string? ServerSigningKey { get; init; }
|
|
|
|
[JsonPropertyName("serverEncryptingKey")]
|
|
public string? ServerEncryptingKey { get; init; }
|
|
|
|
[JsonPropertyName("serverInitializationVector")]
|
|
public string? ServerInitializationVector { get; init; }
|
|
|
|
public static KeyLogRecord From(ChannelKeyMaterial material)
|
|
{
|
|
return new KeyLogRecord
|
|
{
|
|
ChannelId = material.ChannelId,
|
|
TokenId = material.TokenId,
|
|
SecurityPolicyUri = material.SecurityPolicyUri,
|
|
SecurityMode = material.SecurityMode.ToString(),
|
|
CreatedAt = new DateTimeOffset(DateTime.SpecifyKind(material.CreatedAt, DateTimeKind.Utc)),
|
|
LifetimeMs = material.Lifetime,
|
|
ClientNonce = ToBase64(material.ClientNonce),
|
|
ServerNonce = ToBase64(material.ServerNonce),
|
|
ClientSigningKey = ToBase64(material.ClientSigningKey),
|
|
ClientEncryptingKey = ToBase64(material.ClientEncryptingKey),
|
|
ClientInitializationVector = ToBase64(material.ClientInitializationVector),
|
|
ServerSigningKey = ToBase64(material.ServerSigningKey),
|
|
ServerEncryptingKey = ToBase64(material.ServerEncryptingKey),
|
|
ServerInitializationVector = ToBase64(material.ServerInitializationVector)
|
|
};
|
|
}
|
|
|
|
public ChannelKeyMaterial ToMaterial()
|
|
{
|
|
if (!Enum.TryParse(SecurityMode, ignoreCase: false, out MessageSecurityMode mode))
|
|
{
|
|
throw new PcapDiagnosticsException($"Invalid OPC UA key-log security mode '{SecurityMode}'.");
|
|
}
|
|
|
|
return new ChannelKeyMaterial(
|
|
ChannelId,
|
|
TokenId,
|
|
SecurityPolicyUri,
|
|
mode,
|
|
CreatedAt.UtcDateTime,
|
|
LifetimeMs,
|
|
FromBase64(ClientNonce),
|
|
FromBase64(ServerNonce),
|
|
FromBase64(ClientSigningKey),
|
|
FromBase64(ClientEncryptingKey),
|
|
FromBase64(ClientInitializationVector),
|
|
FromBase64(ServerSigningKey),
|
|
FromBase64(ServerEncryptingKey),
|
|
FromBase64(ServerInitializationVector));
|
|
}
|
|
|
|
private static string? ToBase64(byte[]? value)
|
|
{
|
|
return value is { Length: > 0 } ? Convert.ToBase64String(value) : null;
|
|
}
|
|
|
|
private static byte[]? FromBase64(string? value)
|
|
{
|
|
return string.IsNullOrEmpty(value) ? null : Convert.FromBase64String(value);
|
|
}
|
|
}
|
|
}
|