Example #1
0
def radare_kungfu(files):
    unsafe = ('strcpy', 'strcat', 'sprintf', 'vsprintf', 'gets', 'strlen', 'scanf', 'fscanf', 'sscanf', 'vscanf', 'vsscanf', 'vfscanf', 'realpath', 'getopt', 'getpass', 'streadd', 'strecpy', 'strtrns', 'getwd')
    for fi in files:
        filename = fi[0]
        if isElf(filename):
            #print("File is binary, running radare & saving result to database")
            r2=r2pipe.open("/tmp/111"+filename)
            r2.cmd("s 0")
            r2i = r2.cmd("i")
            fi[5] = unicodedata.normalize('NFKD', r2i).encode('ascii','ignore')
            #I'm commenting this atm because it takes too much time to complete, maybe let's try
            # to get rid of all those warnings?


            # if 'static   true' in r2i: # binary is linked statically, stop analysis
            #     continue
            # r2.cmd('aaa')
            # for function in unsafe:
            #     result = r2.cmd('ii~' + function)
            #     if result:
            #         plt = result.split()[1]
            #         address = plt[4:] # location of unsafe function
            #         formatted = address.split('x', 1)[1].lstrip('0')
            #         tmp = r2.cmd('/c' + formatted)
            #         tmp = tmp.splitlines()
            #         refs = '' # addresses that contain call to current unsafe function
            #         for lines in tmp:
            #             refs = refs + lines.split()[0] + '\n'
    print('returning')
    return
def solve_ch111(fn):
	ringzer0.output('solving')
	r2 = r2pipe.open(fn)
	asm_lines = r2.cmd('aa; s sym.main; pif~&mov dword,rbp | grep ", 0x"').splitlines()
	#   mov dword [rbp - 0x60], 0x485e2beb
	#   mov dword [rbp - 0x5c], 0xc180c931
	# (..)
	shellcode = ''
	for asm_line in asm_lines:
		val = asm_line.split(',')[-1:][0].strip()
		if val.startswith('0x'): val = val[2:]
		val = val.zfill(8)
		shellcode += val.decode('hex')[::-1]
	dlen = 0x22 - 1
	#   0x00000006    add cl, 0x22
	#   0x00000009    xor byte [esi], 0x13
	#   0x0000000c    dec eax
	#   0x0000000d    inc esi
	#   0x0000000f    loop 9
	# (..)
	dloc = 0x2d + 5
	#   0x0000002d    e8d0ffffff   call 2
	buf = shellcode[dloc:dloc+dlen]
	xr = 0x4a
	r = ''.join(chr(ord(c) ^ xr) for c in buf).strip()
	ringzer0.output('solved', r)
	return r
Example #3
0
 def find_functions(self, mapping):
     fname = mapping._memdumpname
     log.debug('Opening %s', fname)
     # FIXME is that even useful
     import r2pipe
     r2 = r2pipe.open(fname)
     r2.cmd("aaa")
     analysis = r2.cmd("afl")
     print analysis
     res = analysis.split('\n')
     log.debug("len %d - %d", len(analysis), len(res))
     #if len(analysis) > 40:
     #    import pdb
     #    pdb.set_trace()
     nb = 0
     for f_line in res:
         if "0x" not in res:
             continue
         addr, size, bbs, name = f_line.split('  ')
         addr = int(addr, 16)
         if addr == 0x0:
             continue
         size = int(size)
         bbs = int(bbs)
         self.functions[mapping.start+addr] = (size, bbs, name)
         nb += 1
     log.debug('Found %d functions in 0x%x', nb, mapping.start)
Example #4
0
def scan_file(file_path):

    ret = []

    print('Scanning \"%s\"...' % file_path)

    # start radare instance
    r2 = r2pipe.open(file_path)

    # perform initial analysis
    r2.cmd('aa;aad')

    # enumerate available functions
    for addr in r2.cmdj('aflqj'):

        # check for vulnerable function
        if match_func(r2, addr):

            print('VULNERABLE FUNCTION: %s' % addr)

            ret.append(addr)

    # close radare instance
    r2.quit()

    return ret
Example #5
0
def radare_kungfu(files):
    unsafe = ('strcpy', 'strcat', 'sprintf', 'vsprintf', 'gets', 'strlen', 'scanf', 'fscanf', 'sscanf', 'vscanf', 'vsscanf', 'vfscanf', 'realpath', 'getopt', 'getpass', 'streadd', 'strecpy', 'strtrns', 'getwd')
    results=[]
    for fi in files:
        filename = fi[0]
        if isElf(filename):
            #print("File is binary, running radare & saving result to database")
            r2=r2pipe.open("/tmp/111"+filename)
            r2.cmd("s 0")
            r2i = r2.cmd("i")
            fi[5] = unicodedata.normalize('NFKD', r2i).encode('ascii','ignore')
            if 'static   false' in r2i: # binary is linked statically, stop analysis
                continue
            r2.cmd('aaa')
            for function in unsafe:
                result = r2.cmd('ii~' + function)

                if result:
                    results.append(result)
                    plt = result.split()[1]
                    address = plt[4:] # location of unsafe function
                    formatted = address.split('x', 1)[1].lstrip('0')
                    tmp = r2.cmd('/c' + formatted)
                    tmp = tmp.splitlines()
                    refs = '' # addresses that contain call to current unsafe function
                    for lines in tmp:
                        refs = refs + lines.split()[0] + '\n'
            fi.append(results)
    return
Example #6
0
	def __init__(self, filename):
		self.r = r2pipe.open(filename)
		self.gp = self.r.cmdj("ij")["core"]["size"]
		self.r.cmd("e anal.gp = " + str(self.gp))
		self.r.cmd("e io.cache = true")
		self.r.cmd("e asm.arch = bpf")
		self.r.cmd("e cfg.bigendian=true")
		self.r.cmd("aaa")
