Beispiel #1
0
def main(argv=None):
    if argv is None:
        argv = sys.argv[:]

    try:
        seg = prompt_for_segment()
    except BadInputError:
        logger.error('bad input, exiting...')
        return -1

    with open(seg.path, 'rb') as f:
        buf = f.read()

    seglen = len(buf)
    if seglen % 0x1000 != 0:
        seglen = seglen + (0x1000 - (seglen % 0x1000))

    if not idc.AddSeg(seg.addr, seg.addr + seglen, 0, 1, 0, idaapi.scPub):
        logger.error('failed to add segment: 0x%x', seg.addr)
        return -1

    if not idc.RenameSeg(seg.addr, seg.name):
        logger.warning('failed to rename segment: %s', seg.name)

    if not idc.SetSegClass(seg.addr, 'CODE'):
        logger.warning('failed to set segment class CODE: %s', seg.name)

    if not idc.SegAlign(seg.addr, idc.saRelPara):
        logger.warning('failed to align segment: %s', seg.name)

    idaapi.patch_many_bytes(seg.addr, buf)
Beispiel #2
0
def formbook_patch_encrypted_bytecode():
    text_segm = ida_segment.get_segm_by_name('.text')
    if not text_segm:
        return idaapi.BADADDR

    seg_start = text_segm.startEA
    seg_end = text_segm.endEA
    fb_decrypt = FormBookDecryption()
    rc4_key = "faddefad156c45629c95d5f429363b0653ad5c1d".decode('hex')  # same as rc4_final from formbook_decrypt_hashes_and_strings()

    for i in [(0x40, 0x48), (0x41, 0x49), (0x42, 0x4a), (0x43, 0x4b), (0x44, 0x4c)]:
        egg_pattern = ''.join('{:02x} '.format(x) for x in [i[0], 0x90, 0x90, 0x90, i[1]])
        encrypted_start = idaapi.find_binary(seg_start, seg_end, egg_pattern, 16, idaapi.SEARCH_DOWN)
        if encrypted_start != idaapi.BADADDR:
            encrypted_end = idaapi.find_binary(encrypted_start + 5, seg_end, "90 90 90 90", 16, idaapi.SEARCH_DOWN)
            if encrypted_end != idaapi.BADADDR:
                encrypted_start += 5
                patch_length = encrypted_end - encrypted_start
                if idaapi.visit_patched_bytes(encrypted_start, encrypted_end, callback_on_patched_bytes) == 0:
                    encrypted_buff = idaapi.get_bytes(encrypted_start, patch_length)
                    decrypted_buff = fb_decrypt.decrypt_func2(encrypted_buff, rc4_key)
                    print('Patching encrypted bytecode at 0x{:x} ({:d} bytes)'.format(encrypted_start, patch_length))
                    idaapi.patch_many_bytes(encrypted_start, decrypted_buff)
                else:
                    print('Encrypted bytecode at 0x{:x} ({:d} bytes) is already patched'.format(encrypted_start, patch_length))
Beispiel #3
0
    def make_segment(self, offset, size, class_name="DATA", name="pe_map", data=None):
        """Create a new section in the IDB"""
        idc.AddSeg(offset, offset + size, 0, 1, 0, idaapi.scPub)
        idc.RenameSeg(offset, str(name))
        idc.SetSegClass(offset, str(class_name))
        #idc.SegAlign(offset, idc.saRelPara)
        if data:
            idaapi.patch_many_bytes(offset, bytes(data))

        self.ret = None
        return self.ret
