Exemplo n.º 1
0
    def set_enum(name):
        if (idaapi.get_enum(str(name)) != idaapi.BADADDR):
            idaapi.del_enum(idaapi.get_enum(str(name)))

        ok = idc.add_enum(-1, str(name), 1)
        if not ok:
            print("Could not add enum {name}".format(name=name))
Exemplo n.º 2
0
    def activate(self, ctx):
        # print("ctx.cur_ea : 0x%x" % ctx.cur_ea)
        # print("ctx.cur_extracted_ea : 0x%x" % ctx.cur_extracted_ea)

        # Extract selected enum
        instruction = idc.GetDisasm(ctx.cur_ea)
        selection = ctx.cur_extracted_ea

        # correctly parse the selected value as int (hex or decimal)
        # since ctx.cur_extracted_ea has a bug (IDA always consider
        # the selected value as hex)
        if instruction.find("{0:X}h".format(selection)) != -1:
            # print("hex value found !")
            selected_value = ctx.cur_extracted_ea
        elif instruction.find("{0:d}".format(selection)) != -1:
            # print("int value found !")
            selected_value = int("%x" % ctx.cur_extracted_ea)
        else:
            # print("nothing selected !")
            return 1

        # next power of two for masking
        selected_value_mask = self.shift_bit_length(selected_value) - 1
        # print("selected_value : 0x%X" % selected_value)
        # print("selected_value mask : 0x%X" % selected_value_mask)

        # query magnum db
        url = SearchMagicNumber.MAGNUMDB_QUERY.format(
            value=selected_value, key=SearchMagicNumber.MAGNUMDB_KEY)
        answer = urlopen(url)
        results = json.loads(answer.read())

        # Let the user select the best answer
        c = ChooseMagicNumber(selected_value, results["Items"])
        selected_index = c.Show(modal=True)
        if selected_index < 0:
            return

        # Apply the newly found enum
        selected_item = results["Items"][selected_index]
        selected_name = selected_item["Title"].encode('ascii')
        selected_value = int(selected_item["Value"])

        # serial is important since several entries can have the same value
        entryid, serial = self._manager.add_magnumdb_entry(
            selected_name, selected_value)

        # locate the operand where to apply the enum
        insn = idautils.DecodeInstruction(ctx.cur_ea)
        for op in filter(lambda o: o.type == idaapi.o_imm, insn.Operands):

            # heuristic : the selected immediate is the first in the instruction with
            # the same exact value (we are using a mask since IDA loves to set FFFFFFFF to high words)
            if op.value & selected_value_mask == selected_value:
                # Apply the enum
                idc.OpEnumEx(ctx.cur_ea, op.n,
                             idaapi.get_enum("_IDA_MAGNUMDB"), serial)
                break

        return 1
Exemplo n.º 3
0
    def get_flag_and_id(size, type):
        flag = 0x00000000
        typeid = -1

        if size == 1:
            flag = 0x00000000  # byte
        elif size == 2:
            flag = 0x10000000  # word
        elif size == 4:
            flag = 0x20000000  # dword
        elif size == 8:
            flag = 0x30000000  # qword
        try:
            typeTable = type.get("table")
        except AttributeError:
            return {"flag": flag, "typeid": typeid}

        if typeTable == "PDOMCStructure" or typeTable == "PDOMCPPClassType":
            flag = 0x60000000
            typeid = idaapi.get_struc_id(str(type.get("name")))
            return {"flag": flag, "typeid": typeid}
        elif typeTable == "PDOMCEnumeration" or typeTable == "PDOMCPPEnumeration":
            typeid = idaapi.get_enum_size(
                idaapi.get_enum(str(type.get("name"))))
        elif typeTable == "PDOMCTypedef" or typeTable == "PDOMCPPTypedef":
            return IDAtools.get_flag_and_id(size, type.get("type"))

        return {"flag": flag, "typeid": typeid}
Exemplo n.º 4
0
    def ensure_magnumdb_enum_type(self):
        """Ensure we have a valid MAGNUMDB enum"""

        enum_id = idaapi.get_enum("_IDA_MAGNUMDB")
        if enum_id == 0xffffffffffffffff:
            enum_id = idaapi.add_enum(idaapi.BADADDR, "_IDA_MAGNUMDB", 0)

        return enum_id
Exemplo n.º 5
0
def tid_is_enum(tid):
    # get_enum_name return name for struc or enum
    tid_name = idaapi.get_enum_name(tid)

    if idaapi.get_enum(tid_name) != idc.BADADDR:
        return True

    return False
Exemplo n.º 6
0
def by_name(name):
    '''Return an enum id with the specified ``name``.'''
    res = idaapi.get_enum(name)
    if res == idaapi.BADADDR:
        raise LookupError(
            "{:s}.by_name({!r}) : Unable to locate enumeration.".format(
                __name__, name))
    return res