Example #7
0
	def __init__(self, binary, bininfo, force=False):
		self.binary = binary
		self.bininfo = bininfo
		self.force = force

		# open binary in Radare2 and trigger binary analysis
		self.r2 = r2pipe.open(self.binary)
		self.r2.cmd('aaa')  # analyze all referenced code

		# done
		return
Example #8
0
def loadModule():
    global r2
    modules = r2.cmdj("ilj")
    for module in modules:
        # If we found a python shared library
        if "python" in module.lower():
            modulePath = _findModuleFullPath(module)
            write("Loading shared library {0} ... ".format(module))
            # TODO: Better support for finding modules
            r2_module = r2pipe.open(modulePath,["-AA"])
            write("[ Done ]\n")
            return (r2_module, module)

    return (None, None)
Example #9
0
 def __init__(self, binfile, logfile=None):
     self.r2 = r2pipe.open(binfile)
     self.r2.cmd("aaa")
     self.r2.cmd("e asm.esil = true")
     self.r2.cmd("e scr.color = false")
     self.r2.cmd("e io.cache = true")
     self.r2.cmd("aei")
     self.r2.cmd("aeip")
     self.stats = {}
     self.binfile = binfile
     self.logfile = logfile
     self.logs = []
     self.prev_state = {}
     self.last_emulated = {}
Example #10
0
def parse_elf(workspace, file):
    r2 = r2pipe.open(file.filepath)
    r2.cmd("aa")
    r2.cmd("afl")
    result = r2.cmd("agC")
    output_dir = os.path.join(workspace, "graphs")
    if not os.path.exists(output_dir):
            os.makedirs(output_dir)

    out_file = os.path.join(output_dir, file.hash)
    graph = pydot.graph_from_dot_data(result)
    graph[0].write_png(out_file)
    file.graph_file = out_file
    file.save()
    print("%s parsed" % file.filepath)
Example #11
0
    def __init__(self, filename, filecontent=None):
        self.r = r2pipe.open(filename)
        self.r.cmd("e io.cache = true")
        self.r.cmd("e asm.arch = bpf")
        self.inited = False

        if filecontent != None:
            self.filecontent = filecontent
            self.inject_filecontent()
        else:
            self.gp = self.r.cmdj("ij")["core"]["size"]
            self.filecontent = None

        self.r.cmd("e anal.gp = " + str(self.gp))
        self.r.cmd("e cfg.bigendian=true")
        self.r.cmd("aaa")
Example #12
0
 def __init__(self, filename, anal, debug=False, force_replace=False, write=False):
     self.debug = debug
     self.force = force_replace
     flags = ["-q"]
     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 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")
def ch15():
	ch, s = 15, ringzer0.login()
	sections = ringzer0.read_challenge(s, ch)
	title, msg, chksum = sections['title'], sections['elf message'], sections['checksum']
	
	ringzer0.output('solving')
	elf = msg
	while re.match(r'^[a-zA-Z0-9+/]*={0,3}$', elf):
		elf = base64.b64decode(elf)
	elf = elf[::-1]
	elf_md5 = hashlib.md5(elf).hexdigest()
	if chksum != elf_md5:
		ringzer0.error('checksum mismatch ({0} vs {1})'.format(chksum, elf_md5))
	result = ''
	with ringzer0.tmpfile() as (fd, fn):
		ringzer0.write_bin_file(fd, elf)
		
		r2 = r2pipe.open(fn)
		asm_lines = r2.cmd('aa; s sym.main; pif~&mov,rbp').splitlines()
		asm_rg = re.compile(r'^mov [^,]*\[rbp\s?-\s?([0-9a-fx]+)\],\s?([^\s]+)$')
		asm_vals, top = {}, 0
		for asm_line in asm_lines:
			rx = re.match(asm_rg, asm_line)
			if not rx: 
				continue
			pos, val = rx.group(1), rx.group(2)
			if val.startswith('r'): 
				continue
			if val.startswith('0x'): val = val[2:]
			if len(val) % 2 == 1: val = '0' + val
			pos, val = int(pos, 16), val.decode('hex')
			asm_vals[pos] = val
			top = max(top, pos)
		stack = bytearray('\0' * top)
		
		for k in sorted(asm_vals, reverse=True):
			v = asm_vals[k]
			stack[top - k:len(v)] = v[::-1]
		result = stack[:stack.index('\00')]
	ringzer0.output('solved', result)
	
	response = ringzer0.submit_challenge(s, ch, result)
	ringzer0.output('response', response)
def solve_ch11(fn):
	ringzer0.output('solving')
	r2 = r2pipe.open(fn)
	asm_lines = r2.cmd('aa; s sym.main; pif~&mov,word,eax | grep ", 0x"').splitlines()
	#   mov dword [eax], 0x47414c46
	#   mov dword [eax + 4], 0x3930342d
	#   mov word [eax + 8], 0x32
	#   mov dword [eax], 0x75393438
	#   mov dword [eax + 4], 0x6a326f69
	#   mov word [eax + 8], 0x66
	#   mov dword [eax], 0x6a736c6b
	#   mov dword [eax + 4], 0x6c6b34
	buf = ''
	for asm_line in asm_lines:
		val = asm_line.split(',')[-1:][0].strip()
		if val.startswith('0x'): val = val[2:]
		buf += val.decode('hex')[::-1]
	ringzer0.output('solved', buf)
	return buf
Example #15
0
    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 #16
