-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRuleChecker.cs
More file actions
686 lines (609 loc) · 31.8 KB
/
Copy pathRuleChecker.cs
File metadata and controls
686 lines (609 loc) · 31.8 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
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace SCAScanner;
// ---------------------------------------------------------------------------
// Result types
// ---------------------------------------------------------------------------
/// <summary>Result of evaluating a single rule string from a check's rules list.</summary>
public sealed record RuleResult(bool Passed, bool Invalid, string Detail);
/// <summary>Result of evaluating an entire check (all its rules + condition).</summary>
public sealed record CheckResult(
CheckStatus Status,
string Reason,
IReadOnlyList<RuleResult> RuleResults);
// ---------------------------------------------------------------------------
// Checker
// ---------------------------------------------------------------------------
public static class RuleChecker
{
private sealed class RuleCheckResult
{
public CheckStatus Status { get; set; }
public string Detail { get; set; } = string.Empty;
}
// =========================================================================
// Check evaluation (applies condition: all / any / none)
// =========================================================================
public static CheckResult EvaluateCheck(Check check, PolicyVariables? variables)
{
List<RuleResult> results = check.Rules
.Select(r => EvaluateRule(RuleParser.Parse(r, variables)))
.ToList();
bool hasInvalid = results.Any(r => r.Invalid);
bool hasValidPass = results.Where(r => !r.Invalid).Any(r => r.Passed);
bool hasValidFail = results.Where(r => !r.Invalid).Any(r => !r.Passed);
int passCount = results.Count(r => r.Passed && !r.Invalid);
int validCount = results.Count(r => !r.Invalid);
// Evaluate based on condition type and whether there are invalid rules
CheckCondition condType = check.ConditionEnum;
CheckStatus status;
string reason;
if (condType == CheckCondition.Any)
{
// ANY: requires at least one rule to pass
// If there's a valid pass, result is PASS (even with invalids)
// If all valid rules fail (none pass), result is FAIL (proven outcome)
// If all rules are invalid, result is INVALID (can't execute any)
if (hasValidPass)
{
status = CheckStatus.Passed;
reason = $"Condition 'ANY': at least one rule passed";
}
else if (validCount == 0)
{
// All rules are invalid → can't execute any
status = CheckStatus.Invalid;
reason = "Check invalid: all rules cannot be executed";
}
else
{
// All valid rules fail (none pass) → proven to fail
status = CheckStatus.Failed;
reason = $"Condition 'ANY': {passCount}/{validCount} rules passed";
}
}
else if (condType == CheckCondition.All)
{
// ALL: requires all rules to pass
// If there are any invalid rules, we can't confirm all pass → INVALID (unless proven to fail)
// But a single definite failure overrides invalid (proves it will fail)
bool allValidPass = !hasValidFail && validCount > 0;
if (hasInvalid)
{
if (validCount == 0)
{
// All rules are invalid → can't execute any
status = CheckStatus.Invalid;
reason = "Check invalid: all rules cannot be executed";
}
else if (hasValidFail)
{
// Have both invalid and valid fails → proven to fail
status = CheckStatus.Failed;
reason = $"Condition 'ALL': {passCount}/{validCount} rules passed";
}
else if (allValidPass)
{
// All valid rules pass but some are invalid → can't confirm all pass
status = CheckStatus.Invalid;
reason = "Check invalid: one or more rules cannot be executed";
}
else
{
// All valid rules fail → definitely FAIL
status = CheckStatus.Failed;
reason = $"Condition 'ALL': {passCount}/{validCount} rules passed";
}
}
else
{
// No invalid rules, use standard ALL logic
bool allPassed = results.All(r => r.Passed);
status = allPassed ? CheckStatus.Passed : CheckStatus.Failed;
reason = $"Condition 'ALL': {passCount}/{validCount} rules passed";
}
}
else if (condType == CheckCondition.None)
{
// NONE: requires all rules to fail (none pass)
// If we know at least one rule passed (without being invalid), result is FAIL
// If all rules are invalid, result is INVALID
// If there are invalid rules but no passes, result is INVALID
if (hasValidPass)
{
status = CheckStatus.Failed;
reason = $"Condition 'NONE': {passCount}/{validCount} rules passed";
}
else if (hasInvalid)
{
// If all rules are invalid, can't execute any
if (validCount == 0)
{
status = CheckStatus.Invalid;
reason = "Check invalid: all rules cannot be executed";
}
else
{
// Some rules are invalid but valid ones all failed
status = CheckStatus.Invalid;
reason = "Check invalid: one or more rules cannot be executed";
}
}
else
{
bool nonePassed = results.All(r => !r.Passed);
status = nonePassed ? CheckStatus.Passed : CheckStatus.Failed;
reason = $"Condition 'NONE': {passCount}/{validCount} rules passed";
}
}
else
{
// CheckCondition.Unknown — unrecognised YAML value
status = CheckStatus.Invalid;
reason = $"Unknown condition '{check.Condition}' — must be 'all', 'any', or 'none'";
}
return new CheckResult(status, reason, results);
}
// =========================================================================
// Single rule evaluation (respects overall negation)
// =========================================================================
public static RuleResult EvaluateRule(ParsedRule rule)
{
// If the rule definition itself is invalid, return invalid status
if (rule.Invalid)
{
return new RuleResult(false, true, $"Invalid rule: {rule.InvalidReason ?? "malformed"}");
}
RuleCheckResult checkResult = rule.Type switch
{
RuleType.File => CheckFile(rule),
RuleType.Directory => CheckDirectory(rule),
RuleType.Process => CheckProcess(rule),
RuleType.Command => CheckCommand(rule),
RuleType.Registry => CheckRegistry(rule),
_ => new RuleCheckResult { Status = CheckStatus.Failed, Detail = "Unknown rule type" }
};
// If the rule is invalid, propagate that status and don't apply negation
if (checkResult.Status == CheckStatus.Invalid)
return new RuleResult(false, true, checkResult.Detail);
bool innerPassed = checkResult.Status == CheckStatus.Passed;
bool finalPassed = rule.Negated ? !innerPassed : innerPassed;
string finalDetail = rule.Negated ? $"[NEGATED] {checkResult.Detail}" : checkResult.Detail;
return new RuleResult(finalPassed, false, finalDetail);
}
// =========================================================================
// Rule type handlers
// =========================================================================
// ── File ─────────────────────────────────────────────────────────────────
private static RuleCheckResult CheckFile(ParsedRule rule)
{
// Handle comma-separated file paths (OR logic: stop at first existing)
string[] files = rule.Target.Split(',');
string? foundFile = null;
foreach (string file in files)
{
string trimmedFile = file.Trim();
if (File.Exists(trimmedFile))
{
foundFile = trimmedFile;
break;
}
}
if (foundFile is null)
{
// If the file doesn't exist and we need to check its content, that's invalid
if (rule.HasContentCheck)
return new RuleCheckResult { Status = CheckStatus.Invalid, Detail = $"Cannot check content: file not found at {rule.Target}" };
// If the file doesn't exist and we just need to check existence, it fails
return new RuleCheckResult { Status = CheckStatus.Failed, Detail = $"File not found: {rule.Target}" };
}
if (!rule.HasContentCheck)
{
FileInfo info = new(foundFile);
int lineCount;
try
{
lineCount = File.ReadAllLines(foundFile).Length;
}
catch (UnauthorizedAccessException ex)
{
return new RuleCheckResult { Status = CheckStatus.Invalid, Detail = $"Permission denied reading '{foundFile}': {ex.Message}" };
}
catch (IOException ex)
{
return new RuleCheckResult { Status = CheckStatus.Invalid, Detail = $"I/O error reading '{foundFile}': {ex.Message}" };
}
return new RuleCheckResult { Status = CheckStatus.Passed, Detail = $"File exists: {foundFile} ({FormatBytes(info.Length)}, {lineCount} lines)" };
}
try
{
string content = File.ReadAllText(foundFile);
var (matched, detail) = EvaluateContent(content, rule.ContentConditions, label: $"'{foundFile}'");
return new RuleCheckResult { Status = matched ? CheckStatus.Passed : CheckStatus.Failed, Detail = detail };
}
catch (UnauthorizedAccessException ex)
{
return new RuleCheckResult { Status = CheckStatus.Invalid, Detail = $"Permission denied reading '{foundFile}': {ex.Message}" };
}
catch (Exception ex)
{
return new RuleCheckResult { Status = CheckStatus.Failed, Detail = $"Cannot read '{foundFile}': {ex.Message}" };
}
}
// ── Directory ────────────────────────────────────────────────────────────
private static RuleCheckResult CheckDirectory(ParsedRule rule)
{
// Handle comma-separated directory paths (OR logic: stop at first existing)
string[] dirs = rule.Target.Split(',');
string? foundDir = null;
foreach (string dir in dirs)
{
string trimmedDir = dir.Trim();
if (Directory.Exists(trimmedDir))
{
foundDir = trimmedDir;
break;
}
}
if (foundDir is null)
{
// If the directory doesn't exist and we need to check content, that's invalid
if (rule.HasContentCheck)
return new RuleCheckResult { Status = CheckStatus.Invalid, Detail = $"Cannot check content: directory not found at {rule.Target}" };
// If the directory doesn't exist and we just need to check existence, it fails
return new RuleCheckResult { Status = CheckStatus.Failed, Detail = $"Directory not found: {rule.Target}" };
}
if (!rule.HasContentCheck)
{
int count;
try
{
count = Directory.GetFiles(foundDir).Length;
}
catch (UnauthorizedAccessException ex)
{
return new RuleCheckResult { Status = CheckStatus.Invalid, Detail = $"Permission denied reading '{foundDir}': {ex.Message}" };
}
catch (IOException ex)
{
return new RuleCheckResult { Status = CheckStatus.Invalid, Detail = $"I/O error reading '{foundDir}': {ex.Message}" };
}
return new RuleCheckResult { Status = CheckStatus.Passed, Detail = $"Directory exists: {foundDir} ({count} files)" };
}
// For directory rules: match patterns against filenames (one per line).
// Delegates to EvaluateContent() so AND (&&) conditions and negation work
// consistently with file/command rules.
try
{
string[] allFiles = Directory.GetFiles(foundDir);
// Build content: one filename per line so EvaluateContent line logic applies
string fileNames = string.Join("\n", allFiles.Select(Path.GetFileName));
var (matched, detail) = EvaluateContent(fileNames, rule.ContentConditions, label: $"files in '{foundDir}'");
return new RuleCheckResult { Status = matched ? CheckStatus.Passed : CheckStatus.Failed, Detail = detail };
}
catch (UnauthorizedAccessException ex)
{
return new RuleCheckResult { Status = CheckStatus.Invalid, Detail = $"Permission denied reading '{foundDir}': {ex.Message}" };
}
catch (Exception ex)
{
return new RuleCheckResult { Status = CheckStatus.Failed, Detail = $"Error checking directory '{foundDir}': {ex.Message}" };
}
}
// ── Process ──────────────────────────────────────────────────────────────
private static RuleCheckResult CheckProcess(ParsedRule rule)
{
// Support both literal process names and regex patterns (p:r:PATTERN)
if (rule.Target.StartsWith("r:", StringComparison.Ordinal))
{
// Regex pattern matching
string pattern = rule.Target[2..];
try
{
var regex = new System.Text.RegularExpressions.Regex(pattern);
Process[] allProcs = Process.GetProcesses();
var matchedProcs = allProcs.Where(p => regex.IsMatch(p.ProcessName)).ToArray();
if (matchedProcs.Length > 0)
{
string pids = string.Join(", ", matchedProcs.Select(p => p.Id));
string names = string.Join(", ", matchedProcs.Select(p => p.ProcessName).Distinct());
return new RuleCheckResult { Status = CheckStatus.Passed, Detail = $"Process matching pattern '{pattern}' is running: {names} (PID: {pids})" };
}
return new RuleCheckResult { Status = CheckStatus.Failed, Detail = $"No process matching pattern '{pattern}' found" };
}
catch (System.Text.RegularExpressions.RegexParseException ex)
{
return new RuleCheckResult { Status = CheckStatus.Failed, Detail = $"Invalid regex pattern '{pattern}': {ex.Message}" };
}
}
else
{
// Literal process name matching
Process[] procs = Process.GetProcessesByName(rule.Target);
bool running = procs.Length > 0;
if (running)
{
string pids = string.Join(", ", procs.Select(p => p.Id));
return new RuleCheckResult { Status = CheckStatus.Passed, Detail = $"Process '{rule.Target}' is running (PID: {pids})" };
}
return new RuleCheckResult { Status = CheckStatus.Failed, Detail = $"Process '{rule.Target}' is not running (0 instances found)" };
}
}
// ── Command ──────────────────────────────────────────────────────────────
private static RuleCheckResult CheckCommand(ParsedRule rule)
{
try
{
string shell, args;
if (OperatingSystem.IsWindows())
{
// Always use PowerShell on Windows for consistency and to support full paths
// like "%WINDIR%\SysNative\WindowsPowerShell\v1.0\powershell <args>"
// Expand Windows-style %VAR% environment variables (cmd.exe syntax)
// so they work in PowerShell
string expandedTarget = System.Environment.ExpandEnvironmentVariables(rule.Target);
// If the command itself is a path to powershell.exe, extract just the arguments
// (e.g., "C:\Windows\...\powershell.exe secedit /export ..." -> "secedit /export ...")
string commandToRun = ExtractPowerShellArguments(expandedTarget) ?? expandedTarget;
shell = "powershell.exe";
args = $"-NoProfile -Command \"{commandToRun}\"";
}
else
{
shell = "/bin/sh";
args = $"-c \"{rule.Target.Replace("\"", "\\\"")}\"";
}
ProcessStartInfo psi = new(shell, args)
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
};
using Process proc = Process.Start(psi)!;
// Read stdout and stderr concurrently to avoid deadlock when
// either buffer fills, then combine them (many commands — like dscl —
// write diagnostic output to stderr rather than stdout).
Task<string> stdoutTask = proc.StandardOutput.ReadToEndAsync();
Task<string> stderrTask = proc.StandardError.ReadToEndAsync();
bool streamsFinished = Task.WaitAll([stdoutTask, stderrTask], millisecondsTimeout: 10_000);
bool procExited = proc.WaitForExit(5_000);
if (!streamsFinished || !procExited)
{
proc.Kill(entireProcessTree: true);
}
string output = stdoutTask.Result + stderrTask.Result;
if (!rule.HasContentCheck)
{
bool ok = proc.ExitCode == 0;
string value = Truncate(output.Trim().ReplaceLineEndings(" "), 80);
return new RuleCheckResult { Status = ok ? CheckStatus.Passed : CheckStatus.Failed, Detail = $"Exit code {proc.ExitCode} → \"{value}\"" };
}
// For content checks: non-zero exit code is only INVALID if:
// Exit code is 127 (command not found)
// Other exit codes (1, 2, etc.) mean the command ran but failed → evaluate output or fail
if (proc.ExitCode == 127)
{
return new RuleCheckResult { Status = CheckStatus.Invalid, Detail = $"Command execution failed with exit code {proc.ExitCode}" };
}
var (matched, detail) = EvaluateContent(output, rule.ContentConditions, label: $"`{rule.Target}`");
return new RuleCheckResult { Status = matched ? CheckStatus.Passed : CheckStatus.Failed, Detail = detail };
}
catch (Exception ex)
{
return new RuleCheckResult { Status = CheckStatus.Failed, Detail = $"Failed to run command '{rule.Target}': {ex.Message}" };
}
}
// ── Registry ─────────────────────────────────────────────────────────────
private static RuleCheckResult CheckRegistry(ParsedRule rule)
{
if (!OperatingSystem.IsWindows())
return new RuleCheckResult { Status = CheckStatus.Invalid, Detail = "Registry checks are only supported on Windows — skipped on this platform" };
try
{
string keyPath = rule.Target;
int firstBackslash = keyPath.IndexOf('\\');
if (firstBackslash < 0)
return new RuleCheckResult { Status = CheckStatus.Failed, Detail = $"Invalid registry key path: {keyPath}" };
string hiveName = keyPath[..firstBackslash].ToUpperInvariant();
string subKey = keyPath[(firstBackslash + 1)..];
// Support both full names and common short aliases
Microsoft.Win32.RegistryKey? hive = hiveName switch
{
"HKEY_LOCAL_MACHINE" or "HKLM" => Microsoft.Win32.Registry.LocalMachine,
"HKEY_CURRENT_USER" or "HKCU" => Microsoft.Win32.Registry.CurrentUser,
"HKEY_CLASSES_ROOT" or "HKCR" => Microsoft.Win32.Registry.ClassesRoot,
"HKEY_USERS" or "HKU" => Microsoft.Win32.Registry.Users,
"HKEY_CURRENT_CONFIG" or "HKCC" => Microsoft.Win32.Registry.CurrentConfig,
_ => null
};
if (hive is null)
return new RuleCheckResult { Status = CheckStatus.Failed, Detail = $"Unknown registry hive: '{hiveName}' — valid hives: HKLM, HKCU, HKCR, HKU, HKCC" };
using Microsoft.Win32.RegistryKey? key = hive.OpenSubKey(subKey);
if (key is null)
{
// If key doesn't exist and we need to check content patterns, that's invalid
// (2-part rules checking value existence should still FAIL)
if (rule.ContentConditions.Count > 0)
return new RuleCheckResult { Status = CheckStatus.Invalid, Detail = $"Cannot check content: registry key not found at {keyPath}" };
// If key doesn't exist and we just need to check existence, it fails
return new RuleCheckResult { Status = CheckStatus.Failed, Detail = $"Registry key not found: {keyPath}" };
}
// ── Key existence only ────────────────────────────────────────
if (!rule.HasContentCheck)
{
int valueCount = key.ValueCount;
return new RuleCheckResult { Status = CheckStatus.Passed, Detail = $"Registry key exists: {keyPath} ({valueCount} values)" };
}
// ── 3-part: KEY -> ValueName -> [DataPattern] ─────────────────
if (rule.RegistryValueName is not null)
{
object? value = key.GetValue(rule.RegistryValueName);
if (value is null)
{
// If value doesn't exist and we need to check its data, that's invalid
if (rule.ContentConditions.Count > 0)
return new RuleCheckResult { Status = CheckStatus.Invalid, Detail = $"Cannot check content: registry value '{rule.RegistryValueName}' not found in '{keyPath}'" };
// If value doesn't exist and we just need to check its existence, it fails
return new RuleCheckResult { Status = CheckStatus.Failed, Detail = $"Registry value '{rule.RegistryValueName}' not found in '{keyPath}'" };
}
string valueStr = value.ToString() ?? string.Empty;
// Value exists, no data pattern required
if (rule.ContentConditions.Count == 0)
return new RuleCheckResult { Status = CheckStatus.Passed, Detail = $"Registry value '{rule.RegistryValueName}' = \"{valueStr}\" in '{keyPath}'" };
// Match data pattern against the value string
var (matched, detail) = EvaluateContent(valueStr, rule.ContentConditions,
label: $"'{rule.RegistryValueName}' in {keyPath}");
return new RuleCheckResult { Status = matched ? CheckStatus.Passed : CheckStatus.Failed, Detail = detail };
}
// ── Fallback: match content against all name=value pairs ──────
System.Text.StringBuilder allValues = new();
foreach (string name in key.GetValueNames())
allValues.AppendLine($"{name}={key.GetValue(name)}");
var (matched2, detail2) = EvaluateContent(allValues.ToString(), rule.ContentConditions, label: keyPath);
return new RuleCheckResult { Status = matched2 ? CheckStatus.Passed : CheckStatus.Failed, Detail = detail2 };
}
catch (Exception ex)
{
return new RuleCheckResult { Status = CheckStatus.Failed, Detail = $"Registry error: {ex.Message}" };
}
}
// =========================================================================
// Content evaluation (shared by File, Directory, Command, Registry)
// =========================================================================
/// <summary>
/// Evaluates one or more content conditions against <paramref name="content"/>.
///
/// Single condition → line-by-line: pass if ANY line satisfies the condition
/// (or, for negated, if NO line matches the pattern).
///
/// Multiple (&&) conditions → line-by-line: pass if ANY line simultaneously
/// satisfies ALL conditions (Wazuh semantics).
/// </summary>
private static (bool matched, string detail) EvaluateContent(
string content,
List<ContentCondition> conditions,
string label)
{
if (conditions.Count == 0)
return (true, "No content conditions");
if (conditions.Count == 1)
return EvaluateSingleCondition(content, conditions[0], label);
// Multi-condition (&&): look for a line that satisfies ALL conditions
string[] lines = SplitLines(content);
foreach (string line in lines)
{
if (conditions.All(c => LineMatchesCondition(line, c)))
return (true, $"Matched line in {label}: \"{Truncate(line.Trim(), 80)}\"");
}
// Show the first non-empty line as context for the failure
string sample = lines.FirstOrDefault(l => l.Trim().Length > 0)?.Trim() ?? "(empty)";
return (false, $"No single line in {label} satisfies all {conditions.Count} AND-conditions (first line: \"{Truncate(sample, 60)}\")");
}
private static (bool, string) EvaluateSingleCondition(
string content, ContentCondition cond, string label)
{
if (cond.Operator == ContentOperator.Numeric)
return EvaluateNumeric(content, cond, label);
string[] lines = SplitLines(content);
if (!cond.Negated)
{
// Pass if ANY line matches the pattern
foreach (string line in lines)
{
if (MatchesPattern(line, cond.Pattern, cond.Operator))
return (true, $"Matched line in {label}: \"{Truncate(line.Trim(), 80)}\"");
}
// Show the first line as context so the user knows what was actually there
string sample = lines.FirstOrDefault(l => l.Trim().Length > 0)?.Trim() ?? "(empty)";
return (false, $"Pattern `{cond.Pattern}` not found in {label} (first line: \"{Truncate(sample, 60)}\")");
}
else
{
// Pass if NO line matches the pattern
foreach (string line in lines)
{
if (MatchesPattern(line, cond.Pattern, cond.Operator))
return (false, $"Forbidden pattern found in {label}: \"{Truncate(line.Trim(), 80)}\"");
}
// Show first line to confirm what IS in the content
string sample = lines.FirstOrDefault(l => l.Trim().Length > 0)?.Trim() ?? "(empty)";
return (true, $"Pattern `{cond.Pattern}` absent from {label} (actual first line: \"{Truncate(sample, 60)}\")");
}
}
private static (bool, string) EvaluateNumeric(
string content, ContentCondition cond, string label)
{
Regex regex;
try { regex = new Regex(cond.Pattern, RegexOptions.Multiline); }
catch { return (false, $"Invalid numeric regex pattern: `{cond.Pattern}`"); }
Match match = regex.Match(content);
if (!match.Success || match.Groups.Count < 2)
{
string sample = content.Trim().ReplaceLineEndings(" ");
return (false, $"Pattern `{cond.Pattern}` found no capture group in {label} (actual: \"{sample}\")");
}
if (!double.TryParse(match.Groups[1].Value, out double value))
return (false, $"Captured '{match.Groups[1].Value}' in {label} is not numeric");
(bool met, string sym) = cond.NumericOp switch
{
NumericComparison.LessThan => (value < cond.NumericValue, "<"),
NumericComparison.LessThanOrEqual => (value <= cond.NumericValue, "<="),
NumericComparison.Equal => (value == cond.NumericValue, "=="),
NumericComparison.NotEqual => (value != cond.NumericValue, "!="),
NumericComparison.GreaterThanOrEqual => (value >= cond.NumericValue, ">="),
NumericComparison.GreaterThan => (value > cond.NumericValue, ">"),
_ => (false, "?")
};
bool finalPassed = cond.Negated ? !met : met;
return (finalPassed, $"Captured value = {value} ({value} {sym} {cond.NumericValue} → {(finalPassed ? "PASS" : "FAIL")}) from {label}");
}
// =========================================================================
// Helpers
// =========================================================================
private static bool MatchesPattern(string line, string pattern, ContentOperator op) =>
op switch
{
ContentOperator.Literal => line.Contains(pattern, StringComparison.Ordinal),
ContentOperator.Regex => Regex.IsMatch(line, pattern),
_ => false
};
private static bool LineMatchesCondition(string line, ContentCondition cond)
{
bool raw = MatchesPattern(line, cond.Pattern, cond.Operator);
return cond.Negated ? !raw : raw;
}
private static string[] SplitLines(string text) =>
text.Split(['\n', '\r'], StringSplitOptions.RemoveEmptyEntries);
private static string Truncate(string s, int max) => StringUtils.Truncate(s, max);
private static string FormatBytes(long bytes) =>
bytes switch
{
< 1024 => $"{bytes} B",
< 1024 * 1024 => $"{bytes / 1024.0:F1} KB",
_ => $"{bytes / (1024.0 * 1024):F1} MB"
};
/// <summary>
/// If the command is a full path to powershell.exe, extract just the arguments.
/// For example: "C:\Windows\...\powershell.exe secedit /export ..." returns "secedit /export ..."
/// Returns null if the command is not a PowerShell path (should use original command).
/// </summary>
private static string? ExtractPowerShellArguments(string command)
{
// Match paths ending with "powershell" or "powershell.exe" (case-insensitive)
// Look for the last occurrence to handle paths with spaces
int psIndex = command.LastIndexOf("powershell", StringComparison.OrdinalIgnoreCase);
if (psIndex < 0) return null;
// Check if it's "powershell.exe" or just "powershell"
int endIndex = psIndex + "powershell".Length;
if (endIndex < command.Length && command[endIndex..].StartsWith(".exe", StringComparison.OrdinalIgnoreCase))
endIndex += 4;
// Extract everything after "powershell" or "powershell.exe"
if (endIndex < command.Length)
{
string remainder = command[endIndex..].TrimStart();
if (!string.IsNullOrEmpty(remainder))
return remainder;
}
return null;
}
}