|
| 1 | +using System.Globalization; |
| 2 | +using System.Net.Sockets; |
| 3 | +using System.Text; |
| 4 | +using System.Text.Encodings.Web; |
| 5 | +using System.Text.Json; |
| 6 | +using System.Text.Json.Serialization; |
| 7 | +using Microsoft.Extensions.Options; |
| 8 | +using Tawny.Domain; |
| 9 | +using Tawny.Domain.Entities; |
| 10 | + |
| 11 | +namespace Tawny.Api.Services; |
| 12 | + |
| 13 | +public sealed class WazuhSinkOptions |
| 14 | +{ |
| 15 | + public bool Enabled { get; set; } |
| 16 | + public string Host { get; set; } = ""; |
| 17 | + public int Port { get; set; } = 514; |
| 18 | + public string Protocol { get; set; } = "udp"; |
| 19 | + public int Facility { get; set; } = 16; |
| 20 | + public string AppName { get; set; } = "tawny"; |
| 21 | + public string Hostname { get; set; } = ""; |
| 22 | + public int MaxMessageBytes { get; set; } = 8192; |
| 23 | +} |
| 24 | + |
| 25 | +public sealed class WazuhAlertSink( |
| 26 | + IOptions<WazuhSinkOptions> options, |
| 27 | + ILogger<WazuhAlertSink> log) : IAlertSink |
| 28 | +{ |
| 29 | + private readonly WazuhSinkOptions _options = options.Value; |
| 30 | + |
| 31 | + public async Task PublishAsync( |
| 32 | + Agent agent, |
| 33 | + IReadOnlyList<Alert> alerts, |
| 34 | + IReadOnlyDictionary<long, TelemetryEvent> telemetryEvents, |
| 35 | + CancellationToken ct) |
| 36 | + { |
| 37 | + if (!_options.Enabled || alerts.Count == 0) |
| 38 | + { |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + if (string.IsNullOrWhiteSpace(_options.Host)) |
| 43 | + { |
| 44 | + log.LogWarning("Wazuh sink is enabled but Tawny:Wazuh:Host is empty."); |
| 45 | + return; |
| 46 | + } |
| 47 | + if (_options.Port is < 1 or > 65535) |
| 48 | + { |
| 49 | + log.LogWarning("Wazuh sink is enabled but Tawny:Wazuh:Port is outside the valid range."); |
| 50 | + return; |
| 51 | + } |
| 52 | + if (!string.Equals(_options.Protocol, "udp", StringComparison.OrdinalIgnoreCase) |
| 53 | + && !string.Equals(_options.Protocol, "tcp", StringComparison.OrdinalIgnoreCase)) |
| 54 | + { |
| 55 | + log.LogWarning("Wazuh sink is enabled but Tawny:Wazuh:Protocol must be udp or tcp."); |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + foreach (var alert in alerts) |
| 60 | + { |
| 61 | + telemetryEvents.TryGetValue(alert.TelemetryEventId, out var telemetryEvent); |
| 62 | + var message = WazuhSyslogFormatter.Format(_options, agent, alert, telemetryEvent); |
| 63 | + try |
| 64 | + { |
| 65 | + await SendAsync(message, ct); |
| 66 | + } |
| 67 | + catch (Exception ex) when (ex is SocketException or IOException or OperationCanceledException) |
| 68 | + { |
| 69 | + log.LogWarning(ex, "Failed to publish alert {AlertId} to Wazuh sink.", alert.Id); |
| 70 | + } |
| 71 | + } |
| 72 | + log.LogInformation( |
| 73 | + "Published {AlertCount} alert(s) to Wazuh sink {Host}:{Port}/{Protocol}.", |
| 74 | + alerts.Count, |
| 75 | + _options.Host, |
| 76 | + _options.Port, |
| 77 | + _options.Protocol); |
| 78 | + } |
| 79 | + |
| 80 | + private async Task SendAsync(string message, CancellationToken ct) |
| 81 | + { |
| 82 | + var bytes = Encoding.UTF8.GetBytes(message); |
| 83 | + if (string.Equals(_options.Protocol, "tcp", StringComparison.OrdinalIgnoreCase)) |
| 84 | + { |
| 85 | + using var tcp = new TcpClient(); |
| 86 | + await tcp.ConnectAsync(_options.Host, _options.Port, ct); |
| 87 | + await using var stream = tcp.GetStream(); |
| 88 | + await stream.WriteAsync(bytes, ct); |
| 89 | + await stream.WriteAsync("\n"u8.ToArray(), ct); |
| 90 | + return; |
| 91 | + } |
| 92 | + |
| 93 | + using var udp = new UdpClient(); |
| 94 | + await udp.SendAsync(bytes, _options.Host, _options.Port, ct); |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +public static class WazuhSyslogFormatter |
| 99 | +{ |
| 100 | + private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) |
| 101 | + { |
| 102 | + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, |
| 103 | + PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, |
| 104 | + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.SnakeCaseLower) }, |
| 105 | + }; |
| 106 | + |
| 107 | + public static string Format( |
| 108 | + WazuhSinkOptions options, |
| 109 | + Agent agent, |
| 110 | + Alert alert, |
| 111 | + TelemetryEvent? telemetryEvent) |
| 112 | + { |
| 113 | + var timestamp = alert.CreatedAt.ToUniversalTime().ToString("MMM dd HH:mm:ss", CultureInfo.InvariantCulture); |
| 114 | + var hostname = SanitizeSyslogToken(string.IsNullOrWhiteSpace(options.Hostname) |
| 115 | + ? Environment.MachineName |
| 116 | + : options.Hostname); |
| 117 | + var appName = SanitizeSyslogToken(options.AppName); |
| 118 | + var priority = Math.Clamp(options.Facility, 0, 23) * 8 + Severity(alert.Severity); |
| 119 | + |
| 120 | + var eventJson = BuildJson(agent, alert, telemetryEvent, includeTelemetryPayload: true); |
| 121 | + var message = $"<{priority}>{timestamp} {hostname} {appName}: {eventJson}"; |
| 122 | + var maxBytes = Math.Max(options.MaxMessageBytes, 1024); |
| 123 | + if (Encoding.UTF8.GetByteCount(message) <= maxBytes) |
| 124 | + { |
| 125 | + return message; |
| 126 | + } |
| 127 | + |
| 128 | + eventJson = BuildJson(agent, alert, telemetryEvent, includeTelemetryPayload: false); |
| 129 | + return $"<{priority}>{timestamp} {hostname} {appName}: {eventJson}"; |
| 130 | + } |
| 131 | + |
| 132 | + private static string BuildJson( |
| 133 | + Agent agent, |
| 134 | + Alert alert, |
| 135 | + TelemetryEvent? telemetryEvent, |
| 136 | + bool includeTelemetryPayload) |
| 137 | + { |
| 138 | + var payload = includeTelemetryPayload && telemetryEvent is not null |
| 139 | + ? telemetryEvent.Payload |
| 140 | + : null; |
| 141 | + |
| 142 | + return JsonSerializer.Serialize(new |
| 143 | + { |
| 144 | + integration = "tawny", |
| 145 | + event_kind = "alert", |
| 146 | + alert_id = alert.Id, |
| 147 | + alert_title = alert.Title, |
| 148 | + alert_description = alert.Description, |
| 149 | + alert_severity = alert.Severity, |
| 150 | + alert_status = alert.Status, |
| 151 | + alert_created_at = alert.CreatedAt, |
| 152 | + rule_id = alert.AlertRuleId, |
| 153 | + agent_id = agent.Id, |
| 154 | + tenant_id = agent.TenantId, |
| 155 | + agent_hostname = agent.Hostname, |
| 156 | + agent_os = agent.OperatingSystem, |
| 157 | + agent_os_version = agent.OsVersion, |
| 158 | + agent_architecture = agent.Architecture, |
| 159 | + agent_version = agent.AgentVersion, |
| 160 | + telemetry_id = telemetryEvent?.Id, |
| 161 | + telemetry_type = telemetryEvent?.EventType, |
| 162 | + telemetry_occurred_at = telemetryEvent?.OccurredAt, |
| 163 | + telemetry_received_at = telemetryEvent?.ReceivedAt, |
| 164 | + telemetry_payload_json = payload, |
| 165 | + telemetry_payload_omitted = telemetryEvent is not null && !includeTelemetryPayload, |
| 166 | + }, JsonOptions); |
| 167 | + } |
| 168 | + |
| 169 | + private static int Severity(AlertSeverity severity) => severity switch |
| 170 | + { |
| 171 | + AlertSeverity.Critical => 2, |
| 172 | + AlertSeverity.High => 3, |
| 173 | + AlertSeverity.Medium => 4, |
| 174 | + AlertSeverity.Low => 5, |
| 175 | + _ => 5, |
| 176 | + }; |
| 177 | + |
| 178 | + private static string SanitizeSyslogToken(string value) |
| 179 | + { |
| 180 | + var token = string.IsNullOrWhiteSpace(value) ? "tawny" : value.Trim(); |
| 181 | + var builder = new StringBuilder(token.Length); |
| 182 | + foreach (var c in token) |
| 183 | + { |
| 184 | + builder.Append(char.IsWhiteSpace(c) || c == ':' ? '-' : c); |
| 185 | + } |
| 186 | + return builder.ToString(); |
| 187 | + } |
| 188 | +} |
0 commit comments