Exemple #1
0
def get_fileregion_offset(ea):
    file_offset = idaapi.get_fileregion_offset(ea)
    if file_offset == -1:
        raise exceptions.NoFileOffset(
            "Address 0x{:08X} is not mapped to any file offset.".format(ea))

    return file_offset
Exemple #2
0
    def run(self, arg):
        print("Running")
        PE = peutils_t()
        print("Image base is %016X" % PE.imagebase)
        print("Exporting functions...")
        filename = os.path.splitext(idc.GetIdbPath())[0] + ".sym"
        rawOffsetsFilename = os.path.splitext(idc.GetIdbPath())[0] + ".raw.sym"
        f = open(filename, 'w')
        rawOffsetsFile = open(rawOffsetsFilename, 'w')

        count = 0
        for address, name in Names():
            offset = address - PE.imagebase
            rawOffset = idaapi.get_fileregion_offset(address)
            if idc.GetFunctionFlags(address) != -1:
                size = idc.FindFuncEnd(address) - address
            else:
                size = 4

            #namesList.append((offset, name))
            count += 1
            f.write("%08X %08X;%s\n" % (offset, size, name))
            rawOffsetsFile.write("%08X %08X;%s\n" % (rawOffset, size, name))

        f.close()
        rawOffsetsFile.close()

        print("%d functions exported" % count)
def map(ea, size, newea, **kwds):
    """Map `size` bytes of data from `ea` into a new segment at `newea`.

    The keyword `name` can be used to name the segment.
    """

    # grab the file offset and the data we want
    fpos, data = idaapi.get_fileregion_offset(ea), database.read(ea, size)
    if len(data) != size:
        raise E.ReadOrWriteError(
            u"{:s}.map({:#x}, {:+#x}, {:#x}{:s}) : Unable to read {:#x} bytes from {:#x}."
            .format(
                __name__, ea, size, newea,
                u", {:s}".format(utils.string.kwargs(kwds)) if kwds else '',
                size, ea))

    # rebase the data to the new address
    res = idaapi.mem2base(data, newea, fpos)
    if not res:
        raise E.DisassemblerError(
            u"{:s}.map({:#x}, {:+#x}, {:#x}{:s}) : Unable to remap {:#x}:{:+#x} to {:#x}."
            .format(
                __name__, ea, size, newea,
                u", {:s}".format(utils.string.kwargs(kwds)) if kwds else '',
                ea, size, newea))

    # now we can create the new segment
    return new(newea, size, kwds.get("name", "map_{:x}".format(ea)))
Exemple #4
0
def map(ea, size, newea, **kwds):
    """Map ``size`` bytes of data from ``ea`` into a new segment at ``newea``.
    ``name`` can be used to name the segment.
    """
    fpos,data = idaapi.get_fileregion_offset(ea),database.read(ea, size)
    if len(data) != size:
        raise ValueError("{:s}.map({:x}, {:#x}, {:x}) : Unable to read {:#x} bytes from {:#x}".format(__name__, ea, size, newea, size, ea))
    res = idaapi.mem2base(data, newea, fpos)
    if not res:
        raise ValueError("{:s}.map({:x}, {:#x}, {:x}) : Unable to remap {:#x}:{:+#x} to {:#x}".format(__name__, ea, size, newea, ea, size, newea))
    return create(newea, size, kwds.get("name', 'map_{:x}".format(ea)))
Exemple #5
0
def output_segments(out):
    """Dump binary segmentation."""
    info = idaapi.get_inf_structure()
    size = "r32" if info.is_32bit else "r64"
    out.writelines(('(', info.get_proc_name()[1], ' ', size, ' ('))
    for seg in idautils.Segments():
        out.write("\n({} {} {:d} ({:#x} {:d}))".format(
            idaapi.get_segm_name(seg),
            "code" if idaapi.segtype(seg) == idaapi.SEG_CODE else "data",
            idaapi.get_fileregion_offset(seg),
            seg, idaapi.getseg(seg).size()))
    out.write("))\n")
 def byte_patched(self, ea):
     if ea != idaapi.BADADDR:
         patched_byte = get_byte(ea)
         orginal_byte = get_original_byte(ea)
         file_offset = idaapi.get_fileregion_offset(ea)
         if file_offset != -1:
             patched_bytes_dict[ea] = [file_offset, orginal_byte, patched_byte]
         else:
             patched_bytes_dict[ea] = [-1, orginal_byte, patched_byte]
         print "[*] Byte patched at (ea %x file_offset %x) : %x -> %x" % (ea, file_offset, orginal_byte, patched_byte)
         
     return 0
