Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
162 changes: 162 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,161 @@ 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!);

// The caller is the user captured when the request was created: the session may
// have been reactivated under another user while the request was running. A
// session-less context (or one whose session is gone) still names the caller, and an
// anonymous request (no ClientUserId) is not attributed to a later user.
e.SetChildValue(systemContext, BrowseNames.ClientUserId, context.ClientUserId!, false);
if (context.Session == null)
{
e.SetChildValue(systemContext, BrowseNames.SessionId, context.SessionId, false);
}

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>
/// <param name="actionTimeStamp">
/// When the call started (the ActionTimeStamp); capture it before invoking the method.
/// Defaults to now, for a call that was rejected before it ran.
/// </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,
DateTime? actionTimeStamp = 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),
actionTimeStamp ?? DateTime.UtcNow
); // 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 Expand Up @@ -3002,5 +3157,12 @@ public static partial void ErrorWhileReportingReportTrustListUpdatedAuditEvent(
public static partial void ErrorWhileReportingTrustListUpdateRequestedAuditEvent(
this ILogger logger,
Exception ex);

/// <summary>
/// Logs an audit event sink of a composite that threw.
/// </summary>
[LoggerMessage(EventId = ServerEventIds.AuditEvents + 25, Level = LogLevel.Error,
Message = "Audit event sink {Sink} failed.")]
public static partial void AuditEventSinkFailed(this ILogger logger, Exception ex, string sink);
}
}
74 changes: 70 additions & 4 deletions src/Opc.Ua.Server/Diagnostics/IAuditEventSink.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

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

namespace Opc.Ua.Server
Expand Down Expand Up @@ -37,11 +39,34 @@ public interface IAuditEventSink
void ReportAuditEvent(ISystemContext context, AuditEventState e);
}

/// <summary>
/// An <see cref="IAuditEventSink"/> that can also receive an audit event asynchronously.
/// </summary>
/// <remarks>
/// The server uses it for the events it reports through
/// <c>IServerInternal.ReportEventAsync</c>, so a sink that may wait (for example the address
/// space, when a monitored item's event channel is full) does not block the reporting
/// thread and observes the caller's cancellation token.
/// </remarks>
public interface IAsyncAuditEventSink : IAuditEventSink
{
/// <summary>
/// Receives one audit event asynchronously.
/// </summary>
/// <param name="context">The context the event was raised in.</param>
/// <param name="e">The audit event. Do not change it.</param>
/// <param name="cancellationToken">The cancellation token.</param>
ValueTask ReportAuditEventAsync(
ISystemContext context,
AuditEventState e,
CancellationToken cancellationToken = default);
}

/// <summary>
/// The default <see cref="IAuditEventSink"/>: publishes the audit event in the address space
/// of the server, so subscribed clients receive it.
/// </summary>
public sealed class AddressSpaceAuditEventSink : IAuditEventSink
public sealed class AddressSpaceAuditEventSink : IAsyncAuditEventSink
{
/// <summary>
/// Creates the sink for <paramref name="server"/>.
Expand All @@ -59,14 +84,24 @@ public void ReportAuditEvent(ISystemContext context, AuditEventState e)
m_server.PublishAuditEvent(context, e);
}

/// <inheritdoc/>
public ValueTask ReportAuditEventAsync(
ISystemContext context,
AuditEventState e,
CancellationToken cancellationToken = default)
{
return m_server.PublishAuditEventAsync(context, e, cancellationToken);
}

private readonly ServerInternalData m_server;
}

/// <summary>
/// Forwards each audit event to several sinks in order. A sink that throws is logged and
/// does not stop the sinks after it.
/// does not stop the sinks after it. Asynchronously, it awaits each
/// <see cref="IAsyncAuditEventSink"/> and stops when the report is cancelled.
/// </summary>
public sealed class CompositeAuditEventSink : IAuditEventSink
public sealed class CompositeAuditEventSink : IAsyncAuditEventSink
{
/// <summary>
/// Creates the composite sink.
Expand Down Expand Up @@ -133,7 +168,38 @@ public void ReportAuditEvent(ISystemContext context, AuditEventState e)
}
catch (Exception ex)
{
m_logger?.LogError(ex, "Audit event sink {Sink} failed.", sink.GetType().Name);
m_logger?.AuditEventSinkFailed(ex, sink.GetType().Name);
}
}
}

/// <inheritdoc/>
public async ValueTask ReportAuditEventAsync(
ISystemContext context,
AuditEventState e,
CancellationToken cancellationToken = default)
{
foreach (IAuditEventSink sink in m_sinks)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
if (sink is IAsyncAuditEventSink asyncSink)
{
await asyncSink.ReportAuditEventAsync(context, e, cancellationToken).ConfigureAwait(false);
}
else
{
sink.ReportAuditEvent(context, e);
}
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
m_logger?.AuditEventSinkFailed(ex, sink.GetType().Name);
}
}
}
Expand Down
Loading
Loading