Beispiel #4
0
def load_file(li, neflags, fmt):
    # Assume BCM20734 == cortex-m3
    idaapi.set_processor_type('arm:armv7-m', idaapi.SETPROC_ALL | idaapi.SETPROC_FATAL)

    parser = FwParser(li)

    fw_index = parser.active_fw
    if len(parser.fw) > 1:
        msg = ['SPI dump has more than one PatchRAM image.\n\nEnter the index of the one to load:']
        for i in range(len(parser.fw)):
            if parser.fw_present(i):
                msg.append('%i @ 0x%08x %s' % (i, parser.fw_offsets[i],
                    '[active]' if i == parser.active_fw else ''))
        fw_index = ida_kernwin.asklong(parser.active_fw, '\n'.join(msg))

    # Create known memory regions
    make_seg([0x0, 0xC8000], 1)
    make_seg([0x260000, 0x26C000], 1)
    make_seg([0xD0000, 0xE0000])
    make_seg([0x200000, 0x248000])
    load_bin_file(0x0, "Choose ROM 1 (@0x000000)")
    load_bin_file(0x260000, "Choose ROM 2 (@0x260000)")
    load_bin_file(0xD0000, "Choose RAM_LO (@0x0D0000)")
    load_bin_file(0x200000, "Choose RAM_HI (@0x200000)")

    # The PatchRAM changes will show up as patched bytes
    load_rampatch = 0
    if ram_loaded == 0:
        load_rampatch = ida_kernwin.askbuttons_c('Yes', 'No', 'Not sure', 1,'Do you want to patch ROM 1 and RAM regions with the provided PatchRAM?\n\n')
        if load_rampatch == 1:
            print('Patching ROM1, RAM_LO and RAM_HI:')
            parser.process({0x08 : lambda r: idaapi.patch_many_bytes(r.addr, r.data), 0x0a : lambda r: idaapi.patch_many_bytes(r.addr, r.data)}, fw_index)
            print('ROM 1, RAM_LO and RAM_HI regions were patched.')
    elif ram_loaded == 1:
        print('Patching ROM1:')
        parser.process({0x08 : lambda r: idaapi.patch_many_bytes(r.addr, r.data)}, fw_index)
        print('Only one RAM region loaded. ROM 1 was patched.')
    elif ram_loaded == 2:
        load_rampatch = ida_kernwin.askbuttons_c('Yes', 'No', 'Not sure', 0,'RAM_LO and RAM_HI were loaded.\n\nDo you want to patch them with the provided PatchRAM?\n\n')
        if load_rampatch == -1 or load_rampatch == 0:
            print('Patching ROM1:')
            parser.process({0x08 : lambda r: idaapi.patch_many_bytes(r.addr, r.data)}, fw_index)
            print('RAM_LO and RAM_HI loaded. ROM 1 was patched.')
        elif load_rampatch == 1:
            print('Patching ROM1, RAM_LO and RAM_HI:')
            parser.process({0x08 : lambda r: idaapi.patch_many_bytes(r.addr, r.data), 0x0a : lambda r: idaapi.patch_many_bytes(r.addr, r.data)}, fw_index)
            print('RAM_LO and RAM_HI loaded. ROM 1 and both RAM regions were patched.')

    # Code is THUMB only
    idc.SetReg(0x0, 't', 1)

    return 1
Beispiel #5
0
    def patchIDB(self,buff):
        for i in buff: # process file contents

            i=i.strip() # strip new line
            jumpaddr,datastr=self.extractStackData(i) # extract jump address and four double words from each line 
            
            for rawbytes in datastr: # process each double word
                
                idc.jumpto(jumpaddr) # jump to segment address 
                temp = self.convertRawHexData(rawbytes)  # process word string into bytes
                idaapi.patch_many_bytes(jumpaddr,temp) # patch bytes at jumpaddr
                self.setComment("Address: 0x%x \tStack Value: %s" % (jumpaddr,rawbytes)) # create a comment at each double word in segment
                jumpaddr +=4 # increment jumpaddr by 4 bytes