Exemple #7
0
def map(ea, size, newea, **kwds):
    '''Map /size/ bytes of data from /ea/ into a new segment at /newea/

    /name/ can be used to name the segment.
    '''
    fpos, data = idaapi.get_fileregion_offset(ea), database.read(ea, size)
    if len(data) != size:
        raise Exception, "Unable to read %x bytes from %x" % (size, ea)
    res = idaapi.mem2base(data, newea, fpos)
    if not res:
        raise Exception, "Unable to remap %x:+%x to %x" % (ea, size, newea)
    return create(newea, size, kwds.get('name', 'map_%x' % ea))
Exemple #8
0
def map(ea, size, newea, **kwds):
    '''Map /size/ bytes of data from /ea/ into a new segment at /newea/

    /name/ can be used to name the segment.
    '''
    fpos,data = idaapi.get_fileregion_offset(ea),database.read(ea, size)
    if len(data) != size:
        raise Exception, "Unable to read %x bytes from %x"% (size, ea)
    res = idaapi.mem2base(data, newea, fpos)
    if not res:
        raise Exception, "Unable to remap %x:+%x to %x"% (ea, size, newea)
    return create(newea, size, kwds.get('name', 'map_%x'% ea))
Exemple #9
0
def output_segments(out):
    """Dump binary segmentation."""
    info = idaapi.get_inf_structure()
    size = "r32" if info.is_32bit else "r64"
    out.writelines(('(', info.get_proc_name()[1], ' ', size, ' ('))
    for seg in idautils.Segments():
        out.write("\n({} {} {:d} ({:#x} {:d}))".format(
            get_segm_name(seg),
            "code" if idaapi.segtype(seg) == idaapi.SEG_CODE else "data",
            idaapi.get_fileregion_offset(seg),
            seg, idaapi.getseg(seg).size()))
    out.write("))\n")
Exemple #10
0
def get_file_range():
    image_begin = -1
    image_end = -1
    for seg in idautils.Segments():
        begin_offset = idaapi.get_fileregion_offset(seg) 
        end_offset = begin_offset + idaapi.getseg(seg).size()

        if image_begin == -1:
            image_begin = begin_offset
        image_end = end_offset

    #print("// image 0x%x-0x%x" % (image_begin, image_end))
    print("// extract image: dd skip=$((0x%x)) count=$((0x%x-0x%x)) if=%s of=%s.data bs=1" % \
        (image_begin, image_end, image_begin, idaapi.get_input_file_path(), basename))
Exemple #11
0
def map(ea, size, newea, **kwds):
    """Map `size` bytes of data from `ea` into a new segment at `newea`.

    The keyword `name` can be used to name the segment.
    """
    fpos, data = idaapi.get_fileregion_offset(ea), database.read(ea, size)
    if len(data) != size:
        raise E.ReadOrWriteError(
            "{:s}.map({:#x}, {:+#x}, {:#x}) : Unable to read {:#x} bytes from {:#x}."
            .format(__name__, ea, size, newea, size, ea))
    res = idaapi.mem2base(data, newea, fpos)
    if not res:
        raise E.DisassemblerError(
            "{:s}.map({:#x}, {:+#x}, {:#x}) : Unable to remap {:#x}:{:+#x} to {:#x}."
            .format(__name__, ea, size, newea, ea, size, newea))
    return new(newea, size, kwds.get("name', 'map_{:x}".format(ea)))
def patch_file(data, changed_bytes):

    for ea, byte, original_byte in changed_bytes:
        print '%08x: %02x original(%02x)' % (ea, byte, original_byte)

        file_offset = idaapi.get_fileregion_offset(ea)

        original_char = chr(original_byte)
        char = chr(byte)

        if data[file_offset] == original_char:
            data[file_offset] = char

    patched_file = idc.AskFile(1, '*.*', 'Choose new file')
    if patched_file:
        with file(patched_file, 'wb') as f:
            f.write(''.join(data))
