Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
147 changes: 147 additions & 0 deletions src/Opc.Ua.Server/Diagnostics/AuditEvents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1769,6 +1769,153 @@ public static void ReportAuditTransferSubscriptionEvent(
}
}

/// <summary>
/// Reports the AuditSessionEventType event of a Session service set request
/// (CloseSession) or a TransferSubscriptions request that failed with a service fault
/// (OPC 10000-4 §6.5.6, §6.5.10): Status is false and the Message carries the fault.
/// </summary>
/// <param name="server">The server which reports audit events.</param>
/// <param name="context">The operation context of the failed request.</param>
/// <param name="sourceName">The SourceName, for example <c>Session/CloseSession</c>.</param>
/// <param name="fault">The service fault.</param>
/// <param name="logger">A contextual logger to log to</param>
internal static void ReportAuditSessionServiceFaultEvent(
this IAuditEventServer? server,
OperationContext context,
string sourceName,
ServiceResultException fault,
ILogger logger)
{
if (server?.Auditing != true)
{
// current server does not support auditing
return;
}

try
{
ISystemContext systemContext = server.DefaultAuditContext;

var e = new AuditSessionEventState(null);

var message = new TranslationInfo(
"AuditSessionEvent",
"en-US",
$"{sourceName} for session ID:{context.SessionId} failed. Result: {fault.Message}.");

InitializeAuditSessionEvent(
systemContext,
e,
message,
false,
context.Session!,
context.AuditEntryId!);

// a session-less context (or one whose session is gone) still names the caller
if (context.Session == null)
{
e.SetChildValue(systemContext, BrowseNames.ClientUserId, context.ClientUserId!, false);
e.SetChildValue(systemContext, BrowseNames.SessionId, context.SessionId, false);
}
Comment thread
romanett marked this conversation as resolved.
Resolved

e.SetChildValue(systemContext, BrowseNames.SourceName, sourceName, false);
if (sourceName == kTransferSubscriptionsSourceName)
{
// OPC 10000-5 §6.4.7: the session is the SourceNode of a TransferSubscriptions
// audit event, as in ReportAuditTransferSubscriptionEvent
e.SetChildValue(systemContext, BrowseNames.SourceNode, context.SessionId, false);
}

server.ReportAuditEvent(systemContext, e);
}
catch (Exception ex)
{
logger.ErrorWhileReportingAuditEventEvent(ex);
}
}

/// <summary>
/// The SourceName of the audit events of the TransferSubscriptions service.
/// </summary>
internal const string kTransferSubscriptionsSourceName = "Session/TransferSubscriptions";