Beispiel #6
0
    def OnEditLine(self, n):

        # Empty list
        if n == -1:
            return

        # Multiselect START_SEL/END_SEL protocol
        if n == -2 or n ==-3:
            return

        ea = self.items_data[n][0]
        fpos =  self.items_data[n][1]
        patch_buf = self.items_data[n][3]
        orig_buf = self.items_data[n][4]

        addr_str = "%#x" % ea
        fpos_str = "%#x" % fpos if fpos != -1 else "N/A"     
        patch_str = self.items[n][3]
        org_str = self.items[n][4]    

        # Create the form
        f = PatchEditForm(addr_str, fpos_str, patch_str, org_str)

        # Execute the form
        ok = f.Execute()
        if ok == 1:

            # Convert hex bytes to binary
            buf = f.strPatch.value
            buf = buf.replace(' ','')       # remove spaces
            buf = buf.replace('\\x','')     # remove '\x' prefixes
            buf = buf.replace('0x','')      # remove '0x' prefixes
            try:
                buf = binascii.unhexlify(buf)   # convert to bytes
            except Exception as e:
                idaapi.warning("Invalid input: %s" % e)
                f.Free()
                return

            # Restore original bytes first
            idaapi.put_many_bytes(ea, struct.pack("B"*len(orig_buf), *orig_buf))

            # Now apply newly patched bytes
            idaapi.patch_many_bytes(ea, buf)

            # Refresh all IDA views
            self.refreshitems()

        # Dispose the form
        f.Free()
    def OnEditLine(self, n):

        # Empty list
        if n == -1:
            return

        # Multiselect START_SEL/END_SEL protocol
        if n == -2 or n ==-3:
            return

        ea = self.items_data[n][0]
        fpos =  self.items_data[n][1]
        patch_buf = self.items_data[n][3]
        orig_buf = self.items_data[n][4]

        addr_str = "%#x" % ea
        fpos_str = "%#x" % fpos if fpos != -1 else "N/A"     
        patch_str = self.items[n][3]
        org_str = self.items[n][4]    

        # Create the form
        f = PatchEditForm(addr_str, fpos_str, patch_str, org_str)

        # Execute the form
        ok = f.Execute()
        if ok == 1:

            # Convert hex bytes to binary
            buf = f.strPatch.value
            buf = buf.replace(' ','')       # remove spaces
            buf = buf.replace('\\x','')     # remove '\x' prefixes
            buf = buf.replace('0x','')      # remove '0x' prefixes
            try:
                buf = binascii.unhexlify(buf)   # convert to bytes
            except Exception, e:
                idaapi.warning("Invalid input: %s" % e)
                f.Free()
                return

            # Restore original bytes first
            idaapi.put_many_bytes(ea, struct.pack("B"*len(orig_buf), *orig_buf))

            # Now apply newly patched bytes
            idaapi.patch_many_bytes(ea, buf)

            # Refresh all IDA views
            self.refreshitems()
            idaapi.refresh_idaview_anyway()
    def show_edit_form(self):
        selection, start_ea, end_ea = idaapi.read_selection()
        
        if not selection:
            start_ea = idaapi.get_screen_ea()
            end_ea = start_ea + 1
        if start_ea != idaapi.BADADDR and end_ea != idaapi.BADADDR:
            if end_ea > start_ea:
                buf_len = end_ea - start_ea
                buf = get_many_bytes(start_ea, buf_len) or "\xFF"*buf_len
                buf_str = " ".join(["%02X" % ord(x) for x in buf])

                fpos = idaapi.get_fileregion_offset(start_ea)

                addr_str = "%#X" % start_ea
                fpos_str = "%#x" % fpos if fpos != -1 else "N/A" 

                f = PatchEditForm(addr_str, fpos_str, buf_str, buf_str)

                # Execute the form
                ok = f.Execute()
                if ok == 1:

                    # Convert hex bytes to binary
                    buf = f.strPatch.value
                    buf = buf.replace(' ','')       # remove spaces
                    buf = buf.replace('\\x','')     # remove '\x' prefixes
                    buf = buf.replace('0x','')      # remove '0x' prefixes
                    try:
                        buf = binascii.unhexlify(buf)   # convert to bytes
                    except Exception, e:
                        idaapi.warning("Invalid input: %s" % e)
                        f.Free()
                        return

                    # Now apply newly patched bytes
                    idaapi.patch_many_bytes(start_ea, buf)

                    # Refresh all IDA views
                    self.patch_view.refreshitems()
                    idaapi.refresh_idaview_anyway()

                # Dispose the form
                f.Free()