def patch_file(data, changed_bytes):
    
    for ea, byte, original_byte in changed_bytes:
        print '%08x: %02x original(%02x)' % (ea, byte, original_byte)
                
        file_offset = idaapi.get_fileregion_offset( ea )
        
        original_char = chr( original_byte )
        char = chr( byte )
        
        if data[ file_offset ] == original_char:
            data[ file_offset ] = char
    
    patched_file = idc.AskFile( 1, '*.*', 'Choose new file')
    if patched_file:
        with file(patched_file, 'wb') as f:
            f.write( ''.join( data ) )
Exemple #14
0
def dump_loader_info(output_filename):
    """Dump information for BAP's loader into output_filename."""
    from idautils import Segments
    import idc

    idaapi.autoWait()

    with open(output_filename, 'w+') as out:
        info = idaapi.get_inf_structure()
        size = "r32" if info.is_32bit else "r64"
        out.write("(%s %s (" % (info.get_proc_name()[1], size))
        for seg in Segments():
            out.write("\n(%s %s %d (0x%X %d))" % (
                idaapi.get_segm_name(seg),
                "code" if idaapi.segtype(seg) == idaapi.SEG_CODE else "data",
                idaapi.get_fileregion_offset(seg),
                seg, idaapi.getseg(seg).size()))
        out.write("))\n")
Exemple #15
0
def map(ea, size, newea, **kwds):
    """Map `size` bytes of data from `ea` into a new segment at `newea`.

    The keyword `name` can be used to name the segment.
    """

    # grab the file offset and the data we want
    fpos, data = idaapi.get_fileregion_offset(ea), database.read(ea, size)
    if len(data) != size:
        raise E.ReadOrWriteError(u"{:s}.map({:#x}, {:+#x}, {:#x}{:s}) : Unable to read {:#x} bytes from {:#x}.".format(__name__, ea, size, newea, u", {:s}".format(utils.string.kwargs(kwds)) if kwds else '', size, ea))

    # rebase the data to the new address
    res = idaapi.mem2base(data, newea, fpos)
    if not res:
        raise E.DisassemblerError(u"{:s}.map({:#x}, {:+#x}, {:#x}{:s}) : Unable to remap {:#x}:{:+#x} to {:#x}.".format(__name__, ea, size, newea, u", {:s}".format(utils.string.kwargs(kwds)) if kwds else '', ea, size, newea))

    # now we can create the new segment
    return new(newea, size, kwds.get("name", "map_{:x}".format(ea)))
Exemple #16
0
def dump_loader_info(output_filename):
    """Dump information for BAP's loader into output_filename."""
    from idautils import Segments
    import idc

    idaapi.autoWait()

    with open(output_filename, 'w+') as out:
        info = idaapi.get_inf_structure()
        size = "r32" if info.is_32bit else "r64"
        out.write("(%s %s (" % (info.get_proc_name()[1], size))
        for seg in Segments():
            out.write("\n(%s %s %d (0x%X %d))" % (
                idaapi.get_segm_name(seg),
                "code" if idaapi.segtype(seg) == idaapi.SEG_CODE else "data",
                idaapi.get_fileregion_offset(seg),
                seg, idaapi.getseg(seg).size()))
        out.write("))\n")
    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()
Exemple #18
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()
Exemple #19
0
    def OnCreate(self, form):
        try:
            f = open(GetInputFilePath().decode("utf-8"), "rb")
        except:
            f = open(GetInputFilePath(), "rb")
        self.data = f.read()
        f.close()

        self.Seg = [[idaapi.get_fileregion_offset(i), i] for i in Segments()]
        self.Seg.append([len(self.data), 0])

        try:
            self.parent = self.FormToPyQtWidget(form)
        except:
            self.parent = self.FormToPySideWidget(form)
        self.path = QLineEdit()
        self.label1 = QLabel("Yara Path : ")
        self.PathButton = QPushButton("Yara File")
        self.PathButton.clicked.connect(self.choose_path)
        self.label2 = QLabel("Hyara Rule")
        self.CheckButton = QCheckBox()
        self.SearchButton = QPushButton("Search")
        self.SearchButton.clicked.connect(self.Search)

        self.layout = QVBoxLayout()
        GL1 = QGridLayout()
        GL1.addWidget(self.label1, 0, 0)
        GL1.addWidget(self.path, 0, 1)
        GL1.addWidget(self.PathButton, 0, 2)
        GL1.addWidget(self.label2, 0, 3)
        GL1.addWidget(self.CheckButton, 0, 4)
        self.layout.addLayout(GL1)
        self.layout.addWidget(self.SearchButton)

        self.tableWidget = QTableWidget()
        self.tableWidget.cellClicked.connect(self.jump_addr)
        self.tableWidget.setRowCount(0)
        self.tableWidget.setColumnCount(4)
        self.tableWidget.setHorizontalHeaderLabels(["Address", "Rule name", "Variable name", "String"])
        self.layout.addWidget(self.tableWidget)

        self.parent.setLayout(self.layout)
