Пример #1
0
    def from_address(cls, address: int, class_name: str, view: BinaryView):
        if address == 0:
            return None

        from_bytes = get_from_bytes(view)

        ivar_list_t_type = view.types['ivar_list_t']

        ivar_list_t = Type.named_type_from_type(
            'ivar_list_t', ivar_list_t_type
        )

        ivar_t = view.types['ivar_t']

        members = get_structure_members(address, ivar_list_t_type, view)

        view.define_user_data_var(address, ivar_list_t)

        ivars = {}
        start = address + ivar_list_t_type.width
        end = start + members['count'] * ivar_t.width
        step = ivar_t.width
        for ivar in range(start, end, step):
            new_ivar = Ivar.from_address(ivar, class_name, view)
            ivars[new_ivar.name] = new_ivar

        return cls(address, **members, ivars=ivars)
Пример #2
0
def _lookup_type(type_string: str, view: BinaryView):
    if type_string in basic_types:
        return basic_types[type_string]
    elif type_string == '*':
        return Type.pointer(view.arch, Type.char())
    elif type_string.startswith('@'):
        if type_string[2:-1] in view.types:
            return Type.pointer(
                view.arch,
                Type.named_type_from_type(
                    type_string[2:-1],
                    view.types[type_string[2:-1]]
                )
            )
        elif type_string != '@?' and type_string != '@':
            if type_string[2:-1]:
                new_type = Type.named_type_from_type(
                    type_string[2:-1], Type.structure_type(Structure()))
                view.define_user_type(type_string[2:-1], new_type)
            else:
                new_type = Type.void()
            return Type.pointer(view.arch, new_type)
        else:
            return Type.pointer(view.arch, Type.void())
    elif type_string.startswith('#'):
        return Type.pointer(view.arch, Type.void())
    elif type_string == ':':
        return view.types['SEL']
    else:
        return Type.pointer(view.arch, Type.void())
def pp(bv: bn.BinaryView):
    pre_define_types(bv, ntdll)

    Config.set_library_file(directories_config.libclang_library_file)
    index: Index = Index.create()
    tu: TranslationUnit = index.parse(
        ntdll.header_list[0],
        args=ntdll.pre_proccessor_args)  # args for clang parser

    root_node = tu.cursor

    for node in root_node.get_children():
        bn.log.log_debug(
            f'{"*" * 30}\nDEFINING NODE: \n {node.spelling} {node.type.spelling} \n'
            f'node.kind: {node.kind}, node.type.kind: {node.type.kind}\n {"*" * 30}'
        )
        ast_handlers.define_type(node, bv)

    # Create the type lib from the parsed types
    ####################################################################
    ntdll_tl = bn.TypeLibrary.new(bn.Architecture["x86"], "ntdll.dll")
    ntdll_tl.add_platform(bn.Platform["windows-x86"])

    for node in root_node.get_children():
        bn.log.log_debug(
            f'{"*" * 30}\nEXPORTING NODE: \n {node.spelling} {node.type.spelling} \n'
            f'node.kind: {node.kind}, node.type.kind: {node.type.kind}\n {"*" * 30}'
        )
        var_type = bv.get_type_by_name(node.spelling)
        if isinstance(var_type, bn.Type):
            bv.export_type_to_library(ntdll_tl, node.spelling, var_type)
    ntdll_tl.finalize()
    ntdll_tl.write_to_file(directories_config.base_proccessed_header_folder +
                           'ntdll_type_lib.btl')
Пример #4
0
def _define_classes(view: BinaryView, class_t: Type):
    __objc_data = view.sections.get('__objc_data')

    if __objc_data is None:
        raise KeyError('This binary has no __objc_data section')

    for addr in range(__objc_data.start, __objc_data.end, class_t.width):
        current_class = Class.from_address(addr, view)

        log_debug(f"Created {current_class}")

    __objc_classrefs = view.sections.get('__objc_classrefs')

    if __objc_classrefs is None:
        raise KeyError('This binary has no __objc_classrefs section')

    for addr in range(__objc_classrefs.start, __objc_classrefs.end,
                      view.address_size):
        view.define_user_data_var(addr, Type.pointer(view.arch, class_t))

        class_addr = int.from_bytes(
            view.read(addr, view.address_size),
            "little" if view.endianness is Endianness.LittleEndian else "big")

        class_ = view.session_data['ClassList'].get(
            class_addr) if class_addr else None

        if class_ is not None:
            log_debug(f"{addr:x} points to {class_!r}")
            view.define_user_symbol(
                Symbol(SymbolType.DataSymbol, addr,
                       f"_OBJC_CLASS_$_{class_.vtable.name}@GOT"))
