예제 #1
0
def main():
    start_time = time.time()

    # Split program arguments.
    # ======================================================================== #
    prg_options, prg_arguments = split_command_line(sys.argv)

    binary_path = prg_arguments[0]

    # Loading binary.
    # ======================================================================== #
    print("[+] Loading binary...")

    barf = BARF(binary_path)

    if barf.binary.architecture not in [ARCH_X86, ARCH_ARM]:
        print("[-] Architecture not supported!")

        sys.exit(1)

    # Setup emulator.
    # ======================================================================== #
    ctx_init, start, end, hooks = setup_emulator(barf.emulator, barf.binary, prg_arguments)

    # Emulate.
    # ======================================================================== #
    barf.emulate(context=ctx_init, start=start, end=end, hooks=hooks, print_asm=False)

    end_time = time.time()

    total_time = end_time - start_time

    print("[+] Total processing time: {0:8.3f}s".format(total_time))
예제 #2
0
def TstBarf(file_path):
	barf = BARF(file_path)

	# Recover CFG.

	sys.stdout.write("dir=%s\n"%str(dir(barf)))
	cfg = barf.recover_cfg()
	basna = os.path.basename(file_path)

	# Save CFG to a .dot file.
	cfg.save(basna)
예제 #3
0
def De_IS(filename, start):
    # sys.argv = ["test.py", "/Users/mark/Desktop/de_obfuscator/IS/New-test/total/inssub", "0x694"]
    # if len(sys.argv) != 3:
    #     print 'Usage: python DeInsSub.py filename function_address(hex)'
    #     exit(0)

    # filename = sys.argv[1]
    start = int(start, 16)
    filename = filename
    # start = int(start, 16)
    barf = BARF(filename)
    base_addr = barf.binary.entry_point >> 12 << 12

    cfg = barf.recover_cfg(start)
    blocks = cfg.basic_blocks

    print('The function has %d blocks. ' % len(blocks))

    origin = open(filename, 'rb')
    data = list(origin.read())

    for block in blocks:
        opposite = []
        #查找所用的MOV指令,然后记录所用寄存器值相反的对
        # for ins in block.instrs:
        #     if ins.mnemonic_full.startswith(u'mvn'):
        #         if ins.operands[0].name not in opposite:
        #             opposite[ins.operands[0].name] = ins.operands[1].name

        block_size = len(block.instrs)
        ADDHex, ADDnop = check_add(block, block_size)
        data = fix_substitution(data, ADDHex, ADDnop, base_addr)
        SUBHex, SUBnop = check_sub(block, block_size)
        data = fix_substitution(data, SUBHex, SUBnop, base_addr)
        XORHex, XORnop = check_xor(block, block_size)
        data = fix_substitution(data, XORHex, XORnop, base_addr)
        ANDHex, ANDnop = check_and(block, block_size)
        data = fix_substitution(data, ANDHex, ANDnop, base_addr)
        ORHex, ORnop = check_or(block, block_size)
        data = fix_substitution(data, ORHex, ORnop, base_addr)

    origin.close()
    # recovery = open(filename + '_recovered', 'wb')
    path = sys.argv[3]
    if not os.path.exists(path + filename.split('/')[-2] + '/'):
        os.mkdir(path + filename.split('/')[-2] + '/')
    recovery = open(
        path + filename.split('/')[-2] + '/' + filename.split('/')[-1] +
        '_recovered', 'wb')

    recovery.write(''.join(data))
    recovery.close()
    print 'Successful! The recovered file: %s' % (filename + '_recovered')
예제 #4
0
def main():
    start_time = time.time()

    # Split program arguments.
    # ======================================================================== #
    prg_options, prg_arguments = split_command_line(sys.argv)

    binary_path = prg_arguments[0]

    # Loading binary.
    # ======================================================================== #
    print("[+] Loading binary...")

    barf = BARF(binary_path)

    if barf.binary.architecture not in [ARCH_X86, ARCH_ARM]:
        print("[-] Architecture not supported!")

        sys.exit(1)

    # Setup emulator.
    # ======================================================================== #
    ctx_init, start, end, hooks = setup_emulator(barf.ir_emulator, barf.binary,
                                                 prg_arguments)

    # Emulate.
    # ======================================================================== #
    barf.emulate(context=ctx_init,
                 start=start,
                 end=end,
                 hooks=hooks,
                 print_asm=False)

    end_time = time.time()

    total_time = end_time - start_time

    print("[+] Total processing time: {0:8.3f}s".format(total_time))