Beispiel #9
0
    def show_edit_form(self):
        selection, start_ea, end_ea = idaapi.read_selection()
        
        if not selection:
            start_ea = idaapi.get_screen_ea()
            end_ea = start_ea + 1

        buf_len = end_ea - start_ea
        buf = idaapi.get_many_bytes(start_ea, buf_len) or "\xFF"*buf_len
        buf_str = " ".join(["%02X" % x for x in buf])

        fpos = idaapi.get_fileregion_offset(start_ea)

        addr_str = "%#X" % start_ea
        fpos_str = "%#x" % fpos if fpos != -1 else "N/A" 

        f = PatchEditForm(addr_str, fpos_str, buf_str, buf_str)

        # Execute the form
        ok = f.Execute()
        if ok == 1:

            # Convert hex bytes to binary
            buf = f.strPatch.value
            buf = buf.replace(' ','')       # remove spaces
            buf = buf.replace('\\x','')     # remove '\x' prefixes
            buf = buf.replace('0x','')      # remove '0x' prefixes
            try:
                buf = binascii.unhexlify(buf)   # convert to bytes
            except Exception as e:
                idaapi.warning("Invalid input: %s" % e)
                f.Free()
                return

            # Now apply newly patched bytes
            idaapi.patch_many_bytes(start_ea, buf)

            # Refresh all IDA views
            self.patch_view.Refresh()

        # Dispose the form
        f.Free()
def patch_decoded(decoded_strings, define=True):
    '''
    Description:
        Patches the bytes at each encoded string location with the decoded string value.
        Assumes null termination.

    Input:
        decoded_strings - A list of successfully decoded strings.
        define - When True, defines a string in the IDB

    Output:
        Makes a string in IDA at the string's start_location
    '''
    for decoded_string in sorted(decoded_strings,
                                 key=lambda string: string.string_location):
        if decoded_string.string_location in [INVALID, UNUSED, idc.BADADDR]:
            continue
        idaapi.patch_many_bytes(decoded_string.startEA,
                                decoded_string.as_bytes)
        if define:
            define_string(decoded_string)
Beispiel #11
0
def show_xor_with_key_form():
    selection, start_ea, end_ea = idaapi.read_selection()

    if not selection:
        start_ea = idaapi.get_screen_ea()

    # Create the form
    f = XorWithKeyForm(start_ea)

    # Execute the form
    ok = f.Execute()
    if ok == 1:
        start_ea = f.intStartEA.value
        target_length = f.intLength.value
        key = f.rString.value

        if target_length < 0:
            slog("target lenth is wrong " + str(target_length))
            return

        if idaapi.IDA_SDK_VERSION >= 700:
            buf = ida_bytes.get_bytes(start_ea, target_length)
        else:
            buf = ida_bytes.get_many_bytes(start_ea, target_length)

        if buf is None:
            slog("Failed to get bytes")
            return

        lbuf = list(buf)
        lkey = list(key)
        for i in range(target_length):
            lbuf[i] = chr(ord(lbuf[i]) ^ ord(lkey[i % len(lkey)]))

        # Now apply newly patched bytes
        buf = "".join(lbuf)
        idaapi.patch_many_bytes(start_ea, buf)

    # Dispose the form
    f.Free()
Beispiel #12
0
    def patch(self, fill_char=None, define=True):
        """
        Patches the original encoded string with the decoded string.

        :param str fill_char:
            Character to use to fill left over space if decoded data
            is shorter than its encoded data. (defaults to leaving the original data)
        :param bool define: Whether to define the string after patching.
        """
        if self.decoded_data in (INVALID, UNUSED):
            return
        if self.string_location in (INVALID, UNUSED, idc.BADADDR):
            return
        decoded_data = self.as_bytes
        if fill_char:
            decoded_data += fill_char * (len(self.encoded_data) - len(decoded_data))
        try:
            idaapi.patch_many_bytes(self.startEA, decoded_data)
            if define:
                self.define()
        except TypeError:
            append_debug("String type for decoded string from location 0x{:08x}.".format(self.startEA))