/// <summary>
/// Reports an <see cref="AuditUpdateMethodEventState"/> (or a subtype that
/// <paramref name="factory"/> creates) for a completed method call, the event every
/// state-changing method raises on success and on failure (OPC 10000-4 §6.5.9). The
/// SourceName is <c>Attribute/Call</c> (OPC 10000-5 §6.4.27), and the ClientUserId and
/// ClientAuditEntryId come from <paramref name="systemContext"/>.
/// </summary>
/// <remarks>
/// The caller passes the input arguments it may disclose: an argument that carries a
/// secret (a password, a key, a credential secret) must be replaced before it is passed,
/// because audit events are kept and forwarded.
/// </remarks>
/// <typeparam name="TEvent">The audit event type.</typeparam>
/// <param name="server">The server which reports audit events.</param>
/// <param name="systemContext">The context of the method call.</param>
/// <param name="objectId">The Object the Method was called on (the SourceNode).</param>
/// <param name="methodId">The Method.</param>
/// <param name="inputArguments">The input arguments, with secrets removed.</param>
/// <param name="result">The result of the call.</param>
/// <param name="factory">Creates the event.</param>
/// <param name="logger">A contextual logger to log to</param>
/// <param name="configure">Sets the fields of the subtype, if any.</param>
public static void ReportAuditMethodCallEvent<TEvent>(
this IAuditEventServer? server,
ISystemContext systemContext,
NodeId objectId,
NodeId methodId,
ArrayOf<Variant> inputArguments,
ServiceResult? result,
Func<TEvent> factory,
ILogger logger,
Action<ISystemContext, TEvent>? configure = null)
where TEvent : AuditUpdateMethodEventState
{
if (server?.Auditing != true || factory == null)
{
// current server does not support auditing
return;
}

try
{
TEvent e = factory();
StatusCode statusCode = result?.StatusCode ?? StatusCodes.Good;
string eventName = e.GetType().Name;
var message = new TranslationInfo(
eventName,
"en-US",
$"Method {methodId} on {objectId} returns StatusCode: {statusCode.ToString(null, CultureInfo.InvariantCulture)}.");

e.Initialize(
systemContext,
null,
EventSeverity.Min,
new LocalizedText(message),
StatusCode.IsGood(statusCode),
DateTime.UtcNow
Comment thread
romanett marked this conversation as resolved.
Resolved
); // initializes Status, ActionTimeStamp, ServerId, ClientAuditEntryId, ClientUserId

e.SetChildValue(systemContext, BrowseNames.SourceNode, objectId, false);
e.SetChildValue(systemContext, BrowseNames.SourceName, "Attribute/Call", false);
e.SetChildValue(systemContext, BrowseNames.LocalTime, TimeZoneDataType.Local, false);
e.SetChildValue(systemContext, BrowseNames.ClientUserId, systemContext.UserId!, false);
e.SetChildValue(systemContext, BrowseNames.ClientAuditEntryId, systemContext.AuditEntryId!, false);
e.SetChildValue(systemContext, BrowseNames.MethodId, methodId, false);
e.SetChildValue(systemContext, BrowseNames.InputArguments, inputArguments, false);

configure?.Invoke(systemContext, e);

server.ReportAuditEvent(systemContext, e);
}
catch (Exception ex)
{
logger.ErrorWhileReportingAuditEventEvent(ex);
}
}

/// <summary>
/// Raise CertificateUpdatedAudit event
/// </summary>
Expand Down
145 changes: 145 additions & 0 deletions src/Opc.Ua.Server/KeyCredential/KeyCredentialPushSubject.Audit.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
// SPDX-FileCopyrightText: Copyright (c) 2005-2026, OPC Federation AISBL
// SPDX-License-Identifier: MIT

using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;