Пример #5
0
def _parse_function_type(type_string: str,
                         self_name: str,
                         view: BinaryView,
                         is_class=False) -> Type:
    log_debug(f'_parse_function_type {type_string}')
    ret_type_str = type_string[0]

    # Handle structures defined in the function types
    if ret_type_str == '{':
        ret_type, type_string = _parse_structure(type_string[1:], view)
    else:
        ret_type = _lookup_type(ret_type_str, view)
        type_string = type_string[1:]

    stack_size = ''.join(takewhile(str.isdigit, type_string))
    type_string = type_string[len(stack_size):]
    stack_size = int(stack_size) if stack_size else None

    args = []
    while type_string:
        if type_string[0] == '{':
            arg_type, type_string = _parse_structure(type_string[1:], view)
            args.append(Type.pointer(view.arch, arg_type))
        else:
            arg_type = ''.join(
                takewhile(lambda i: not str.isdigit(i), type_string))
            type_string = type_string[len(arg_type):]
            args.append(_lookup_type(arg_type, view))

        arg_stack_offset = ''.join(takewhile(str.isdigit, type_string))
        type_string = type_string[len(arg_stack_offset):]

    # we know that the first parameter is the 'self' parameter if it's not
    # an objc_msgSend_stret or objc_msgSendSuper_stret. Otherwise it's the
    # second one.
    if ret_type.type_class == TypeClass.NamedTypeReferenceClass:
        log_debug(f'return value is {ret_type}')
        ret_type = Type.pointer(view.arch, ret_type)
        args.insert(0, FunctionParameter(ret_type, 'ret_value'))

        if len(args) < 2:
            args.append(None)

        args[1] = FunctionParameter(
            Type.pointer(
                view.arch,
                (Type.named_type_from_type(self_name, view.types[self_name])
                 if not is_class else Type.named_type_from_type(
                     'class_t', view.get_type_by_name('class_t')))), 'self')
    else:
        args[0] = FunctionParameter(
            Type.pointer(
                view.arch,
                (Type.named_type_from_type(self_name, view.types[self_name])
                 if not is_class else Type.named_type_from_type(
                     'class_t', view.get_type_by_name('class_t')))), 'self')

    function_type = Type.function(ret_type, args)

    return function_type
Пример #6
0
    def __create_class_name_type(bv: BinaryView, vmt: DelphiVMT, out_struct: types.Structure) -> bool:
        vmt_offsets = vmt.vmt_offsets

        if not vmt.seek_to_vmt_offset(vmt_offsets.cVmtClassName):
            return False

        class_name_ptr = vmt.read_ptr()

        if class_name_ptr is None:
            return False

        if not vmt.seek_to_code(class_name_ptr):
            return False

        class_name_len = vmt.read8()

        if class_name_len is None:
            return False

        class_name_struct = types.Structure()
        class_name_struct.append(Type.int(1, False), 'length')
        class_name_struct.append(Type.array(Type.char(), class_name_len), 'value')
        struct_type = Type.structure_type(class_name_struct)

        bv.define_user_data_var(class_name_ptr, struct_type)
        out_struct.append(Type.pointer(bv.arch, struct_type), 'cVmtClassName')

        # Create Symbole for class name
        class_name_sym = Symbol(SymbolType.DataSymbol, class_name_ptr, f'{vmt.class_name}Name')
        bv.define_user_symbol(class_name_sym)

        return True
Пример #7
0
    def from_address(cls, address: int, view: BinaryView):
        if address == 0:
            return None

        property_list_t_type = view.types['property_list_t']

        property_list_t = Type.named_type_from_type(
            'property_list_t', property_list_t_type
        )

        property_t = view.types['property_t']

        if view.get_data_var_at(address) is None:
            view.define_user_data_var(address, property_list_t)

        members = get_structure_members(address, property_list_t_type, view)

        properties = dict()
        start = address + property_list_t_type.width
        end = start + members['count'] * property_t.width
        step = property_t.width
        for property_addr in range(start, end, step):
            property_ = Property.from_address(property_addr, view)
            if property_ is not None:
                properties[property_.name] = property_

        return cls(address, **members, properties=properties)