Beispiel #13
0
def write_data(ea, blob, reanalyze=True):
    """ Write bytes to idb """
    if reanalyze: idc.MakeUnknown(ea, len(blob), 0)
    idaapi.patch_many_bytes(ea, blob)
    if reanalyze: idc.MakeCode(ea)
Beispiel #14
0
    def activate(self, ctx):
        if self.action in ACTION_CONVERT:
            # convert
            selection, start, end = idaapi.read_selection()
            if selection:
                size = end - start
            elif ItemSize(ScreenEA()) > 1:
                start = ScreenEA()
                size = ItemSize(start)
                end = start + size
            else:
                return False

            data = idaapi.get_many_bytes(start, size)
            name = Name(start)
            if not name:
                name = "data"
            if data:
                print "\n[+] Dump 0x%X - 0x%X (%u bytes) :" % (start, end, size)
                if self.action == ACTION_CONVERT[0]:
                    # escaped string
                    print '"%s"' % "".join("\\x%02X" % ord(b) for b in data)
                elif self.action == ACTION_CONVERT[1]:
                    # hex string
                    print "".join("%02X" % ord(b) for b in data)
                elif self.action == ACTION_CONVERT[2]:
                    # C array
                    output = "unsigned char %s[%d] = {" % (name, size)
                    for i in range(size):
                        if i % 16 == 0:
                            output += "\n    "
                        output += "0x%02X, " % ord(data[i])
                    output = output[:-2] + "\n};"
                    print output
                elif self.action == ACTION_CONVERT[3]:
                    # C array word
                    data += "\x00"
                    array_size = (size + 1) / 2
                    output = "unsigned short %s[%d] = {" % (name, array_size)
                    for i in range(0, size, 2):
                        if i % 16 == 0:
                            output += "\n    "
                        output += "0x%04X, " % u16(data[i:i+2])
                    output = output[:-2] + "\n};"
                    print output
                elif self.action == ACTION_CONVERT[4]:
                    # C array dword
                    data += "\x00" * 3
                    array_size = (size + 3) / 4
                    output = "unsigned int %s[%d] = {" % (name, array_size)
                    for i in range(0, size, 4):
                        if i % 32 == 0:
                            output += "\n    "
                        output += "0x%08X, " % u32(data[i:i+4])
                    output = output[:-2] + "\n};"
                    print output
                elif self.action == ACTION_CONVERT[5]:
                    # C array qword
                    data += "\x00" * 7
                    array_size = (size + 7) / 8
                    output = "unsigned long %s[%d] = {" % (name, array_size)
                    for i in range(0, size, 8):
                        if i % 32 == 0:
                            output += "\n    "
                        output += "%#018X, " % u64(data[i:i+8])
                    output = output[:-2] + "\n};"
                    print output.replace("0X", "0x")
                elif self.action == ACTION_CONVERT[6]:
                    # python list
                    print "[%s]" % ", ".join("0x%02X" % ord(b) for b in data)
                elif self.action == ACTION_CONVERT[7]:
                    # python list word
                    data += "\x00"
                    print "[%s]" % ", ".join("0x%04X" % u16(data[i:i+2]) for i in range(0, size, 2))
                elif self.action == ACTION_CONVERT[8]:
                    # python list dword
                    data += "\x00" * 3
                    print "[%s]" % ", ".join("0x%08X" % u32(data[i:i+4]) for i in range(0, size, 4))
                elif self.action == ACTION_CONVERT[9]:
                    # python list qword
                    data += "\x00" * 7
                    print "[%s]" %  ", ".join("%#018X" % u64(data[i:i+8]) for i in range(0, size, 8)).replace("0X", "0x")
        elif self.action == ACTION_XORDATA:
            selection, start, end = idaapi.read_selection()
            if not selection:
                if ItemSize(ScreenEA()) > 1:
                    start = ScreenEA()
                    end = start + ItemSize(start)
                else:
                    return False

            data = idaapi.get_many_bytes(start, end - start)
            x = AskLong(0, "Xor with...")
            if x:
                x &= 0xFF
                print "\n[+] Xor 0x%X - 0x%X (%u bytes) with 0x%02X:" % (start, end, end - start, x)
                print repr("".join(chr(ord(b) ^ x) for b in data))
        elif self.action == ACTION_FILLNOP:
            selection, start, end = idaapi.read_selection()
            if selection:
                idaapi.patch_many_bytes(start, "\x90" * (end - start))
                print "\n[+] Fill 0x%X - 0x%X (%u bytes) with NOPs" % (start, end, end - start)
        elif self.action == ACTION_SCANVUL:
            print "\n[+] Finding Format String Vulnerability..."
            found = []
            for addr in idautils.Functions():
                name = GetFunctionName(addr)
                if "printf" in name and "v" not in name and SegName(addr) in (".text", ".plt", ".idata"):
                    xrefs = idautils.CodeRefsTo(addr, False)
                    for xref in xrefs:
                        vul = self.check_fmt_function(name, xref)
                        if vul:
                            found.append(vul)
            if found:
                print "[!] Done! %d possible vulnerabilities found." % len(found)
                ch = VulnChoose("Vulnerability", found, None, False)
                ch.Show()
            else:
                print "[-] No format string vulnerabilities found."
        else:
            return 0

        return 1