0
    def __init__(self, so_file_name, apk):

        # set apk parent name
        self.apk_filename = apk.get_filename().split('/')[-1]

        # dump so_file for further analysis
        self.dump_file(so_file_name, apk)

        # extract name from apk path
        self.so_file_name = so_file_name.split('/')[-1]

        with open('test/'+self.so_file_name, 'rb') as f:
            elffile = ELFFile(f)
            self.arch = parse_arch(elffile.header.e_machine)

        r2 = r2pipe.open('test/' + self.so_file_name)

        # build signature from JNI_OnLoad mnemonics
        self.build_signature(r2)

        self.build_hash()
Example #17
0
			if len(reg) == 2 and reg in reg2off: del reg2off[reg]


if __name__ == '__main__':
	parser = argparse.ArgumentParser()
	parser.add_argument('--impptr', dest='impptr', type=int, default=None)
	parser.add_argument('--func_name', dest='func_name', type=str, default=None)
	args = parser.parse_args()

	impptr = None
	func_name = None

	if args.impptr:
		impptr = args.impptr
		if impptr % 2 != 0: impptr -= 1
		func_name = 'func.%08x' % impptr
		impptr = hex(impptr)
	elif args.func_name:
		func_name = args.func_name
		impptr = func_name
	else:
		print('Please provide an imp pointer or func name')
		exit()

	r = r2pipe.open('http://*****:*****@ %s' % (func_name, impptr))

	func = r.cmdj('pdfj @ %s' % impptr)
	resolve_selectors_in_func(r, func)

Example #18
0
# -*-coding:utf-8-*-
import json

import pandas as pd
import r2pipe as r2

dataframe = pd.DataFrame(columns=['name_function', 'opcodes'])
r2p = r2.open('example')
r2p.cmd('aaa')
afl = json.loads(r2p.cmd('aflj'))
functionNamesArray = []
opcodesArray = []

for i in xrange(len(afl)):
    functionNamesArray.append(str(afl[i]['name']))
    opcodes = ""
    for offset in json.loads(r2p.cmd('pdj @' + str(afl[i]['name']))):
        try:
            opcodes += ':' + offset['opcode']
        except KeyError:
            pass
    opcodesArray.append(opcodes)

dataframe = pd.DataFrame({
    'name_function': functionNamesArray,
    'opcodes': opcodesArray
})
dataframe.to_csv('dataset.csv')
Example #19
0
import r2pipe

r2 = r2pipe.open("#!pipe")

_dis = r2.cmd ("pd 5")
print(_dis)
_hex = r2.cmd ("px 64")
print(_hex)
Example #20
0
            if f.Show():
                symbols = get_ida_symbols()
                output_file = f.txtFile.value
                write_symbols(f.input_elf, output_file, symbols)
                f.Free()

        def term(self):
            pass

    def PLUGIN_ENTRY():
        return Syms2Elf_t()

elif USE_R2:

    import r2pipe
    r2p = r2pipe.open()
    log = log_r2

    if len(sys.argv) < 2:
        log("%s - %s" % (PLUG_NAME, VERSION))
        log("Usage: $syms2elf <output file>")
        sys.exit(0)

    file_info = r2p.cmdj("ij").get("core")

    if file_info['format'].lower() in ('elf', 'elf64'):
        symbols = get_r2_symbols()
        write_symbols(file_info['file'], sys.argv[1], symbols)
    else:
        log("The input file is not a ELF")
Example #21
0
#/usr/bin/env python

import r2pipe
from os import system
import time

if __name__ == "__main__":
    print("[+] Spawning r2 tcp and http servers")
    system ("pkill r2")
    system ("r2 -qc.:9080 /bin/ls &")
    system ("r2 -qc=h /bin/ls &")
    time.sleep(1)

    # Test r2pipe with local process
    print("[+] Testing python r2pipe local")
    rlocal = r2pipe.open("/bin/ls")
    print(rlocal.cmd("pi 5"))
    #print rlocal.cmd("pn")
    info = rlocal.cmdj("ij")
    print ("Architecture: " + info['bin']['machine'])

    # Test r2pipe with remote tcp process (launch it with "r2 -qc.:9080 myfile")
    print("[+] Testing python r2pipe tcp://")
    rremote = r2pipe.open("tcp://127.0.0.1:9080")
    disas = rremote.cmd("pi 5")
    if not disas:
        print("Error with remote tcp conection")
    else:
        print(disas)

    # Test r2pipe with remote http process (launch it with "r2 -qc=H myfile")
Example #22
0
import random
import sys
import r2pipe
import time
'''profile: chall.rr2
#!/usr/bin/rarun2
program=./chall
stdin="AAAA"
stdout=
'''
r = r2pipe.open("./chall")
r.cmd('e dbg.profile=chall.rr2')
r.cmd('doo')  # initially you are debugging rarun2
r.cmd('db 0x0040008e')
r.cmd('dc')
print r.cmd('drj')
print(chr(27) + "[0;33m" + "[+]Key: " + chr(27) + "[0m")
key = r.cmdj('pxj 46@%s' % 0x0040010c)
print(key)
key_value = 10


def check_key(key):
    char_sum = 0
    for c in key:
        char_sum += ord(c)
    sys.stdout.write("{0:3} | {1}      \r".format(char_sum, key))
    sys.stdout.flush()
    return char_sum

Example #23
0
        # to get EIP with the FNSTENV technique
        # (http://gynvael.coldwind.pl/n/eip_from_fpu_x86).
        #
        # So we take note of the offset of the latest FPU instruction,
        # on put it in `esp` when `fnstenv` is encounted.
        if current_op['family'] == 'fpu':
            if current_op['opcode'].startswith('fnstenv'):
                r.cmd('wv %d @ esp' % lastfpu)
            else:
                lastfpu = current_op['offset']

        # Check for end of loop opcodes
        if current_op['opcode'].startswith('loop') and r.cmdj('arj')['ecx'] <= 1:
            lastloop = current_op['offset'] + current_op['size'];

        r.cmd('aes')

    print('[-] We emulated %d instructions, giving up' % i)


