Python r2pipe.open() Examples

The following are 30 code examples of r2pipe.open(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module r2pipe , or try the search function .
Example #1
Source File: function_handler.py    From Firmware_Slap with GNU General Public License v3.0 7 votes vote down vote up
def get_function_information(file_name):
    func_list = []

    r2_ins = r2pipe.open(file_name, flags=["-2"])
    '''
    Commands = ['aa', 'afr', '& aap', '& aac', '& aar', '& aaE',
            '& aaf', '& aas', '& aae', '& aav', '&&', 'afva', 'afta']
    
    for command in tqdm(Commands, desc="Analysis Running"):
        r2_ins.cmd(command)
    '''

    r2_ins.cmd('aaa')
    try:
        func_list = r2_ins.cmdj('aflj')
    except:
        func_list = []
    r2_ins.quit()
    return func_list 
Example #2
Source File: pimp.py    From pimp with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, name):
        self.name = name

        self.r2 = r2pipe.open()

        bininfo = self.r2.cmdj("ij")["bin"]
        self.arch = bininfo["arch"]
        self.bits = bininfo["bits"]
        self.regs = self.r2.cmdj("drlj")
        self.switch_flagspace(self.name)

        self.sections = self.get_sections()
        imports = self.get_imports()
        self.imports = {}
        for imp in imports:
            self.imports[imp["plt"]] = imp["name"]
        exports = self.get_exports()
        self.exports = {}
        for exp in exports:
            self.exports[exp["name"]] = exp["vaddr"] 
Example #3
Source File: solve_chicken.py    From angr-doc with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def main():
    print(solve("df8737d9d5aee3cee6320e7313414458fdfb10552a8e6c8ea45753102ba4509a"))
    return
    import os
    for i, filename in enumerate(os.listdir("bc9cd8ff91a55ecee73caf85c3d55e45")):
        if i % 8 != int(sys.argv[1]):
            continue
        solution_file = "%s.solution" % filename
        if os.path.exists(solution_file):
            continue
        print(i, filename)
        try:
            sol = solve(filename)
            if not sol:
                continue
        except ValueError:
            print("oops failed on %s" % filename)
            continue
        # data = sol.encode("base64")
        with open(solution_file, "wb") as f:
            f.write(sol)
        #print("Send this:" + data)
        #sock.send(data + "\n") 
Example #4
Source File: occult.py    From angr-doc with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def main():
    import os
    for i, filename in enumerate(os.listdir("occult_dist")):
        if i % 8 != int(sys.argv[1]):
            continue
        solution_file = "%s.solution" % filename
        if os.path.exists(solution_file):
            continue
        print(i, filename)
        try:
            sol = solve(filename)
        except ValueError:
            print("oops failed on %s" % filename)
            continue
        # data = sol.encode("base64")
        with open(solution_file, "wb") as f:
            f.write(sol)
        #print("Send this:" + data)
        #sock.send(data + "\n") 
Example #5
Source File: r2parser.py    From metame with MIT License 6 votes vote down vote up
def __init__(self, filename, anal, debug=False, force_replace=False, write=False):
        self.debug = debug
        self.force = force_replace
        flags = []
        if write:
            flags.append("-w")
        print("[INFO] Opening file with r2")
        self.r2 = r2pipe.open(filename, flags)
        info = json.loads(self.r2.cmd("ij").replace("\\", "\\\\"))
        if "bin" not in info.keys():
            raise Exception("[ERROR] File type not supported")
        if not info["bin"]["bits"] in constants.supported_bits or \
           not info["bin"]["arch"] in constants.supported_archs:
            raise Exception("[ERROR] Architecture not supported")
        self.arch = info["bin"]["arch"]
        self.bits = info["bin"]["bits"]
        if anal:
            print("[INFO] Analyzing functions with r2")
            self.r2.cmd("aaa") 
Example #6
Source File: utils.py    From flashre with GNU Lesser General Public License v3.0 6 votes vote down vote up
def cache(filename):
    """
    A simple decorator to cache results to disk.
    """

    def decorator(func):
        """Note: it is the function that is finally returned"""
        def cached_function(*args):
            """Note: needed to access the returned value"""
            try:
                return pickle.load(open(filename, "r"))
            except IOError:
                value = func(*args)
                pickle.dump(value, open(filename, "w"))
                return value
        return cached_function

    return decorator 