Beispiel #15
0
    pc = triton.getSymbolicRegisterValue(triton.REG.RIP)

rax_ast = triton.buildSymbolicRegister(triton.REG.RAX)
rax_ast = triton.getFullAst(rax_ast)
rax_ast = triton.simplify(rax_ast, True)
start = time.time()
print("[+] computing Arybo representation...")
e = atools.tritonast2arybo(rax_ast, use_exprs=True, use_esf=False)
print("[+] got Arybo expression, evalute it...")
e = aexprs.eval_expr(e, use_esf=False)
end = time.time()
diff = end - start
print("[*] Arybo evaluation computed in %0.4fs" % diff)
app = e.vectorial_decomp([rdi.v])
exp = atools.identify(app, "rdi")
print("[*] Identified expression: rax = %s" % aexprs.prettyprint(exp))
asm = easm.asm_binary(exp, ("rax", 64), {"rdi": ("rdi", 64)},
                      "x86_64-unknown-unknwon")
print("[*] Assembled expression: %s" % asm.encode("hex"))

func_size = func.endEA - 1 - func.startEA
if len(asm) > func_size:
    printf("[-] Final assembly does not fit in the original function!")
asm_nop = asm + "\x90" * (func_size - len(asm))
func_start = int(func.startEA)
func_end = int(func.endEA)
idaapi.patch_many_bytes(func_start, asm_nop)
idaapi.do_unknown_range(func_start, func_end, 0)
idaapi.auto_make_code(func_start)
idaapi.auto_make_proc(func_start)
Beispiel #16
0
    def show_import_form(self):
        selection, start_ea, end_ea = idaapi.read_selection()

        if not selection:
            start_ea = idaapi.get_screen_ea()
            end_ea = start_ea + 1

        # Create the form
        f = DataImportForm(start_ea, end_ea);

        # Execute the form
        ok = f.Execute()
        if ok == 1:

            start_ea = f.intStartEA.value
            end_ea = f.intEndEA.value

            if f.rFile.selected:
                imp_file = f.impFile.value

                try:
                    f_imp_file = open(imp_file,'rb')
                except Exception as e:
                    idaapi.warning("File I/O error({0}): {1}".format(e.errno, e.strerror))
                    return
                else:
                    buf = f_imp_file.read()
                    f_imp_file.close()

            else:

                buf = f.strPatch.value

                # Hex values, unlike string literal, needs additional processing
                if f.rHex.selected:
                    buf = buf.replace(' ','')       # remove spaces
                    buf = buf.replace('\\x','')     # remove '\x' prefixes
                    buf = buf.replace('0x','')      # remove '0x' prefixes
                    try:
                        buf = binascii.unhexlify(buf)   # convert to bytes
                    except Exception as e:
                        idaapi.warning("Invalid input: %s" % e)
                        f.Free()
                        return

            if not len(buf):
                idaapi.warning("There was nothing to import.")
                return

            # Trim to selection if needed:
            if f.cSize.checked:
                buf_size = end_ea - start_ea
                buf = buf[0:buf_size]

            # Now apply newly patched bytes
            idaapi.patch_many_bytes(start_ea, buf)

            # Refresh all IDA views
            self.patch_view.Refresh()

        # Dispose the form
        f.Free()
