Using msfrop to find ROP gadgets

Metasploit provides a very convenient tool to find ROP gadgets: msfrop. It not only enables us to list all the ROP gadgets but also allows us to search through those gadgets to find the appropriate gadgets for our required actions. Let's say we need to see all the gadgets that can help us to perform a pop operation over the ECX register. We can do this using msfrop, as follows:

As soon as we provide the -s switch for searching and -v for verbose output, we start getting a list of all the gadgets where the POP ECX instruction is used. Let's see the results:

We can see that we have various gadgets that can perform the POP ECX task with ease. However, to build a successful Metasploit module that can exploit the target application in the presence of DEP, we need to develop a chain of these ROP gadgets without executing anything from the stack. Let's understand the ROP bypass for DEP through the following diagram:

On the left side, we have the layout for a standard application. In the middle, we have an application that is attacked using a buffer overflow vulnerability, causing the overwrite of the EIP register. On the right, we have the mechanism for the DEP bypass, where instead of overwriting EIP with the JMP ESP address, we overwrite it with the address of the ROP gadget, followed by another ROP gadget, and so on until the execution of the shellcode is achieved.

How will the execution of instructions bypass hardware-enabled DEP protection?

The answer is simple. The trick is to chain these ROP gadgets to call a VirtualProtect() function, which is a memory protection function used to make the stack executable so that the shellcode can execute. Let's look at the steps we need to perform to get the exploit to work under DEP protection:

  1. Find the offset to the EIP register
  2. Overwrite the register with the first ROP gadget
  3. Continue overwriting with the rest of the gadgets until the shellcode becomes executable
  4. Execute the shellcode