fix(management)+fix(cli): neutralize CSV formula injection + align export columns; deadline + Ctrl-C on audit export streaming (arch-review 2026-08-19 P6-7 + P6-8)
P6-7 (CWE-1236): AuditEndpoints CSV export quoted cells on comma/quote/CR/LF but never neutralized a leading =, +, -, @, TAB, or CR — inbound-API-caller text landing in Target/ErrorMessage/RequestSummary/ResponseSummary/Extra could execute as a formula/DDE trigger when opened in Excel. AppendField now prefixes a literal single quote on free-text columns only (never the GUID/enum/numeric/date/bool columns the exporter formats itself), applied before RFC 4180 quoting. The CSV was also missing ExecutionId/ ParentExecutionId/SourceNode that the JSONL export already carried; both are now 24 columns in the same AuditExportRow order. A second, independently maintained CSV writer (CentralUI's AuditLogExportService, feeding the Audit Log page's bulk-export button) had the identical gap and got the identical fix + column alignment. P6-8: `audit export` was the one CLI HTTP path with no deadline at all — a residual gap from the ManagementHttpClient timeout-honesty fix, which made HttpClient.Timeout infinite and the per-call token the single deadline everywhere except this streamed GET. RunExportAsync now takes a headers- received deadline (CancelAfter, reusing ManagementHttpClient. DefaultConnectTimeout) around the initial GetAsync, an inactivity deadline around the streaming copy (rearmed on every successful read, so large exports are bounded by silence, not total size), and an external CancellationToken wired to Console.CancelKeyPress in AuditCommands so Ctrl-C cancels promptly. A stalled/faulted stream now produces a friendly error noting the partial output file instead of hanging or dumping a stack trace.
This commit is contained in:
@@ -218,16 +218,32 @@ public static class AuditCommands
|
||||
Actor = result.GetValue(actorOption),
|
||||
};
|
||||
|
||||
// Ctrl-C is the one way to abort an in-flight export other than the
|
||||
// headers/inactivity deadlines below — mirrors the CancellationTokenSource
|
||||
// owned by DebugCommands' streaming debug-view command (arch-review
|
||||
// 2026-08-19 P6-8: this was the one CLI HTTP path with NO deadline at all).
|
||||
using var cts = new CancellationTokenSource();
|
||||
ConsoleCancelEventHandler onCancel = (_, e) =>
|
||||
{
|
||||
e.Cancel = true;
|
||||
cts.Cancel();
|
||||
};
|
||||
Console.CancelKeyPress += onCancel;
|
||||
|
||||
try
|
||||
{
|
||||
using var client = new ManagementHttpClient(connection.Url!, connection.Username!, connection.Password!);
|
||||
return await AuditExportHelpers.RunExportAsync(client, args, Console.Out, DateTimeOffset.UtcNow);
|
||||
return await AuditExportHelpers.RunExportAsync(client, args, Console.Out, DateTimeOffset.UtcNow, cts.Token);
|
||||
}
|
||||
catch (FormatException ex)
|
||||
{
|
||||
OutputFormatter.WriteError(ex.Message, "INVALID_ARGUMENT");
|
||||
return 1;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Console.CancelKeyPress -= onCancel;
|
||||
}
|
||||
});
|
||||
return cmd;
|
||||
}
|
||||
|
||||
@@ -106,10 +106,34 @@ public static class AuditExportHelpers
|
||||
return "?" + string.Join("&", parts);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deadline for receiving the export response's headers (i.e. the server has
|
||||
/// started responding), measured from the start of the request. This is the
|
||||
/// one bound <see cref="ManagementHttpClient.SendGetStreamAsync"/> does NOT
|
||||
/// carry on its own — <see cref="ManagementHttpClient"/>'s <c>HttpClient.Timeout</c>
|
||||
/// is deliberately <see cref="Timeout.InfiniteTimeSpan"/> (see its doc comment)
|
||||
/// and <see cref="SocketsHttpHandler.ConnectTimeout"/> bounds only the TCP/TLS
|
||||
/// connect phase, not a connected-but-silent server. Reuses
|
||||
/// <see cref="ManagementHttpClient.DefaultConnectTimeout"/> as the standard CLI
|
||||
/// per-call default (arch-review 2026-08-19 P6-8).
|
||||
/// </summary>
|
||||
public static readonly TimeSpan DefaultHeadersTimeout = ManagementHttpClient.DefaultConnectTimeout;
|
||||
|
||||
/// <summary>
|
||||
/// Inactivity deadline for the streaming body copy: reset on every chunk
|
||||
/// successfully read, so a large export keeps streaming indefinitely as long
|
||||
/// as bytes keep arriving, but a stream that goes silent mid-transfer (a
|
||||
/// hung/crashed server holding the connection open) is bounded rather than
|
||||
/// hanging the CLI forever — the residual gap the timeout-honesty fix
|
||||
/// (<c>ManagementHttpClient.DefaultConnectTimeout</c> doc comment) left in this
|
||||
/// one path (arch-review 2026-08-19 P6-8).
|
||||
/// </summary>
|
||||
public static readonly TimeSpan DefaultInactivityTimeout = ManagementHttpClient.DefaultConnectTimeout;
|
||||
|
||||
/// <summary>
|
||||
/// Executes the export: GETs <c>/api/audit/export</c> and copies the response body
|
||||
/// stream directly to <see cref="AuditExportArgs.Output"/>. The body is never fully
|
||||
/// buffered — <see cref="Stream.CopyToAsync(Stream)"/> streams in fixed-size chunks.
|
||||
/// buffered — the copy streams in fixed-size chunks via <see cref="Stream.ReadAsync(Memory{byte}, CancellationToken)"/>.
|
||||
/// A <c>501 Not Implemented</c> (parquet not yet supported server-side) prints the
|
||||
/// server message and returns a non-zero exit code.
|
||||
/// </summary>
|
||||
@@ -117,16 +141,43 @@ public static class AuditExportHelpers
|
||||
/// <param name="args">The export arguments containing filters and output file path.</param>
|
||||
/// <param name="output">Text writer for command output messages.</param>
|
||||
/// <param name="now">The current time for resolving relative time specifications.</param>
|
||||
/// <param name="cancellationToken">
|
||||
/// External cancellation (e.g. the CLI's Ctrl-C handler) — cancelling this
|
||||
/// stops the export promptly at either the headers wait or the next stream
|
||||
/// read, with a "cancelled" (not timed-out) message.
|
||||
/// </param>
|
||||
/// <param name="headersTimeout">
|
||||
/// Override for <see cref="DefaultHeadersTimeout"/> — test seam.
|
||||
/// </param>
|
||||
/// <param name="inactivityTimeout">
|
||||
/// Override for <see cref="DefaultInactivityTimeout"/> — test seam.
|
||||
/// </param>
|
||||
/// <returns>0 on success, 1 on general error, or 2 on authorization failure.</returns>
|
||||
public static async Task<int> RunExportAsync(
|
||||
ManagementHttpClient client, AuditExportArgs args, TextWriter output, DateTimeOffset now)
|
||||
ManagementHttpClient client, AuditExportArgs args, TextWriter output, DateTimeOffset now,
|
||||
CancellationToken cancellationToken = default,
|
||||
TimeSpan? headersTimeout = null,
|
||||
TimeSpan? inactivityTimeout = null)
|
||||
{
|
||||
var qs = BuildQueryString(args, now);
|
||||
|
||||
using var headersCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
headersCts.CancelAfter(headersTimeout ?? DefaultHeadersTimeout);
|
||||
|
||||
HttpResponseMessage response;
|
||||
try
|
||||
{
|
||||
response = await client.SendGetStreamAsync("api/audit/export" + qs, CancellationToken.None);
|
||||
response = await client.SendGetStreamAsync("api/audit/export" + qs, headersCts.Token);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
OutputFormatter.WriteError("Export cancelled.", "CANCELLED");
|
||||
return 1;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
OutputFormatter.WriteError("Request timed out waiting for the server to respond.", "TIMEOUT");
|
||||
return 1;
|
||||
}
|
||||
catch (HttpRequestException ex)
|
||||
{
|
||||
@@ -138,7 +189,7 @@ public static class AuditExportHelpers
|
||||
{
|
||||
if (response.StatusCode == HttpStatusCode.NotImplemented)
|
||||
{
|
||||
var message = await response.Content.ReadAsStringAsync();
|
||||
var message = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||
OutputFormatter.WriteError(
|
||||
string.IsNullOrWhiteSpace(message)
|
||||
? "Export format not implemented by the server."
|
||||
@@ -149,7 +200,7 @@ public static class AuditExportHelpers
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
var message = await response.Content.ReadAsStringAsync();
|
||||
var message = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||
// Honour the documented "authorization failure → exit 2"
|
||||
// contract on the REST audit surface as well. HTTP 403 is the
|
||||
// primary signal; the server may also surface UNAUTHORIZED /
|
||||
@@ -164,17 +215,69 @@ public static class AuditExportHelpers
|
||||
return isAuthFailure ? 2 : 1;
|
||||
}
|
||||
|
||||
await using var source = await response.Content.ReadAsStreamAsync();
|
||||
await using var source = await response.Content.ReadAsStreamAsync(cancellationToken);
|
||||
await using var destination = new FileStream(
|
||||
args.Output, FileMode.Create, FileAccess.Write, FileShare.None,
|
||||
bufferSize: 81920, useAsync: true);
|
||||
await source.CopyToAsync(destination);
|
||||
|
||||
try
|
||||
{
|
||||
await CopyWithInactivityTimeoutAsync(
|
||||
source, destination, inactivityTimeout ?? DefaultInactivityTimeout, cancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
OutputFormatter.WriteError($"Export cancelled; partial file written to {args.Output}.", "CANCELLED");
|
||||
return 1;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
OutputFormatter.WriteError(
|
||||
"Export stalled — no data received from the server for "
|
||||
+ $"{(inactivityTimeout ?? DefaultInactivityTimeout).TotalSeconds:0}s; "
|
||||
+ $"partial file written to {args.Output}.",
|
||||
"TIMEOUT");
|
||||
return 1;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or HttpRequestException)
|
||||
{
|
||||
OutputFormatter.WriteError(
|
||||
$"Export failed while streaming the response: {ex.Message}; partial file written to {args.Output}.",
|
||||
"STREAM_FAILED");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
output.WriteLine($"Exported audit log to {args.Output}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies <paramref name="source"/> to <paramref name="destination"/> in fixed-size
|
||||
/// chunks, rearming an inactivity deadline before every read so the copy is bounded
|
||||
/// only by silence, not by total size — a multi-hundred-MB export keeps streaming as
|
||||
/// long as bytes keep arriving. <paramref name="cancellationToken"/> (external, e.g.
|
||||
/// Ctrl-C) and the inactivity deadline share one linked token; callers distinguish the
|
||||
/// two causes via <c>cancellationToken.IsCancellationRequested</c> after catching
|
||||
/// <see cref="OperationCanceledException"/>.
|
||||
/// </summary>
|
||||
private static async Task CopyWithInactivityTimeoutAsync(
|
||||
Stream source, Stream destination, TimeSpan inactivityTimeout, CancellationToken cancellationToken)
|
||||
{
|
||||
using var readCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
var buffer = new byte[81920];
|
||||
while (true)
|
||||
{
|
||||
readCts.CancelAfter(inactivityTimeout);
|
||||
var bytesRead = await source.ReadAsync(buffer.AsMemory(), readCts.Token);
|
||||
if (bytesRead == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
await destination.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Best-effort parse of the server's JSON error envelope (<c>{ "error": ..., "code": ... }</c>)
|
||||
/// to extract the <c>code</c> field. Returns null if the body is empty, not valid JSON, or
|
||||
|
||||
@@ -20,8 +20,9 @@ namespace ZB.MOM.WW.ScadaBridge.CentralUI.Services;
|
||||
/// Output is capped at a caller-supplied <c>maxRows</c> ceiling; when the cap
|
||||
/// is hit the service appends a <c># Capped at … rows. Use the CLI for larger
|
||||
/// exports.</c> footer line so an operator can tell a truncated download from
|
||||
/// a complete one. The header row contains the 21 columns of
|
||||
/// <see cref="AuditEvent"/> in declaration order.
|
||||
/// a complete one. The header row contains the same 24 columns, in the same
|
||||
/// order, as the ManagementService CLI's CSV export (arch-review 2026-08-19
|
||||
/// P6-7 — the two CSV writers were found to have drifted and are kept aligned).
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public interface IAuditLogExportService
|
||||
@@ -92,7 +93,7 @@ public sealed class AuditLogExportService : IAuditLogExportService
|
||||
leaveOpen: true);
|
||||
writer.NewLine = "\r\n"; // RFC 4180
|
||||
|
||||
// Header — 21 columns in AuditEvent declaration order.
|
||||
// Header — 24 columns in AuditEventView declaration order.
|
||||
await writer.WriteLineAsync(Header);
|
||||
|
||||
int written = 0;
|
||||
@@ -160,13 +161,14 @@ public sealed class AuditLogExportService : IAuditLogExportService
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// CSV helpers
|
||||
// CSV helpers — 24 columns, kept aligned with the ManagementService CLI's
|
||||
// CSV export (arch-review 2026-08-19 P6-7)
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>The 21 column names in <see cref="AuditEvent"/> declaration order.</summary>
|
||||
/// <summary>The 24 column names, in <see cref="AuditEventView"/> declaration order.</summary>
|
||||
internal const string Header =
|
||||
"EventId,OccurredAtUtc,IngestedAtUtc,Channel,Kind,CorrelationId," +
|
||||
"SourceSiteId,SourceInstanceId,SourceScript,Actor,Target,Status," +
|
||||
"EventId,OccurredAtUtc,IngestedAtUtc,Channel,Kind,CorrelationId,ExecutionId,ParentExecutionId," +
|
||||
"SourceSiteId,SourceNode,SourceInstanceId,SourceScript,Actor,Target,Status," +
|
||||
"HttpStatus,DurationMs,ErrorMessage,ErrorDetail,RequestSummary," +
|
||||
"ResponseSummary,PayloadTruncated,Extra,ForwardState";
|
||||
|
||||
@@ -174,7 +176,12 @@ public sealed class AuditLogExportService : IAuditLogExportService
|
||||
/// Serialises one <see cref="AuditEventView"/> as a CSV row (no trailing newline).
|
||||
/// Each nullable column renders as the empty string when null; non-null
|
||||
/// scalars use invariant culture so an export taken on one locale parses
|
||||
/// cleanly on another.
|
||||
/// cleanly on another. Free-text columns are run through
|
||||
/// <see cref="NeedsFormulaNeutralization"/> before RFC 4180 quoting so a
|
||||
/// leading <c>=</c>/<c>+</c>/<c>-</c>/<c>@</c>/TAB/CR can't be interpreted as
|
||||
/// a formula or DDE trigger by a spreadsheet application (CWE-1236;
|
||||
/// arch-review 2026-08-19 P6-7). GUID/enum/numeric/date/bool columns this
|
||||
/// formatter generates itself are never neutralized.
|
||||
/// </summary>
|
||||
/// <param name="evt">The audit event view to format as a CSV row.</param>
|
||||
/// <returns>An RFC 4180 CSV row string (no trailing newline) for the supplied event.</returns>
|
||||
@@ -187,20 +194,23 @@ public sealed class AuditLogExportService : IAuditLogExportService
|
||||
AppendField(sb, evt.Channel.ToString());
|
||||
AppendField(sb, evt.Kind.ToString());
|
||||
AppendField(sb, evt.CorrelationId?.ToString());
|
||||
AppendField(sb, evt.SourceSiteId);
|
||||
AppendField(sb, evt.SourceInstanceId);
|
||||
AppendField(sb, evt.SourceScript);
|
||||
AppendField(sb, evt.Actor);
|
||||
AppendField(sb, evt.Target);
|
||||
AppendField(sb, evt.ExecutionId?.ToString());
|
||||
AppendField(sb, evt.ParentExecutionId?.ToString());
|
||||
AppendField(sb, evt.SourceSiteId, freeText: true);
|
||||
AppendField(sb, evt.SourceNode, freeText: true);
|
||||
AppendField(sb, evt.SourceInstanceId, freeText: true);
|
||||
AppendField(sb, evt.SourceScript, freeText: true);
|
||||
AppendField(sb, evt.Actor, freeText: true);
|
||||
AppendField(sb, evt.Target, freeText: true);
|
||||
AppendField(sb, evt.Status.ToString());
|
||||
AppendField(sb, evt.HttpStatus?.ToString(CultureInfo.InvariantCulture));
|
||||
AppendField(sb, evt.DurationMs?.ToString(CultureInfo.InvariantCulture));
|
||||
AppendField(sb, evt.ErrorMessage);
|
||||
AppendField(sb, evt.ErrorDetail);
|
||||
AppendField(sb, evt.RequestSummary);
|
||||
AppendField(sb, evt.ResponseSummary);
|
||||
AppendField(sb, evt.ErrorMessage, freeText: true);
|
||||
AppendField(sb, evt.ErrorDetail, freeText: true);
|
||||
AppendField(sb, evt.RequestSummary, freeText: true);
|
||||
AppendField(sb, evt.ResponseSummary, freeText: true);
|
||||
AppendField(sb, evt.PayloadTruncated.ToString());
|
||||
AppendField(sb, evt.Extra);
|
||||
AppendField(sb, evt.Extra, freeText: true);
|
||||
AppendField(sb, evt.ForwardState?.ToString());
|
||||
return sb.ToString();
|
||||
}
|
||||
@@ -211,7 +221,7 @@ public sealed class AuditLogExportService : IAuditLogExportService
|
||||
private static string FormatDate(DateTime value) =>
|
||||
value.ToString("O", CultureInfo.InvariantCulture);
|
||||
|
||||
private static void AppendField(StringBuilder sb, string? value, bool first = false)
|
||||
private static void AppendField(StringBuilder sb, string? value, bool first = false, bool freeText = false)
|
||||
{
|
||||
if (!first) sb.Append(',');
|
||||
if (string.IsNullOrEmpty(value))
|
||||
@@ -219,6 +229,14 @@ public sealed class AuditLogExportService : IAuditLogExportService
|
||||
return;
|
||||
}
|
||||
|
||||
// OWASP CSV-injection neutralization (CWE-1236): prefix a literal single
|
||||
// quote before RFC 4180 quoting so a free-text cell starting with a
|
||||
// formula/DDE trigger character renders as inert text in Excel.
|
||||
if (freeText && NeedsFormulaNeutralization(value))
|
||||
{
|
||||
value = "'" + value;
|
||||
}
|
||||
|
||||
// RFC 4180: quote on comma / quote / CR / LF; double-up embedded quotes.
|
||||
bool needsQuoting = value.IndexOfAny(s_quoteTriggers) >= 0;
|
||||
if (!needsQuoting)
|
||||
@@ -242,5 +260,16 @@ public sealed class AuditLogExportService : IAuditLogExportService
|
||||
sb.Append('"');
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when <paramref name="value"/> starts with a character a spreadsheet
|
||||
/// application would treat as a formula/DDE-launch trigger — the OWASP CSV
|
||||
/// Injection standard set: <c>=</c>, <c>+</c>, <c>-</c>, <c>@</c>, TAB, CR.
|
||||
/// </summary>
|
||||
private static bool NeedsFormulaNeutralization(string value)
|
||||
{
|
||||
var c = value[0];
|
||||
return c == '=' || c == '+' || c == '-' || c == '@' || c == '\t' || c == '\r';
|
||||
}
|
||||
|
||||
private static readonly char[] s_quoteTriggers = { ',', '"', '\r', '\n' };
|
||||
}
|
||||
|
||||
@@ -760,17 +760,30 @@ public static class AuditEndpoints
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// CSV helpers — 21 columns in AuditEvent declaration order
|
||||
// CSV helpers — 24 columns, same order/naming as the JSONL export
|
||||
// (AuditExportRow property declaration order; arch-review 2026-08-19 P6-7)
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
public const string CsvHeader =
|
||||
"EventId,OccurredAtUtc,IngestedAtUtc,Channel,Kind,CorrelationId," +
|
||||
"SourceSiteId,SourceInstanceId,SourceScript,Actor,Target,Status," +
|
||||
"EventId,OccurredAtUtc,IngestedAtUtc,Channel,Kind,CorrelationId,ExecutionId,ParentExecutionId," +
|
||||
"SourceSiteId,SourceNode,SourceInstanceId,SourceScript,Actor,Target,Status," +
|
||||
"HttpStatus,DurationMs,ErrorMessage,ErrorDetail,RequestSummary," +
|
||||
"ResponseSummary,PayloadTruncated,Extra,ForwardState";
|
||||
|
||||
/// <summary>
|
||||
/// Formats a single <see cref="AuditEvent"/> as an RFC 4180 CSV row matching <see cref="CsvHeader"/>.
|
||||
/// Free-text columns (anything that can carry inbound-API-caller-controlled or
|
||||
/// site-script-controlled text — <see cref="AuditExportRow.SourceSiteId"/>,
|
||||
/// <see cref="AuditExportRow.SourceNode"/>, <see cref="AuditExportRow.SourceInstanceId"/>,
|
||||
/// <see cref="AuditExportRow.SourceScript"/>, <see cref="AuditExportRow.Actor"/>,
|
||||
/// <see cref="AuditExportRow.Target"/>, <see cref="AuditExportRow.ErrorMessage"/>,
|
||||
/// <see cref="AuditExportRow.ErrorDetail"/>, <see cref="AuditExportRow.RequestSummary"/>,
|
||||
/// <see cref="AuditExportRow.ResponseSummary"/>, <see cref="AuditExportRow.Extra"/>) are run
|
||||
/// through <see cref="NeedsFormulaNeutralization"/> before RFC 4180 quoting so a leading
|
||||
/// <c>=</c>/<c>+</c>/<c>-</c>/<c>@</c>/TAB/CR can't be interpreted as a formula or DDE
|
||||
/// trigger by a spreadsheet application (CWE-1236). GUID/enum/numeric/date/bool columns the
|
||||
/// exporter formats itself are never neutralized — none of them can start with a trigger
|
||||
/// character, and neutralizing a signed numeric column would corrupt it.
|
||||
/// </summary>
|
||||
/// <param name="evt">The audit event to format.</param>
|
||||
/// <returns>An RFC 4180 CSV row string (no trailing newline) for the supplied event.</returns>
|
||||
@@ -783,20 +796,23 @@ public static class AuditEndpoints
|
||||
AppendField(sb, evt.Channel.ToString());
|
||||
AppendField(sb, evt.Kind.ToString());
|
||||
AppendField(sb, evt.CorrelationId?.ToString());
|
||||
AppendField(sb, evt.SourceSiteId);
|
||||
AppendField(sb, evt.SourceInstanceId);
|
||||
AppendField(sb, evt.SourceScript);
|
||||
AppendField(sb, evt.Actor);
|
||||
AppendField(sb, evt.Target);
|
||||
AppendField(sb, evt.ExecutionId?.ToString());
|
||||
AppendField(sb, evt.ParentExecutionId?.ToString());
|
||||
AppendField(sb, evt.SourceSiteId, freeText: true);
|
||||
AppendField(sb, evt.SourceNode, freeText: true);
|
||||
AppendField(sb, evt.SourceInstanceId, freeText: true);
|
||||
AppendField(sb, evt.SourceScript, freeText: true);
|
||||
AppendField(sb, evt.Actor, freeText: true);
|
||||
AppendField(sb, evt.Target, freeText: true);
|
||||
AppendField(sb, evt.Status.ToString());
|
||||
AppendField(sb, evt.HttpStatus?.ToString(CultureInfo.InvariantCulture));
|
||||
AppendField(sb, evt.DurationMs?.ToString(CultureInfo.InvariantCulture));
|
||||
AppendField(sb, evt.ErrorMessage);
|
||||
AppendField(sb, evt.ErrorDetail);
|
||||
AppendField(sb, evt.RequestSummary);
|
||||
AppendField(sb, evt.ResponseSummary);
|
||||
AppendField(sb, evt.ErrorMessage, freeText: true);
|
||||
AppendField(sb, evt.ErrorDetail, freeText: true);
|
||||
AppendField(sb, evt.RequestSummary, freeText: true);
|
||||
AppendField(sb, evt.ResponseSummary, freeText: true);
|
||||
AppendField(sb, evt.PayloadTruncated.ToString());
|
||||
AppendField(sb, evt.Extra);
|
||||
AppendField(sb, evt.Extra, freeText: true);
|
||||
AppendField(sb, evt.ForwardState?.ToString());
|
||||
return sb.ToString();
|
||||
}
|
||||
@@ -807,7 +823,7 @@ public static class AuditEndpoints
|
||||
private static string FormatDate(DateTime value) =>
|
||||
value.ToString("O", CultureInfo.InvariantCulture);
|
||||
|
||||
private static void AppendField(StringBuilder sb, string? value, bool first = false)
|
||||
private static void AppendField(StringBuilder sb, string? value, bool first = false, bool freeText = false)
|
||||
{
|
||||
if (!first) sb.Append(',');
|
||||
if (string.IsNullOrEmpty(value))
|
||||
@@ -815,6 +831,16 @@ public static class AuditEndpoints
|
||||
return;
|
||||
}
|
||||
|
||||
// OWASP CSV-injection neutralization (CWE-1236): a free-text cell whose
|
||||
// first character would be interpreted by a spreadsheet application as a
|
||||
// formula/DDE trigger is prefixed with a literal single quote. Applied
|
||||
// BEFORE RFC 4180 quoting, and only to free-text columns — never to the
|
||||
// GUID/enum/numeric/date/bool columns this formatter generates itself.
|
||||
if (freeText && NeedsFormulaNeutralization(value))
|
||||
{
|
||||
value = "'" + value;
|
||||
}
|
||||
|
||||
// RFC 4180: quote on comma / quote / CR / LF; double-up embedded quotes.
|
||||
if (value.IndexOfAny(s_quoteTriggers) < 0)
|
||||
{
|
||||
@@ -837,5 +863,16 @@ public static class AuditEndpoints
|
||||
sb.Append('"');
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when <paramref name="value"/> starts with a character a spreadsheet
|
||||
/// application would treat as a formula/DDE-launch trigger — the OWASP CSV
|
||||
/// Injection standard set: <c>=</c>, <c>+</c>, <c>-</c>, <c>@</c>, TAB, CR.
|
||||
/// </summary>
|
||||
private static bool NeedsFormulaNeutralization(string value)
|
||||
{
|
||||
var c = value[0];
|
||||
return c == '=' || c == '+' || c == '-' || c == '@' || c == '\t' || c == '\r';
|
||||
}
|
||||
|
||||
private static readonly char[] s_quoteTriggers = { ',', '"', '\r', '\n' };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user