예제 #5
0
#! /usr/bin/env python

import os
import sys

from barf import BARF

if __name__ == "__main__":
    #
    # Open file
    #
    try:
        filename = os.path.abspath("../../samples/toy/x86/constraint2")
        barf = BARF(filename)
    except Exception as err:
        print err

        print "[-] Error opening file : %s" % filename

        sys.exit(1)

    #
    # Check constraint
    #

    # 80483ed:       55                      push   ebp
    # 80483ee:       89 e5                   mov    ebp,esp
    # 80483f0:       83 ec 10                sub    esp,0x10
    # 80483f3:       8b 45 f4                mov    eax,DWORD PTR [ebp-0xc]
    # 80483f6:       0f af 45 f8             imul   eax,DWORD PTR [ebp-0x8]
    # 80483fa:       83 c0 05                add    eax,0x5
예제 #6
0
#! /usr/bin/env python

from barf import BARF

if __name__ == "__main__":
    #
    # Open file
    #
    barf = BARF("../../samples/bin/constraint2.x86")

    #
    # Check constraint
    #

    # 80483ed:       55                      push   ebp
    # 80483ee:       89 e5                   mov    ebp,esp
    # 80483f0:       83 ec 10                sub    esp,0x10
    # 80483f3:       8b 45 f4                mov    eax,DWORD PTR [ebp-0xc]
    # 80483f6:       0f af 45 f8             imul   eax,DWORD PTR [ebp-0x8]
    # 80483fa:       83 c0 05                add    eax,0x5
    # 80483fd:       89 45 fc                mov    DWORD PTR [ebp-0x4],eax
    # 8048400:       8b 45 fc                mov    eax,DWORD PTR [ebp-0x4]
    # 8048403:       c9                      leave
    # 8048404:       c3                      ret

    print("[+] Adding instructions to the analyzer...")

    for addr, asm_instr, reil_instrs in barf.translate(start=0x80483ed, end=0x8048402):
        print("0x{0:08x} : {1}".format(addr, asm_instr))

        for reil_instr in reil_instrs:
예제 #7
0
        sat = code_analyzer.check() == 'sat'

        logger.info("BB @ {:#x} sat? {}".format(bb_curr.address, sat))

        if not sat:
            break

    # Return satisfiability.
    return sat


if __name__ == "__main__":
    #
    # Open file
    #
    barf = BARF("./samples/bin/constraint3.x86")

    #
    # Check constraint
    #

    # 80483ed:       55                      push   ebp
    # 80483ee:       89 e5                   mov    ebp,esp
    # 80483f0:       83 ec 10                sub    esp,0x10
    # 80483f3:       c7 45 f0 01 00 00 00    mov    DWORD PTR [ebp-0x10],0x1
    # 80483fa:       81 7d f4 44 43 42 41    cmp    DWORD PTR [ebp-0xc],0x41424344
    # 8048401:       75 19                   jne    804841c <main+0x2f>
    # 8048403:       81 7d f8 48 47 46 45    cmp    DWORD PTR [ebp-0x8],0x45464748
    # 804840a:       75 10                   jne    804841c <main+0x2f>
    # 804840c:       81 7d fc ef cd ab 00    cmp    DWORD PTR [ebp-0x4],0xabcdef
    # 8048413:       75 07                   jne    804841c <main+0x2f>
#! /usr/bin/env python

import os
import sys

from barf import BARF
from barf.arch import ARCH_ARM_MODE_ARM

if __name__ == "__main__":
    #
    # Open file
    #
    try:
        filename = os.path.abspath("../../bin/arm/constraint1")
        barf = BARF(filename)
    except Exception as err:
        print err

        print "[-] Error opening file : %s" % filename

        sys.exit(1)

    #
    # Check constraint
    #

    # 00008390 <main>:
    #     8390:    e52db004     push    {fp}        ; (str fp, [sp, #-4]!)
    #     8394:    e28db000     add    fp, sp, #0
    #     8398:    e24dd014     sub    sp, sp, #20
    #     839c:    e51b2008     ldr    r2, [fp, #-8]