Example #7
Source File: r2_bin_carver.py    From radare2-scripts with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description='Carve binaries from MiniDumps.')
    parser.add_argument('dmp', help='The MiniDump file to carve from')
    parser.add_argument('offset', help='Offset to carve from')
    parser.add_argument('size', help='Size of binary to carve')
    parser.add_argument('-b', type=str, help='Magic bytes to check for, e.g. MZ')
    parser.add_argument('-p', '--patch', action='store_true', help='Patch carved PE files')
    args = parser.parse_args()

    # FIXME: Won't redirect r2pipe, will have to 2>/dev/null for now!
    f = open(os.devnull, 'w')
    sys.stderr = f

    output_file = carve(args.dmp, args.offset, args.size, args.b)

    if args.patch:
        patch(output_file) 
Example #8
Source File: r2_bin_carver.py    From radare2-scripts with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def carve(file_path, offset, size, magic=None):
    r2 = r2pipe.open(file_path, ['-z'])
    if magic:
        magic_bytes = hexlify(bytes(magic, 'ascii'))
        print('[+] Checking for magic: %s - %x' % (magic, int(magic_bytes, 16)))
        header = r2.cmd("p8 %x @ %s" % (len(magic), offset))
        if bytes(header, 'ascii') != magic_bytes:
            print("[+] No magic found, exiting...")
            exit()
        else:
            print("[+] Magic found, carving...")

    r2.cmd("s %s" % (offset))
    r2.cmd('wtf %s.%s %s' % (file_path, offset, size))
    print("[+] Carving to %s.%s" % (file_path, offset))
    return '%s.%s' % (file_path, offset) 
Example #9
Source File: utils.py    From flashre with GNU Lesser General Public License v3.0 6 votes vote down vote up
def get_r2pipe(filename, offset, options=None):
    """
    Get a r2pipe handle ready to analyse a flashair binary.
    """

    # Set the miasm architecture
    os.putenv("R2M2_ARCH", "mepl")

    # Use the r2m2 architecture
    default_options = ["-a", "r2m2"]

    # Map the binary at a given location
    default_options += ["-m", hex(offset)]

    # Decrease r2 verbosity
    default_options += ["-e", "bin.verbose=false"]

    # Add user specified options
    if isinstance(options, list):
        default_options += options

    return r2pipe.open(filename, default_options) 
Example #10
Source File: static_analysis.py    From LiSa with Apache License 2.0 6 votes vote down vote up
def run_analysis(self):
        """Main analysis method.

        :returns: Dictionary containing analysis results.
        """
        log.info('Static Analysis started.')

        # start radare2
        self._r2 = r2pipe.open(self._file.path, ['-2'])
        self._r2.cmd('aaa')

        # binary info
        self._r2_info()

        # strings
        self._load_strings()

        self._r2.quit()
        log.info('Static Analysis finished.')

        return self._output 
Example #11
Source File: main.py    From sonare with MIT License 5 votes vote down vote up
def __init__(self):
        # open empty, we'll open files later
        self.r2 = r2pipe.open('--')
        self.opcodeAddrs = [] 
Example #12
Source File: r2_keeper.py    From bootloader_instrumentation_suite with MIT License 5 votes vote down vote up
def gets(f, cmd):
    if f in files.keys():
        handle = files[f]
    else:
        handle = r2pipe.open(f, ['-2'])
        files[f] = handle
        entry[f] = handle.cmd("s")
        handle.cmd('e anal.bb.maxsize=10000')
        handle.cmd('aac*')

    out = handle.cmd(cmd)
    return out 
Example #13
Source File: PRG_analysis.py    From ICSREF with MIT License 5 votes vote down vote up
def __find_io(self):
        """
        Find program INPUTS and OUTPUTS based on TRG information

        Assumes I/O memory locations will appear as direct offsets in the program
        and are kind of unique

        """

        # Read data from TRG file
        with open(trg_file, 'r') as f:
            trg_data = f.readlines()
        # Search for hex
        hex_pattern = re.compile('([0-9a-fA-F])*')
        # Find input_start, output_start, input_size, output_size
        for line in trg_data:
            if 'BaseAddressOfInputSegment' in line:
                input_start = re.search(hex_pattern, line.split('=')[1].replace('16#','')).group(0)
                input_start = int(input_start, 16)
            if 'BaseAddressOfOutputSegment' in line:
                output_start = re.search(hex_pattern, line.split('=')[1].replace('16#','')).group(0)
                output_start = int(output_start, 16)
            if 'SizeOfInputSegment' in line:
                input_size = re.search(hex_pattern, line.split('=')[1].replace('16#','')).group(0)
                input_size = int(input_size, 16)
            if 'SizeOfOutputSegment' in line:
                output_size = re.search(hex_pattern, line.split('=')[1].replace('16#','')).group(0)
                output_size = int(output_size, 16)

        # Find inputs/outputs offsets in the code
        self.inputs = {}
        self.outputs = {}
        for i in range(input_start, input_start + input_size, 1):
            match = self.__allindices(self.hexdump, struct.pack('<I', i))
            if match:
                self.inputs[hex(i)]=[hex(k) for k in match]
        for i in range(output_start, output_start + output_size, 1):
            match = self.__allindices(self.hexdump, struct.pack('<I', i))
            if match:
                self.outputs[hex(i)]=[hex(k) for k in match]
        return 0 