Пример #8
0
def incompletearray_type(node: Cursor, bv: bn.BinaryView):
    # TODO: There is no good way to parse an incomplete array into binaryNinja since we do not know its size.
    # For now, convert an incomplete array to a complete array with a very big size since it will probably be defined
    # on the heap anyway.
    bn.log.log_debug(f'incompletearray_type: Processing {node.type.spelling} {node.spelling}, \n'
                     f'node.kind: {node.kind}, node.type.kind: {node.type.kind}')
    bn_array_element_type = node.type.get_array_element_type()
    if check_if_base_type(bn_array_element_type):
        var_type, var_name = bv.parse_type_string(bn_array_element_type.spelling)
    elif bn_array_element_type.kind == TypeKind.POINTER:
        # The array element type is a pointer - it does not have a declaration node so we cannot directly call
        # define_type().
        # Example: int *a[]
        if check_if_base_type(bn_array_element_type.get_pointee()):
            pointee_type_string = bn_array_element_type.get_pointee().spelling
            if pointee_type_string in void_types:
                pointee_type_string = 'void'
            pointee_var_type, pointee_var_name = bv.parse_type_string(pointee_type_string)
        else:
            pointee_var_name, pointee_var_type = define_type(bn_array_element_type.get_pointee().get_declaration(), bv)
        var_type = bn.Type.pointer(bv.arch, pointee_var_type)
    else:
        var_name, var_type = define_type(bn_array_element_type.get_declaration(), bv)
    array = bn.Type.array(var_type, INCOMPLETE_ARRAY_ARBITRARY_SIZE)

    return node.spelling, array
Пример #9
0
    def from_address(cls, address: int, view: BinaryView):
        if address == 0:
            return None

        property_t_type = view.types['property_t']
        property_t = Type.named_type_from_type(
            'property_t', property_t_type
        )

        if view.get_data_var_at(address) is None:
            view.define_user_data_var(
                address, property_t
            )

        members = get_structure_members(address, property_t_type, view)

        members['name'] = (
            view.get_ascii_string_at(members['name'], 1).value
            if members['name'] else ''
        )

        members['attributes'] = (
            view.get_ascii_string_at(members['attributes'], 1).value
            if members['attributes'] else ''
        )

        return cls(address, **members)
Пример #10
0
 def __init__(self, data):
     BinaryView.__init__(self, file_metadata=data.file, parent_view=data)
     self.raw = data
     if data.file.filename.endswith('.bin.16'):
         orig_file = data.file.filename[:-3]
         global strings
         strings = find_strings(orig_file)
Пример #11
0
    def from_address(cls,
                     address: int,
                     self_type: str,
                     view: BinaryView,
                     is_class=False):
        if address == 0:
            return None

        method_list_t_type = view.get_type_by_name('method_list_t')

        method_list_t = Type.named_type_from_type('method_list_t',
                                                  method_list_t_type)

        method_t = view.get_type_by_name('method_t')

        if view.get_data_var_at(address) is None:
            view.define_user_data_var(address, method_list_t)

        members = get_structure_members(address, method_list_t_type, view)

        methods = dict()
        start = address + method_list_t_type.width
        end = start + members['count'] * method_t.width
        step = method_t.width
        for method_addr in range(start, end, step):
            method = Method.from_address(method_addr, self_type, view,
                                         is_class)
            if method is not None:
                methods[method.name] = method

        return cls(address, **members, methods=methods)
Пример #12
0
def add_members(view: BinaryView, structure: StructureBuilder, start: int, length: int):
    offset = 0
    br = BinaryReader(view)

    if (dv := view.get_data_var_at(start)) is None:
        dv = view.get_next_data_var_after(start)
        offset = dv.address - start
Пример #13
0
 def __init__(self, parent):
     BinaryView.__init__(self,
                         parent_view=parent,
                         file_metadata=parent.file)
     self.value_cache = {}
     self.error_cache = {}
     self.arch = parent.arch
     self.platform = parent.platform
Пример #14
0
 def __init__(self, data: BinaryView):
     actual_data = data.read(0, len(data)).decode('utf8')
     binfile = BinFile()
     binfile.add(actual_data)
     decoded = b''.join(s.data for s in binfile.segments)
     parent = BinaryView.new(data=decoded)
     self.hex_segments = binfile.segments
     BinaryView.__init__(self, file_metadata=data.file, parent_view=parent)