예제 #9
0
#! /usr/bin/env python

from barf import BARF

if __name__ == "__main__":
    #
    # Open file
    #
    barf = BARF("../../samples/bin/constraint1.arm")

    #
    # Check constraint
    #

    # 00008390 <main>:
    #     8390:    e52db004     push    {fp}        ; (str fp, [sp, #-4]!)
    #     8394:    e28db000     add    fp, sp, #0
    #     8398:    e24dd014     sub    sp, sp, #20
    #     839c:    e51b2008     ldr    r2, [fp, #-8]
    #     83a0:    e51b300c     ldr    r3, [fp, #-12]
    #     83a4:    e0823003     add    r3, r2, r3
    #     83a8:    e2833005     add    r3, r3, #5
    #     83ac:    e50b3010     str    r3, [fp, #-16]
    #     83b0:    e51b3010     ldr    r3, [fp, #-16]
    #     83b4:    e1a00003     mov    r0, r3
    #     83b8:    e28bd000     add    sp, fp, #0
    #     83bc:    e8bd0800     ldmfd    sp!, {fp}
    #     83c0:    e12fff1e     bx    lr

    start_addr = 0x8390
    end_addr = 0x83bc
#! /usr/bin/env python

from __future__ import absolute_import
from __future__ import print_function

from barf import BARF

if __name__ == "__main__":
    #
    # Open file
    #
    barf = BARF("./samples/bin/constraint1.arm")

    #
    # Check constraint
    #

    # 00008390 <main>:
    #     8390:    e52db004     push    {fp}        ; (str fp, [sp, #-4]!)
    #     8394:    e28db000     add    fp, sp, #0
    #     8398:    e24dd014     sub    sp, sp, #20
    #     839c:    e51b2008     ldr    r2, [fp, #-8]
    #     83a0:    e51b300c     ldr    r3, [fp, #-12]
    #     83a4:    e0823003     add    r3, r2, r3
    #     83a8:    e2833005     add    r3, r3, #5
    #     83ac:    e50b3010     str    r3, [fp, #-16]
    #     83b0:    e51b3010     ldr    r3, [fp, #-16]
    #     83b4:    e1a00003     mov    r0, r3
    #     83b8:    e28bd000     add    sp, fp, #0
    #     83bc:    e8bd0800     ldmfd    sp!, {fp}
    #     83c0:    e12fff1e     bx    lr
예제 #11
0
#! /usr/bin/env python

import os
import sys

from barf import BARF
from barf.arch import ARCH_ARM_MODE_ARM

if __name__ == "__main__":
    #
    # Open file
    #
    try:
        filename = os.path.abspath("../../bin/arm/constraint2")
        barf = BARF(filename)
    except Exception as err:
        print err

        print "[-] Error opening file : %s" % filename

        sys.exit(1)

    #
    # Check constraint
    #

    # 00008390 <main>:
    #     8390:    e52db004     push    {fp}        ; (str fp, [sp, #-4]!)
    #     8394:    e28db000     add    fp, sp, #0
    #     8398:    e24dd014     sub    sp, sp, #20
    #     839c:    e51b3008     ldr    r3, [fp, #-8]
