Skip to content

feat(Rules): ✨ Refactor event handling and introduce RuleHelpers#212

Merged
PrzemyslawKlys merged 36 commits intomasterfrom
EventsUpgrades
Nov 24, 2025
Merged

feat(Rules): ✨ Refactor event handling and introduce RuleHelpers#212
PrzemyslawKlys merged 36 commits intomasterfrom
EventsUpgrades

Conversation

@PrzemyslawKlys
Copy link
Member

  • Updated event handling logic to utilize RuleHelpers for provider and channel checks.
  • Enhanced data parsing methods for better handling of timestamps and integer values.
  • Improved code readability and maintainability across multiple event rule classes.

* Updated event handling logic to utilize `RuleHelpers` for provider and channel checks.
* Enhanced data parsing methods for better handling of timestamps and integer values.
* Improved code readability and maintainability across multiple event rule classes.
…with endpoint parsing

* Introduced `RemoteIp` and `RemotePort` to capture additional endpoint details.
* Implemented `ParseEndpoint` method to extract IP and port from the `RemoteEndpoint` string.
* Updated constructor to utilize new properties for better event detail tracking.
@claude
Copy link

claude bot commented Nov 23, 2025

Claude finished @PrzemyslawKlys's task —— View job


Pull Request Review

I've conducted a comprehensive review of this significant refactoring PR that introduces RuleHelpers and enhances event handling. Here's my analysis:

Review Checklist:

  • Read repository guidelines and setup instructions
  • Analyze RuleHelpers implementation and design
  • Review the LogsClearedSecurity provider fix
  • Sample key rule classes for code quality patterns
  • Examine test coverage and quality
  • Assess performance implications
  • Check for security concerns
  • Provide final recommendations

🎯 Overall Assessment: STRONG APPROVAL

This is an excellent refactoring that significantly improves code quality, maintainability, and consistency across the codebase.

Code Quality & Best Practices

Excellent Design Patterns:

  • RuleHelpers provides clean utility methods with consistent APIs
  • Proper separation of concerns with internal static class design
  • Good use of params arrays for flexible method signatures (IsProvider, IsChannel)
  • Consistent null checking and defensive programming throughout
  • Well-documented XML comments with usage examples

Strong Implementation Highlights:

  • Culture-invariant parsing with proper UTC conversion (ParseUnlabeledOsTimestamp)
  • Case-insensitive string comparisons for provider/channel matching
  • Efficient caching for enum flag descriptions using ConcurrentDictionary
  • Smart IP address normalization for IPv6-mapped addresses

Security Analysis

No Security Concerns Identified:

  • Input validation is appropriate throughout RuleHelpers
  • No hardcoded secrets or sensitive data exposure
  • Proper handling of untrusted event data with defensive parsing
  • Safe enum conversion with validation checks

Security Enhancement:

  • The LogsClearedSecurity fix properly handles both "EventLog" and "Microsoft-Windows-Eventlog" providers (Sources/EventViewerX/Rules/Logging/LogsClearedSecurity.cs:19), ensuring security events aren't missed due to provider name variations

Performance Considerations

Performance Optimizations:

  • Caching Strategy: Smart use of ConcurrentDictionary<Type, EnumFlag[]> for flag descriptions to avoid repeated reflection
  • Efficient Parsing: Multiple parsing attempts with early returns in ParseUnlabeledOsTimestamp
  • Memory Efficient: Minimal allocations in helper methods

Potential Improvements:

  • Consider caching compiled regex patterns in AADSyncImportStatus.cs:42-45 as static readonly fields to avoid recompilation

Bug Fixes & Reliability

Critical Bug Fix Validated:
The LogsClearedSecurity provider issue was correctly addressed. The rule now properly handles both:

  • Legacy "EventLog" provider
  • Modern "Microsoft-Windows-Eventlog" provider

This ensures security log clearing events (1102/1105) are reliably detected.

Test Coverage Assessment