Пример #15
0
    def from_address(cls, address: int, class_name: str, view: BinaryView):
        if address == 0:
            return None

        from_bytes = get_from_bytes(view)

        ivar_t_type = view.types['ivar_t']
        ivar_t = Type.named_type_from_type(
            'ivar_t', ivar_t_type
        )

        members = get_structure_members(address, ivar_t_type, view)
        member_dict = {m.name: m for m in ivar_t_type.structure.members}

        # x64 uses uint64_t for offset, but everything else
        # uses uint32_t
        ivar_offset_type = (
            member_dict['offset'].type.target
            if view.arch != Architecture['x86_64']
            else Type.int(8, False)
        )
        ivar_offset_type.const = True

        if view.get_data_var_at(address) is None:
            view.define_user_data_var(address, ivar_t)

        if members['name'] != 0:
            name_string = view.get_ascii_string_at(members['name'], 1)
            if name_string is not None:
                members['name'] = name_string.value
        else:
            members['name'] = ''

        if members['type']:
            type_string = view.get_ascii_string_at(members['type'], 1).value
            members['type'] = _lookup_type(type_string, view)

        if not members['type']:
            members['type'] = Type.pointer(view.arch, Type.void())

        if members['offset']:
            view.define_user_data_var(members['offset'], ivar_offset_type)
            view.define_user_symbol(
                Symbol(
                    SymbolType.DataSymbol,
                    members['offset'],
                    f'{members["name"]}_offset',
                    namespace=class_name
                )
            )
            members['offset'] = from_bytes(
                view.read(members['offset'],
                          member_dict['offset'].type.target.width)
            )
        else:
            members['offset'] = None

        return cls(address, **members)
Пример #16
0
    def __init__(self, data):
        """
        Once our view is selected, this method is called to actually create it.
        :param data: the file data
        """
        BinaryView.__init__(self, file_metadata=data.file, parent_view=data)
        self.platform = Architecture['DUMB'].standalone_platform

        self.parse_format(data)
Пример #17
0
def _parse_structure(type_string: str, view: BinaryView) -> Type:
    type_name = ''.join(
        takewhile(lambda i: i != '=', type_string)
    )

    type_string = type_string[len(type_name)+1:]

    fields = []
    while type_string:
        if type_string[0] == '{':
            field_type, type_string = _parse_structure(type_string[1:], view)
            fields.append(field_type)

        elif type_string[0] == '}':
            type_string = type_string[1:]
            break

        elif type_string[0] == '[':
            array_size = ''.join(takewhile(str.isdigit, type_string[1:]))
            array_type = ''.join(
                takewhile(lambda i: i != ']', type_string[1:])
            )
            type_string = type_string[len(array_size)+len(array_type)+2:]

            fields.append(
                Type.array(_lookup_type(array_type, view), int(array_size))
            )

        elif type_string[0] == ']':
            type_string = type_string[1:]
            continue

        elif _lookup_type(type_string[0], view):
            fields.append(_lookup_type(type_string[0], view))
            type_string = type_string[1:]

        else:
            log_debug(f"Not sure what is going on with this type: {type_string!r}")
            raise NotImplementedError(f"{type_string!r}")

    parsed_struct = Structure()

    for field in fields:
        parsed_struct.append(field)

    log_debug(f"Created {type_name}={parsed_struct}")
        
    view.define_user_type(type_name, Type.structure_type(parsed_struct))

    return (
        Type.named_type_from_type(
            type_name,
            view.types.get(type_name)
        ),
        type_string
    )