예제 #12
0
def De_BCF(filename, start):
    # sys.argv = ["test.py", '/Users/mark/Desktop/de_obfuscator/benchmark/binary/pyramid-bcf-sub', "0x72c"]
    # start = int(sys.argv[2], 16)
    start = int(start, 16)
    # filename = sys.argv[1]
    filename = filename
    barf = BARF(filename)

    base_addr = barf.binary.entry_point >> 12 << 12
    cfg = barf.recover_cfg(start)
    cmp_blocks, opaque_predicate_blocks = get_predicate_blocks(cfg)
    print(cmp_blocks)
    print(opaque_predicate_blocks)

    blocks = cfg.basic_blocks
    fixhex = []
    fixaddr = []

    # for each block
    for block in blocks:
        command = ''
        # compare blocks(0 for beq(taken), 1 for bne(not-taken))
        if hex(block.address) in cmp_blocks:
            if cmp_blocks[hex(block.address)] == 0:
                for branch in block.branches:
                    if branch[1] == 'taken':
                        off_set = hex(branch[0] - block.instrs[-1].address)
                        command = 'b    #' + off_set

            elif cmp_blocks[hex(block.address)] == 1:
                for branch in block.branches:
                    if branch[1] == 'not-taken':
                        off_set = hex(branch[0] - block.instrs[-1].address)
                        command = 'b    #' + off_set

        # opaque predicate blocks(0 for beq(taken), 1,2 for bne(not-taken))
        if hex(block.address) in opaque_predicate_blocks:
            if opaque_predicate_blocks[hex(block.address)] == 0:
                for branch in block.branches:
                    if branch[1] == 'taken':
                        off_set = hex(branch[0] - block.instrs[-1].address)
                        command = 'b    #' + off_set

            elif opaque_predicate_blocks[hex(block.address)] == 1 or \
                    opaque_predicate_blocks[hex(block.address)] == 2:
                for branch in block.branches:
                    if branch[1] == 'not-taken':
                        off_set = hex(branch[0] - block.instrs[-1].address)
                        command = 'b    #' + off_set

        # change the conditional jump before opaque_predicate_blocks to unconditional jump
        # (force the flow through opaque_predicate_blocks)
        for branch in block.branches:
            if hex(branch[0]) in opaque_predicate_blocks and block.instrs[
                    -1].mnemonic_full == u'blt':
                off_set = hex(branch[0] - block.instrs[-1].address)
                command = 'b    #' + off_set

        # if command.startswith('b'):
        # print command
        if command != '':
            bcommand = bytes(command)
            hexcommand = ''

            try:
                # Initialize engine in X86-32bit mode
                ks = Ks(KS_ARCH_ARM, KS_MODE_LITTLE_ENDIAN)
                encoding, count = ks.asm(bcommand)
                for i in encoding:
                    hexcommand = hexcommand + hex(int(i)) + ','
                fixaddr.append(block.instrs[-1].address)
                fixhex.append(hexcommand)
            except KsError as e:
                print("ERROR: %s" % e)
        # elif command.startswith('negative,'):
        #     hexcommand = ''
        #     off_set = command.split(',')[-1]
        #     x = int(off_set, 16) - 8
        #     x &= 0x3FFFFFF
        #     x >>= 2
        #     tmp = hex(0xEB000000 + x)
        #     for i in range(len(tmp), 2, -2):
        #         hexcommand = hexcommand + '0x' + tmp[i-2:i] + ','
        #     fixaddr.append(block.instrs[-1].address)
        #     fixhex.append(hexcommand)

    origin = open(filename, 'rb')
    data = list(origin.read())

    print fixaddr, fixhex
    data = fix_instruction_substitution(data, fixhex, fixaddr, base_addr)
    origin.close()
    path = sys.argv[3]
    recovery = open(
        path + filename.split('/')[-2] + '/' + filename.split('/')[-1] +
        '_recovered', 'wb')
    recovery.write(''.join(data))
    recovery.close()
    print 'Successful! The recovered file: %s' % (filename + '_recovered')
예제 #13
0
#! /usr/bin/env python

import os
import sys

from barf import BARF

if __name__ == "__main__":
    #
    # Open file
    #
    try:
        filename = os.path.abspath("../../samples/toy/x86/constraint3")
        barf = BARF(filename)
    except Exception as err:
        print err

        print "[-] Error opening file : %s" % filename

        sys.exit(1)

    #
    # Check constraint
    #

    # 80483ed:       55                      push   ebp
    # 80483ee:       89 e5                   mov    ebp,esp
    # 80483f0:       83 ec 10                sub    esp,0x10
    # 80483f3:       c7 45 f0 01 00 00 00    mov    DWORD PTR [ebp-0x10],0x1
    # 80483fa:       81 7d f4 44 43 42 41    cmp    DWORD PTR [ebp-0xc],0x41424344
    # 8048401:       75 19                   jne    804841c <main+0x2f>