if len(sys.argv) != 2:
    print('[*] Usage: %s sample' % sys.argv[0])
    sys.exit(0)

r = r2pipe.open(sys.argv[1])
r.cmd('e asm.comments=false');
r.cmd('e asm.lines=false');
r.cmd('e asm.flags=false');
initESIL()
decode(r)
Example #24
0
 def __init__(self, path_to_elf: str, config: dict):
     self.config = config
     self.api = r2pipe.open(path_to_elf)
Example #25
0
#!/usr/bin/env python3

import r2pipe

r2 = r2pipe.open("pykspa.exe")


def auto_analyze(r2):
    r2.cmd("aaa")


def get_xref(r2):
    return r2.cmd("ax~section..data:0[1]").strip("\n")


def get_function(r2, address):
    f_offset = r2.cmd(f"pd 2 @ {address}~:1[4] ").strip("\n")
    return f_offset


def get_multiple_refs(r2, address):
    addrs = r2.cmd(f"axt @ {address}~[1]").split("\n")
    del addrs[-1]
    return addrs


def write_to_file(size, addr, name):
    r2.cmd(f"wtf {name} {size} @ {addr}")


def dump_things(r2, address):
Example #26
0
inc ecx
cmp ecx, {}
jb decode

jumpToOEP:
jmp {}

