Harden memory layer: fix char sizing, ref structs, count guards, ReadString advance

Second-review fixes, each covered by a regression test in MemoryHardeningTests:

- MarshalCache: special-case char (Size=2; Marshal.SizeOf reports 1/ANSI but the
  blittable path reads a 2-byte UTF-16 unit). TypeRequiresMarshal now also trips on
  RuntimeHelpers.IsReferenceOrContainsReferences<T>() so reference-carrying structs
  route to the marshal path instead of throwing in MemoryMarshal.Read. Document that
  the MarshalAs scan is top-level only.
- MemoryBase.Read<T>(count): reject negative count (ArgumentOutOfRangeException) and
  guard elementSize*count overflow. Same overflow guard on Write<T>(values).
- MemoryBase.ReadString: advance by bytes actually read, not the requested amount, so
  a partial read no longer skips the unread tail of the window.
- ExternalReader: default to a minimal access set (not AllAccess, which over-requests
  and fails on protected processes); wrap Process.MainModule in try/catch so a
  bitness-mismatched or protected target yields ImageBase=Zero instead of throwing.
- NativeMethods: WaitForSingleObject and CreateRemoteThread's threadId are DWORD (uint),
  not int — the signatures no longer sign-flip.

Deferred: hoisting the identical ExternalReader/InProcessReader byte-IO into MemoryBase
(cosmetic; skipped to avoid colliding with concurrent Phase 3 edits).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
kbe
2026-07-21 19:47:24 +02:00
co-authored by Claude Opus 4.8
parent f7236eea9b
commit 7c5e72e0e0
5 changed files with 251 additions and 15 deletions
+22 -3
View File
@@ -15,13 +15,23 @@ public sealed class ExternalReader : MemoryBase
private readonly IntPtr _imageBase;
private bool _disposed;
/// <summary>
/// The default access rights: enough to read, write, allocate, query, run a remote
/// thread, and wait on it. This deliberately omits <see cref="ProcessAccess.AllAccess"/>,
/// which over-requests and makes <c>OpenProcess</c> fail on protected processes where
/// these narrower rights would succeed.
/// </summary>
public const ProcessAccess DefaultAccess =
ProcessAccess.VmRead | ProcessAccess.VmWrite | ProcessAccess.VmOperation
| ProcessAccess.QueryInformation | ProcessAccess.CreateThread | ProcessAccess.Synchronize;
/// <summary>
/// Opens a process for external memory access.
/// </summary>
/// <param name="process">The target process.</param>
/// <param name="desiredAccess">The access rights to request. Defaults to
/// <see cref="ProcessAccess.AllAccess"/>.</param>
public ExternalReader(Process process, ProcessAccess desiredAccess = ProcessAccess.AllAccess)
/// <see cref="DefaultAccess"/>.</param>
public ExternalReader(Process process, ProcessAccess desiredAccess = DefaultAccess)
{
_handle = NativeMethods.OpenProcess(desiredAccess, false, process.Id);
if (_handle.IsInvalid)
@@ -31,7 +41,16 @@ public sealed class ExternalReader : MemoryBase
$"OpenProcess failed for PID {process.Id}: error {error}");
}
_imageBase = process.MainModule?.BaseAddress ?? IntPtr.Zero;
// Process.MainModule throws Win32Exception for a bitness-mismatched or protected
// target; a missing image base must not sink the whole reader.
try
{
_imageBase = process.MainModule?.BaseAddress ?? IntPtr.Zero;
}
catch (System.ComponentModel.Win32Exception)
{
_imageBase = IntPtr.Zero;
}
}
/// <inheritdoc />