Beispiel #17
0
def write(ea, data, original=False):
    return idaapi.patch_many_bytes(
        ea, data) if original else idaapi.put_many_bytes(ea, data)
                    except Exception, e:
                        idaapi.warning("Invalid input: %s" % e)
                        f.Free()
                        return

            if not len(buf):
                idaapi.warning("There was nothing to import.")
                return

            # Trim to selection if needed:
            if f.cSize.checked:
                buf_size = end_ea - start_ea
                buf = buf[0:buf_size]

            # Now apply newly patched bytes
            idaapi.patch_many_bytes(start_ea, buf)

            # Refresh all IDA views
            self.patch_view.refreshitems()
            idaapi.refresh_idaview_anyway()

        # Dispose the form
        f.Free()

#--------------------------------------------------------------------------
# Patch Notify Hook
#--------------------------------------------------------------------------

patched_bytes_dict = {}

# Dummy function
Beispiel #19
0
def relocate_segment(source, destination, size):
	buf = idaapi.get_many_bytes(source, size)
	idaapi.patch_many_bytes(destination, buf)
Beispiel #20
0
 def fun(addr, bs):
     idaapi.patch_many_bytes(addr, bs)
Beispiel #21
0
def write(ea, data, original=False):
    return idaapi.patch_many_bytes(ea, data) if original else idaapi.put_many_bytes(ea, data)