Example #14
Source File: PRG_analysis.py    From ICSREF with MIT License 5 votes vote down vote up
def __find_functions(self):
        """
        Produces disassembly listings for all functions
        """
        # Open an r2pipe to radare2 \m/
        r2=r2pipe.open(self.path)
        # Set r2 architecture configuration - Processor specific
        r2.cmd('e asm.arch=arm; e asm.bits=32; e cfg.bigendian=false')
        # Instantiate Functions
        for i in range(len(self.FunctionBoundaries)):
            # Code disassembly
            # Start: MOV, STMFD, MOV
            start_code = self.FunctionBoundaries[i][0]
            # Stop: LDMDB
            stop_code = self.FunctionBoundaries[i][1]
            length_code = stop_code - start_code
            disasm_code = r2.cmd('b {}; pD @{}'.format(length_code ,start_code))
            # Add spaces for formating purposes and consistency in disassembly string
            disasm_code = (12 * ' ' + disasm_code).split('\n')
            # Add data
            # Start at code stop
            start_data = stop_code
            # Stop at beginning of next (or special case for last function from header)
            if i == len(self.FunctionBoundaries)-1:
                stop_data = self.program_end
            else:
                stop_data = self.FunctionBoundaries[i+1][0]
            length_data = stop_data - start_data
            # Data disassembly
            disasm_data = r2.cmd('pxr {} @{}'.format(length_data ,start_data))
            disasm_data = disasm_data.split('\n')
            # Disassembly formating
            for i,line in enumerate(disasm_data):
                disasm_data[i] = '            {}     {}      {}'.format(line[:11], line[14:23], line [14:])
            disasm = disasm_code + disasm_data
            self.Functions.append(Function(self.path, start_code, stop_data, self.hexdump[start_code:stop_data], disasm))
        r2.quit()
        return 0 
Example #15
Source File: PRG_analysis.py    From ICSREF with MIT License 5 votes vote down vote up
def __find_statlibs(self):
        entry_offset = self.Functions[-1].start
        stop_offset  = self.FunctionBoundaries[-1][1]-8
        funs = [x for x, _ in self.FunctionBoundaries]
        # Change 0x2000 location of writing address in OUTRO with 0x10000000 to not overwrite code
        code_start = '\x00\x20\x00\x00'
        with open('temphexdump.bin', 'w') as f:
            hexdump_mod = self.hexdump.replace(code_start, '\x00\x00\x00\x10')
            f.write(hexdump_mod)
        proj = angr.Project('temphexdump.bin', load_options={'main_opts': {'backend': 'blob', 'custom_base_addr': 0, 'custom_arch':'ARMEL', 'custom_entry_point':0x50}, 'auto_load_libs':False})
        state = proj.factory.entry_state()
        state.regs.pc = entry_offset
        simgr = proj.factory.simulation_manager(state)
        # Initialize some (0xFF) mem locations so taht execution doesn't jump to end.
        for i in range(0,0xFF,4):
            simgr.active[0].mem[simgr.active[0].regs.r0 + i].long = 0xFFFFFFFF
        # Run the code to create the static offsets in memory
        simgr.explore(find=stop_offset)
        statlibs = {}
        i = 0
        while len(statlibs) < len(funs) - 1:
            mem_val = state.solver.eval(simgr.found[0].mem[simgr.found[0].regs.r1 + i].int.resolved)
            if mem_val in funs:
                statlibs[i + 8] = 'sub_{:x}'.format(mem_val)
            i += 4
        os.remove('temphexdump.bin')
        return statlibs 
Example #16
Source File: PRG_analysis.py    From ICSREF with MIT License 5 votes vote down vote up
def __read_file(self):
        """
        Reads hexdump from file
        """
        with open(self.path, 'rb') as f_in:
            file_bytes = f_in.read()
        return file_bytes 
Example #17
Source File: PRG_analysis.py    From ICSREF with MIT License 5 votes vote down vote up
def __save_object(self):
        """
        Serializes the object instance and saves it to a file using the dill module
        """
        # Create directory for output results
        path = os.path.join('results', self.name)
        try: 
            os.makedirs(path)
        except OSError:
            if not os.path.isdir(path):
                raise
        dat_f = os.path.join(path, '{}_init_analysis.dat'.format(self.name))
        
        with open(dat_f, 'w') as f:
            dill.dump(self, f) 
