Memory Hooks

The ‘memhook’ can be used to add custom hooks without using BOFs. This command can overwrite any valid region in memory with the opcodes provided by the operator, using indirect syscalls. Shown below is a simple example which prints a statement before and after calling Environment.Exit().

using System;
using System.Collections.Generic;
using System.Reflection;

namespace EnvExit
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Before Exit");
            Environment.Exit(0);
            Console.WriteLine("This should not print if patch failed\n");
        }
    }
}

Ths Environment.Exit() method resides in mscorlib.ni.dll. We can patch this method with a ‘xor rax, rax; ret’ to stop C-sharp executables from exiting when the dotnet is loaded in the current process with the ‘sharpinline’ command. The dotnet code to extract the Environment.Exit() address is available in the BRc4 package. This address can be patched with any user provided opcode. In the below example, it’s over written with opcodes to return zero in the rax register, before finally running the above dotnet code to check if the process still exits.

As can be seen in x64dbg below, the memory location is now patched. This command is extremely powerful as you can manipulate the execution flow of functions on the fly including patching of syscalls at runtime.