Пример #18
0
def parse_get_class(view: BinaryView, objc_getClass: int):
    log_debug(f"parse_get_class(view, {objc_getClass:x})")
    xrefs = view.get_code_refs(objc_getClass)

    for xref in xrefs:
        mlil = xref.function.mlil
        get_class_call = xref.function.get_low_level_il_at(xref.address).mlil

        if not get_class_call.params:
            continue

        class_param = get_class_call.params[0]
        log_debug(f"class_param is {class_param.operation!r}")

        if class_param.operation in (
                MediumLevelILOperation.MLIL_CONST,
                MediumLevelILOperation.MLIL_CONST_PTR):
            class_name_ptr = view.get_ascii_string_at(class_param.constant, 1)
            if class_name_ptr is None:
                continue

            class_name = class_name_ptr.value

            cls_ = Type.named_type_from_type(
                class_name,
                view.types.get(class_name)
            )

            if cls_ is None:
                continue

            cls_ptr = Type.pointer(view.arch, cls_)

            output = get_class_call.output[0] if get_class_call.output else None

            if output is None:
                continue

            log_debug(f"Updating {output!r} to {cls_ptr}")
            xref.function.create_user_var(output, cls_ptr, output.name)
            log_debug(f"Now {output!r}")

            # Update any variable that is directly set to this variable (but not if
            # the variable just happened to be used in the expression)
            for use in mlil.get_ssa_var_uses(get_class_call.ssa_form.output.dest[0]):
                log_debug(f"Checking {use!r}")
                if use.operation != MediumLevelILOperation.MLIL_SET_VAR:
                    continue

                if use.src.operation != MediumLevelILOperation.MLIL_VAR:
                    continue

                log_debug(f"Updating {use.dest!r} to {cls_ptr}")
                xref.function.create_user_var(use.dest, cls_ptr, use.dest.name)
                log_debug(f"Now {use.dest!r}")
Пример #19
0
def var_decl(node: Cursor, bv: bn.BinaryView):
    bn.log.log_debug(f'var_decl: Processing var {node.underlying_typedef_type.spelling} {node.spelling}')
    var_type, name = bv.parse_type_string(f'{node.type.spelling} {node.spelling}')

    try:
        bv.define_user_type(name, var_type)
        bn.log.log_debug(f'var_decl: Successfully processed var {node.underlying_typedef_type.spelling} '
                         f'{node.spelling}')
        return str(name), var_type
    except Exception as e:
        bn.log.log_debug(f'var_decl: Failed Processing var {node.underlying_typedef_type.spelling} {node.spelling} '
                         f'with exception {e}')
Пример #20
0
	def __init__(self, parent):
		self.memory = DebugMemoryView(parent)
		self.local_view = parent
		BinaryView.__init__(self, parent_view=self.memory, file_metadata=self.memory.file)
		self.arch = parent.arch
		self.platform = parent.platform

		self.saved_bases = {}

		# TODO: Read segments from debugger
		length = self.memory.perform_get_length()
		self.add_auto_segment(0, length, 0, length, SegmentFlag.SegmentReadable | SegmentFlag.SegmentWritable | SegmentFlag.SegmentExecutable)
		self.add_auto_section("Memory", 0, length)
Пример #21
0
 def __init__(self, data):
     """
     Create memory map segments for the image
     We use only the ROM data, no additional data is mapped.
     Interpreter segment is not loaded to not confuse the user when looking at the image in the hex viewer
     """
     BinaryView.__init__(self, parent_view=data, file_metadata=data.file)
     self.platform = Architecture['CHIP-8'].standalone_platform
     self.data = data
     self.add_auto_segment(0x200, len(data), 0, len(data), SegmentFlag.SegmentReadable | SegmentFlag.SegmentWritable | SegmentFlag.SegmentExecutable | SegmentFlag.SegmentContainsCode)
     self.add_user_section('ROM Data', 0x200, len(data), SectionSemantics.ReadOnlyCodeSectionSemantics)
     self.add_entry_point(0x200)
     self.get_function_at(0x200).name = 'entry'
Пример #22
0
def _add_xrefs(view: BinaryView):
    log_debug('_add_xrefs')
    method_t = view.types.get('method_t')
    if method_t is None:
        return

    method_t_struct = method_t.structure

    method_t_name = method_t_struct['name']

    for function in view.functions:
        data_refs = view.get_data_refs(function.start)

        log_debug(f'{function.name}: {data_refs}')

        method_t_list = [
            var
            for var in map(
                view.get_data_var_at,
                (ref for ref in data_refs)
            )
        ]

        log_debug(f'{function.name}: {method_t_list}')

        for method in method_t_list:
            name_ptr = int.from_bytes(
                view.read(method.address + method_t_name.offset, view.address_size),
                "little" if view.endianness == Endianness.LittleEndian else "big"
            )

            for xref in view.get_code_refs(name_ptr):
                xref_mlil = xref.function.get_low_level_il_at(xref.address).mmlil

                if xref_mlil is None:
                    log_debug(f'{xref.address:x}')
                    return

                if xref_mlil.operation == MediumLevelILOperation.MLIL_SET_VAR:
                    call_mlil = next(
                        (use
                        for use in xref_mlil.function.get_ssa_var_uses(xref_mlil.ssa_form.dest)
                        if (use.instr_index > xref_mlil.instr_index and
                            use.il_basic_block == xref_mlil.il_basic_block)),
                        None
                    )
                else:
                    return

                if call_mlil is not None:
                    xref.function.set_user_xref(call_mlil.address, function.start)