Example #18
Source File: apk.py    From fufluns with GNU General Public License v3.0 5 votes vote down vote up
def _apk_analysis(apk):
	pipes = []
	try:
		extract_apk(apk)

		dexes = glob.glob(os.path.join(apk.unzip, "*.dex"))
		for dex in dexes:
			apk.logger.notify("opening {}.".format(os.path.basename(dex)))
			r2 = r2pipe.open(dex)
			if r2 is None:
				apk.logger.error("cannot open file {}.".format(os.path.basename(dex)))
				continue
			r2.filename = dex
			pipes.append(r2)
		if len(pipes) < 1:
			_cleanup(apk, pipes, False)
			return

		for file in os.listdir(os.path.join(os.path.dirname(__file__), "tests")):
			if file == "__init__.py" or not file.endswith('.py'):
				continue
			modpath = 'android.tests.' + os.path.splitext(file)[0]
			mod = importlib.import_module(modpath)
			apk.logger.notify(mod.name_test())
			mod.run_tests(apk, pipes, utils, r2help, au)
	except Exception as ex:
		_cleanup(apk, pipes, True)
		raise ex
	_cleanup(apk, pipes, False)
	apk.done.set(True) 
Example #19
Source File: ipa.py    From fufluns with GNU General Public License v3.0 5 votes vote down vote up
def _ipa_analysis(ipa):
	ipa.logger.notify("opening ipa.")
	try:
		with zipfile.ZipFile(ipa.filename, "r") as zip_ref:
			zip_ref.extractall(ipa.directory)
	except Exception:
		ipa.logger.error("cannot unzip file.")
		_cleanup(ipa, None, False)
		return

	r2 = r2pipe.open("ipa://" + ipa.filename)
	if r2 is None:
		ipa.logger.error("cannot open file.")
		_cleanup(ipa, None, False)
		return

	for file in os.listdir(os.path.join(os.path.dirname(__file__), "tests")):
		if file == "__init__.py" or not file.endswith('.py'):
			continue
		try:
			modpath = 'ios.tests.' + os.path.splitext(file)[0]
			mod = importlib.import_module(modpath)
			ipa.logger.notify(mod.name_test())
			mod.run_tests(ipa, r2, utils, r2help)
		except Exception as e:
			_cleanup(ipa, r2, True)
			raise e
	_cleanup(ipa, r2, False)
	ipa.done.set(True) 
Example #20
Source File: Easy_Pickings.py    From Easy-Pickings with GNU General Public License v3.0 5 votes vote down vote up
def get_functions(binary):
    print("[~] Using Radare2 to build function list...")
    r2 = r2pipe.open(binary)
    r2.cmd('aaaa')
    return [func for func in json.loads(r2.cmd('aflj'))] 
Example #21
Source File: input_vectors_r2.py    From FACT_core with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, path_to_elf: str, config: dict):
        self.config = config
        self.api = r2pipe.open(path_to_elf) 
Example #22
Source File: winFunctionDetector.py    From Zeratool with GNU General Public License v3.0 5 votes vote down vote up
def getWinFunctions(binary_name):

    winFunctions = {}

    #Initilizing r2 with with function call refs (aac)
    r2 = r2pipe.open(binary_name)
    r2.cmd('aaa')
    
    functions = [func for func in json.loads(r2.cmd('aflj'))]
    
    #Check for function that gives us system(/bin/sh)
    for func in functions:
        if 'system' in str(func['name']):
            system_name = func['name']

            #Get XREFs
            refs = [func for func in json.loads(r2.cmd('axtj @ {}'.format(system_name)))]
            for ref in refs:
                if 'fcn_name' in ref:
                    winFunctions[ref['fcn_name']] = ref

    #Check for function that reads flag.txt
    #Then prints flag.txt to STDOUT
    known_flag_names = ["flag","pass"]

    strings = [string for string in json.loads(r2.cmd('izj'))]
    for string in strings:
        value = string['string']
        if any([x in value for x in known_flag_names]):
            address = string['vaddr']

            #Get XREFs
            refs = [func for func in json.loads(r2.cmd('axtj @ {}'.format(address)))]
            for ref in refs:
                if 'fcn_name' in ref:
                    winFunctions[ref['fcn_name']] = ref

    for k,v in winFunctions.items():
        print("[+] Found win function {}".format(k))

    return winFunctions 