Beispiel #22
0
    def activate(self, ctx):
        if self.action in ACTION_CONVERT:
            # convert
            selection, start, end = idaapi.read_selection()
            if selection:
                size = end - start
            elif ItemSize(ScreenEA()) > 1:
                start = ScreenEA()
                size = ItemSize(start)
                end = start + size
            else:
                return False

            data = idaapi.get_many_bytes(start, size)
            name = Name(start)
            if not name:
                name = "data"
            if data:
                print("\n[+] Dump 0x%X - 0x%X (%u bytes) :" % (start, end, size))
                if self.action == ACTION_CONVERT[0]:
                    # escaped string
                    print('"%s"' % "".join("\\x%02X" % ord(b) for b in data))
                elif self.action == ACTION_CONVERT[1]:
                    # hex string
                    print("".join("%02X" % ord(b) for b in data))
                elif self.action == ACTION_CONVERT[2]:
                    # C array
                    output = "unsigned char %s[%d] = {" % (name, size)
                    for i in range(size):
                        if i % 16 == 0:
                            output += "\n    "
                        output += "0x%02X, " % ord(data[i])
                    output = output[:-2] + "\n};"
                    print(output)
                elif self.action == ACTION_CONVERT[3]:
                    # C array word
                    data += "\x00"
                    array_size = (size + 1) / 2
                    output = "unsigned short %s[%d] = {" % (name, array_size)
                    for i in range(0, size, 2):
                        if i % 16 == 0:
                            output += "\n    "
                        output += "0x%04X, " % u16(data[i:i+2])
                    output = output[:-2] + "\n};"
                    print(output)
                elif self.action == ACTION_CONVERT[4]:
                    # C array dword
                    data += "\x00" * 3
                    array_size = (size + 3) / 4
                    output = "unsigned int %s[%d] = {" % (name, array_size)
                    for i in range(0, size, 4):
                        if i % 32 == 0:
                            output += "\n    "
                        output += "0x%08X, " % u32(data[i:i+4])
                    output = output[:-2] + "\n};"
                    print(output)
                elif self.action == ACTION_CONVERT[5]:
                    # C array qword
                    data += "\x00" * 7
                    array_size = (size + 7) / 8
                    output = "unsigned long %s[%d] = {" % (name, array_size)
                    for i in range(0, size, 8):
                        if i % 32 == 0:
                            output += "\n    "
                        output += "%#018X, " % u64(data[i:i+8])
                    output = output[:-2] + "\n};"
                    print(output.replace("0X", "0x"))
                elif self.action == ACTION_CONVERT[6]:
                    # python list
                    print("[%s]" % ", ".join("0x%02X" % ord(b) for b in data))
                elif self.action == ACTION_CONVERT[7]:
                    # python list word
                    data += "\x00"
                    print("[%s]" % ", ".join("0x%04X" % u16(data[i:i+2]) for i in range(0, size, 2)))
                elif self.action == ACTION_CONVERT[8]:
                    # python list dword
                    data += "\x00" * 3
                    print("[%s]" % ", ".join("0x%08X" % u32(data[i:i+4]) for i in range(0, size, 4)))
                elif self.action == ACTION_CONVERT[9]:
                    # python list qword
                    data += "\x00" * 7
                    print("[%s]" %  ", ".join("%#018X" % u64(data[i:i+8]) for i in range(0, size, 8)).replace("0X", "0x"))
        elif self.action == ACTION_XORDATA:
            selection, start, end = idaapi.read_selection()
            if not selection:
                if ItemSize(ScreenEA()) > 1:
                    start = ScreenEA()
                    end = start + ItemSize(start)
                else:
                    return False

            data = idaapi.get_many_bytes(start, end - start)
            x = AskLong(0, "Xor with...")
            if x:
                x &= 0xFF
                print("\n[+] Xor 0x%X - 0x%X (%u bytes) with 0x%02X:" % (start, end, end - start, x))
                print(repr("".join(chr(ord(b) ^ x) for b in data)))
        elif self.action == ACTION_FILLNOP:
            selection, start, end = idaapi.read_selection()
            if selection:
                idaapi.patch_many_bytes(start, "\x90" * (end - start))
                print("\n[+] Fill 0x%X - 0x%X (%u bytes) with NOPs" % (start, end, end - start))
        elif self.action == ACTION_SCANVUL:
            print("\n[+] Finding Format String Vulnerability...")
            found = []
            for addr in idautils.Functions():
                name = GetFunctionName(addr)
                if "printf" in name and "v" not in name and SegName(addr) in (".text", ".plt", ".idata"):
                    xrefs = idautils.CodeRefsTo(addr, False)
                    for xref in xrefs:
                        vul = self.check_fmt_function(name, xref)
                        if vul:
                            found.append(vul)
            if found:
                print("[!] Done! %d possible vulnerabilities found." % len(found))
                ch = VulnChoose("Vulnerability", found, None, False)
                ch.Show()
            else:
                print("[-] No format string vulnerabilities found.")
        else:
            return 0

        return 1
Beispiel #23
0
def write_data(ea, blob, reanalyze=True):
    """ Write bytes to idb """
    if reanalyze: idc.MakeUnknown(ea, len(blob), 0)
    idaapi.patch_many_bytes(ea, blob)
    if reanalyze: idc.MakeCode(ea)
Beispiel #24
0
def write_memory(start, data, destructive=False):
    if destructive:
        idaapi.put_many_bytes(start, data)

    else:
        idaapi.patch_many_bytes(start, data)
Beispiel #25
0
                    except Exception, e:
                        idaapi.warning("Invalid input: %s" % e)
                        f.Free()
                        return

            if not len(buf):
                idaapi.warning("There was nothing to import.")
                return

            # Trim to selection if needed:
            if f.cSize.checked:
                buf_size = end_ea - start_ea
                buf = buf[0:buf_size]

            # Now apply newly patched bytes
            idaapi.patch_many_bytes(start_ea, buf)

            # Refresh all IDA views
            self.patch_view.Refresh()

        # Dispose the form
        f.Free()


#--------------------------------------------------------------------------
# Plugin
#--------------------------------------------------------------------------
class idapatcher_t(plugin_t):

    flags = idaapi.PLUGIN_UNL
    comment = "Enhances manipulation and application of patched bytes."