Exemplo n.º 7
0
def by_name(name):
    '''Return the identifier for the enumeration with the given `name`.'''
    res = idaapi.get_enum(utils.string.to(name))
    if res == idaapi.BADADDR:
        raise E.EnumerationNotFoundError(
            u"{:s}.by_name({!r}) : Unable to locate enumeration by the name \"{:s}\"."
            .format(__name__, name, utils.string.escape(name, '"')))
    return res
Exemplo n.º 8
0
 def __call__(self):
     if self.is_enum:
         idaapi.set_enum_name(idaapi.get_enum(self.oldname.encode('utf-8')),
                              self.newname.encode('utf-8'))
     else:
         idaapi.set_enum_member_name(
             idaapi.get_enum_member_by_name(self.oldname.encode('utf-8')),
             self.newname.encode('utf-8'))
Exemplo n.º 9
0
def by_name(name):
    '''Return the identifier for the enumeration with the given `name`.'''
    res = idaapi.get_enum(name)
    if res == idaapi.BADADDR:
        raise E.EnumerationNotFoundError(
            "{:s}.by_name({!r}) : Unable to locate enumeration by the name {!r}."
            .format(__name__, name, name))
    return res
Exemplo n.º 10
0
 def __call__(self):
     if self.op == 'hex':
         idc.OpHex(self.ea, self.n)
     if self.op == 'bin':
         idc.OpBinary(self.ea, self.n)
     if self.op == 'dec':
         idc.OpDecimal(self.ea, self.n)
     if self.op == 'chr':
         idc.OpChr(self.ea, self.n)
     if self.op == 'oct':
         idc.OpOctal(self.ea, self.n)
     if self.op == 'enum':
         id = idaapi.get_enum(self.extra['ename'].encode('utf-8'))
         idc.OpEnumEx(self.ea, self.n, id, self.extra['serial'])
Exemplo n.º 11
0
    def get_size(name, type, line):
        if type == "BasicType":
            try:
                return idc.SizeOf(idc.parse_decl(str(name), 0)[1])
            except:
                try:
                    idc.SizeOf(
                        idc.parse_decl(str(line.get("type").get("name")),
                                       0)[1])
                except:
                    return 1

        elif type == "ArrayType":
            subType = line.get("type")
            if not subType:
                return line.get("size")
            typeSize = IDAtools.get_size(str(subType.get("name")),
                                         subType.get("table"), subType)
            try:
                return (typeSize * int(line.get("size")))
            except TypeError:
                return 1
        elif type == "PointerType" or type == "ReferenceType" or type == "QualifierType":
            return 4
        elif type == "CFunctionType" or type == "CPPFunctionType":
            return 4
        elif type == "PDOMCEnumeration" or type == "PDOMCPPEnumeration":
            return idaapi.get_enum_size(idaapi.get_enum(str(name)))
        elif type == "PDOMCStructure" or type == "PDOMCPPClassType":
            return idaapi.get_struc_size(idaapi.get_struc_id(str(name)))
        elif type == "PDOMCTypedef" or type == "PDOMCPPTypedef":
            subType = line.get("type")
            if not subType:
                return 1
            return IDAtools.get_size(subType.get("name"), subType.get("table"),
                                     subType)
        else:
            raise Exception("Missing case", type)
Exemplo n.º 12
0
def by_name(name):
    '''Return the identifier for the enumeration with the given `name`.'''
    res = idaapi.get_enum(utils.string.to(name))
    if res == idaapi.BADADDR:
        raise E.EnumerationNotFoundError(u"{:s}.by_name({!r}) : Unable to locate enumeration by the name \"{:s}\".".format(__name__, name, utils.string.escape(name, '"')))
    return res
Exemplo n.º 13
0
 def __call__(self):
     ida_enum.set_enum_bf(idaapi.get_enum(self.ename.encode('utf-8')),
                          self.bf_flag)
Exemplo n.º 14
0
 def __call__(self):
     idaapi.add_enum_member(idaapi.get_enum(self.ename.encode('utf-8')),
                            self.name.encode('utf-8'), self.value,
                            self.bmask)
Exemplo n.º 15
0
def _get_enum(name):
    """Get an existing enum ID"""
    eid = idaapi.get_enum(name)
    if eid == idaapi.BADADDR:
        raise exceptions.EnumNotFound('Enum "{}" does not exist.'.format(name))
    return eid
Exemplo n.º 16
0
 def __call__(self):
     idaapi.del_enum_member(idaapi.get_enum(self.ename.encode('utf-8')),
                            self.value, self.serial, self.bmask)
Exemplo n.º 17
0
def byName(name):
    '''Return an enum id by it's /name/'''
    res = idaapi.get_enum(name)
    if res == idaapi.BADADDR:
        raise Exception, "enum.byName(%r):unable to locate enumeration"% name
    return res
Exemplo n.º 18
0
 def __call__(self):
     idc.del_enum(idaapi.get_enum(self.ename.encode('utf-8')))