Exemple #20
0
def get_upload_func_info(ea):
    """
    get function upload info by IDA Pro

    Args:
        ea(ea_t): function address

    Returns:
        func_info(dict): function info
    """
    func_info = {}
    try:
        hf = idaapi.hexrays_failure_t()
        if idaapi.IDA_SDK_VERSION >= 730:
            cfunc = idaapi.decompile(ea, hf, idaapi.DECOMP_NO_WAIT)
        else:
            cfunc = idaapi.decompile(ea, hf)
        func_info['feature'] = str(cfunc)
        func_info['pseudo_code'] = str(cfunc)
    except Exception as e:
        print(str(e))
        return None

    func_info['binary_file'] = idaapi.get_root_filename()
    binary_sha256 = idaapi.retrieve_input_file_sha256()
    binary_sha256 = binary_sha256.hex() if isinstance(binary_sha256,
                                                      bytes) else binary_sha256
    func_info['binary_sha256'] = binary_sha256
    func_info['binary_offset'] = idaapi.get_fileregion_offset(ea)
    func_info['platform'] = get_platform_info()
    func_info['name'] = idaapi.get_func_name(ea)

    func_bytes = b''
    for start, end in idautils.Chunks(idaapi.get_func(ea).start_ea):
        fb = idaapi.get_bytes(start, end - start)
        func_bytes += fb
    func_bytes = func_bytes.hex() if isinstance(func_bytes,
                                                bytes) else func_bytes
    func_info['func_bytes'] = func_bytes

    return func_info
Exemple #21
0
def extract_vtable_pac_codes(vtable_ea):
    pac_codes = []
    # Open the file.
    path = idc.get_input_file_path()
    with open(path, "rb") as kernelcache_file:
        # Seek to the offset of the vtable.
        offset = idaapi.get_fileregion_offset(vtable_ea)
        kernelcache_file.seek(offset)
        # Loop over each entry in the vtable.
        ea = vtable_ea
        while True:
            # Break if we've reached the end of the vtable.
            vmethod = idc.get_qword(ea)
            if vmethod == 0:
                break
            # Get the original value from the original file.
            original = kernelcache_file.read(8)
            value, = struct.unpack("<Q", original)
            # Extract the type code and add it to the list.
            pac_code = (value & 0x0000ffff00000000) >> 32
            pac_codes.append(pac_code)
            # Advance.
            ea += 8
    return pac_codes
Exemple #22
0
def format_bb(bb):
    return (
        "0x%x,0x%x" %
        (bb.start_ea - baseaddr, idaapi.get_fileregion_offset(bb.start_ea)))
