Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_fauxware():
amd64 = archinfo.arch_from_id('amd64')
args = {
'i386': [
('authenticate', SimCCCdecl(
archinfo.arch_from_id('i386'),
args=[SimStackArg(4, 4), SimStackArg(8, 4)], sp_delta=4
)
),
],
'x86_64': [
('authenticate', SimCCSystemVAMD64(
amd64,
args=[SimRegArg('rdi', 8), SimRegArg('rsi', 8)],
sp_delta=8
)
),
],
}
for arch, lst in args.items():
yield run_fauxware, arch, lst
def test_fauxware():
amd64 = archinfo.arch_from_id('amd64')
args = {
'i386': [
('authenticate', SimCCCdecl(
archinfo.arch_from_id('i386'),
args=[SimStackArg(4, 4), SimStackArg(8, 4)], sp_delta=4
)
),
],
'x86_64': [
('authenticate', SimCCSystemVAMD64(
amd64,
args=[SimRegArg('rdi', 8), SimRegArg('rsi', 8)],
sp_delta=8
)
),
ctype_tolower_loc = lambda state, arguments: simuvex.SimProcedures['libc.so.6']['__ctype_tolower_loc'](FAKE_ADDR, archinfo.arch_from_id('AMD64')).execute(state, arguments=arguments)
ctype_toupper_loc = lambda state, arguments: simuvex.SimProcedures['libc.so.6']['__ctype_toupper_loc'](FAKE_ADDR, archinfo.arch_from_id('AMD64')).execute(state, arguments=arguments)
]
class LifterBF(GymratLifter):
instrs = all_instrs
# Tell PyVEX that this lifter exists.
register(LifterBF, 'BF')
if __name__ == '__main__':
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import logging
logging.getLogger('pyvex').setLevel(logging.DEBUG)
logging.basicConfig()
irsb_ = pyvex.IRSB(None, 0, arch=archinfo.arch_from_id('bf'))
test1 = b'<>+-[].,'
test2 = b'<>+-[].,'
lifter = LifterBF(irsb_, test1, len(test1) , len(test1), 0, None)
lifter.lift()
lifter.irsb.pp()
irsb_ = pyvex.IRSB(None, 0, arch=ArchBF())
lifter = LifterBF(irsb_, test2, len(test2),len(test2),0, None)
lifter.lift()
lifter.irsb.pp()
def from_string(data, log_level = logging.WARNING, address_offset = None, bad_bytes = None, filter_func = None):
gadgets_dict = pickle.loads(data)
gadgets_list = [item for sublist in gadgets_dict.values() for item in sublist] # Flatten list of lists
# Turn the names of the arch back into archinfo classes (Which aren't pickle-able)
for gadget in gadgets_list:
gadget.arch = archinfo.arch_from_id(gadget.arch)
# Filter the gadgets if necessary
if filter_func != None:
gadgets_list = filter_func(gadgets_list)
gl = GadgetList(gadgets_list, log_level)
if address_offset != None:
gl.adjust_base_address(address_offset)
if bad_bytes != None:
just_good_gadgets = GadgetList(log_level = log_level, bad_bytes = bad_bytes)
for gadget in gl.foreach():
if not gadget.has_bad_address(bad_bytes):
just_good_gadgets.add_gadget(gadget)
gl = just_good_gadgets
self.struct_byteorder = self._detect_byteorder(struct.unpack("=I", binary_file.read(4))[0])
# parse the mach header:
# (ignore all irrelevant fiels)
self._parse_mach_header(binary_file)
# determine architecture
arch_ident = self._detect_arch_ident()
if not arch_ident:
raise CLECompatibilityError(
"Unsupported architecture: 0x{0:X}:0x{1:X}".format(self.cputype, self.cpusubtype))
# Create archinfo
# Note that this should be customized for Apple ABI (TODO)
self.set_arch(
archinfo.arch_from_id(arch_ident, endness="lsb" if self.struct_byteorder == "<" else "msb"))
# Start reading load commands
lc_offset = (7 if self.arch.bits == 32 else 8) * 4
# Possible optimization: Remove all unecessary calls to seek()
# Load commands have a common structure: First 4 bytes identify the command by a magic number
# second 4 bytes determine the commands size. Everything after this generic "header" is command-specific
# this makes parsing the commands easy.
# The documentation for Mach-O is at http://opensource.apple.com//source/xnu/xnu-1228.9.59/EXTERNAL_HEADERS/mach-o/loader.h
count = 0
offset = lc_offset
while count < self.ncmds and (offset - lc_offset) < self.sizeofcmds:
count += 1
(cmd, size) = self._unpack("II", binary_file, offset, 8)
# check for segments that interest us
import argparse
parser = argparse.ArgumentParser(description="Run the gadget locator on the supplied binary")
parser.add_argument('filename', type=str, default=None, help='The file (executable/library) to load gadgets from')
parser.add_argument('-arch', type=str, default="AMD64", help='The architecture of the binary')
parser.add_argument('-big_endian', required=False, action='store_true', help="Whether the architecture is big endian or not")
parser.add_argument('-finder_type', type=str, default="mem", help='The type of gadget finder (memory, file)')
parser.add_argument('-o', type=str, default=None, help='File to write the gadgets to')
parser.add_argument('-parser_type', type=str, default="cle", help='The type of file parser (cle, pyelf, radare)')
parser.add_argument('-v', required=False, action='store_true', help='Verbose mode')
parser.add_argument('-validate', required=False, action='store_true', help='Validate gadgets with z3')
args = parser.parse_args()
finder_type = factories.get_finder_from_name(args.finder_type)
logging_level = logging.DEBUG if args.v else logging.WARNING
arch = archinfo.arch_from_id(args.arch, 'Iend_BE' if args.big_endian else 'Iend_LE')
finder = finder_type(args.filename, arch, 0, logging_level, args.parser_type)
gadget_list = finder.find_gadgets(args.validate)
if args.o == None:
for gadget in gadget_list.foreach():
print gadget
else:
fd = open(args.o, "w")
fd.write(gadget_list.to_string())
fd.close()
self._is_java_jni_project = self.project and self.project.is_java_jni_project
# Arch
if self._is_java_jni_project:
self._arch = { "soot" : project.arch,
"vex" : project.simos.native_simos.arch }
# This flag indicates whether the current ip is a native address or
# a soot address descriptor.
# Note: We cannot solely rely on the ip to make that decsision,
# because the registers (storing the ip) are part of the
# plugins that are getting toggled (=> mutual dependence).
self.ip_is_soot_addr = False
else:
self._arch = arch if arch is not None else project.arch.copy() if project is not None else None
if type(self._arch) is str:
self._arch = archinfo.arch_from_id(self._arch)
# the options
if options is None:
if mode is None:
l.warning("SimState defaulting to symbolic mode.")
mode = "symbolic"
options = o.modes[mode]
if isinstance(options, (set, list)):
options = SimStateOptions(options)
if add_options is not None:
options |= add_options
if remove_options is not None:
options -= remove_options
self.options = options
self.mode = mode
def _canonicalize(self, number, arch, abi_list):
if type(arch) is str:
arch = archinfo.arch_from_id(arch)
if type(number) is str:
return number, arch, None
for abi in abi_list:
mapping = self.syscall_number_mapping[abi]
if number in mapping:
return mapping[number], arch, abi
return 'sys_%d' % number, arch, None
else:
raise Exception("Could not find field in arch %s for %s" % (archname, fieldname))
fieldsize = type_sizes[typename] * (1 if arraylen is None else arraylen)
arch_data[archname][fieldname] = (offset, fieldsize)
import archinfo
def canon_name(archh, offseth):
for some_name, (some_offset, _) in archh.registers.items():
if some_offset == offseth and some_name in arch_data[archh.vex_arch[7:].lower()]:
return some_name
return None
for archname in arch_data:
try:
arch = archinfo.arch_from_id(archname)
except (archinfo.ArchError, RuntimeError):
print('Skipping', archname)
continue
new_register_names = {}
new_registers_reverse = {}
misses = []
for a_offset, a_fieldname in arch.register_names.items():
cname = canon_name(arch, a_offset)
if cname is None:
misses.append((a_offset, a_fieldname))
continue
new_offset, new_size = arch_data[archname][cname]
# deal with picking up subregisters? shouldn't need to, beyond the above...
new_register_names[new_offset] = a_fieldname