originalBinary:
'''.format(diff_start, diff_len, original_EP + 1),
                vma=new_EP)

# Read the compressed code from the original file

diff_file = 'diff.bin'

r2 = r2pipe.open('kaboom_real_flag.exe')
r2.cmd('s {}'.format(diff_start))
r2.cmd('wtf {} {}'.format(diff_file, diff_len))
r2.quit()

# Patch the kaboom file

print(disasm(shellcode, vma=new_EP))

r2 = r2pipe.open('kaboom_jebaited.exe',
                 flags=['-w'])  # Open file in write mode
r2.cmd('s {}'.format(new_EP))  # Seek to the new entry point
r2.cmd('wxs {}'.format(
    enhex(shellcode)))  # Write the shellcode and seek to the end
r2.cmd('wff {}'.format(diff_file))  # Write the original compressed binary
r2.quit()
                if i + 1 >= len(opcodes):
                    print('size is too long')
                    break
                i += 1

                opcode = opcodes[i]
                if opcode['mnemonic'] != 'call':
                    print('no call')
                    break

                status = FindStatus.FOUND_RET
                return addr

            i += 1

    return None


if __name__ == '__main__':
    if len(sys.argv) < 4:
        sys.exit(-1)
    r = r2pipe.open(sys.argv[1], radare2home=sys.argv[2])
    func_addr = get_private_addr(r)
    with open(sys.argv[3], 'w') as fd:
        if func_addr is None:
            fd.write('-1')
        else:
            fd.write(str(func_addr))
    r.quit()
    sys.exit(0)
Example #28
0
 def __init__(self, filename, use_symbol, depth):
     self.r2 = r2pipe.open(filename, flags=['-2'])
     self.filename = filename
     self.arch, _ = self.get_arch()
     self.top_depth = depth
     self.use_symbol = use_symbol
Example #29
0
    args = parser.parse_args()
    argv = args.binary
    arguments = ' '.join(argv[1:])
    binary = argv[0]
    target = args.target
    offset = args.offset
    skip = args.skip
    profile = args.profile
    module = target.endswith(".so")

    cprint(
        "[!] This program could have unexpected effect. Use it with caution !!!",
        "red")

    r2 = r2pipe.open(binary)

    if profile:
        print("[+] Setting profile from {}".format(profile))
        r2.cmd("e dbg.profile=" + profile)

    print("[+] Opening {} in debug mode".format(binary))
    #r2.cmd("doo " + arguments)
    r2.cmd("doo")

    # skip sigchld handler
    r2.cmd("dko 17 skip")

    print("[+] Getting address of target function")
    if not module:
        start = r2.cmd("s @ sym." + target)
# py -m pip install r2pipe
# download radare2, and put it in your PATH
import r2pipe
import json

r = r2pipe.open(filename="cryptowall.bin")


def get_eip():
    return json.loads(r.cmd('drj'))['rip']


r.cmd('aaaa')
r.cmd('doo')
r.cmd('db main')
r.cmd('doo')
r.cmd('dc')
r.cmd('dc')
r.cmd('dc')  # should be in main now
print('Found main: ' + hex(get_eip()))

r.cmd('db 0x00402dda')  # breakpoint at the end of push eax
r.cmd('dc')
r.cmd('ds 2')  # step into eax
print('Found Second stage loader: ' + hex(get_eip()))
print(r.cmd('pd 10'))  # now we are inside the stage 2 of unpacking

print("Hold your horses... this may take awhile")
r.cmd('dsu 0x0302CA57')
print('Inside Second stage loaders call to EAX: ' + hex(get_eip()))
r.cmd('ds 1')  #step into EAX
Example #31
0
 def command(self, command):
     r = r2pipe.open(__sessions__.current.file.path)
     self.log('info', r.cmd(command))
Example #32
0
File: main.py Project: sapir/sonare
 def __init__(self):
     # open empty, we'll open files later
     self.r2 = r2pipe.open('--')
     self.opcodeAddrs = []
Example #33
0
import r2pipe

r2 = r2pipe.open("./<name_of_binary>")

#rax = r2.cmd("aer rax")
#print(r2.cmd("pvz @ {}".format(rax)))
#text = raw_input()
#rax = r2.cmd("aer rax")
#r2.cmd("w {} @ {}".format(text, rax))

Example #34
0
graph.node('0x400d80', 'ret local_1_4')
graph.node('0x400ba4', 'if (local_1_4 != 0) green')
graph.node('0x400c02', 'if (arg2[0] == arg2[1]) green')
graph.node('0x400d6d', 'local_1_4 = 1')
graph.node('0x400c24', 'arg2[arg2[0] + 1] = arg1[arg1[0] + 2]\n++arg1[0]\n--arg2[0]\nlocal_1_4 = 0')
graph.node('0x400bc1', 'if (arg1[0] < arg1[1]) green')
graph.node('0x400c9d', 'if (arg1[arg1[0] + 2] < arg2[arg2[0] + 2]) green')
graph.node('0x400d61', 'nop')
graph.node('0x400cd0', 'arg2[arg2[0] + 1] = arg1[arg1[0] + 2]\n++arg1[0]\n--arg2[0]\nlocal_1_4 = 0')
graph.node('0x400d49', 'nop')
graph.node('0x400be3', 'if (arg2[0] != 0) green')
graph.node('0x400b84', 'if (arg1 != 0) green', peripheries = '2')
graph.node('0x400d55', 'nop')

r = r2pipe.open('jail_break_bin')
r.cmd('aaa')
r.cmd('s 0x00400960')
jes = r.cmd('pdf~je[1,4]')

controls = {}
for je in jes.splitlines():
    offset, jump = map(lambda x:int(x, 16), je.split(' '))

    bb = r.cmdj('pdbj @' + str(offset))
    try:
        sub, = (x for x in bb if 'sub eax, ' in x['opcode'])
        control = int(sub['opcode'].split(',')[1], 16)
        controls[control] = jump

    except ValueError:
junk blocks from APT32 (Ocean Lotus) samples.
"""

__author__ = "Itay Cohen, aka @megabeets_"
__company__ = "Check Point Software Technologies Ltd"

# Check if we're running from cutter
try:
    import cutter
    from PySide2.QtWidgets import QAction
    pipe = cutter
    cutter_available = True
# If no, assume running from radare2
except:
    import r2pipe
    pipe = r2pipe.open()
    cutter_available = False


class GraphDeobfuscator:
    # A list of pairs of opposite conditional jumps
    jmp_pairs = [['jno', 'jo'], ['jnp', 'jp'], ['jb', 'jnb'], ['jl', 'jnl'],
                 ['je', 'jne'], ['jns', 'js'], ['jnz', 'jz'], ['jc', 'jnc'],
                 ['ja', 'jbe'], ['jae', 'jb'], ['je', 'jnz'], ['jg', 'jle'],
                 ['jge', 'jl'], ['jpe', 'jpo'], ['jne', 'jz']]

    def __init__(self, pipe, verbose=False):
        """an initialization function for the class
        
        Arguments:
            pipe {r2pipe} -- an instance of r2pipe or Cutter's wrapper
Example #36
0
parser.add_argument('-e', '--emulation',help='EMULATE THE SHELLCODE OF THE FUNCTION')
parser.add_argument('-o', '--emulationAtAddress',type= any ,help='CHOSE THE ADDRESS WHERE YOU WANT TO EMULATE ')
parser.add_argument('-se', '--symbexec',help='SYMBOLICALLY EXECUTE THE SHELLCODE OF THE FUNCTION')
parser.add_argument('-sim', '--similarity',help='ip of the server ')
argdAction = parser.parse_args()
argDump=parser.parse_args()
argSize=parser.parse_args()
argAdd=parser.parse_args()
argEmu=parser.parse_args()
argOffset=parser.parse_args()
argSymb=parser.parse_args()
argFile=parser.parse_args()
argSimilarity=parser.parse_args()
if argFile.binaryfile:
	print str(argFile.binaryfile)
 	r2 = r2pipe.open(str(argFile.binaryfile))
	r2.cmdj("aaa")
	function_list = r2.cmdj("aflj") # Analysis Function List Json
	i=0
	for function in function_list:
		if (argdAction.action=="addr") :
			 print("@ of  %s =  0x%x" %(function['name'],function['offset']))
		elif (argdAction.action=="size"):
			 print("[+] FunctionSize "+str(i)+": 0x%x " %(function['size']))
		elif(argdAction.action=="name"):
			print('[+] FunctionName' +str(i)+" " +function['name'])
		elif (argdAction.action=="dump"):
			print('[+] FunctionDump '+str(i)+":  "+function['name']+ " = " +(r2.cmd("p8" +" "+ str(function["size"])+ " @ " + function["name"]) ))
		i += 1
		try:
			con = lite.connect('deko.db')
Example #37
0
# Requires:
# - r2 from git
# - r2pipe 0.9.0
# - r2pm -i lang-python
# - Python 2 or 3
#
# HowTo:
# - Run r2 -c=h /bin/ls
# - Run r2 -C http://localhost:9090/cmd/
# - Run r2 -i talkto.py /bin/ls
#

import r2pipe

try:
    r2 = r2pipe.open()
    r2.cmd("e cfg.user=pancake")
    r2.cmd("e cfg.log=true")

    r2.cmd("T this is me")
    r2.cmd("CC hello world")
    logs = r2.cmd("T")
    print(logs)
except:
    print("You need r2pm -i lang-python")
    pass

last = ""
last2 = ""
r2r = r2pipe.open("http://localhost:9090")
r2r.cmd("e cfg.log=true")
Example #38
0
#!/usr/bin/env python
import sys
import r2pipe

r2p = r2pipe.open()
num = int(sys.argv[1])
if num == 0x80:
	r = r2p.cmdj("arj")
	if r['eax'] == 1:
		print "[SYSCALL EXIT] %d"%(r['ebx'])
	elif r['eax'] == 4:
		msg = r2p.cmd("psz %d@%d"%(r['edx'], r['ecx']))
		print "[WRITE SYSCALL] ==> %s"%(msg)
elif num == 3:
	print "[INT3]"
else:
	print ("[unhandled SYSCALL %d]"%num)
Example #39
0
import r2pipe

r2 = r2pipe.open("pongo://")
h = r2.cmd("e asm.arch=arm")
h = r2.cmd("e asm.bits=64")

# print(r2.cmd("=!help"))

entrypoint = 0x100000000
r2.cmd("s " + str(entrypoint))
dis = r2.cmd("pd 10")
print("pongoOS entrypoint:")
print(dis)
Example #40
0
        print("Error" + result['error']['message'])
        return
    return result


def show_results(res):
    for r in res['stats']:
        print("# %20s %s" % (r, res['stats'][r]))
    for r in res['results']:
        sys.stdout.write("%s  %8d  %s" % (r['sha1'], r['size'], r['label']))
        m = get_metadata(r['sha1'])
        print "  %s %s %s" % (m['fn'], ' ' * (20 - len(m['fn'])), m['fd'])


bly = BinarlyAPI(api_key=APIKEY, use_http=usehttp, project=PROJECT)
r2p = r2pipe.open('#!pipe')


def halp():
    print "Usage: r2bly [op] [...]"
    print "  Binarly extension for radare2 delivered by pancake."
    print "Operations:"
    print "  fcn      - find all functions smaller than X"
    print "  hex (..) - find files matching given hexpairs"
    print "  imp      - find files matching all imports"
    print "  sha [..] - identify current file or given hash by using the sha1"
    print "  str      - find which files contain all long strings"
    print "  key      - set api key"
    print "Radare2:"
    print "  \"$r2bly=#!pipe python test.py\""
    print "  $r2bly str"
def get_config():
    r = r2pipe.open('test_bin')
    return Config(r)
Example #42
0
from __future__ import print_function

import r2pipe

r2 = r2pipe.open("#!pipe")

_dis = r2.cmd("pd 5")
print(_dis)
_hex = r2.cmd("px 64")
print(_hex)
#!/usr/bin/env python
import sys
import os
import shutil
import tempfile
import r2pipe
import subprocess
import json

f = tempfile.NamedTemporaryFile(delete=False)
f.close()

shutil.copy2('/usr/libexec/kextd', f.name)

r2 = r2pipe.open(f.name, writeable=True, bits=64)

out = subprocess.check_output(['rabin2', '-j', '-i', '/usr/libexec/kextd'])
data = json.loads(out)
imports = data['imports']

needs_patching = filter(
	lambda x: x['name'].startswith('SecStaticCodeCheckValidity'),
	imports
)

for fun in needs_patching:
	r2.cmd('s {}'.format(fun['plt']))
	r2.cmd('"wa xor eax, eax; ret"')

	print 'Patched {}'.format(fun['name'])
Example #44
0
    def _get_r2pipe(self):
        """Get the r2pipe handle"""

        if not hasattr(self, "r2"):
            self.r2 = r2pipe.open("-")
Example #45
0
import r2pipe
import sys
import os

r2 = r2pipe.open("/bin/ls")
libpath = ['', '.', '/lib', '/usr/lib']
output = 'aa'
# output = 'dot'

done = {}

def findlib(lib):
	if os.path.isfile(lib):
		return lib
	for a in libpath:
		if os.path.isfile("%s/%s"%(a, lib)):
			return "%s/%s"%(a, lib)
	return []

def getlibs(lib):
	return r2.syscmdj("rabin2 -lj %s"%(lib))['libs']

def filter(s):
	return s.replace("-","_").replace("+","x")

def makeNode(name):
	r2.cmd("agn %s"%(filter(name)))

def makeEdge(f,t):
	r2.cmd("age %s %s"%(filter(f), filter(t)))
Example #46
0
#/usr/bin/env python

import r2pipe
from os import system
import time

if __name__ == "__main__":
    print("[+] Spawning r2 tcp and http servers")
    system("pkill r2")
    system("radare2 -qc.:9080 /bin/ls &")
    system("radare2 -qc=h /bin/ls &")
    time.sleep(1)

    # Test r2pipe with local process
    print("[+] Testing python r2pipe local")
    rlocal = r2pipe.open("/bin/ls")
    print(rlocal.cmd("pi 5"))
    #print rlocal.cmd("pn")
    info = rlocal.cmdj("ij")
    print("Architecture: " + info['bin']['machine'])

    # Test r2pipe with remote tcp process (launch it with "radare2 -qc.:9080 myfile")
    print("[+] Testing python r2pipe tcp://")
    rremote = r2pipe.open("tcp://127.0.0.1:9080")
    disas = rremote.cmd("pi 5")
    if not disas:
        print("Error with remote tcp conection")
    else:
        print(disas)

    # Test r2pipe with remote http process (launch it with "radare2 -qc=H myfile")
Example #47
0
import r2pipe

r2=r2pipe.open("/bin/ls", ["-nd"])
for a in range(1,10):
	regs = r2.cmdj("drj")
	print "0x%x  0x%x"%(regs['rip'],regs['rsp'])
	r2.cmd("ds")
Example #48
0
 def __init__(self, flags=[], filename=None):
     if not filename:
         self.r2 = r2pipe.open(flags=flags)
     else:
         self.r2 = r2pipe.open(filename, flags=flags)
Example #49
0
useCurses = True
useArch = "x86"
useBits = "32"

ctr = 0
uidx = 0
user = []
name = []
wins = []
size = []
orig = []
stdscr = None

memsize = 1024
maxprogsize = 64
r2 = r2pipe.open('malloc://%d'%(memsize))
#r2 = r2pipe.open('/bin/ls')
r2.cmd("e asm.arch=%s"%(useArch))
r2.cmd("e asm.bits=%s"%(useBits))
r2.cmd("e scr.color=true")
r2.cmd("aei")
r2.cmd("aeim")

def get_random_offsets():
	while True:
		rand = []
		addr = random.randint(0, memsize - maxprogsize)
		for a in sys.argv[1:]:
			rand.append(addr)
			addr = addr + random.randint(maxprogsize, maxprogsize + 300)
			if addr + maxprogsize > memsize:
Example #50
0
def dump(file):
    global output, parserOutput, scriptCategory, parseScripts, methodInfo
    print("Opening file {0}".format(file))
    filename = os.path.split(os.path.splitext(file)[0])[-1]
    loadHashes(scriptCategory + "_")

    if 'common' in filename or 'item' in filename:
        return

    r2 = r2pipe.open(file)
    r2.cmd('e anal.bb.maxsize = 0x10000')
    r2.cmd('e anal.vars = false')
    sections = r2.cmdJ("isj")
    loadMethodInfo(sections)
    game = next(
        (x for x in sections
         if "lua2cpp::create_agent_fighter_animcmd_{0}_".format(scriptCategory)
         in x.demname and "_share_" not in x.demname), None)
    if game:
        print("{0} found".format(game.demname))

        af = r2.cmdJ('s {0};af;pdfj'.format(game.vaddr))

        p = ParseAnimcmdList(r2, af, sections)

        print("Scripts extracted"
              )  #, {0} articles found .format(len(p.ArticleScripts))

        if not os.path.exists(output):
            os.makedirs(output)

        if not os.path.exists("{0}/{1}".format(output, filename)):
            os.makedirs("{0}/{1}".format(output, filename))

        if parseScripts:
            if not os.path.exists(parserOutput):
                os.makedirs(parserOutput)

            if not os.path.exists("{0}/{1}".format(parserOutput, filename)):
                os.makedirs("{0}/{1}".format(parserOutput, filename))

        if len(p.Issues) > 0:
            #Log missing scripts in file due to issues on parsing or radare2 output
            None
            #f = open("{0}/{1}/{2}.txt".format(output, filename, "missing"), "w")
            #f.write("")
            #f.close()

        for article in p.ArticleScripts:

            print("Dumping article {0} scripts, count: {1}".format(
                article.findHashValue(), len(article.scriptsHash)))

            if not os.path.exists("{0}/{1}/{2}".format(
                    output, filename, article.findHashValue())):
                os.makedirs("{0}/{1}/{2}".format(output, filename,
                                                 article.findHashValue()))

            if parseScripts:
                if not os.path.exists("{0}/{1}/{2}".format(
                        parserOutput, filename, article.findHashValue())):
                    os.makedirs("{0}/{1}/{2}".format(parserOutput, filename,
                                                     article.findHashValue()))

            for hash in article.scriptsHash:

                scriptStart = r2.cmdJ('s {0};pdj 20'.format(hash.address))
                scriptAddress = ParseAnimcmdStart(scriptStart).address

                if scriptAddress:
                    script = r2.cmdJ('s {0};aF;pdfj'.format(scriptAddress))

                    if parseScripts:
                        try:
                            parser = Parser(r2, script, hash.findHashValue(),
                                            sections)
                            pf = open(
                                '{0}/{1}/{2}/{3}.txt'.format(
                                    parserOutput, filename,
                                    article.findHashValue(),
                                    hash.findHashValue()), 'w')
                            pf.write(parser.Output())
                            pf.close()
                        except:
                            print("Couldn't parse {0}".format(
                                hash.findHashValue()))

                    #script = script.replace('\r', '')
                    #exists = os.path.exists("{0}/{1}/{2}/{3}.txt".format(output, filename, article.findHashValue(), hash.findHashValue()))
                    #if not exists:
                    #f = open("{0}/{1}/{2}/{3}.txt".format(output, filename, article.findHashValue(), hash.findHashValue()), "w")
                    #f.write(script)
                    #f.close()
                    #else:
                    #    v = 2
                    #    while exists:
                    #        exists = os.path.exists("{0}/{1}/{2}/{3} ({4}).txt".format(output, filename, article.findHashValue(), hash.findHashValue(), v))
                    #        if not exists:
                    #            f = open("{0}/{1}/{2}/{3} ({4}).txt".format(output, filename, article.findHashValue(), hash.findHashValue(), v), "w")
                    #            f.write(script)
                    #            f.close()
                    #        v += 1

    else:
        print('animcmd_game not found on file {0}'.format(file))

    r2.quit()
Example #51
0
import os
import r2pipe
import string

r2 = r2pipe.open("count")
char_list = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_")
good_string = list('ah_ah_ah_ah_902C7b10fE4a')
#good_string = list('ah')
instring = list('')
dc_count = 1
r2.cmd("doo")
bp_1 = '80485d3'
bp_2 = '80485da'
r2.cmd("db 0x" + bp_1)
r2.cmd("db 0x" + bp_2)
r2.cmd('dbc 0x'+bp_1+' "echo 80485d3"')
r2.cmd('dbc 0x'+bp_2+' "echo 80485da"')
r2.cmd('db')
for dc_count in range (25, 45):
	for test_char in char_list:
		#os.system('clear')
		null = r2.cmd("doo " + "".join(good_string) + "".join(instring)+test_char)
		output = r2.cmd(str(dc_count) +"dc")
		if bp_1 in output:
		   continue
		if bp_2 in output:
		   instring+=test_char
		   print("Instring: " + "".join(instring))
		   break
import r2pipe
import json
import os

# ------------------------------------------------------------------------------------------------------------------------------------
# This script intends to decide, thanks to the output data it generates, which sorting criterion to use in the radar2_analysis-v2.py
# ------------------------------------------------------------------------------------------------------------------------------------

################################################## USER SECTION #######################################################
# Choose the analysis and listing commands you want to apply to the input file
ANALYSIS_CMD = "aa"
LISTING_CMD = "aflj~{}"
#######################################################################################################################

# opening the input executable file
r2 = r2pipe.open(str(sys.argv[1]))

# basic analysis and listing commands
r2.cmd(ANALYSIS_CMD)
aflj_output = r2.cmd(LISTING_CMD)

# loading and processing the json output
print("Loading and processing the json output...")
aflj_json = json.loads(aflj_output)
aflj_lines_number = len(aflj_json)

columnTitleRow = "programName,calltype, realsz, diff, name, cc, indegree, nargs, difftype, edges, outdegree, cost, nlocals, offset, ebbs, nbbs, type, size, datarefs, cref_c, cref_j\n"
parameters = [
    "calltype", "realsz", "diff", "name", "cc", "indegree", "nargs",
    "difftype", "edges", "outdegree", "nlocals", "cost", "offset", "ebbs",
    "nbbs", "type", "size"
Example #53
0
 def command(self, command):
     r = r2pipe.open(__sessions__.current.file.path)
     print(r.cmd(command))
Example #54
0
import r2pipe

r2functionprefix = "sym.ntdll.dll_"

r2p = r2pipe.open("ntdll.dll")
r2p.cmd("aaa")
funcs = r2p.cmdj("aflj")

# parse Nt-functions
nt_functions = []
for f in funcs:
    if f['name'].startswith(r2functionprefix + "Nt"):
        nt_functions.append(f)

# get syscall numbers
# mov eax, sysnum ; is at offset 0x3

offsets = {}
for f in nt_functions:
    disas = r2p.cmdj("pdj 1 @ {}".format(f['offset'] + 0x3))
    try:
        offsets[f['name']] = disas[0]['val']
    except:
        print(f['name'])

# print C-style defines
print("\n")
for o in offsets:
    print("#define {} {}".format(o[len(r2functionprefix):], offsets[o]))
Example #55
0
        self.list_type = r2.cmdj("idddj list_head")
        self.current = int(r2.cmd("iddv list_head.next @ %s" % head), 16)
        self.head = get_addr(head)
        self.type = r2.cmdj("idddj %s" % type)
        self.type_name = type
        self.offset = get_field(self.type, field)["offset"]
        self.debug = debug

    def __iter__(self):
        return self

    def next(self):  # Python 3: def __next__(self)
        if self.debug == 1:
            print(" - head: %d - current: %d" % (self.head, int(self.current)))

        if (int(self.current) == self.head):
            raise StopIteration
        else:
            new_offset = self.current - self.offset
            res = r2.cmdj("iddvj %s @ %d" % (self.type_name, new_offset))
            cmd = "iddv list_head.next @ %d" % self.current
            self.current = int(r2.cmd(cmd), 16)
            return res


r2 = r2pipe.open()

for i in list("sym.key_types_list", "key_type", "link"):
    print r2.cmd("ps @ %s" % i["name"])
    #print i
def get_print():
    r = r2pipe.open('test_bin')
    return Print(r)
import r2pipe

r2=r2pipe.open("/bin/ls", False, False, True)
for a in range(1,10):
	regs = r2.cmdj("drj")
	print "0x%x  0x%x"%(regs['rip'],regs['rsp'])
	r2.cmd("ds")
Example #58
0
 def __init__(self, path):
     self.r = r2pipe.open(path)
Example #59
0
def valid_url(string):
    url = re.findall(
        'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',
        string)
    return url


def valid_ip(address):
    try:
        socket.inet_aton(address)
        return True
    except:
        return False


r = r2pipe.open("Unpacked_Lab01-02.exe")
r.cmd('aaa')
print(
    chr(27) + "[1;36m" +
    "\t\t\t\t\tSTAGE 1 - RECON: Getting information about Sections" + chr(27) +
    "[0m")
out = r.cmdj('iSj')
for i in range(len(out)):
    print(out[i]["name"])
    print("[+] Virtual Size: %i" % out[i]["vsize"])
    print("[+] Raw Data Size: %i" % out[i]["size"])
    print("[+] Permission: %s" % out[i]["perm"])

print(
    chr(27) + "[1;36m" +
    "\t\t\t\t\tSTAGE 1 - RECON: Getting information from Strings in PE File" +
Example #60
0
if len(sys.argv) == 4:
    dump_debug_info(
        'DUMP-MODE enabled, all patches are dumped into the specified dump_computed_patches.json'
    )
    dump_mode = True
    patch_dump_file = sys.argv[3]
sc_stats = {}
# We should not seek for patch guide when stats indicate no guards, see #42
if len(sys.argv) == 5:
    sc_stats = json.load(open(sys.argv[4]))
    if sc_stats["numberOfGuards"] == 0:
        print 'SC stats indicates there is nothing to be patched'
        exit(0)
# open binary
file_to_open = sys.argv[1]
r2 = r2pipe.open(file_to_open)
# find addresses and sizes of all functions
r2.cmd("aa")
r2.cmd("aac")
function_list = r2.cmdj("aflj")
funcs = {}
for function in function_list:
    attr = {'size': function['size'], 'offset': function['offset']}
    funcs[function['name']] = attr

#import pprint
#pprint.pprint(funcs)

# open patch guide
guide_to_open = sys.argv[2]
if not os.path.exists(guide_to_open):