Good Test Foundation:

  • Comprehensive RuleHelpers tests cover core functionality (TestRuleHelpers.cs)
  • Proper use of mocking with FakeEventRecord for isolated testing
  • Tests validate case-insensitive behavior and message fallback logic

Test Coverage Gaps to Address in Future:

  • Azure AD Sync rules (AADSyncImportStatus, AADSyncCycleStage, etc.) lack unit tests
  • No integration tests for the provider fix scenarios
  • Missing performance benchmarks for the caching mechanisms

🔧 Minor Suggestions

  1. Regex Optimization (AADSyncImportStatus.cs:42-45):

    private static readonly Regex WatermarkHashRegex = new("Hash:\\s*(?<h>[A-Za-z0-9+/=\\-]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
  2. Error Handling Enhancement (RuleHelpers.cs:114):
    Consider logging parse failures for debugging:

    if (!string.IsNullOrWhiteSpace(v) && int.TryParse(v, out var i)) return i;
    // Could add optional logging: InternalLogger.Debug($"Failed to parse '{v}' as integer from key '{k}'");
  3. Documentation: Consider adding a README section explaining the RuleHelpers migration for contributors

📊 Impact Analysis

Positive Impacts:

  • Maintainability: Centralized utilities reduce code duplication
  • Consistency: Standardized provider/channel checking across 100+ files
  • Reliability: Fixed critical security event detection bug
  • Performance: Efficient caching and parsing strategies

Migration Risk: Low - Changes are backward-compatible with existing rule interfaces

🏆 Final Recommendation

APPROVE - This is high-quality refactoring work that:

  • Fixes a critical security detection bug
  • Improves code maintainability significantly
  • Follows C# best practices consistently
  • Maintains backward compatibility
  • Includes appropriate test coverage for core functionality

The large scope (100 files, 36 commits) is well-justified given the systematic nature of the refactoring and the clear benefits achieved.


Copy link

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

- Introduced new named events for Azure AD Connect:
  * `AADSyncCycleStage`
  * `AADSyncProvisionCredentialsPing`
  * `AADSyncPasswordHashSyncStatus`
  * `AADSyncImportStatus`
  * `AADSyncFilterStatus`
- Enhances event tracking capabilities for Azure AD synchronization processes.
* Introduced `AADSyncCycleStage`, `AADSyncFilterStatus`, `AADSyncImportStatus`, `AADSyncPasswordHashSyncStatus`, and `AADSyncProvisionCredentialsPing` classes to handle various Azure AD synchronization events.
* Enhanced `RuleHelpers` with a new method to retrieve the best message text for events.
* Updated `OSCrash` to improve event handling by specifying the provider.
…ication enums

* Enhanced documentation for various enums related to BitLocker protection types, volume types, elevated tokens, failure reasons, impersonation levels, keywords, known logs, event levels, logon types, NAS port types, parallel options, PowerShell editions, status codes, sub-status codes, ticket encryption types, and virtual accounts.
* Improved clarity and understanding of each enum's purpose and usage.
* Added `inheritdoc` for overridden properties in `ADGroupPolicyChanges`, `ADGroupPolicyEdits`, and `ADGroupPolicyLinks`.
* Improved documentation for methods and constructors across group policy classes.
* Ensured consistent handling of event IDs and log names in the Security log.
…perties

* Added properties for `Computer`, `Action`, `AccountName`, `IpAddress`, `IpPort`, `TicketOptions`, `Status`, `EncryptionType`, `PreAuthType`, `WeakEncryptionAlgorithm`, and `When` to `KerberosTGTRequest` and `KerberosTicketFailure`.
* Updated `CanHandle` method to ensure proper event handling.
* Improved documentation for clarity.

feat(Logging): ✨ Improve logging event handling with new attributes

* Introduced properties for `Computer`, `Action`, `BackupPath`, `LogType`, `Who`, and `When` in `LogsClearedOther` and `LogsClearedSecurity`.
* Enhanced `CanHandle` method to check for specific providers.

feat(NPS): ✨ Expand Network Access Authentication Policy event handling

* Added properties for `Computer`, `Action`, `When` in `NetworkAccessAuthenticationPolicy`.
* Updated `CanHandle` method to accept events based on ID/log matching.

feat(SQL): ✨ Refine SQL Database Created event handling

* Introduced properties for `Computer`, `DatabaseName`, and `When` in `SqlDatabaseCreated`.
* Enhanced `CanHandle` method for better event matching.

feat(Windows): ✨ Augment OS event handling with additional details

* Added properties for `Computer`, `Action`, `ObjectAffected`, `ActionDetails`, `ActionTimestampUtc`, `ActionTimestampIso`, `Who`, and `When` in `OSCrash` and `OSBugCheck`.
* Improved `CanHandle` method to verify event sources.
…and improved metadata

* Added comprehensive XML documentation for methods and properties across various classes.
* Improved clarity of `QuickProbeResult` and `WatcherManager` by adding summaries for key properties.
* Enhanced `BuildWinEventFilter` method documentation to clarify parameters and return types.
* Updated `TimePeriod` enum with detailed descriptions for each time range.
…mmaries and improved metadata

* Added detailed summaries and improved metadata for various event rules.
* Updated classes for Hyper-V, IIS, and Windows events to include additional properties and descriptions.
* Ensured all event handling classes now provide clear documentation for better maintainability.
… handling with detailed properties

* Added detailed properties to `CertificateIssued`, `DhcpLeaseCreated`, `ExchangeDatabaseMounted`, and `KerberosServiceTicket` classes.
* Improved event handling capabilities by including relevant metadata such as `Computer`, `Action`, `Requester`, and `When`.
* Updated `CanHandle` methods to provide better context for event processing.
- Added new properties to various event classes to capture additional details such as `Computer`, `Action`, `When`, and specific attributes related to changes in Active Directory objects.
- Improved documentation with XML comments for better clarity on each property and method.
- Ensured that all new properties are initialized correctly in their respective constructors.
- Updated event handling logic to accommodate new attributes, enhancing the overall functionality and traceability of Active Directory events.
* Added remarks to `PreAuthType`, `Status`, and `TicketOptions` enums for clarity on expected values.
* Updated `ADComputerChangeDetailed`, `ADComputerCreateChange`, and `ADComputerDeleted` classes with summaries for better understanding of their functionality.
* Enhanced `ADGroupPolicyChanges`, `GpoCreated`, and `Replication` classes with additional documentation for future development.
* Improved `ADUserStatus`, `DhcpLeaseCreated`, `VmCheckpointCreated`, and `VmShutdown` classes with detailed property descriptions.
* Removed the `Status` enum and replaced it with `StatusCode` for better clarity and type safety.
* Updated `GetStatus` method to `GetStatusCode`, enhancing parsing logic for hex values.
* Adjusted `KerberosTGTRequest` to utilize the new `StatusCode` handling.
* Ensured consistent provider metadata retrieval in `GetProviders`.
* Improved watcher management logic to prevent duplicate entries.
* Implement integration tests for `Find-WinEvent` functionality.
* Ensure that logs for 'Application' and 'System' can be listed without errors.
* Validate that querying specific event types does not throw exceptions.
* Suppress additional nullable/test analyzer warnings in tests.
* Ensure product warnings still surface in main builds.
* Implement tests for parsing OS timestamps, case insensitivity in providers and channels, and message retrieval logic.
* Enhance test coverage for event handling functionality.
* Improved XML documentation for `ParseUnlabeledOsTimestamp`, `ParseDateTimeLoose`, and `GetMessage` methods.
* Added examples and parameter descriptions to clarify usage.
* Introduced new methods `IsProvider` and `IsChannel` with detailed summaries for better event filtering.
…ions

* Improved XML documentation for multiple cmdlets.
* Added detailed descriptions and usage examples for:
  - `Clear-EVXLog`
  - `Get-EVXEvent`
  - `Get-EVXFilter`
  - `Get-EVXInfo`
  - `Get-EVXLog`
  - `Get-EVXProviderList`
  - `Get-EVXWatcher`
  - `New-EVXLog`
  - `Remove-EVXLog`
  - `Remove-EVXSource`
  - `Start-EVXWatcher`
  - `Stop-EVXWatcher`
  - `Write-EVXEntry`
* Implemented tests to validate the parsing of encryption and status fields in Kerberos TGT requests.
* Ensured comprehensive coverage for various attributes including `AccountName`, `IpAddressNormalized`, and `ResponseTicket`.
…tion

* Added new properties to `KerberosTGTRequest` for better tracking of ticket options, status, and encryption types.
* Improved `EventsHelper` with methods to describe ticket options, status codes, and pre-authentication types.
* Introduced normalization for IP addresses in `RuleHelpers`.
* Updated unit tests to validate new functionality and ensure robustness.
…timeout

* Introduced a new property `QuerySessionTimeoutMs` to manage stall timeout while reading events from logs.
* This allows for unbounded reads when set to <=0, enhancing flexibility in event querying.
* Changed target frameworks to `net472`, `net8.0`, and `net10.0`.
* Updated `Microsoft.NET.Test.Sdk` to version `18.0.1`.
* Updated `xunit.runner.visualstudio` to version `3.1.5`.
* Enhanced test methods for better null handling and thread safety.
* Removed support for `8.0.x` and set `DOTNET_VERSION` to `10.0.x` in both `test-dotnet.yml` and `test-powershell.yml`.
* Ensures consistency across workflows and aligns with the latest .NET standards.
…rray

* Set default value for `Type` property to `Array.Empty<NamedEvents>()` to prevent null reference issues.
* Updated project file to configure `XmlDoc2CmdletDocStrict` for `net10.0` target framework.
* Refactored tests to utilize `Active Directory Web Services.evtx` for consistency.
* Enhanced assertions to check for `GatheredFrom` and `LogName` fields.
* Removed redundant checks and improved clarity in test descriptions.
… host behaviors

* Adjusted the test to accept both behaviors of `EndInvoke` to prevent flaky CI.
* Ensured that the test does not throw an error when the pipeline is stopped.
…em logs

* Implemented tests to verify event retrieval from Application and System logs without specifying MachineName.
* Ensured that the integration tests validate the expected behavior of the `Find-WinEvent` cmdlet.
* Updated `AliasesToExport` and `CmdletsToExport` in `PSEventViewer.psd1` to include 'Clear-EVXLog'.
* Enhanced `CmdletWriteEVXEntry` to support 'Write-Event' alias.
* Improved integration tests for `Find-WinEvent` to validate log names.
…s` to `ADUser`

- Removed the `ADUserLogonKerberos` event type from the codebase.
- Updated the `Find-WinEvent` command to use the `ADUser` type instead.
- Adjusted related tests and properties to reflect the changes in event handling.
* Moved `xpath` declaration outside of conditional blocks for better readability.
* Ensured consistent usage of `xpath` variable across different query scenarios.
* Introduced caching for enum flags to reduce reflection overhead.
* Updated `DescribeFlags` method to utilize cached values for improved performance.
* Adjusted handling of `level` in `SearchEvents` to ensure proper value extraction.
…ject settings

* Added detailed XML documentation for methods in `SearchEvents` class.
* Updated project file to disable documentation file generation.
* Improved clarity of the `Settings` class summary and adjusted thread count description.
… and documentation

- Added properties for `DisplayName`, `LogLinks`, `Events`, `Keywords`, `Opcodes`, `MessageFilePath`, `ResourceFilePath`, `ParameterFilePath`, and `Tasks`.
- Improved documentation for constructors and properties to clarify usage and purpose.

feat(channel-policy): ✨ Expand `ChannelPolicy` model with detailed properties

- Introduced properties such as `MachineName`, `IsEnabled`, `MaximumSizeInBytes`, `LogFilePath`, `Isolation`, `Mode`, and `SecurityDescriptor`.
- Enhanced documentation for each property to improve clarity.

feat(subscription-info): ✨ Add detailed properties to `SubscriptionInfo` model

- Included properties for `Description`, `Enabled`, `ContentFormat`, `DeliveryMode`, `MachineName`, `RawXml`, and `Queries`.
- Improved documentation for better understanding of the model's purpose.

feat(channel-policy-apply-result): ✨ Enhance `ChannelPolicyApplyResult` with additional properties

- Added properties for `MachineName`, `AppliedProperties`, `SkippedOrUnsupported`, and `Errors`.
- Updated documentation to clarify the purpose of each property.

feat(ad-computer-change): ✨ Add documentation to `ADComputerChangeDetailed` rule

- Included a summary for the `CanHandle` method to clarify its functionality.

feat(smb-server-audit): ✨ Document `SMBServerAudit` rule's event handling

- Added a summary for the `CanHandle` method to explain its purpose.

feat(aad-sync-cycle-stage): ✨ Enhance `AADSyncCycleStage` with detailed documentation

- Added summaries for the `CanHandle` method and constructor to clarify their roles.

feat(aad-sync-filter-status): ✨ Document `AADSyncFilterStatus` rule

- Included summaries for properties and methods to improve clarity.

feat(aad-sync-import-status): ✨ Enhance `AADSyncImportStatus` with detailed documentation

- Added summaries for properties and constructor to clarify their roles.

feat(aad-sync-password-hash-sync-status): ✨ Document `AADSyncPasswordHashSyncStatus` rule

- Included summaries for properties and constructor to improve understanding.

feat(aad-sync-provision-credentials-ping): ✨ Enhance `AADSyncProvisionCredentialsPing` with documentation

- Added summaries for properties and constructor to clarify their roles.

feat(kerberos-tgt-request): ✨ Document `KerberosTGTRequest` rule's properties

- Added summaries for new properties to improve clarity.

feat(audit-policy-change): ✨ Enhance `AuditPolicyChange` rule with documentation

- Included summaries for properties to clarify their purpose.

feat(client-group-policies-base): ✨ Document `ClientGroupPoliciesBase` rule

- Added summaries for properties and methods to improve understanding.

feat(network-monitor-driver-loaded): ✨ Document `NetworkMonitorDriverLoaded` rule

- Included a summary for the `CanHandle` method to clarify its functionality.

feat(os-crash-on-audit-fail-recovery): ✨ Enhance `OSCrashOnAuditFailRecovery` with documentation

- Added summaries for properties and constructor to clarify their roles.

feat(os-shutdown): ✨ Document `OSShutdown` rule's properties

- Included summaries for properties to improve clarity.

feat(os-startup): ✨ Enhance `OSStartup` with detailed documentation

- Added summaries for properties to clarify their roles.

feat(os-startup-security): ✨ Document `OSStartupSecurity` rule

- Included summaries for properties to improve understanding.

feat(os-unclean-shutdown): ✨ Enhance `OSUncleanShutdown` with documentation

- Added summaries for properties to clarify their roles.

feat(object-deletion): ✨ Document `ObjectDeletion` rule's properties

- Included summaries for properties to improve clarity.

feat(search-events): ✨ Enhance `SearchEvents` with detailed documentation

- Added summaries for methods to clarify their functionality.
…rties and documentation

* Added `LogName` and `NamedEvent` properties to `AADSyncCycleStage`, `AADSyncFilterStatus`, `AADSyncImportStatus`, `AADSyncPasswordHashSyncStatus`, and `AADSyncProvisionCredentialsPing` classes.
* Enhanced `OSStartupSecurity` class with additional methods and documentation.
* Updated `PSEventViewer.csproj` to use `MatejKafka.XmlDoc2CmdletDoc` version `0.7.0`.
…ckage version to 0.6.0

* Adjusted the version of the `MatejKafka.XmlDoc2CmdletDoc` package to ensure compatibility.
* This change may help resolve issues related to documentation generation.
@PrzemyslawKlys PrzemyslawKlys merged commit 8c0c0de into master Nov 24, 2025
5 checks passed
@PrzemyslawKlys PrzemyslawKlys deleted the EventsUpgrades branch November 24, 2025 18:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant