-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSystemGuardian.cs
More file actions
1177 lines (1078 loc) · 44.4 KB
/
SystemGuardian.cs
File metadata and controls
1177 lines (1078 loc) · 44.4 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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Security.Principal;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32;
namespace SystemGuardian
{
public class GuardianService : ServiceBase
{
#region Native Methods
private static class NativeMethods
{
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool InitializeSecurityDescriptor(out SECURITY_DESCRIPTOR sd, uint dwRevision);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool SetSecurityDescriptorDacl(ref SECURITY_DESCRIPTOR sd, bool daclPresent, IntPtr dacl, bool daclDefaulted);
[DllImport("kernel32.dll")]
public static extern IntPtr GetCurrentProcess();
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool OpenProcessToken(IntPtr ProcessHandle, uint DesiredAccess, out IntPtr TokenHandle);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool GetTokenInformation(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, IntPtr TokenInformation, uint TokenInformationLength, out uint ReturnLength);
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_DESCRIPTOR
{
public byte Revision;
public byte Sbz1;
public ushort Control;
public IntPtr Owner;
public IntPtr Group;
public IntPtr Sacl;
public IntPtr Dacl;
}
public enum TOKEN_INFORMATION_CLASS
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId,
TokenGroupsAndPrivileges,
TokenSessionReference,
TokenSandBoxInert,
TokenAuditPolicy,
TokenOrigin,
TokenElevationType,
TokenLinkedToken,
TokenElevation,
TokenHasRestrictions,
TokenAccessInformation,
TokenVirtualizationAllowed,
TokenVirtualizationEnabled,
TokenIntegrityLevel,
TokenUIAccess,
TokenMandatoryPolicy,
TokenLogonSid,
MaxTokenInfoClass
}
}
#endregion
#region Constants and Fields
private const string ServiceName = "SystemGuardian";
private const string EventLogSource = "SystemGuardian";
private const string EventLogName = "Application";
private readonly string BaseDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "SystemGuardian");
private readonly string LogDirectory;
private readonly string RecoveryDirectory;
private readonly string BackupDirectory;
private CancellationTokenSource _cancellationTokenSource;
private readonly ConcurrentDictionary<string, ComponentInfo> _monitoredComponents;
private readonly BlockingCollection<SystemEvent> _eventQueue;
private readonly HashSet<string> _criticalPaths;
private readonly ManagementEventWatcher _registryWatcher;
private readonly ManagementEventWatcher _deviceWatcher;
private readonly FileSystemWatcher _systemWatcher;
private volatile bool _isInitialized;
#endregion
#region Data Structures
private class ComponentInfo
{
public string Path { get; set; }
public string Hash { get; set; }
public DateTime LastModified { get; set; }
public ComponentType Type { get; set; }
public ComponentStatus Status { get; set; }
public Dictionary<string, string> Metadata { get; set; }
}
private class SystemEvent
{
public DateTime Timestamp { get; set; }
public EventType Type { get; set; }
public string Source { get; set; }
public string Description { get; set; }
public EventSeverity Severity { get; set; }
}
private enum ComponentType
{
Driver,
Service,
SystemFile,
RegistryKey
}
private enum ComponentStatus
{
Normal,
Warning,
Critical,
Isolated
}
private enum EventType
{
SystemChange,
SecurityEvent,
PerformanceIssue,
ComponentFailure
}
private enum EventSeverity
{
Information,
Warning,
Error,
Critical
}
#endregion
public GuardianService()
{
ServiceName = ServiceName;
CanStop = true;
CanShutdown = true;
CanPauseAndContinue = false;
AutoLog = false;
LogDirectory = Path.Combine(BaseDirectory, "Logs");
RecoveryDirectory = Path.Combine(BaseDirectory, "Recovery");
BackupDirectory = Path.Combine(BaseDirectory, "Backups");
_monitoredComponents = new ConcurrentDictionary<string, ComponentInfo>();
_eventQueue = new BlockingCollection<SystemEvent>();
_criticalPaths = new HashSet<string>
{
@"C:\Windows\System32\drivers",
@"C:\Windows\System32",
@"C:\Windows\SysWOW64"
};
InitializeEnvironment();
InitializeEventLog();
InitializeWatchers();
}
private void InitializeEnvironment()
{
try
{
Directory.CreateDirectory(BaseDirectory);
Directory.CreateDirectory(LogDirectory);
Directory.CreateDirectory(RecoveryDirectory);
Directory.CreateDirectory(BackupDirectory);
// Set secure permissions
var directorySecurity = new DirectorySecurity();
directorySecurity.SetAccessRuleProtection(true, false);
var rule = new FileSystemAccessRule(
new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null),
FileSystemRights.FullControl,
InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,
PropagationFlags.None,
AccessControlType.Allow);
directorySecurity.AddAccessRule(rule);
Directory.SetAccessControl(BaseDirectory, directorySecurity);
_isInitialized = true;
}
catch (Exception ex)
{
LogEvent($"Failed to initialize environment: {ex.Message}", EventLogEntryType.Error);
throw;
}
}
private void InitializeEventLog()
{
try
{
if (!EventLog.SourceExists(EventLogSource))
{
EventLog.CreateEventSource(EventLogSource, EventLogName);
}
}
catch (Exception ex)
{
LogEvent($"Failed to initialize event log: {ex.Message}", EventLogEntryType.Error);
throw;
}
}
private void InitializeWatchers()
{
try
{
// Initialize Registry Watcher
_registryWatcher = new ManagementEventWatcher(
new WqlEventQuery("SELECT * FROM RegistryTreeChangeEvent WHERE Hive='HKEY_LOCAL_MACHINE'"));
_registryWatcher.EventArrived += RegistryChangeDetected;
// Initialize Device Watcher
_deviceWatcher = new ManagementEventWatcher(
new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent"));
_deviceWatcher.EventArrived += DeviceChangeDetected;
// Initialize File System Watcher
_systemWatcher = new FileSystemWatcher();
_systemWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
_systemWatcher.Changed += FileSystemChangeDetected;
_systemWatcher.Created += FileSystemChangeDetected;
_systemWatcher.Deleted += FileSystemChangeDetected;
_systemWatcher.Error += FileSystemWatcherError;
}
catch (Exception ex)
{
LogEvent($"Failed to initialize watchers: {ex.Message}", EventLogEntryType.Error);
throw;
}
}
protected override void OnStart(string[] args)
{
try
{
if (!_isInitialized)
{
throw new InvalidOperationException("Service not properly initialized");
}
_cancellationTokenSource = new CancellationTokenSource();
LogEvent("Service starting...", EventLogEntryType.Information);
// Start monitoring tasks
Task.Run(() => MonitorSystem(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
Task.Run(() => ProcessEventQueue(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
// Start watchers
_registryWatcher.Start();
_deviceWatcher.Start();
foreach (var path in _criticalPaths)
{
if (Directory.Exists(path))
{
_systemWatcher.Path = path;
_systemWatcher.EnableRaisingEvents = true;
}
}
// Create initial system snapshot
CreateSystemSnapshot();
LogEvent("Service started successfully", EventLogEntryType.Information);
}
catch (Exception ex)
{
LogEvent($"Service failed to start: {ex.Message}", EventLogEntryType.Error);
Stop();
}
}
protected override void OnStop()
{
try
{
LogEvent("Service stopping...", EventLogEntryType.Information);
_cancellationTokenSource?.Cancel();
_registryWatcher?.Stop();
_deviceWatcher?.Stop();
_systemWatcher.EnableRaisingEvents = false;
// Cleanup and final backup
CreateSystemSnapshot("FinalSnapshot");
CleanupOldRecoveryPoints();
LogEvent("Service stopped successfully", EventLogEntryType.Information);
}
catch (Exception ex)
{
LogEvent($"Error during service shutdown: {ex.Message}", EventLogEntryType.Error);
}
finally
{
_cancellationTokenSource?.Dispose();
_registryWatcher?.Dispose();
_deviceWatcher?.Dispose();
_systemWatcher?.Dispose();
}
}
private async Task MonitorSystem(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
await Task.WhenAll(
MonitorSystemPerformance(cancellationToken),
MonitorServiceHealth(cancellationToken),
VerifySystemIntegrity(cancellationToken)
);
await Task.Delay(TimeSpan.FromMinutes(5), cancellationToken);
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
LogEvent($"System monitoring error: {ex.Message}", EventLogEntryType.Error);
await Task.Delay(TimeSpan.FromMinutes(1), cancellationToken);
}
}
}
private async Task MonitorSystemPerformance(CancellationToken cancellationToken)
{
var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
var memoryCounter = new PerformanceCounter("Memory", "Available MBytes");
while (!cancellationToken.IsCancellationRequested)
{
try
{
var cpuUsage = cpuCounter.NextValue();
var availableMemory = memoryCounter.NextValue();
if (cpuUsage > 90 || availableMemory < 500)
{
_eventQueue.Add(new SystemEvent
{
Timestamp = DateTime.UtcNow,
Type = EventType.PerformanceIssue,
Source = "System Performance",
Description = $"High resource usage - CPU: {cpuUsage}%, Available Memory: {availableMemory}MB",
Severity = EventSeverity.Warning
});
}
await Task.Delay(TimeSpan.FromSeconds(30), cancellationToken);
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
LogEvent($"Performance monitoring error: {ex.Message}", EventLogEntryType.Error);
await Task.Delay(TimeSpan.FromMinutes(1), cancellationToken);
}
}
}
private async Task MonitorServiceHealth(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
foreach (var service in ServiceController.GetServices())
{
var componentKey = $"Service_{service.ServiceName}";
if (!_monitoredComponents.ContainsKey(componentKey))
{
_monitoredComponents.TryAdd(componentKey, new ComponentInfo
{
Path = service.ServiceName,
Type = ComponentType.Service,
Status = ComponentStatus.Normal,
Metadata = new Dictionary<string, string>
{
{ "DisplayName", service.DisplayName },
{ "StartType", service.StartType.ToString() }
}
});
}
if (service.Status == ServiceControllerStatus.Stopped &&
service.StartType == ServiceStartMode.Automatic)
{
_eventQueue.Add(new SystemEvent
{
Timestamp = DateTime.UtcNow,
Type = EventType.ComponentFailure,
Source = $"Service_{service.ServiceName}",
Description = $"Automatic service {service.DisplayName} is stopped",
Severity = EventSeverity.Warning
});
await AttemptServiceRecovery(service);
}
}
await Task.Delay(TimeSpan.FromMinutes(1), cancellationToken);
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
LogEvent($"Service health monitoring error: {ex.Message}", EventLogEntryType.Error);
await Task.Delay(TimeSpan.FromMinutes(1), cancellationToken);
}
}
}
private async Task VerifySystemIntegrity(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
foreach (var component in _monitoredComponents)
{
if (component.Value.Type == ComponentType.SystemFile ||
component.Value.Type == ComponentType.Driver)
{
if (File.Exists(component.Value.Path))
{
var currentHash = CalculateFileHash(component.Value.Path);
var lastModified = File.GetLastWriteTimeUtc(component.Value.Path);
if (currentHash != component.Value.Hash ||
lastModified != component.Value.LastModified)
{
_eventQueue.Add(new SystemEvent
{
Timestamp = DateTime.UtcNow,
Type = EventType.SystemChange,
Source = component.Key,
Description = $"File integrity change detected: {component.Value.Path}",
Severity = EventSeverity.Warning
});
// Update component information
component.Value.Hash = currentHash;
component.Value.LastModified = lastModified;
await VerifyComponentSignature(component.Value);
}
}
else
{
_eventQueue.Add(new SystemEvent
{
Timestamp = DateTime.UtcNow,
Type = EventType.ComponentFailure,
Source = component.Key,
Description = $"Monitored component missing: {component.Value.Path}",
Severity = EventSeverity.Critical
});
await AttemptComponentRecovery(component.Key);
}
}
await Task.Delay(TimeSpan.FromMinutes(15), cancellationToken);
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
LogEvent($"System integrity verification error: {ex.Message}", EventLogEntryType.Error);
await Task.Delay(TimeSpan.FromMinutes(1), cancellationToken);
}
}
}
private async Task ProcessEventQueue(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
if (_eventQueue.TryTake(out SystemEvent evt, 1000, cancellationToken))
{
await HandleSystemEvent(evt);
}
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
LogEvent($"Event processing error: {ex.Message}", EventLogEntryType.Error);
}
}
}
private async Task HandleSystemEvent(SystemEvent evt)
{
try
{
// Log the event
LogEvent(evt.Description, MapSeverityToEventLogEntryType(evt.Severity));
// Take action based on event type and severity
switch (evt.Type)
{
case EventType.ComponentFailure:
if (evt.Severity >= EventSeverity.Error)
{
await CreateRecoveryPoint($"Pre-recovery_{evt.Source}");
await AttemptComponentRecovery(evt.Source);
}
break;
case EventType.SecurityEvent:
if (evt.Severity >= EventSeverity.Warning)
{
await CreateRecoveryPoint($"Security_{evt.Source}");
if (evt.Severity >= EventSeverity.Critical)
{
await IsolateComponent(evt.Source);
}
}
break;
case EventType.SystemChange:
if (evt.Severity >= EventSeverity.Warning)
{
await ValidateSystemChange(evt.Source);
}
break;
case EventType.PerformanceIssue:
if (evt.Severity >= EventSeverity.Error)
{
await AttemptPerformanceRecovery();
}
break;
}
}
catch (Exception ex)
{
LogEvent($"Error handling event {evt.Type} from {evt.Source}: {ex.Message}", EventLogEntryType.Error);
}
}
private async Task ValidateSystemChange(string componentKey)
{
if (_monitoredComponents.TryGetValue(componentKey, out var component))
{
try
{
bool isValid = await VerifyComponentSignature(component);
if (!isValid)
{
_eventQueue.Add(new SystemEvent
{
Timestamp = DateTime.UtcNow,
Type = EventType.SecurityEvent,
Source = componentKey,
Description = "Invalid signature detected on changed component",
Severity = EventSeverity.Critical
});
}
}
catch (Exception ex)
{
LogEvent($"Change validation error for {componentKey}: {ex.Message}", EventLogEntryType.Error);
}
}
}
private async Task AttemptComponentRecovery(string componentKey)
{
if (_monitoredComponents.TryGetValue(componentKey, out var component))
{
try
{
switch (component.Type)
{
case ComponentType.Driver:
await RecoverDriver(component);
break;
case ComponentType.Service:
await RecoverService(component);
break;
case ComponentType.SystemFile:
await RecoverSystemFile(component);
break;
case ComponentType.RegistryKey:
await RecoverRegistryKey(component);
break;
}
}
catch (Exception ex)
{
LogEvent($"Recovery failed for {componentKey}: {ex.Message}", EventLogEntryType.Error);
}
}
}
private async Task RecoverDriver(ComponentInfo component)
{
try
{
// Attempt to restore from backup
var backupPath = Path.Combine(BackupDirectory, Path.GetFileName(component.Path));
if (File.Exists(backupPath))
{
if (await VerifyComponentSignature(new ComponentInfo { Path = backupPath, Type = ComponentType.Driver }))
{
File.Copy(backupPath, component.Path, true);
await ReloadDriver(component.Path);
}
}
else
{
// Attempt to restore from Windows Driver Store
await RestoreFromDriverStore(component.Path);
}
}
catch (Exception ex)
{
throw new Exception($"Driver recovery failed: {ex.Message}", ex);
}
}
private async Task RecoverService(ComponentInfo component)
{
try
{
using (var service = new ServiceController(component.Path))
{
if (service.Status == ServiceControllerStatus.Stopped)
{
service.Start();
await Task.Delay(TimeSpan.FromSeconds(30));
if (service.Status != ServiceControllerStatus.Running)
{
throw new Exception($"Service failed to start: {component.Path}");
}
}
}
}
catch (Exception ex)
{
throw new Exception($"Service recovery failed: {ex.Message}", ex);
}
}
private async Task RecoverSystemFile(ComponentInfo component)
{
try
{
// Attempt to restore from backup
var backupPath = Path.Combine(BackupDirectory, Path.GetFileName(component.Path));
if (File.Exists(backupPath))
{
if (await VerifyComponentSignature(new ComponentInfo { Path = backupPath, Type = ComponentType.SystemFile }))
{
File.Copy(backupPath, component.Path, true);
}
}
else
{
// Attempt to restore from Windows Component Store
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "DISM.exe",
Arguments = $"/Online /Cleanup-Image /RestoreHealth /StartComponentCleanup",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
process.Start();
await process.WaitForExitAsync();
}
}
catch (Exception ex)
{
throw new Exception($"System file recovery failed: {ex.Message}", ex);
}
}
private async Task RecoverRegistryKey(ComponentInfo component)
{
try
{
// Attempt to restore from last known good configuration
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "reg.exe",
Arguments = $"restore \"{component.Path}\" \"{Path.Combine(BackupDirectory, "registry.bak")}\"",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
process.Start();
await process.WaitForExitAsync();
}
catch (Exception ex)
{
throw new Exception($"Registry recovery failed: {ex.Message}", ex);
}
}
private async Task AttemptPerformanceRecovery()
{
try
{
// Analyze and terminate resource-heavy processes
var processes = Process.GetProcesses()
.Where(p => !string.IsNullOrEmpty(p.ProcessName))
.Select(p => new
{
Process = p,
CpuUsage = GetProcessCpuUsage(p),
MemoryUsage = p.WorkingSet64 / (1024 * 1024) // MB
})
.Where(p => p.CpuUsage > 80 || p.MemoryUsage > 1000)
.ToList();
foreach (var proc in processes)
{
_eventQueue.Add(new SystemEvent
{
Timestamp = DateTime.UtcNow,
Type = EventType.PerformanceIssue,
Source = proc.Process.ProcessName,
Description = $"High resource usage - CPU: {proc.CpuUsage}%, Memory: {proc.MemoryUsage}MB",
Severity = EventSeverity.Warning
});
}
// Clean up temporary files
await CleanupTemporaryFiles();
}
catch (Exception ex)
{
LogEvent($"Performance recovery failed: {ex.Message}", EventLogEntryType.Error);
}
}
#region Helper Methods
private string CalculateFileHash(string filePath)
{
using (var sha256 = SHA256.Create())
using (var stream = File.OpenRead(filePath))
{
var hash = sha256.ComputeHash(stream);
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
}
private async Task<bool> VerifyComponentSignature(ComponentInfo component)
{
try
{
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "signtool.exe",
Arguments = $"verify /pa \"{component.Path}\"",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
process.Start();
await process.WaitForExitAsync();
return process.ExitCode == 0;
}
catch (Exception)
{
return false;
}
}
private async Task CreateRecoveryPoint(string description)
{
var timestamp = DateTime.UtcNow.ToString("yyyyMMddHHmmss");
var recoveryPath = Path.Combine(RecoveryDirectory, timestamp);
Directory.CreateDirectory(recoveryPath);
try
{
// Backup critical components
foreach (var component in _monitoredComponents.Values)
{
if (File.Exists(component.Path))
{
File.Copy(component.Path, Path.Combine(recoveryPath, Path.GetFileName(component.Path)), true);
}
}
// Backup registry
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "reg.exe",
Arguments = $"save HKLM \"{Path.Combine(recoveryPath, "registry.hiv")}\"",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
process.Start();
await process.WaitForExitAsync();
// Save recovery point metadata
File.WriteAllText(
Path.Combine(recoveryPath, "metadata.json"),
System.Text.Json.JsonSerializer.Serialize(new
{
Timestamp = DateTime.UtcNow,
Description = description,
Components = _monitoredComponents
}));
}
catch (Exception ex)
{
LogEvent($"Failed to create recovery point: {ex.Message}", EventLogEntryType.Error);
Directory.Delete(recoveryPath, true);
}
}
private void LogEvent(string message, EventLogEntryType type)
{
try
{
EventLog.WriteEntry(EventLogSource, message, type);
File.AppendAllText(
Path.Combine(LogDirectory, $"SystemGuardian_{DateTime.UtcNow:yyyyMMdd}.log"),
$"{DateTime.UtcNow:u}: [{type}] {message}{Environment.NewLine}"
);
}
catch
{
// Fail silently if logging fails
}
}
private EventLogEntryType MapSeverityToEventLogEntryType(EventSeverity severity)
{
return severity switch
{
EventSeverity.Information => EventLogEntryType.Information,
EventSeverity.Warning => EventLogEntryType.Warning,
EventSeverity.Error => EventLogEntryType.Error,
EventSeverity.Critical => EventLogEntryType.Error,
_ => EventLogEntryType.Information
};
}
private float GetProcessCpuUsage(Process process)
{
try
{
var startTime = DateTime.UtcNow;
var startCpuUsage = process.TotalProcessorTime;
Thread.Sleep(500);
var endTime = DateTime.UtcNow;
var endCpuUsage = process.TotalProcessorTime;
var cpuUsedMs = (endCpuUsage - startCpuUsage).TotalMilliseconds;
var totalMsPassed = (endTime - startTime).TotalMilliseconds;
var cpuUsageTotal = cpuUsedMs / (Environment.ProcessorCount * totalMsPassed) * 100;
return (float)cpuUsageTotal;
}
catch
{
return 0;
}
}
private async Task CleanupTemporaryFiles()
{
var tempPaths = new[]
{
Path.GetTempPath(),
@"C:\Windows\Temp",
@"C:\Windows\Prefetch"
};
foreach (var path in tempPaths)
{
try
{
var di = new DirectoryInfo(path);
foreach (var file in di.GetFiles())
{
try
{
if (DateTime.UtcNow - file.LastAccessTimeUtc > TimeSpan.FromDays(7))
{
file.Delete();
}
}
catch
{
// Skip files that cannot be deleted
continue;
}
}
foreach (var dir in di.GetDirectories())
{
try
{
if (DateTime.UtcNow - dir.LastAccessTimeUtc > TimeSpan.FromDays(7))
{
dir.Delete(true);
}
}
catch
{
// Skip directories that cannot be deleted
continue;
}
}
}
catch (Exception ex)
{
LogEvent($"Failed to cleanup temporary files in {path}: {ex.Message}", EventLogEntryType.Warning);
}
}
}
private async Task RestoreFromDriverStore(string driverPath)
{
try
{
var driverFileName = Path.GetFileName(driverPath);
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "pnputil.exe",
Arguments = $"/add-driver \"{driverPath}\" /install",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
process.Start();
await process.WaitForExitAsync();
}
catch (Exception ex)
{
throw new Exception($"Failed to restore driver from store: {ex.Message}", ex);
}
}