-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProcessMonitorWorker.cs
More file actions
633 lines (555 loc) · 22.9 KB
/
ProcessMonitorWorker.cs
File metadata and controls
633 lines (555 loc) · 22.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Management.Infrastructure;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Threading;
using System.Threading.Tasks;
// Configuration Models
public class ProcessMonitorOptions
{
public List<string> ProcessFilters { get; set; } = new();
public List<string> ProcessExcludeFilters { get; set; } = new();
public int CacheExpiryMinutes { get; set; } = 30;
public int StatusUpdateIntervalMinutes { get; set; } = 5;
public int CacheCleanupIntervalMinutes { get; set; } = 10;
public int MaxCacheSize { get; set; } = 10000;
}
// Services
public interface IProcessOwnerService
{
Task<string> GetProcessOwnerSidAsync(int processId);
Task<string> GetProcessNameByIdAsync(uint processId);
}
public class ProcessOwnerService : IProcessOwnerService, IDisposable
{
private readonly ILogger<ProcessOwnerService> _logger;
private readonly Lazy<CimSession> _cimSession;
private bool _disposed = false;
public ProcessOwnerService(ILogger<ProcessOwnerService> logger)
{
_logger = logger;
_cimSession = new Lazy<CimSession>(() => CimSession.Create(null));
}
public async Task<string> GetProcessOwnerSidAsync(int processId)
{
try
{
return await Task.Run(() =>
{
var query = $"SELECT * FROM Win32_Process WHERE ProcessId = {processId}";
var result = _cimSession.Value.QueryInstances(@"root\cimv2", "WQL", query).FirstOrDefault();
if (result == null)
{
_logger.LogError("Process with ID {ProcessId} not found.", processId);
return "UNKNOWN_PROCESS_NOT_FOUND";
}
try
{
var methodResult = _cimSession.Value.InvokeMethod(result, "GetOwnerSid", null);
return methodResult?.OutParameters?["Sid"]?.Value?.ToString() ?? "UNKNOWN_SID_NOT_FOUND";
}
catch (CimException cimEx)
{
_logger.LogError(cimEx, "CIM method 'GetOwnerSid' failed for process {ProcessId}", processId);
return "ERROR_GETTING_SID";
}
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Error getting SID for process {ProcessId}", processId);
return "ERROR_GETTING_SID";
}
}
public async Task<string> GetProcessNameByIdAsync(uint processId)
{
if (processId == 0) return "N/A";
try
{
return await Task.Run(() =>
{
var query = $"SELECT Name FROM Win32_Process WHERE ProcessId = {processId}";
var result = _cimSession.Value.QueryInstances(@"root\cimv2", "WQL", query).FirstOrDefault();
return result?.CimInstanceProperties["Name"]?.Value?.ToString() ?? "N/A";
});
}
catch (Exception ex)
{
_logger.LogWarning(ex, "CIM query for process name failed for PID {ProcessId}", processId);
return "ERROR_GETTING_PROCESS_NAME";
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed && disposing)
{
if (_cimSession.IsValueCreated)
{
_cimSession.Value?.Dispose();
}
}
_disposed = true;
}
}
// Cache Entry Model
public class ProcessCacheEntry
{
public string Sid { get; set; } = string.Empty;
public DateTime LastAccess { get; set; } = DateTime.UtcNow;
public void UpdateAccess()
{
LastAccess = DateTime.UtcNow;
}
}
// Main Worker Class
public class ProcessMonitorWorker : BackgroundService
{
private readonly ILogger<ProcessMonitorWorker> _logger;
private readonly IOptionsMonitor<ProcessMonitorOptions> _optionsMonitor;
private readonly IProcessOwnerService _processOwnerService;
private HashSet<string> _processFilterSet = new(StringComparer.OrdinalIgnoreCase);
private HashSet<string> _processExcludeFilterSet = new(StringComparer.OrdinalIgnoreCase);
private readonly ConcurrentDictionary<int, ProcessCacheEntry> _processSidCache = new();
private readonly object _filterUpdateLock = new object();
private string _lastFilterSnapshot = "";
private ManagementEventWatcher? _startWatcher;
private ManagementEventWatcher? _stopWatcher;
private Timer? _cacheCleanupTimer;
private Timer? _statusTimer;
private ProcessMonitorOptions _currentOptions;
private bool _disposed = false;
public ProcessMonitorWorker(
ILogger<ProcessMonitorWorker> logger,
IOptionsMonitor<ProcessMonitorOptions> optionsMonitor,
IProcessOwnerService processOwnerService)
{
_logger = logger;
_optionsMonitor = optionsMonitor;
_processOwnerService = processOwnerService;
_currentOptions = _optionsMonitor.CurrentValue;
UpdateProcessFilters(_currentOptions.ProcessFilters, _currentOptions.ProcessExcludeFilters);
// Configuration change handler
_optionsMonitor.OnChange(options =>
{
_currentOptions = options;
UpdateProcessFilters(_currentOptions.ProcessFilters, _currentOptions.ProcessExcludeFilters);
});
}
public override Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("=== ProcessMonitorWorker starting ===");
_logger.LogInformation("Base directory: {BaseDirectory}", AppContext.BaseDirectory);
_logger.LogInformation("User context: {UserName}", Environment.UserName);
_logger.LogInformation("Active process filters: {FilterCount}, exclude filters: {ExcludeFilterCount}",
_processFilterSet.Count, _processExcludeFilterSet.Count);
return base.StartAsync(cancellationToken);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
await InitializeWmiWatchersAsync(stoppingToken);
InitializeTimers();
_logger.LogInformation("✓ ProcessMonitorWorker successfully started");
// Keep service running
await Task.Delay(Timeout.Infinite, stoppingToken);
}
catch (OperationCanceledException)
{
_logger.LogInformation("ProcessMonitorWorker stopping gracefully");
}
catch (Exception ex)
{
_logger.LogCritical(ex, "CRITICAL ERROR in ProcessMonitorWorker. Service may become unstable");
throw; // Re-throw to trigger service restart
}
}
private async Task InitializeWmiWatchersAsync(CancellationToken cancellationToken)
{
await Task.Run(() =>
{
try
{
// Dynamische WQL-Query basierend auf den konfigurierten Filtern
string processFilter = BuildProcessFilter();
string baseQuery = string.IsNullOrEmpty(processFilter)
? "TargetInstance ISA 'Win32_Process'"
: $"TargetInstance ISA 'Win32_Process' AND ({processFilter})";
string creationQuery = $"SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE {baseQuery}";
string deletionQuery = $"SELECT * FROM __InstanceDeletionEvent WITHIN 1 WHERE {baseQuery}";
_startWatcher = new ManagementEventWatcher(new WqlEventQuery(creationQuery));
_stopWatcher = new ManagementEventWatcher(new WqlEventQuery(deletionQuery));
_startWatcher.EventArrived += OnProcessStarted;
_stopWatcher.EventArrived += OnProcessStopped;
_logger.LogInformation("Starting WMI event watchers with filter: {ProcessFilter}",
string.IsNullOrEmpty(processFilter) ? "ALL PROCESSES" : processFilter);
_startWatcher.Start();
_stopWatcher.Start();
_logger.LogInformation("✓ WMI event watchers started successfully");
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to initialize WMI watchers");
throw;
}
}, cancellationToken);
}
private string EscapeWqlString(string input)
{
if (string.IsNullOrEmpty(input))
return input;
// Ersetze Apostrophe durch doppelte Apostrophe und escape zusätzlich auch Backslashes
return input.Replace("'", "''").Replace("\\", "\\\\");
}
private string BuildProcessFilter()
{
var includeConditions = new List<string>();
var excludeConditions = new List<string>();
// Include-Filter erstellen (wenn vorhanden)
if (_processFilterSet.Any())
{
var conditions = _processFilterSet
.Select(processName =>
{
if (processName.Contains('*') || processName.Contains('?'))
{
var wqlPattern = processName.Replace("*", "%").Replace("?", "_");
return $"TargetInstance.Name LIKE '{EscapeWqlString(wqlPattern)}'";
}
else
{
return $"TargetInstance.Name = '{EscapeWqlString(processName)}'";
}
});
includeConditions.Add($"({string.Join(" OR ", conditions)})");
}
// Exclude-Filter erstellen (wenn vorhanden)
if (_processExcludeFilterSet.Any())
{
var conditions = _processExcludeFilterSet
.Select(processName =>
{
if (processName.Contains('*') || processName.Contains('?'))
{
var wqlPattern = processName.Replace("*", "%").Replace("?", "_");
return $"NOT TargetInstance.Name LIKE '{EscapeWqlString(wqlPattern)}'";
}
else
{
return $"NOT TargetInstance.Name = '{EscapeWqlString(processName)}'";
}
});
excludeConditions.AddRange(conditions);
}
// Finale Bedingung zusammenbauen
var finalConditions = new List<string>();
if (includeConditions.Any())
{
finalConditions.AddRange(includeConditions);
}
if (excludeConditions.Any())
{
finalConditions.AddRange(excludeConditions);
}
// Wenn keine Filter vorhanden sind, alle Prozesse überwachen
if (!finalConditions.Any())
{
return string.Empty;
}
return string.Join(" AND ", finalConditions);
}
private void UpdateProcessFilters(List<string> filters, List<string> excludeFilters)
{
_logger.LogDebug("Entering UpdateProcessFilters.");
lock (_filterUpdateLock)
{
string snapshot = string.Join(",", filters) + "|" + string.Join(",", excludeFilters);
_logger.LogDebug("snapshot {snapshot}", snapshot);
_logger.LogDebug("_lastFilterSnapshot {_lastFilterSnapshot}", _lastFilterSnapshot);
if (snapshot == _lastFilterSnapshot)
{
_logger.LogDebug("Configuration snapshot identical, skipping update. Last snapshot: {LastSnapshot}", _lastFilterSnapshot);
return;
}
_logger.LogInformation("Configuration changed, reloading settings");
_lastFilterSnapshot = snapshot;
_processFilterSet = new HashSet<string>(filters ?? new List<string>(), StringComparer.OrdinalIgnoreCase);
_processExcludeFilterSet = new HashSet<string>(excludeFilters ?? new List<string>(), StringComparer.OrdinalIgnoreCase);
_logger.LogInformation("Process filters updated: {FilterCount} include filters, {ExcludeFilterCount} exclude filters loaded",
_processFilterSet.Count, _processExcludeFilterSet.Count);
_logger.LogDebug("Active include filters: {@ProcessFilters}", _processFilterSet.ToArray());
_logger.LogDebug("Active exclude filters: {@ProcessExcludeFilters}", _processExcludeFilterSet.ToArray());
// WMI-Watcher neu initialisieren, wenn sie bereits laufen
if (_startWatcher != null || _stopWatcher != null)
{
_logger.LogInformation("Reinitializing WMI watchers due to filter change");
RestartWatchers();
}
}
}
private void RestartWatchers()
{
try
{
// Alte Watcher stoppen und dispose
_startWatcher?.Stop();
_stopWatcher?.Stop();
_startWatcher?.Dispose();
_stopWatcher?.Dispose();
// Neu initialisieren
InitializeWmiWatchersAsync(CancellationToken.None).Wait();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error restarting WMI watchers");
}
}
private void InitializeTimers()
{
// Cache cleanup timer
var cleanupInterval = TimeSpan.FromMinutes(_currentOptions.CacheCleanupIntervalMinutes);
_cacheCleanupTimer = new Timer(CleanupExpiredCacheEntries, null, cleanupInterval, cleanupInterval);
// Status update timer
var statusInterval = TimeSpan.FromMinutes(_currentOptions.StatusUpdateIntervalMinutes);
_statusTimer = new Timer(LogStatusUpdate, null, statusInterval, statusInterval);
_logger.LogInformation("Timers initialized - Cache cleanup: {CleanupInterval}min, Status: {StatusInterval}min",
_currentOptions.CacheCleanupIntervalMinutes, _currentOptions.StatusUpdateIntervalMinutes);
}
private void OnProcessStarted(object sender, EventArrivedEventArgs e)
{
try
{
_ = Task.Run(async () => await HandleProcessEventAsync(e, "Start"));
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in process start event handler");
}
}
private void OnProcessStopped(object sender, EventArrivedEventArgs e)
{
try
{
_ = Task.Run(async () => await HandleProcessEventAsync(e, "Stop"));
}
catch (Exception ex)
{
_logger.LogError(ex, "Error in process stop event handler");
}
}
private async Task HandleProcessEventAsync(EventArrivedEventArgs e, string eventType)
{
try
{
var process = (ManagementBaseObject)e.NewEvent["TargetInstance"];
var name = process["Name"]?.ToString() ?? "N/A";
// Filter check - early return if not monitored
if (!ShouldMonitorProcess(name))
{
return;
}
var pid = Convert.ToInt32(process["ProcessId"]);
var sid = "UNKNOWN";
uint parentPid = Convert.ToUInt32(process["ParentProcessId"]);
string parentName = await _processOwnerService.GetProcessNameByIdAsync(parentPid);
if (eventType == "Start")
{
sid = await _processOwnerService.GetProcessOwnerSidAsync(pid);
// Erzwinge die Cache-Kapazitätsgrenze
if (_processSidCache.Count >= _currentOptions.MaxCacheSize && !_processSidCache.ContainsKey(pid))
{
// Finde und entferne den ältesten Eintrag, um Platz zu schaffen
var oldestEntry = _processSidCache.OrderBy(kvp => kvp.Value.LastAccess).FirstOrDefault();
if (oldestEntry.Key != default)
{
if (_processSidCache.TryRemove(oldestEntry.Key, out _))
{
_logger.LogWarning("Cache-Kapazität von {MaxCacheSize} erreicht. Ältester Eintrag (PID: {EvictedPid}) wird entfernt, um Platz für neuen Prozess (PID: {NewPid}) zu machen.",
_currentOptions.MaxCacheSize, oldestEntry.Key, pid);
}
}
}
_processSidCache[pid] = new ProcessCacheEntry { Sid = sid };
}
else if (eventType == "Stop")
{
if (_processSidCache.TryRemove(pid, out var cachedEntry))
{
sid = cachedEntry.Sid;
}
}
// Rufen Sie die aktualisierte Logging-Methode mit den neuen Parametern auf
LogProcessEvent(eventType, name, pid, sid, Convert.ToInt32(parentPid), parentName, process);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error handling process event: {EventType}", eventType);
}
}
private bool ShouldMonitorProcess(string processName)
{
// Zuerst prüfen, ob der Prozess explizit ausgeschlossen werden soll
if (_processExcludeFilterSet.Any())
{
foreach (var excludeFilter in _processExcludeFilterSet)
{
if (excludeFilter.Contains('*') || excludeFilter.Contains('?'))
{
// Wildcard-Matching für Exclude-Filter
var pattern = "^" + System.Text.RegularExpressions.Regex.Escape(excludeFilter)
.Replace("\\*", ".*")
.Replace("\\?", ".") + "$";
if (System.Text.RegularExpressions.Regex.IsMatch(processName, pattern,
System.Text.RegularExpressions.RegexOptions.IgnoreCase))
{
return false; // Prozess ist ausgeschlossen
}
}
else
{
// Exakte Übereinstimmung für Exclude-Filter
if (string.Equals(processName, excludeFilter, StringComparison.OrdinalIgnoreCase))
{
return false; // Prozess ist ausgeschlossen
}
}
}
}
// Dann prüfen, ob Include-Filter definiert sind
if (_processFilterSet.Any())
{
foreach (var includeFilter in _processFilterSet)
{
if (includeFilter.Contains('*') || includeFilter.Contains('?'))
{
// Wildcard-Matching für Include-Filter
var pattern = "^" + System.Text.RegularExpressions.Regex.Escape(includeFilter)
.Replace("\\*", ".*")
.Replace("\\?", ".") + "$";
if (System.Text.RegularExpressions.Regex.IsMatch(processName, pattern,
System.Text.RegularExpressions.RegexOptions.IgnoreCase))
{
return true; // Prozess ist eingeschlossen
}
}
else
{
// Exakte Übereinstimmung für Include-Filter
if (string.Equals(processName, includeFilter, StringComparison.OrdinalIgnoreCase))
{
return true; // Prozess ist eingeschlossen
}
}
}
return false; // Kein Include-Filter matched
}
// Keine Include-Filter definiert = alle Prozesse überwachen (außer ausgeschlossene)
return true;
}
private void LogProcessEvent(string eventType, string name, int pid, string sid, int parentPid, string parentName, ManagementBaseObject process)
{
_logger.LogInformation(
"Process {EventType}: {ProcessName} (PID: {ProcessId}) User: {UserSid} Parent: {ParentName} (PID: {ParentProcessId}) Path: {ExecutablePath} Command: {CommandLine}",
eventType,
name,
pid,
sid,
parentName,
parentPid,
process["ExecutablePath"]?.ToString() ?? "N/A",
process["CommandLine"]?.ToString() ?? "N/A"
);
}
private void CleanupExpiredCacheEntries(object? state)
{
try
{
var expiryTime = TimeSpan.FromMinutes(_currentOptions.CacheExpiryMinutes);
var cutoffTime = DateTime.UtcNow - expiryTime;
var expiredKeys = _processSidCache
.Where(kvp => kvp.Value.LastAccess < cutoffTime)
.Select(kvp => kvp.Key)
.ToList();
var removedCount = 0;
foreach (var key in expiredKeys)
{
if (_processSidCache.TryRemove(key, out _))
{
removedCount++;
}
}
if (removedCount > 0)
{
_logger.LogDebug("Cache cleanup: removed {RemovedCount} expired entries, {RemainingCount} entries remaining",
removedCount, _processSidCache.Count);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during cache cleanup");
}
}
private void LogStatusUpdate(object? state)
{
try
{
_logger.LogInformation("Service status: Running. Cache entries: {CacheCount}/{MaxCacheSize}, Include filters: {FilterCount}, Exclude filters: {ExcludeFilterCount}",
_processSidCache.Count, _currentOptions.MaxCacheSize, _processFilterSet.Count, _processExcludeFilterSet.Count);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during status update");
}
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("=== ProcessMonitorWorker stopping ===");
try
{
// Stop timers
_cacheCleanupTimer?.Change(Timeout.Infinite, Timeout.Infinite);
_statusTimer?.Change(Timeout.Infinite, Timeout.Infinite);
// Stop WMI watchers
_startWatcher?.Stop();
_stopWatcher?.Stop();
_logger.LogInformation("✓ WMI event watchers stopped successfully");
_logger.LogInformation("✓ Service stopped at: {StopTime}. Final cache count: {CacheCount}",
DateTime.Now, _processSidCache.Count);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during service shutdown");
}
await base.StopAsync(cancellationToken);
}
public override void Dispose()
{
if (!_disposed)
{
try
{
_startWatcher?.Dispose();
_stopWatcher?.Dispose();
_cacheCleanupTimer?.Dispose();
_statusTimer?.Dispose();
(_processOwnerService as IDisposable)?.Dispose();
}
catch (Exception ex)
{
_logger?.LogError(ex, "Error during disposal");
}
_disposed = true;
}
GC.SuppressFinalize(this);
}
}