Exemple #23
0
	def ReplaceFile(self, FileItem,BundleFilePath,NewFilePath):

		print "Start replace file: {}".format(NewFilePath)

		if not os.path.exists(BundleFilePath):
			print "BundleFilePath error!"
			return


		if not os.path.isfile(NewFilePath):
			print "NewFilePath error!"
			return

		f = open(NewFilePath, 'rb')
		NewFileData = f.read()
		f.close()


		if FileItem.IsCompressed == "Y":
			if FileItem.IsGZip == "Y":
				compresseddata = self.CompressGzipToData(NewFileData)
			else:
				compresseddata = self.CompressZLibToData(NewFileData)

			sizediff = FileItem.FileCompressedSize - len(compresseddata)
			print "FileCompressedSize - compresseddata = 0x{:016X} - 0x{:016X} = 0x{:016X}".format(FileItem.FileCompressedSize,len(compresseddata),sizediff)

			if sizediff < 0:
				print "FileCompressedSize < compresseddata,can't replace!"
				return
		else:
			compresseddata = NewFileData
			sizediff = FileItem.FileSize - len(compresseddata)
			print "FileSize - compresseddata = 0x{:016X} - 0x{:016X} = 0x{:016X}".format(FileItem.FileSize,len(compresseddata),sizediff)

			if sizediff < 0:
				print "FileSize < compresseddata,can't replace!"
				return




		FileSizeOffset = idaapi.get_fileregion_offset(FileItem.FileSizeOffset)

		if FileItem.IsCompressed == "Y":
			FileCompressedSizeOffset = idaapi.get_fileregion_offset(FileItem.FileCompressedSizeOffset)

		FileDataOffset = idaapi.get_fileregion_offset(FileItem.FileDataOffset)
		#ea = idaapi.get_fileregion_ea(offset)

		NewFileDataSize = len(NewFileData)
		if FileItem.IsCompressed == "Y":
			NewCompressedDataSize = len(compresseddata)
			print "FileSizeOffset = 0x{:016X},FileCompressedSizeOffset = 0x{:016X},FileDataOffset = 0x{:016X}".format(FileSizeOffset,FileCompressedSizeOffset,FileDataOffset)
		else:
			print "FileSizeOffset = 0x{:016X},FileDataOffset = 0x{:016X}".format(FileSizeOffset,FileDataOffset)
		

		input_file_dir = os.path.dirname(BundleFilePath)
		input_file_fullname = os.path.basename(BundleFilePath) 
		input_file_name,input_file_extname = os.path.splitext(input_file_fullname)
		#分离扩展名:os.path.splitext(r"c:\python\hello.py") --> ("c:\\python\\hello",
		#".py")


		output_file_fullname = '{}_{:%Y%m%d%H%M%S%f}{}'.format(input_file_name, datetime.now(),input_file_extname)
		output_file_fullpath = os.path.join(input_file_dir,output_file_fullname)


		#shutil.copy(BundleFilePath, output_file_fullpath)

		print "new BundleFilePath path:{}".format(output_file_fullpath)



		fp = open(BundleFilePath,"rb")
		data = fp.read() #读出文件内容
		
		fp.close()


		if self.Is64Bit == True:
			NewFileDataSizeData = struct.pack("q",NewFileDataSize)
			if FileItem.IsCompressed == "Y":
				NewCompressedDataSizeData = struct.pack("q",NewCompressedDataSize)
		else:
			NewFileDataSizeData = struct.pack("l",NewFileDataSize)
			if FileItem.IsCompressed == "Y":
				NewCompressedDataSizeData = struct.pack("l",NewCompressedDataSize)

		
		
		#data 不可更改元素,是固定的,必须转成可对元素操作的list
		data = list(data)


		#try:
		#	data[0] = 'a'
		#	data[1] = 'a'
		#	data[2] = 'a'
		#except Exception,e:
		#	print Exception,":",e


		#range(m, n)这里,range()函数产生的是一个从 m至n-1的整数列表


		#update FileSize
		for i in range(0, len(NewFileDataSizeData)):
			data[FileSizeOffset + i] = NewFileDataSizeData[i]

		##update FileCompressedSize
		if FileItem.IsCompressed == "Y":
			for i in range(0, len(NewCompressedDataSizeData)):
				data[FileCompressedSizeOffset + i] = NewCompressedDataSizeData[i]


		##clear FileData
		if FileItem.IsCompressed == "Y":
			for i in range(0, FileItem.FileCompressedSize):
				data[FileDataOffset + i] = chr(0x0)
				pass
		else:
			for i in range(0, FileItem.FileSize):
				data[FileDataOffset + i] = chr(0x0)
				pass

		##update FileData
		for i in range(0, len(compresseddata)):
			data[FileDataOffset + i] = compresseddata[i]
			pass

		fp2 = open(output_file_fullpath,"wb")
		#把data的list转为str并写入文件
		fp2.write(''.join(data))#重写
		fp2.close()


		print "replace ok!"
Exemple #24
0
#Prints basic info needed for the Unlinker INI's to IDA Output Window

#PROBABLY_TODO
#Make it segment sensetive,
#SegName(ea) returns
#if .text use function format,
#if .rdata use rdata format,
#if .data use data format.

#Get current cursor location
cursor = ScreenEA()

#Get function name at current cursor location
function_name = GetFunctionName(cursor)

#Get current Function start address
function_address = GetFchunkAttr(cursor, FUNCATTR_START)

#Get current function file address
file_address = idaapi.get_fileregion_offset(function_address)

#Get current function size
function_size = GetFchunkAttr(cursor, FUNCATTR_END) - GetFchunkAttr(
    cursor, FUNCATTR_START)

#Print gathered info to output
Message("[%s]\n" % function_name)
Message("Address=%Xh\n" % function_address)
Message("FileAddress=%Xh\n" % file_address)
Message("Size=%Xh\n" % function_size)
Exemple #25
0
        s.connect((host, port))
        d = zlib.compress(pickle.dumps(var))
        s.send(d)
        s.close()
        return None
    except Exception, e:
        return str(e)


idaapi.info("Please run the Hiew-Names-Server script and press OK")

idaapi.show_wait_box("Gathering and sending names to %s:%d" % (HOST, PORT))

info = []
for ea, name in idautils.Names():
    offs = idaapi.get_fileregion_offset(ea)
    if offs == idaapi.BADADDR:
        continue

    is_func = False if idaapi.get_func(ea) is None else True
    info.append((offs, name, is_func))

ok = pickle_sendz(HOST, PORT, info)

idaapi.hide_wait_box()

if ok is not None:
    idaapi.warning("Failed to send names:\n" + ok)
else:
    idaapi.info("Names successfully transfered!")
Exemple #26
0
import idaapi
import idc
import idautils
import json

functions = {}
for addr_func in idautils.Functions():
    if idc.hasUserName(idc.GetFlags(addr_func)):
        name = idc.GetFunctionName(addr_func)
        offset = idaapi.get_fileregion_offset(addr_func)
        functions[name] = {"offset": offset, "va": addr_func}

json.dump(functions, open("/tmp/out.json", "wb"))
 def getByteOffsetOfEA(self, ea):
     """Return the file byte offset of ea"""
     return idaapi.get_fileregion_offset(ea)
Exemple #28
0
def get_fileregion_offset(ea):
    file_offset = idaapi.get_fileregion_offset(ea)
    if file_offset == -1:
        raise exceptions.NoFileOffset("Address 0x{:08X} is not mapped to any file offset.".format(ea))

    return file_offset
xrefs = set()


def imp_cb(ea, name, ord):
    if name in ["OutputDebugStringA", "OutputDebugStringW"]:
        for xref in XrefsTo(ea, 0):
            xrefs.add((xref.frm, xref.to))
    return True


nimps = idaapi.get_import_module_qty()

print "Found %d import(s)..." % nimps

for i in xrange(0, nimps):
    name = idaapi.get_import_module_name(i)
    if name.upper() == "KERNEL32":
        print "Walking-> %s" % name
        idaapi.enum_import_names(i, imp_cb)
        break

for frm, to in xrefs:
    offset = idaapi.get_fileregion_offset(frm)
    print "File location: %08x (%08x -> %08x)" % (offset, frm, to)
    try:
        patchFile(frm, offset)
    except:
        pass

idc.Exit(0)
Exemple #30
0
 def getByteOffsetOfEA(self, ea):
     """Return the file byte offset of ea"""
     return idaapi.get_fileregion_offset(ea)
Exemple #31
0
    def get_default_config(analysis_start_va, analysis_stop_va):
        """
        Returns a new AnalyzerConfig for the given entry point & cut
        """
        # this function will use the default parameters
        config = ConfigParser.RawConfigParser()
        config.optionxform = str

        config_path = PluginOptions.config_path
        # Load default part - XXX move this logic to PluginOptions
        configfile = os.path.join(config_path, "conf", "default.ini")
        bc_log.debug("Reading config from %s", configfile)
        r = config.read(configfile)
        if len(r) != 1:
            bc_log.warning("Default config file %s could not be found",
                           configfile)

        code_start_va, code_end_va = ConfigHelpers.get_code_section(
            analysis_start_va)
        code_len = code_end_va - code_start_va

        # [settings] section
        config.add_section('settings')
        config.set('settings', 'mem_model', ConfigHelpers.get_memory_model())
        # IDA doesn't really support real mode
        config.set('settings', 'mode', 'protected')
        config.set('settings', 'call_conv', ConfigHelpers.get_call_convention())
        config.set('settings', 'mem_sz', 32)
        config.set('settings', 'op_sz',
                   ConfigHelpers.get_bitness(code_start_va))
        config.set('settings', 'stack_width', ConfigHelpers.get_stack_width())
        config.set('settings', 'ini_version', 1)

        # [loader section]
        config.add_section('loader')
        # code section va
        config.set('loader', 'code_va', "0x%X" % code_start_va)
        # code section offset
        config.set('loader', 'code_phys',
                   hex(idaapi.get_fileregion_offset(code_start_va)))
        # code section length
        config.set('loader', 'code_length', "0x%0X" % code_len)

        config.set('loader', 'analysis_ep', "0x%0X" % analysis_start_va)

        # Load default GDT/Segment registers according to file type
        ftype = ConfigHelpers.get_file_type()
        # XXX move this logic to PluginOptions
        if ftype == "pe":
            os_specific = os.path.join(config_path, "conf", "windows.ini")
        else:  # default to Linux config if not windows
            os_specific = os.path.join(config_path, "conf", "linux.ini")
        bc_log.debug("Reading OS config from %s", os_specific)
        config.read(os_specific)

        # [binary section]
        config.add_section('binary')
        input_file = idaapi.get_input_file_path()
        if not os.path.isfile(input_file):
            # get_input_file_path returns file path from IDB, which may not
            # exist locally if IDB has been moved (eg. send idb+binary to
            # another analyst)
            guessed_path = idc.GetIdbPath().replace('idb', 'exe')
            if os.path.isfile(guessed_path):
                input_file = guessed_path

        config.set('binary', 'filepath', input_file)
        config.set('binary', 'format', ftype)

        # [sections section]
        config.add_section("sections")
        for s in ConfigHelpers.get_sections():
            config.set("sections", "section[%s]" % s[0],
                       "0x%x, 0x%x, 0x%x, 0x%x" % (s[1], s[2], s[3], s[4]))

        # [state section]
        config.add_section("state")
        regs = ConfigHelpers.get_registers_with_state()
        for rname, val in regs.iteritems():
            if rname != "esp":
                config.set("state", ("reg[%s]" % rname), val)
        # Default stack
        config.set("state", "reg[esp]", "0x2000")
        config.set("state", "stack[0x1000*8192]", "|00|?0xFF")

        imports = ConfigHelpers.get_imports()
        # [import] section
        config.add_section('imports')
        for ea, imp in imports.iteritems():
            if imp[0]:
                name = "%s, \"%s\"" % imp
            else:
                name = "all,\"%s\"" % imp[1]
            config.set('imports', ("0x%x" % ea), name)
        # list all files in config_path/lib/*.{c,no}.
        # for each lib (same base filename) keep .no if it exists, else .c
        headers_filenames = glob.glob(os.path.join(config_path, 'lib', '*.no'))
        # Add .c if there is no associated .no
        for c in glob.glob(os.path.join(config_path, 'lib', '*.c')):
            if c[:-2] + '.no' not in headers_filenames:
                headers_filenames.append(c)
        # remove duplicates
        config.set('imports', 'headers', ','.join(headers_filenames))
        # [libc section]
        # config.add_section('libc')
        # config.set('libc', 'call_conv', 'fastcall')
        # config.set('libc', '*', 'open(@, _)')
        # config.set('libc', '*', 'read<stdcall>(@, *, @)')
        ac = AnalyzerConfig(config)
        ac.analysis_ep = analysis_start_va
        ac.stop_address = analysis_stop_va
        return ac
       s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
       s.connect((host, port))
       d = zlib.compress(pickle.dumps(var))
       s.send(d)
       s.close()
       return None
   except Exception, e:
       return str(e)

idaapi.info("Please run the Hiew-Names-Server script and press OK")

idaapi.show_wait_box("Gathering and sending names to %s:%d" % (HOST, PORT))

info = []
for ea, name in idautils.Names():
    offs = idaapi.get_fileregion_offset(ea)
    if offs == idaapi.BADADDR:
        continue

    is_func = False if idaapi.get_func(ea) is None else True
    info.append((offs, name, is_func))

ok = pickle_sendz(HOST, PORT, info)

idaapi.hide_wait_box()

if ok is not None:
    idaapi.warning("Failed to send names:\n" + ok)
else:
    idaapi.info("Names successfully transfered!")