5.10.1. Exploiting techniques

5.10.1.1. P/Invoke

Platform Invoke (P/Invoke) provides C# the ability to access data structures, callbacks, and functions in a DLL. The basic usage is as shown in the official Platform Invoke documentation. Using the capabilities of P/Invoke, C# programs can easily call standard Windows APIs.

using System;
using System.Runtime.InteropServices;

public class Program
{
    // Import user32.dll (containing the function we need) and define
    // the method corresponding to the native function.
    [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern int MessageBox(IntPtr hWnd, string lpText, string lpCaption, uint uType);

    public static void Main(string[] args)
    {
        // Invoke the function as a regular managed method.
        MessageBox(IntPtr.Zero, "Command-line message box", "Attention!", 0);
    }
}

The disadvantage of P/Invoke is that the referenced API calls will end up in the IAT of the executable, making some sensitive behaviors easily noticed by the protection software. At the same time, some sensitive APIs may be monitored by the protection software, and API calls made in this way are also easily intercepted by the protection software.

5.10.1.2. D/Invoke

On the basis of P/Invoke, some researchers have proposed D/Invoke based on the Delegates mechanism to call the required API in a more subtle way.