#! /usr/bin/env python

import os
import sys

from barf import BARF

if __name__ == "__main__":
    #
    # Open file
    #
    try:
        filename = os.path.abspath("../../samples/toy/x86/constraint1")
        barf = BARF(filename)
    except Exception as err:
        print err

        print "[-] Error opening file : %s" % filename

        sys.exit(1)

    #
    # Check constraint
    #

    # 80483ed:       55                      push   ebp
    # 80483ee:       89 e5                   mov    ebp,esp
    # 80483f0:       83 ec 10                sub    esp,0x10
    # 80483f3:       8b 45 f8                mov    eax,DWORD PTR [ebp-0x8]
    # 80483f6:       8b 55 f4                mov    edx,DWORD PTR [ebp-0xc]
    # 80483f9:       01 d0                   add    eax,edx
#! /usr/bin/env python

from __future__ import absolute_import
from __future__ import print_function

from barf import BARF

if __name__ == "__main__":
    #
    # Open file
    #
    barf = BARF("./samples/bin/constraint1.x86")

    #
    # Check constraint
    #

    # 80483ed:       55                      push   ebp
    # 80483ee:       89 e5                   mov    ebp,esp
    # 80483f0:       83 ec 10                sub    esp,0x10
    # 80483f3:       8b 45 f8                mov    eax,DWORD PTR [ebp-0x8]
    # 80483f6:       8b 55 f4                mov    edx,DWORD PTR [ebp-0xc]
    # 80483f9:       01 d0                   add    eax,edx
    # 80483fb:       83 c0 05                add    eax,0x5
    # 80483fe:       89 45 fc                mov    DWORD PTR [ebp-0x4],eax
    # 8048401:       8b 45 fc                mov    eax,DWORD PTR [ebp-0x4]
    # 8048404:       c9                      leave
    # 8048405:       c3                      ret

    print("[+] Adding instructions to the analyzer...")
예제 #16
0
파일: deflat.py 프로젝트: yype/deflat
def fill_jmp_offset(data, start, offset):
    jmp_offset = struct.pack('<i', offset)
    for i in range(4):
        data[start + i] = jmp_offset[i]

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print 'Usage: python deflat.py filename function_address(hex)'
        exit(0)
    opcode = {'a':'\x87', 'ae': '\x83', 'b':'\x82', 'be':'\x86', 'c':'\x82', 'e':'\x84', 'z':'\x84', 'g':'\x8F', 
              'ge':'\x8D', 'l':'\x8C', 'le':'\x8E', 'na':'\x86', 'nae':'\x82', 'nb':'\x83', 'nbe':'\x87', 'nc':'\x83',
              'ne':'\x85', 'ng':'\x8E', 'nge':'\x8C', 'nl':'\x8D', 'nle':'\x8F', 'no':'\x81', 'np':'\x8B', 'ns':'\x89',
              'nz':'\x85', 'o':'\x80', 'p':'\x8A', 'pe':'\x8A', 'po':'\x8B', 's':'\x88', 'nop':'\x90', 'jmp':'\xE9', 'j':'\x0F'}
    filename = sys.argv[1]
    start = int(sys.argv[2], 16)
    barf = BARF(filename)
    base_addr = barf.binary.entry_point >> 12 << 12
    b = angr.Project(filename, load_options={'auto_load_libs': False, 'main_opts':{'custom_base_addr': 0}})
    cfg = barf.recover_cfg(start=start)
    blocks = cfg.basic_blocks
    prologue = start
    main_dispatcher = cfg.find_basic_block(prologue).direct_branch
    retn, pre_dispatcher = get_retn_predispatcher(cfg)
    relevant_blocks, nop_blocks = get_relevant_nop_blocks(cfg)
    print '*******************relevant blocks************************'
    print 'prologue:%#x' % start
    print 'main_dispatcher:%#x' % main_dispatcher
    print 'pre_dispatcher:%#x' % pre_dispatcher
    print 'retn:%#x' % retn
    print 'relevant_blocks:', [hex(addr) for addr in relevant_blocks]