Skip to content

Instantly share code, notes, and snippets.

@c0d3inj3cT
Last active December 24, 2015 06:59
Show Gist options
  • Save c0d3inj3cT/6760695 to your computer and use it in GitHub Desktop.
Save c0d3inj3cT/6760695 to your computer and use it in GitHub Desktop.
This code can be used to extract opcodes corresponding to ROP gadgets in a shellcode. It detects whether the DWORD is a ROP gadget or a parameter to the ROP gadget. The new file created by this code can be loaded in IDA Pro to analyze the ROP shellcode.
#include <stdio.h>
#include <windows.h>
#include <psapi.h>
// Compile this code using: cl /TC rop.c /link psapi.lib
int main(int argc, char **argv)
{
FILE *fp;
FILE *rop;
HMODULE hm;
MODULEINFO modinfo={0};
int i=0;
int j=0;
int popctr=0;
char * buffer[4];
if(argc != 4)
{
printf("usage: rop.exe <path to module> <shellcode file> <output file>\n");
exit(0);
}
hm = LoadLibrary(argv[1]);
printf("Base address of module is: %x\n", hm);
GetModuleInformation(GetCurrentProcess(), hm, &modinfo, sizeof(modinfo));
printf("Size of the image is: %x\n", modinfo.SizeOfImage);
fp = fopen(argv[2],"rb");
rop = fopen(argv[3], "w");
// Comment the below line if your shellcode does not have a Byte Order Mark
fseek(fp, 2, SEEK_SET);
printf("Searching for ROP gadgets\n");
while(i<100)
{
i++;
if(popctr > 0)
{
while(popctr != 0)
{
fread(buffer, 1, 4, fp);
fwrite(buffer, 1, 4, rop);
popctr--;
}
continue;
}
fread(buffer, 1, 4, fp);
if(((int) (*buffer) < (int) hm) || ((int) (*buffer) > ((int) hm + modinfo.SizeOfImage)))
{
fwrite(buffer, 1, 4, rop);
continue;
}
printf("\nRop Gadget: %x\n",*buffer);
j=0;
while(1)
{
if((unsigned)(unsigned char)(*(*buffer+j)) == 0xc2)
{
fwrite((*buffer+j), 1, 1, rop);
fwrite((*buffer+j+1), 1, 1, rop);
break;
}
else if((unsigned)(unsigned char)(*(*buffer+j)) >= 0x58 && (unsigned)(unsigned char)(*(*buffer+j)) <= 0x5f)
{
popctr++;
fwrite((*buffer+j), 1, 1, rop);
}
else if((unsigned)(unsigned char)(*(*buffer+j)) == 0xc3)
{
fwrite((*buffer+j), 1, 1, rop);
break;
}
else
{
fwrite((*buffer+j), 1, 1, rop );
}
j++;
}
}
fclose(fp);
fclose(rop);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment