Ejemplo n.º 1
0
    def test_analysis_time(self):
        if platform.system() != "Linux" or getpass.getuser() != "jenkins":
            return

        start_time = time.time()
        file_names = [
            os.path.join(os.path.dirname(__file__), "binaries",
                         "quick3dcoreplugin.dll"),
            os.path.join(os.path.dirname(__file__), "binaries", "md5"),
            os.path.join(os.path.dirname(__file__), "binaries", "ls")
        ]

        for file_name in file_names:
            temp_name = next(tempfile._get_candidate_names()) + ".bndb"
            self.unpackage_file(file_name)
            try:
                bv = BinaryViewType.get_view_of_file(file_name)
                bv.create_database(temp_name)
                bv.file.close()
                bv = BinaryViewType.get_view_of_file(temp_name)
                bv.file.close()
            finally:
                if os.path.exists(file_name):
                    os.unlink(file_name)
                if os.path.exists(temp_name):
                    os.unlink(temp_name)

        time_s = time.time() - start_time
        commit = subprocess.check_output(["git", "rev-parse", "HEAD"])[:-1]
        conn = urllib.urlopen(
            "https://script.google.com/macros/s/AKfycbxrZtlgLaWt3l95_7RyH9ceDdFIBm0VaR6jG1-4UDt6CFFCFzQ/exec?BuildID=%s&Test1=%.2f"
            % (commit, time_s))
Ejemplo n.º 2
0
def get_bininfo(bv):
    if bv is None:
        filename = ""
        if len(sys.argv) > 1:
            filename = sys.argv[1]
        else:
            filename = interaction.get_open_filename_input("Filename:")
            if filename is None:
                log.log_warn("No file specified")
                sys.exit(1)

        bv = BinaryViewType.get_view_of_file(filename)
        log.log_to_stdout(True)

    contents = "## %s ##\n" % os.path.basename(bv.file.filename)
    contents += "- START: 0x%x\n\n" % bv.start
    contents += "- ENTRY: 0x%x\n\n" % bv.entry_point
    contents += "- ARCH: %s\n\n" % bv.arch.name
    contents += "### First 10 Functions ###\n"

    contents += "| Start | Name   |\n"
    contents += "|------:|:-------|\n"
    for i in range(min(10, len(bv.functions))):
        contents += "| 0x%x | %s |\n" % (bv.functions[i].start,
                                         bv.functions[i].symbol.full_name)

    contents += "### First 10 Strings ###\n"
    contents += "| Start | Length | String |\n"
    contents += "|------:|-------:|:-------|\n"
    for i in range(min(10, len(bv.strings))):
        start = bv.strings[i].start
        length = bv.strings[i].length
        string = bv.read(start, length)
        contents += "| 0x%x |%d | %s |\n" % (start, length, string)
    return contents
Ejemplo n.º 3
0
def get_bininfo(bv):
	if bv is None:
		filename = ""
		if len(sys.argv) > 1:
			filename = sys.argv[1]
		else:
			filename = interaction.get_open_filename_input("Filename:")
			if filename is None:
				log.log_warn("No file specified")
				sys.exit(1)

		bv = BinaryViewType.get_view_of_file(filename)
		log.redirect_output_to_log()
		log.log_to_stdout(True)

	contents = "## %s ##\n" % bv.file.filename
	contents += "- START: 0x%x\n\n" % bv.start
	contents += "- ENTRY: 0x%x\n\n" % bv.entry_point
	contents += "- ARCH: %s\n\n" % bv.arch.name
	contents += "### First 10 Functions ###\n"

	contents += "| Start | Name   |\n"
	contents += "|------:|:-------|\n"
	for i in xrange(min(10, len(bv.functions))):
		contents += "| 0x%x | %s |\n" % (bv.functions[i].start, bv.functions[i].symbol.full_name)

	contents += "### First 10 Strings ###\n"
	contents += "| Start | Length | String |\n"
	contents += "|------:|-------:|:-------|\n"
	for i in xrange(min(10, len(bv.strings))):
		start = bv.strings[i].start
		length = bv.strings[i].length
		string = bv.read(start, length)
		contents += "| 0x%x |%d | %s |\n" % (start, length, string)
	return contents
Ejemplo n.º 4
0
 def __init__(self, filename: str = None, debug_root: str = None, debug_file: str = None, binary_view = None):
   if filename is None and binary_view is None:
     raise Exception('Must specify either a filename or binary view.')
   if binary_view is None:
     self.binary_view = BinaryViewType.get_view_of_file(filename, update_analysis=False)
   else:
     self.binary_view = binary_view
   assert(self.binary_view is not None)
   self.module = Module()
   self.mapping = BinjaMap(self.binary_view)
   self.debug_root = debug_root
   self.debug_file = debug_file
Ejemplo n.º 5
0
def main():
    bv = BinaryViewType.get_view_of_file(sys.argv[1])
    if bv is None:
        print("Couldn't open %s" % sys.argv[1])
        return

    patch_opaque(bv)

    dbname = sys.argv[1]
    if not dbname.endswith(".bndb"):
        dbname += ".bndb"

    bv.create_database(dbname)
Ejemplo n.º 6
0
def get_bin_view(bv):
    if bv is None:
        filename = ""
        if len(sys.argv) > 1:
            filename = sys.argv[1]
        else:
            filename = interaction.get_open_filename_input("Filename:")
            if filename is None:
                log.log_warn("No file specified")
                sys.exit(1)
        bv = BinaryViewType.get_view_of_file(filename)
        log.log_to_stdout(True)
        return bv
Ejemplo n.º 7
0
def print_syscalls(fileName):
	""" Print Syscall numbers for a provided file """
	bv = BinaryViewType.get_view_of_file(fileName)
	calling_convention = bv.platform.system_call_convention
	if calling_convention is None:
		print('Error: No syscall convention available for {:s}'.format(bv.platform))
		return

	register = calling_convention.int_arg_regs[0]

	for func in bv.functions:
		syscalls = (il for il in chain.from_iterable(func.low_level_il)
					if il.operation == LowLevelILOperation.LLIL_SYSCALL)
		for il in syscalls:
			value = func.get_reg_value_at(il.address, register).value
			print("System call address: {:#x} - {:d}".format(il.address, value))
Ejemplo n.º 8
0
def decode_strings(filename):
    y_offsets = get_yara_offset(filename)
    bv = BinaryViewType.get_view_of_file(filename)
    bv.add_analysis_option("linearsweep")
    bv.update_analysis_and_wait()
    xref_funcs = get_xrefs(bv, y_offsets)
    keys = get_key(bv, y_offsets)

    # TODO: Need to make this work for multiple keys but not y_offset
    XOR_KEY = keys[0].value.value
    #for y in y_offsets:
    #    xor_dec(XOR_KEY, xref_funcs, y_off
    xor_dec(bv, XOR_KEY, xref_funcs, y_offsets)

    # TODO: Again need to have an input dir, or cmdline options
    bv.save('AShldRes_new.dll')
Ejemplo n.º 9
0
def main():
    options = GetOptions()

    log("Loading the binary: {}".format(options.input_file))

    bv = BinaryViewType.get_view_of_file(options.input_file)
    if bv is None:
        print("Could not open {}".format(options.input_file))
        return False

    (success, error_message) = import_pp(options.csv_file, bv,
                                         options.output_name, options)
    if not success:
        print("Error:", error_message)
        return

    log("Writing out {}".format(options.output_name))
    bv.create_database(options.output_name)
    return
Ejemplo n.º 10
0
def main():
    options = GetOptions()
    if options.json_file is None or options.output_name is None:
        print options.usage
        return

    log("Loading the binary: {}".format(options.input_file), options)

    bv = BinaryViewType.get_view_of_file(options.input_file)
    if bv is None:
        print "Could not open {}".format(options.input_file)
        return False

    (success, error_message) = import_ida(options.json_file, bv, options.output_name, options)
    if not success:
        print "Error:", error_message
        print options.usage
        return

    log("Writing out {}".format(options.output_name), options.verbose)
    bv.create_database(options.output_name)
    return
Ejemplo n.º 11
0
 def __init__(self, filename):
     self.filename = os.path.join(os.path.dirname(__file__), filename)
     self.bv = BinaryViewType.get_view_of_file(self.filename)
     if self.bv is None:
         print("%s is not an executable format" % filename)
         return
Ejemplo n.º 12
0
    with io.BytesIO() as output:
        img.save(output, format="GIF")
        gif = output.getvalue()

    # gif string -> base64
    return base64.b64encode(gif)


#------------------------------------------------------------------------------
# main()
#------------------------------------------------------------------------------

if __name__ == '__main__':
    fpath = sys.argv[1]

    bv = BinaryViewType.get_view_of_file(fpath)
    bv.update_analysis_and_wait()

    func2span = {}
    (lowest, highest) = (bv.end, bv.start)
    for f in bv.functions:
        span = function_span(f)
        lowest = min(lowest, span[0][0])
        highest = max(highest, span[-1][1])
        func2span[f] = span
    print('lowest addr: 0x%X' % lowest)
    print('highest addr: 0x%X' % highest)

    width = 2
    length = 4
    while length < (highest - lowest):
Ejemplo n.º 13
0
 def __init__(self, filename, test_store):
     self.filename = filename
     self.bv = BinaryViewType.get_view_of_file(filename)
     if self.bv is None:
         print("%s is not an executable format" % filename)
         return
Ejemplo n.º 14
0
    for font_size in range(12, 1, -1):
        font = ImageFont.truetype('Andale Mono', font_size)
        (tw, th) = font.getsize(label)
        if tw < w and th < h: break

    draw.rectangle((x0, y0, x1 - 1, y1 - 1),
                   outline=settings['outline'],
                   fill=settings['fill'])

    (x, y) = (x0 + w // 2 - tw // 2, y0 + h // 2 - th // 2)
    draw.text((x, y), label, font=font, fill=settings['text_color'])


if __name__ == '__main__':
    bv = BinaryViewType.get_view_of_file(sys.argv[1])
    bv.update_analysis_and_wait()

    img = Image.new('RGB', (width, width))
    draw = ImageDraw.Draw(img)

    seg2data = {}
    for seg in bv.segments:
        seg2data[seg] = {'id': str(seg), 'datum': len(seg), 'children': []}

    scn2data = {}
    for scn in bv.sections.values():
        data = {'id': scn.name, 'datum': len(scn), 'children': []}
        containing_segment = bv.get_segment_at(scn.start)
        seg2data[containing_segment]['children'].append(data)
        scn2data[scn] = data
Ejemplo n.º 15
0
 def __init__(self, file):
     self.bv = BinaryViewType.get_view_of_file(file, update_analysis=False)
Ejemplo n.º 16
0
                          key=lambda k: len(calldict[k]),
                          reverse=True)[0]
        nodes_traversed = recursive_print_node(root, calldict, 0, seen)
        seen.update(nodes_traversed)
        root = None


if __name__ == '__main__':

    STANDALONE_USAGE = 'USAGE: %s <target_file> [args]' % sys.argv[0]
    if len(sys.argv) < 2:
        print(STANDALONE_USAGE)
        exit(0)

    target_file = sys.argv[1]
    remaining_args = sys.argv[2:]

    print('[*] Loading BinaryView of %s' % target_file)
    start_time = time.time()
    bv = BinaryViewType.get_view_of_file(target_file)
    duration = time.time() - start_time
    print('[*] Analysis finished in %.2f seconds\n' % duration)

    start_time = time.time()
    calltree = get_calltree(bv, target_file, remaining_args)
    duration = time.time() - start_time
    print('[*] Calltree collection finished in %.2f seconds\n' % duration)

    print_calltree(calltree)
    print('[*] Done.')
Ejemplo n.º 17
0
 def __init__(self, filename):
     self.filename = os.path.join(os.path.dirname(__file__), filename)
     self.bv = BinaryViewType.get_view_of_file(self.filename)
     if self.bv is None:
         print("%s is not an executable format" % filename)
         return