Пример #23
0
    def from_address(cls, address: int, view: BinaryView):
        if address == 0:
            return None

        from_bytes = get_from_bytes(view)

        protocol_list_t_type = view.get_type_by_name('protocol_list_t')

        protocol_list_t = Type.named_type_from_type('protocol_list_t',
                                                    protocol_list_t_type)

        protocol_t = view.get_type_by_name('protocol_t')

        members = get_structure_members(address, protocol_list_t_type, view)

        view.define_user_data_var(address, protocol_list_t)

        protocols = {}
        start = address + protocol_list_t_type.width
        end = start + members['count'] * view.address_size
        step = view.address_size
        for protocol_ptr in range(start, end, step):
            if not view.get_data_var_at(protocol_ptr):
                view.define_user_data_var(protocol_ptr,
                                          Type.pointer(view.arch, protocol_t))
            protocol = Protocol.from_address(
                from_bytes(view.read(protocol_ptr, view.address_size)), view)

            protocols[protocol.name] = protocol

        return cls(address, **members, protocols=protocols)
Пример #24
0
    def from_address(cls,
                     address: int,
                     self_type: str,
                     view: BinaryView,
                     is_class=False):
        if address == 0:
            return None

        if self_type not in view.types:
            view.define_user_type(self_type, Type.structure_type(Structure()))

        method_t_type = view.types['method_t']
        method_t = Type.named_type_from_type('method_t', method_t_type)

        if view.get_data_var_at(address) is None:
            view.define_user_data_var(address, method_t)

        members = get_structure_members(address, method_t_type, view)

        members['name'] = (view.get_ascii_string_at(members['name'], 1).value
                           if members['name'] else '')

        members['types'] = parse_function_type(
            view.get_ascii_string_at(members['types'], 1).value
            if members['types'] else '', self_type, view, is_class)

        members['imp'] = view.get_function_at(members['imp'])

        if members['imp'] is not None:
            if not is_class:
                method_name = f'-[{self_type} {members["name"]}]'
            else:
                method_name = f'+[{self_type} {members["name"]}]'

            if view.symbols.get(method_name):
                namespace = f'{members["imp"].start}'
            else:
                namespace = None

            view.define_user_symbol(
                Symbol(SymbolType.FunctionSymbol,
                       members['imp'].start,
                       method_name,
                       namespace=namespace))

            if members['types'] is not None:
                members['imp'].function_type = members['types']

        return cls(address, **members)
Пример #25
0
    def get_string(self, bv: BinaryView):
        s = bv.get_string_at(self.const, partial=True)

        if s:
            s = s.value
        else:
            # Get string with size of 3 or less (get_string_at does not return these)
            s = str(bv.read(self.const, 4))
            if "\x00" not in s:
                s = None
            else:
                s = s.split("\x00", 1)[0]
                s = str(s)

        return s
Пример #26
0
    def from_address(cls, address: int, view: BinaryView) -> Class:
        if address == 0:
            return None
        elif address in view.session_data['ClassList']:
            return view.session_data['ClassList'][address]
        else:
            new_class = cls(address, view, None, None, None, {}, {})
            view.session_data['ClassList'][address] = new_class

        from_bytes = get_from_bytes(view)

        members = get_structure_members(address, view.types['class_t'], view)

        isa = Class.from_address(members['isa'], view)
        new_class.isa = isa

        superclass = Class.from_address(members['superclass'], view)
        new_class.superclass = superclass

        vtable = ClassRO.from_address(members['vtable'], view,
                                      new_class.is_meta)
        new_class.vtable = vtable

        class_t = Type.named_type_from_type('class_t', view.types['class_t'])

        view.define_user_data_var(address, class_t)

        if not new_class.is_meta:
            view.session_data['ClassNames'][vtable.name] = new_class
        else:
            view.session_data['ClassNames'][f"{vtable.name}_meta"] = new_class

        if not new_class.is_meta:
            new_class.define_type()
            symbol_name = f'_OBJC_CLASS_$_{vtable.name}'
        else:
            symbol_name = f'_OBJC_METACLASS_$_{vtable.name}'

        view.define_user_symbol(
            Symbol(SymbolType.DataSymbol, address, symbol_name))

        if vtable and vtable.baseMethods is not None:
            new_class._methods = vtable.baseMethods.methods

        if vtable and vtable.baseProtocols is not None:
            new_class._protocols = vtable.baseProtocols.protocols

        return new_class