namespace Opc.Ua.Server
{
/// <summary>
/// The audit events of the KeyCredential push methods (OPC 10000-12 §8.6).
/// </summary>
/// <remarks>
/// <para>
/// Each audited method reports one event when it returns, on success and on failure
/// (including a denied call), as OPC 10000-4 §6.5.9 requires for a method that changes
/// the state of the system:
/// </para>
/// <list type="bullet">
/// <item><c>UpdateCredential</c>: KeyCredentialUpdatedAuditEventType (§8.6.9), with the
/// ResourceUri of the credential. The CredentialSecret is not copied into the event.</item>
/// <item><c>DeleteCredential</c>: KeyCredentialDeletedAuditEventType (§8.6.10), with the
/// ResourceUri of the credential.</item>
/// <item><c>CreateCredential</c>: Part 12 defines no type for it, so it raises an
/// AuditUpdateMethodEventType event.</item>
/// <item><c>GetEncryptingKey</c> only reads, so it is not audited (§6.5.9 makes that
/// optional).</item>
/// </list>
/// </remarks>
public sealed partial class KeyCredentialPushSubject
{
private async ValueTask<CreateCredentialMethodStateResult> OnAuditedCreateCredentialAsync(
ISystemContext context,
MethodState method,
NodeId objectId,
string name,
string resourceUri,
string profileUri,
ArrayOf<string> endpointUrls,
CancellationToken ct = default)
{
CreateCredentialMethodStateResult result = await OnCreateCredentialAsync(
context, method, objectId, name, resourceUri, profileUri, endpointUrls, ct).ConfigureAwait(false);
if (GetAuditServer(context) is { Auditing: true } server)
{
server.ReportAuditMethodCallEvent(
context,
objectId,
method.NodeId,
ArrayOf.Wrapped(new[]
{
Variant.From(name),
Variant.From(resourceUri),
Variant.From(profileUri),
Variant.From(endpointUrls)
}),
result.ServiceResult,
static () => new AuditUpdateMethodEventState(null),
GetAuditLogger(context));
}
return result;
}

private async ValueTask<KeyCredentialUpdateMethodStateResult> OnAuditedUpdateCredentialAsync(
ISystemContext context,
MethodState method,
NodeId objectId,
string credentialId,
ByteString credentialSecret,
string certificateThumbprint,
string securityPolicyUri,
CancellationToken ct = default)
{
KeyCredentialUpdateMethodStateResult result = await OnUpdateCredentialAsync(
context, method, objectId, credentialId, credentialSecret, certificateThumbprint, securityPolicyUri, ct)
.ConfigureAwait(false);
Comment thread
romanett marked this conversation as resolved.
Resolved
if (GetAuditServer(context) is { Auditing: true } server)
{
string resourceUri = GetResourceUri(method);
server.ReportAuditMethodCallEvent(
context,
objectId,
method.NodeId,
ArrayOf.Wrapped(new[]
{
Variant.From(credentialId),
// the (possibly encrypted) secret never goes into an audit event
Variant.From(AuditEvents.RedactedPrivateKey),
Variant.From(certificateThumbprint),
Variant.From(securityPolicyUri)
}),
result.ServiceResult,
static () => new KeyCredentialUpdatedAuditEventState(null),
GetAuditLogger(context),
(auditContext, e) => e.SetChildValue(auditContext, BrowseNames.ResourceUri, resourceUri, false));
}
return result;
}

private async ValueTask<ServiceResult> OnAuditedDeleteCredentialAsync(
ISystemContext context,
MethodState method,
NodeId objectId,
ArrayOf<Variant> inputArguments,
List<Variant> outputArguments,
CancellationToken ct = default)
{
// read before the call: a successful delete removes the credential node
string resourceUri = GetResourceUri(method);
ServiceResult result = await OnDeleteCredentialAsync(
context, method, objectId, inputArguments, outputArguments, ct).ConfigureAwait(false);
if (GetAuditServer(context) is { Auditing: true } server)
{
server.ReportAuditMethodCallEvent(
context,
objectId,
method.NodeId,
inputArguments,
result,
static () => new KeyCredentialDeletedAuditEventState(null),
GetAuditLogger(context),
(auditContext, e) => e.SetChildValue(auditContext, BrowseNames.ResourceUri, resourceUri, false));
}
return result;
}

private static IAuditEventServer? GetAuditServer(ISystemContext context)
{
return (context as ServerSystemContext)?.Server;
}

private static ILogger GetAuditLogger(ISystemContext context)
{
return context.Telemetry?.CreateLogger<KeyCredentialPushSubject>()
?? NullLogger<KeyCredentialPushSubject>.Instance;
}

private static string GetResourceUri(MethodState method)
{
return (method.Parent as KeyCredentialConfigurationState)?.ResourceUri?.Value ?? string.Empty;
}
}
}
8 changes: 4 additions & 4 deletions src/Opc.Ua.Server/KeyCredential/KeyCredentialPushSubject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ namespace Opc.Ua.Server
/// <summary>
/// Binds OPC 10000-12 §8 KeyCredentialConfiguration nodes to an <see cref="IKeyCredentialStore"/>.
/// </summary>
public sealed class KeyCredentialPushSubject
public sealed partial class KeyCredentialPushSubject
{
/// <summary>
/// Fallback namespace URI used for standalone credential configuration instances.
Expand Down Expand Up @@ -103,7 +103,7 @@ public async ValueTask BindAsync(
folder.AddCreateCredential(context, c =>
{
c.OnCall = null;
c.OnCallAsync = OnCreateCredentialAsync;
c.OnCallAsync = OnAuditedCreateCredentialAsync;
});

IList<BaseInstanceState> children = [];
Expand Down Expand Up @@ -568,12 +568,12 @@ private void WireCredentialState(KeyCredentialConfigurationState state, ISystemC
.AddUpdateCredential(context, c =>
{
c.OnCall = null;
c.OnCallAsync = OnUpdateCredentialAsync;
c.OnCallAsync = OnAuditedUpdateCredentialAsync;
})
.AddDeleteCredential(context, c =>
{
c.OnCallMethod2 = null;
c.OnCallMethod2Async = OnDeleteCredentialAsync;
c.OnCallMethod2Async = OnAuditedDeleteCredentialAsync;
});
}

Expand Down
Loading
Loading