Fix bugs and improve input validation across MemNet library#2
Fix bugs and improve input validation across MemNet library#2
Conversation
- Wildcard.cs: Add input validation for token length to prevent
IndexOutOfRangeException on malformed tokens
- AllocationType.cs: Fix MEM_SHARED value conflict (was 0x00001000,
now 0x08000000) to avoid collision with MEM_COMMIT
- ProcessAccessRights.cs: Fix PROCESS_QUERY_LIMITED_INFORMATION value
(was 0x2000, now 0x1000) to avoid collision with PROCESS_SET_CONTEXT
- Library.cs: Add handle validation in Open(IntPtr) to reject invalid
handles (zero or -1)
- Library.cs: Fix misleading error messages ("non-negative" -> "positive")
- Library.cs: Fix integer overflow check in Query() with proper bounds
- Library.cs: Fix default chunk size from 8196 to 8192 (power of 2)
- Library.cs: Add pattern validation in Search() method
- Program.cs: Remove unnecessary unsafe keyword
https://claude.ai/code/session_01TJUYtWajTHrmWrhTco8sBS
There was a problem hiding this comment.
Pull request overview
This PR fixes several correctness issues in MemNet’s constants and memory scanning utilities, and strengthens public API input validation/error messaging.
Changes:
- Corrects Win32 constant values and improves related documentation/comments.
- Improves input validation for handle hijacking and pattern search parsing (including
Wildcardtoken handling). - Adds a safety guard against address arithmetic overflow during memory region enumeration and cleans up an example entry point.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 5 comments.
Show a summary per file
| File | Description |
|---|---|
| MemNet/Wildcard.cs | Reworks Wildcard construction to validate token shape up-front. |
| MemNet/Native/ProcessAccessRights.cs | Adjusts PROCESS_QUERY_LIMITED_INFORMATION value/comment. |
| MemNet/Library.cs | Adds handle validation, improves pattern parsing, adjusts default chunk size, adds overflow guard, and refines error messages. |
| MemNet/Enum/AllocationType.cs | Updates MEM_SHARED constant value. |
| Examples/PatternScanner/Program.cs | Removes unsafe modifier from Main(). |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
MemNet/Library.cs
Outdated
| /// <exception cref="ArgumentNullException">Thrown if the pattern is null or empty.</exception> | ||
| /// <exception cref="ArgumentOutOfRangeException">Thrown if addresses or chunk size are invalid.</exception> | ||
| public List<IntPtr> Search(string pattern, IntPtr startAddress, IntPtr endAddress, int chunkSize = 8196) | ||
| public List<IntPtr> Search(string pattern, IntPtr startAddress, IntPtr endAddress, int chunkSize = 8192) | ||
| { | ||
| var patternTokens = pattern.Split(' '); | ||
| if (string.IsNullOrWhiteSpace(pattern)) | ||
| throw new ArgumentNullException(nameof(pattern), "The search pattern cannot be null or empty."); | ||
|
|
||
| var patternTokens = pattern.Split(' ', StringSplitOptions.RemoveEmptyEntries); | ||
| if (patternTokens.Length == 0) | ||
| throw new ArgumentException("The search pattern contains no valid tokens.", nameof(pattern)); |
There was a problem hiding this comment.
string.IsNullOrWhiteSpace(pattern) throws ArgumentNullException even when pattern is non-null (e.g., " "). This is inconsistent with .NET exception guidelines and also with the XML docs that say "null or empty". Consider throwing ArgumentNullException only when pattern is null, and using ArgumentException for empty/whitespace patterns (or update the docs/messages to explicitly include whitespace).
MemNet/Native/ProcessAccessRights.cs
Outdated
| PROCESS_GET_CONTEXT = 0x1000, | ||
| PROCESS_SET_CONTEXT = 0x2000, |
There was a problem hiding this comment.
PROCESS_QUERY_LIMITED_INFORMATION is now 0x1000, which duplicates the value of PROCESS_GET_CONTEXT in the same [Flags] enum. This makes the flag set ambiguous and can lead to requesting unintended rights. Consider removing/relocating PROCESS_GET_CONTEXT/PROCESS_SET_CONTEXT (they are thread rights, not process rights) or correcting their values so each process right has a unique bit per the Windows docs linked in the header.
| PROCESS_GET_CONTEXT = 0x1000, | |
| PROCESS_SET_CONTEXT = 0x2000, |
MemNet/Wildcard.cs
Outdated
| _highNibble = token[0] == '?' ? null : Convert.ToInt32(token[0].ToString(), 16); | ||
| _lowNibble = token[1] == '?' ? null : Convert.ToInt32(token[1].ToString(), 16); | ||
| } | ||
|
|
There was a problem hiding this comment.
The constructor validates null/length, but it can still throw a FormatException from Convert.ToInt32(..., 16) for tokens like "G?"/"ZZ". Since this PR is aiming for clearer input validation, consider explicitly validating each nibble is either '?' or a hex digit and throwing an ArgumentException with a clear message when invalid.
| _highNibble = token[0] == '?' ? null : Convert.ToInt32(token[0].ToString(), 16); | |
| _lowNibble = token[1] == '?' ? null : Convert.ToInt32(token[1].ToString(), 16); | |
| } | |
| _highNibble = token[0] == '?' ? null : ParseHexNibble(token[0], 0); | |
| _lowNibble = token[1] == '?' ? null : ParseHexNibble(token[1], 1); | |
| } | |
| private static int ParseHexNibble(char c, int position) | |
| { | |
| if (c >= '0' && c <= '9') | |
| return c - '0'; | |
| if (c >= 'A' && c <= 'F') | |
| return c - 'A' + 10; | |
| if (c >= 'a' && c <= 'f') | |
| return c - 'a' + 10; | |
| throw new ArgumentException( | |
| $"Invalid character '{c}' at position {position} in token. Expected '?' or a hexadecimal digit.", | |
| "token"); | |
| } |
- Library.cs: Fix exception types - ArgumentNullException only for null, ArgumentException for empty/whitespace patterns per .NET guidelines - Program.cs: Replace sizeof(IntPtr) with IntPtr.Size to avoid requiring unsafe context - ProcessAccessRights.cs: Remove PROCESS_GET_CONTEXT and PROCESS_SET_CONTEXT as they are thread rights, not process rights (avoids value collision) - Wildcard.cs: Add explicit hex digit validation with clear error message instead of letting Convert.ToInt32 throw FormatException https://claude.ai/code/session_01TJUYtWajTHrmWrhTco8sBS
|
@copilot Review this amendment. |
Summary
This PR addresses several bugs, improves input validation, and fixes incorrect constant values throughout the MemNet library. The changes enhance code robustness and correctness while maintaining backward compatibility.
Key Changes
Bug Fixes
0x00001000to0x08000000(the previous value overlapped with MEM_COMMIT)0x2000to0x1000and updated comment to reflect Windows Vista introduction8196to8192(correct power of 2)baseAddress + regionSizeto prevent integer overflow on address enumerationInput Validation Improvements
StringSplitOptions.RemoveEmptyEntriesError Message Improvements
ArgumentExceptionto XML documentationCode Cleanup
unsafemodifier fromMain()methodImplementation Details
The overflow check in
EnumerateMemoryRegions()prevents potential crashes when enumerating memory regions near the end of the address space. The pattern validation improvements ensure that malformed patterns fail fast with clear error messages rather than causing cryptic failures downstream.