Пример #27
0
def clear_tags(bv: BinaryView, tag_type_name: str):
    tags = [(x, y) for x, y in bv.data_tags if y.type.name == tag_type_name]

    if not tags:
        return

    result = interaction.show_message_box('Delete old tag?', (
        'DelphiNinja has detected several tags associated with VMTs. Would you like to '
        'remove these tags?\nWARNING: This will not remove associated structures.'
    ), MessageBoxButtonSet.YesNoButtonSet, MessageBoxIcon.QuestionIcon)

    if result != MessageBoxButtonResult.YesButton:
        return

    for addy, tag in tags:
        bv.remove_user_data_tag(addy, tag)
Пример #28
0
def _get_structure_members(address: int, t: Type, view: BinaryView) -> dict:
    from_bytes = _get_from_bytes(view)

    return {
        m.name: from_bytes(view.read(address + m.offset, m.type.width))
        for m in t.structure.members
    }
Пример #29
0
def define_anonymous_type(node: Cursor, bv: bn.BinaryView) -> bn.Type:
    # An anonymous type must be either a Struct\UNION\ENUM.
    # In order to simplify working with binaryNinja, an anonymized type is de-anonymized:
    # The name of the anonymous type is a hash of its location in the source file prepended by 'anon_'
    bn.log.log_debug(f'define_anonymous_type: Processing {node.type.spelling}')

    struct = bn.Structure()
    struct.width = node.type.get_size()
    struct.alignment = node.type.get_align()
    struct_name = 'anon_' + xxhash.xxh64_hexdigest(node.type.spelling)

    for field in node.type.get_fields():
        bn_field_type = bv.get_type_by_name(field.spelling)
        field_name = field.spelling
        if not bn_field_type:
            # Need to define the field type
            # if field.is_anonymous():
            #    field_name, bn_field_type = define_anonymous_type(field, bv)
            # else:
            field_name, bn_field_type = define_type(field.get_definition(), bv)
        bn.log.log_debug(f'define_anonymous_type: Appending field - {bn_field_type} {field_name}')
        struct.append(bn_field_type, field_name)

    # Check if the underlying struct is a union
    if node.type.kind == TypeKind.ELABORATED:
        if node.type.get_named_type().get_declaration().kind == CursorKind.UNION_DECL:
            # set type to union
            struct.type = bn.StructureType.UnionStructureType

    return struct_name, bn.Type.structure_type(struct)
Пример #30
0
def enum_decl(node: Cursor, bv: bn.BinaryView):
    bn.log.log_debug(f'enum_decl: Processing enum {node.type.spelling} {node.spelling}')

    enum = bn.Enumeration()
    for enum_member in node.get_children():
        enum.append(enum_member.spelling, enum_member.enum_value)

    try:
        if node.spelling:
            enum_name = node.spelling
        else:
            enum_name = node.type.spelling
        bv.define_user_type(enum_name, bn.Type.enumeration_type(bv.arch, enum))
        bn.log.log_debug(f'enum_decl: Successfully processed enum {node.spelling}')
        return node.spelling, bn.Type.enumeration_type(bv.arch, enum)
    except Exception as e:
        bn.log.log_debug(f'enum_decl: Failed Processing enum {node.spelling} with exception {e}')
Пример #31
0
def main():
    if len(sys.argv) != 2:
        print('Usage: {} <file>'.format(sys.argv[0]))
        return -1

    target = sys.argv[1]

    bv = BinaryView.open(target)
    view_type = next(bvt for bvt in bv.available_view_types if bvt.name != 'Raw') 
    if not view_type:
        print('Error: Unable to get any other view type besides Raw')
        return -1

    bv = bv.file.get_view_of_type(view_type.name)
    bv.update_analysis_and_wait()

    print_syscalls(bv)