Example #23
Source File: overflowExploiter.py    From Zeratool with GNU General Public License v3.0 5 votes vote down vote up
def getRegValues(filename,endAddr):

    r2 = r2pipe.open(filename)
    r2.cmd('doo')
    r2.cmd('dcu {}'.format(endAddr))
    regs = json.loads(r2.cmd('drj'))
    r2.quit()
    return regs 
Example #24
Source File: overflowExploiter.py    From Zeratool with GNU General Public License v3.0 5 votes vote down vote up
def findShellcode(filename,endAddr,shellcode,commandInput):

    hex_str = shellcode[:4].encode('hex')

    abs_path = os.path.abspath(filename)


    #If you know a better way to direct stdin please let me know
    os.system('env > temp.env')
    with open('command.input','w') as f:
        f.write(commandInput)
    with open('temp.rr2','w') as f:
        f.write("program={}\nstdin=command.input\nenvfile={}\n".format(filename,"temp.env"))
#        f.write("program={}\nstdin=command.input\nclearenv=true\nenvfile={}\n".format(abs_path,"temp.env"))


    r2 = r2pipe.open(filename)
    r2.cmd('e dbg.profile = temp.rr2')
    r2.cmd('ood')
    r2.cmd('dcu {}'.format(endAddr))
    r2.cmd('s ebp')
    r2.cmd('e search.maxhits =1')
    r2.cmd('e search.in=dbg.map')   #Need to specify this for r2pipe
    loc = json.loads(r2.cmd('/xj {}'.format(hex_str)))

    #Cleaning up
    if os.path.exists('command.input'):
        os.remove('command.input')
    if os.path.exists('temp.rr2'):
        os.remove('temp.rr2')
    if os.path.exists('temp.env'):
        os.remove('temp.env')


    return loc 
Example #25
Source File: occult.py    From angr-doc with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_symbol_addr(s, symbol_name):
    r2 = r2pipe.open("occult_dist/%s" % s)
    symbols = r2.cmdj("isj")
    symbol = next(iter(symbol for symbol in symbols if symbol['name'] == symbol_name))
    return symbol['vaddr'] + 0x400000 
Example #26
Source File: solve_chicken.py    From angr-doc with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_symbol_addr(s, symbol_name):
    r2 = r2pipe.open("bc9cd8ff91a55ecee73caf85c3d55e45/%s" % s)
    symbols = r2.cmdj("isj")
    symbol = next(iter(symbol for symbol in symbols if symbol['name'] == symbol_name))
    return symbol['vaddr'] 
Example #27
Source File: syms2elf.py    From syms2elf with GNU General Public License v3.0 5 votes vote down vote up
def save(self, output):
        with open(output, 'wb') as f:
            f.write(self.binary) 
Example #28
Source File: main.py    From sonare with MIT License 5 votes vote down vote up
def open(self, path):
        # not using 'oc' command because it resets r2's -q flag, don't know what
        # else.

        # close all
        self.cmd('o--')

        # then open the new file
        # TODO: escaping?
        self.cmd('o {}', path)

        self.analyze()
        self.opcodeAddrs = self._getOpcodeAddrs()
        self.symbolFlags = SortedListWithKey(self.getFlags('symbols'),
            key=lambda f: f['offset']) 
Example #29
Source File: main.py    From sonare with MIT License 5 votes vote down vote up
def __init__(self, path):
        QMainWindow.__init__(self)
        self.setMinimumSize(QSize(600, 400))

        self.font = QFont(self.FONT_NAME, self.FONT_SIZE)
        self.fontMetrics = QFontMetricsF(self.font)

        palette = self.palette()
        # palette.setColor(QPalette.Window, self.WINDOW_COLOR)
        # palette.setColor(QPalette.WindowText, self.DEFAULT_TEXT_COLOR)
        palette.setColor(QPalette.Base, self.BG_COLOR)
        palette.setColor(QPalette.Text, self.DEFAULT_TEXT_COLOR)
        self.setPalette(palette)

        self._makeMenus()

        self.core = Core()

        self.open(path)

        self._makeScene()
        self._makeFlagList()

        self.funcName = None

        self._updateWindowTitle() 
Example #30
Source File: main.py    From sonare with MIT License 5 votes vote down vote up
def open(self, path):
        self.core.open(path)

        self.filePath = path

        arch = self.core.getR2Cfg('asm.arch')
        if arch == 'x86':
            self.asmFormatter = X86AsmFormatter(self)
        elif arch == 'mips':
            self.asmFormatter = MipsAsmFormatter(self)
        else:
            raise NotImplementedError("asm formatting for {}".format(arch))