Esempio n. 1
0
 def add_fast_dict_from_all_vuln_func(self):
     mgr_t = FESinkFuncMgr()
     for func_name, xref_list in mgr_t.gen_sink_func_xref():
         if not func_name in self.vuln_func_fast_dict:
             tag = SINK_FUNC[func_name]['tag']
             print('func_name: ', func_name)
             print('xref_list: ', len(xref_list))
             if tag == FUNC_TAG['PRINTF']:
                 items = printf_func_analysis(func_name, xref_list)
                 self.add_fast_dict_from_items(items)
             elif tag == FUNC_TAG['STRING']:
                 items = str_func_analysis(func_name, xref_list)
                 self.add_fast_dict_from_items(items)
             elif tag == FUNC_TAG['SCANF']:
                 items = scanf_func_analysis(func_name, xref_list)
                 self.add_fast_dict_from_items(items)
             elif tag == FUNC_TAG['SYSTEM']:
                 items = system_func_analysis(func_name, xref_list)
                 self.add_fast_dict_from_items(items)
             elif tag == FUNC_TAG['MEMORY']:
                 items = mem_func_analysis(func_name, xref_list)
                 self.add_fast_dict_from_items(items)
             else:
                 FELogger.info("未支持函数%s" % func_name)
         else:
             continue
Esempio n. 2
0
    def btn_del_all_vuln_bpt(self, code=0):
        """删除断点 所有危险函数漏洞地址"""
        for xref_addr_t in reduce(lambda x, y: x + y,
                                  self.vuln_func_fast_dict.values()):
            ida_dbg.del_bpt(xref_addr_t)

        FELogger.info('已删除断点:危险函数漏洞分析(全部)')
Esempio n. 3
0
    def add_or_del_one_xref_bpt(self, is_add):
        if is_add == True:
            action = idc.add_bpt
            act_info = '添加'
        else:
            action = idc.del_bpt
            act_info = '删除'

        tgt_t = ida_kernwin.ask_str('', 0, '请输入危险函数名')
        if tgt_t in SINK_FUNC:
            if not tgt_t in self.sink_func_xref_dict:
                mgr_t = FESinkFuncMgr()
                xref_list = mgr_t.get_one_func_xref(tgt_t)

                if not xref_list:
                    FELogger.warn("未找到函数%s" % tgt_t)
                    return

                tmp_list = []
                for xref_addr in xref_list:
                    tmp_list.append(xref_addr)
                    action(xref_addr)
                self.sink_func_xref_dict[tgt_t] = tmp_list
            else:
                for xref_addr_t in self.sink_func_xref_dict[tgt_t]:
                    action(xref_addr_t)
            FELogger.info("已%s断点:危险函数调用地址(%s)" % (act_info, tgt_t))
        else:
            FELogger.warn("未支持函数")
Esempio n. 4
0
    def btn_add_all_vuln_bpt(self, code=0):
        """添加断点 所有危险函数漏洞地址"""
        self.add_fast_dict_from_all_vuln_func()

        for xref_addr_t in reduce(lambda x, y: x + y,
                                  self.vuln_func_fast_dict.values()):
            ida_dbg.add_bpt(xref_addr_t, 0, idc.BPT_DEFAULT)

        FELogger.info('已添加断点:危险函数漏洞分析(全部)')
Esempio n. 5
0
 def trace_next(self, blk, node, reg):
     """
     下一轮回溯
     """
     for ref_addr in self.get_all_ref(blk.start_ea):
         block = self.get_blk(ref_addr)
         if block:
             FELogger.info("基本块跳转\t"+hexstr(ref_addr)+"\t"+idc.generate_disasm_line(ref_addr, 0))
             node_t = self.create_tree_node(ref_addr, prev=node)
             self.dfs(node_t, reg, block)
Esempio n. 6
0
 def btn_del_one_vuln_bpt(self, code=0):
     """删除断点 某个危险函数漏洞地址"""
     tgt_t = ida_kernwin.ask_str('', 0, '请输入危险函数名')
     if tgt_t in SINK_FUNC:
         if tgt_t in self.vuln_func_fast_dict:
             for xref_addr_t in self.vuln_func_fast_dict[tgt_t]:
                 ida_dbg.del_bpt(xref_addr_t)
         FELogger.info("已删除断点:危险函数漏洞分析(%s)" % tgt_t)
     else:
         FELogger.warn("未支持函数")
Esempio n. 7
0
 def btn_del_tmp_func_bpt(self, code=0):
     """删除临时函数断点"""
     tgt_t = ida_kernwin.ask_str('', 0, '请输入任意函数名')
     try:
         if tgt_t in self.tmp_func_dict:
             for xref_addr_t in self.tmp_func_dict[tgt_t]:
                 ida_dbg.del_bpt(xref_addr_t)
             CUSTOM_FUNC.pop(tgt_t)
         FELogger.info("已删除断点:指定函数调用地址 %s" % tgt_t)
     except Exception:
         FELogger.warn("请输入函数名")
Esempio n. 8
0
    def add_tmp_func(self, info_only=False):
        """
        添加临时sink函数
        info_only: 在添加函数信息的同时是否添加断点
        """

        input_str = ida_kernwin.ask_text(
            0, '',
            "请输入任意函数名/函数地址,及各参数类型(none, int, str),可输入多行\n例如:\nstrcmp str str")
        try:
            rules = [x.strip() for x in input_str.strip().split('\n')]
            for rule in rules:
                tgt_t = rule.split(' ')[0].strip()
                args_rule = [x.strip() for x in rule.split(' ')[1:]]

                if not tgt_t in self.tmp_func_dict:
                    if tgt_t.startswith('0x'):
                        addr_t = int(tgt_t, 16)
                        addr_hexstr = hexstr(addr_t)
                        CUSTOM_FUNC[addr_hexstr] = {'args_rule': args_rule}
                        self.tmp_func_dict[addr_hexstr] = [addr_t]
                        if info_only == False:
                            ida_dbg.add_bpt(addr_t, 0, idc.BPT_DEFAULT)
                    else:
                        for func_addr_t in idautils.Functions():
                            func_name_t = ida_funcs.get_func_name(func_addr_t)
                            if func_name_t == tgt_t:
                                CUSTOM_FUNC[func_name_t] = {
                                    'args_rule': args_rule
                                }
                                self.tmp_func_dict[func_name_t] = []
                                for xref_addr_t in idautils.CodeRefsTo(
                                        func_addr_t, 0):
                                    self.tmp_func_dict[func_name_t].append(
                                        xref_addr_t)
                                    if info_only == False:
                                        ida_dbg.add_bpt(
                                            xref_addr_t, 0, idc.BPT_DEFAULT)
                                    else:
                                        continue
                                break
                            else:
                                continue
                else:
                    CUSTOM_FUNC[tgt_t] = {'args_rule': args_rule}
                    for xref_addr_t in self.tmp_func_dict[tgt_t]:
                        if info_only == False:
                            ida_dbg.add_bpt(xref_addr_t, 0, idc.BPT_DEFAULT)
                        else:
                            continue
                FELogger.info("已添加断点:%s" % rule)
        except Exception as e:
            FELogger.info("输入信息有误:%s" % e)
Esempio n. 9
0
 def get_all_bpt_list(self):
     """
     获取所有断点的地址列表
     """
     bpt_list = []
     bpt_num = ida_dbg.get_bpt_qty()
     bpt_t = ida_dbg.bpt_t()
     for i in range(bpt_num):
         if ida_dbg.getn_bpt(i, bpt_t) == True:
             bpt_list.append(bpt_t.ea)
         else:
             FELogger.info("获取断点失败 %d" % i)
     return bpt_list
Esempio n. 10
0
    def activate(self, ctx):
        if self.get_xdbg_hook_status():
            FELogger.info('关闭调试事件记录')
            self.dbg_hook.unhook()
        else:
            FELogger.info('启用调试事件记录')

            if ida_kernwin.ask_yn(0, '是否单步调试?') == 1:
                self.dbg_hook.step_dbg = True
            else:
                self.dbg_hook.step_dbg = False
            self.dbg_hook.hook()

        self.set_xdbg_hook_status()
Esempio n. 11
0
def system_func_analysis(func_name, xref_list):
    """
    system系列函数漏洞分析    
    """

    vuln_flag = 0
    addr1 = 0
    str1 = ''

    func_name_t = func_name
    xref_list_t = xref_list
    items = []
    vuln_rule = SINK_FUNC[func_name_t]['vuln_rule']
    vuln_reg = vuln_rule[0]['vuln_regs'][0]

    FELogger.info('检测%s漏洞' % vuln_rule[0]['vuln_type'])
    for xref_addr_t in xref_list_t:
        FELogger.info("从%s回溯来源地址%s" % (hexstr(xref_addr_t), vuln_reg))
        tracer = FEArgsTracer(xref_addr_t, vuln_reg)
        source_addr = tracer.run()
        print('source_addr: ', source_addr)
        # 判断是否找到目标地址
        if source_addr == []:
            FELogger.info("目标地址未找到%s" % hexstr(xref_addr_t))
            vuln_flag = 1
        else:
            for cmd_addr in source_addr:
                addr1 = cmd_addr
                # 判断字符串是否来自内存
                if idc.get_operand_type(cmd_addr, 1) == ida_ua.o_mem:
                    cmd_str = FEStrMgr.get_mem_string(cmd_addr)
                    # 判断是否找到字符串
                    if cmd_str == []:
                        FELogger.info("硬编码命令未找到%s" % hexstr(xref_addr_t))
                        vuln_flag = 1
                    else:
                        vuln_flag = 0
                        str1 = cmd_str[0]
                else:
                    FELogger.info("命令来自外部%s" % hexstr(xref_addr_t))
                    vuln_flag = 1

        data = AnalysisChooseData(vuln=vuln_flag,
                                  name=func_name_t,
                                  ea=xref_addr_t,
                                  addr1=addr1,
                                  str1=str1)
        items.append(data)
    return items
Esempio n. 12
0
    def btn_dfs_test_1(self, code=0):
        addr_t = ida_kernwin.ask_str('', 0, '请输入回溯起点地址')
        reg_t = ida_kernwin.ask_str('', 0, '请输入回溯寄存器')
        if (addr_t and addr_t != '') and (reg_t and reg_t != ''):
            try:
                addr_t = int(addr_t, 16)
            except Exception:
                FELogger.warn("无效地址")
                return

            FELogger.info("从地址%s回溯寄存器%s" % (hexstr(addr_t), reg_t))
            tracer = FEArgsTracer(addr_t, reg_t)
            source_addr = tracer.run()
            print('source_addr: ', source_addr)
        else:
            FELogger.warn("请输入起点地址和寄存器")
Esempio n. 13
0
    def btn_import_all_bpt_addr(self, code=0):
        """
        导入离线断点
        """
        cur_workpath = os.getcwd()
        csv_filepath = os.path.join(
            cur_workpath, '%s_bpt.csv' % ida_nalt.get_root_filename())

        if os.path.exists(csv_filepath):
            with open(csv_filepath, 'r') as f:
                next(f)
                reader = csv.reader(f)
                for row in reader:
                    ida_dbg.add_bpt(int(row[0], 16), 0, idc.BPT_DEFAULT)
            FELogger.info("导入断点完成:%s" % csv_filepath)
        else:
            FELogger.warn("文件不存在:%s" % csv_filepath)
Esempio n. 14
0
        def do_export():
            st = ida_auto.set_ida_state(idc.IDA_STATUS_WORK)
            xml = XmlExporter(1)

            try:
                try:
                    xml.export_xml()
                    FELogger.info("已导出IDA数据到XML")
                except Cancelled:
                    ida_kernwin.hide_wait_box()
                    FELogger.warn("已取消XML导出")
                except Exception as e:
                    ida_kernwin.hide_wait_box()
                    FELogger.warn("导出XML失败 %s" % e)
            finally:
                xml.cleanup()
                ida_auto.set_ida_state(st)
Esempio n. 15
0
    def btn_export_all_bpt_addr(self, code=0):
        """
        导出离线断点
        """
        cur_workpath = os.getcwd()
        csv_filepath = os.path.join(
            cur_workpath, '%s_bpt.csv' % ida_nalt.get_root_filename())

        bpt_list = self.get_all_bpt_list()
        bpt_list = [[format(bpt, '#010x')[2:]] for bpt in bpt_list]

        header = ['breakpoints']
        with open(csv_filepath, 'w', newline='') as f:
            ff = csv.writer(f)
            ff.writerow(header)
            ff.writerows(bpt_list)

        FELogger.info("导出断点完成:%s" % csv_filepath)
Esempio n. 16
0
 def dfs(self, node, reg, blk):
     """深度优先搜索
     node: 当前节点
     reg: 回溯寄存器
     blk: 当前基本块
     """
     blk_t = blk
     if self.get_node_nums() < self.max_node:    # 避免路径爆炸
         if self.push_cache_node(node['addr'], reg): # 避免重复,加快速度
             cur_t, reg_t = self.trace_block(blk_t, node, reg)
             if reg_t:
                 # 如果返回一个新的寄存器,开启下一轮回溯
                 self.trace_next(blk_t, node, reg_t)
             else:
                 self.cache['addr'].add(cur_t)
         else:
             FELogger.info("该块已经回溯,取消操作")
     else:
         FELogger.info("超出最大回溯块数量")
Esempio n. 17
0
 def btn_dfs_test_2(self, code=0):
     tgt_t = ida_kernwin.ask_str('', 0, '请输入函数名')
     reg_t = ida_kernwin.ask_str('', 0, '请输入回溯寄存器')
     if (tgt_t and tgt_t != '') and (reg_t and reg_t != ''):
         for func_addr_t in idautils.Functions():
             func_name_t = ida_funcs.get_func_name(func_addr_t)
             if func_name_t == tgt_t:
                 for xref_addr_t in idautils.CodeRefsTo(func_addr_t, 0):
                     if ida_funcs.get_func(xref_addr_t):
                         FELogger.info("从地址%s回溯寄存器%s" %
                                       (hexstr(xref_addr_t), reg_t))
                         tracer = FEArgsTracer(xref_addr_t,
                                               reg_t,
                                               max_node=256)
                         source_addr = tracer.run()
                         print('source_addr: ', source_addr)
                 break
         else:
             FELogger.warn("请输入函数名和寄存器")
Esempio n. 18
0
    def add_or_del_all_xref_bpt(self, is_add):
        if is_add == True:
            action = idc.add_bpt
            act_info = '添加'
        else:
            action = idc.del_bpt
            act_info = '删除'

        if self.sink_func_xref_dict == {}:
            mgr_t = FESinkFuncMgr()
            for func_name, xref_list in mgr_t.gen_sink_func_xref():
                tmp_list = []
                for xref_addr_t in xref_list:
                    tmp_list.append(xref_addr_t)
                    action(xref_addr_t)
                self.sink_func_xref_dict[func_name] = tmp_list
        else:
            for xref_addr_t in reduce(lambda x, y: x + y,
                                      self.sink_func_xref_dict.values()):
                action(xref_addr_t)
        FELogger.info('已%s断点:危险函数调用地址(全部)' % act_info)
Esempio n. 19
0
    def btn_imp_ghidra_funcs(self, code=0):
        """
        导入Ghidra函数列表
        """
        ghidra_filepath = os.path.join(os.getcwd(), 'ghidra_func_addrs.csv')
        ghidra_path = ida_kernwin.ask_str(ghidra_filepath, 0,
                                          '导入的Ghidra导出函数文件路径')

        func_addrs = list(idautils.Functions())
        make_func_addrs = []
        if ghidra_path and ghidra_path != '':
            if os.path.exists(ghidra_path):
                with open(ghidra_path, 'rb') as f:
                    next(f)
                    reader = csv.reader(f)
                    for row in reader:
                        addr = int(row[0].strip('\"'), 16)
                        if ida_funcs.add_func(addr) == True:
                            make_func_addrs.append(addr)
                        else:
                            if addr not in func_addrs:
                                FELogger.info("创建函数%s失败" % hexstr(addr))
                FELogger.info("Ghidra导出函数文件:%s,已导入" % ghidra_path)
            else:
                FELogger.erro("未找到Ghidra导出函数文件:%s" % ghidra_path)
        else:
            FELogger.warn("请输入Ghidra导出函数文件路径")

        FELogger.info("成功创建%d个新函数" % len(make_func_addrs))
Esempio n. 20
0
    def btn_add_one_vuln_bpt(self, code=0):
        """添加断点 某个危险函数漏洞地址"""
        tgt_t = ida_kernwin.ask_str('', 0, '请输入危险函数名')
        if tgt_t in SINK_FUNC:
            if not tgt_t in self.vuln_func_fast_dict:
                mgr_t = FESinkFuncMgr()
                xref_list = mgr_t.get_one_func_xref(tgt_t)
                tag = SINK_FUNC[tgt_t]['tag']

                if not xref_list:
                    FELogger.warn("未找到函数%s" % tgt_t)
                    return

                if tag == FUNC_TAG['PRINTF']:
                    items = printf_func_analysis(tgt_t, xref_list)
                    self.add_fast_dict_from_items(items)
                elif tag == FUNC_TAG['STRING']:
                    items = str_func_analysis(tgt_t, xref_list)
                    self.add_fast_dict_from_items(items)
                elif tag == FUNC_TAG['SCANF']:
                    items = scanf_func_analysis(tgt_t, xref_list)
                    self.add_fast_dict_from_items(items)
                elif tag == FUNC_TAG['SYSTEM']:
                    items = system_func_analysis(tgt_t, xref_list)
                    self.add_fast_dict_from_items(items)
                elif tag == FUNC_TAG['MEMORY']:
                    items = mem_func_analysis(tgt_t, xref_list)
                    self.add_fast_dict_from_items(items)
                else:
                    FELogger.info("未支持函数%s" % tgt_t)

            if tgt_t in self.vuln_func_fast_dict:
                for xref_addr_t in self.vuln_func_fast_dict[tgt_t]:
                    ida_dbg.add_bpt(xref_addr_t, 0, idc.BPT_DEFAULT)

            FELogger.info('已添加断点:危险函数漏洞分析(%s)' % tgt_t)
        else:
            FELogger.warn("未支持函数")
Esempio n. 21
0
    def check_src_reg(xref_addr_t, src_reg, siz_addr_t=0):
        vuln_flag = 0
        addr1 = 0
        str1 = ''

        if siz_addr_t == 0:
            str_siz_addr = ''
        else:
            str_siz_addr = hexstr(siz_addr_t)

        FELogger.info("从%s回溯来源地址%s" % (hexstr(xref_addr_t), src_reg))
        src_tracer = FEArgsTracer(xref_addr_t, src_reg)
        src_source_addr = src_tracer.run()
        print('src_source_addr: ', src_source_addr)
        # 判断是否找到字符串来源地址
        if src_source_addr == []:
            FELogger.info("未找到目标地址%s" % hexstr(xref_addr_t))
            vuln_flag = 1
        else:
            for src_addr in src_source_addr:
                addr1 = src_addr
                src_str = FEStrMgr.get_mem_string(src_addr)
                # 判断是否找到字符串
                if src_str == []:
                    FELogger.info('来源字符串未找到%s' % hexstr(xref_addr_t))
                    vuln_flag = 1
                else:
                    # 判断来源地址是否为内存
                    str1 = src_str[0]
                    if idc.get_operand_type(src_addr, 1) != ida_ua.o_mem:
                        vuln_flag = 1
                    else:
                        vuln_flag = 0

        data = AnalysisChooseData(vuln=vuln_flag,
                                  name=func_name_t,
                                  ea=xref_addr_t,
                                  addr1=addr1,
                                  str1=str1,
                                  other1=str_siz_addr)
        items.append(data)
Esempio n. 22
0
def str_func_analysis(func_name, xref_list):
    """
    str操作类函数漏洞分析
    """
    def check_src_reg(xref_addr_t, src_reg, siz_addr_t=0):
        vuln_flag = 0
        addr1 = 0
        str1 = ''

        if siz_addr_t == 0:
            str_siz_addr = ''
        else:
            str_siz_addr = hexstr(siz_addr_t)

        FELogger.info("从%s回溯来源地址%s" % (hexstr(xref_addr_t), src_reg))
        src_tracer = FEArgsTracer(xref_addr_t, src_reg)
        src_source_addr = src_tracer.run()
        print('src_source_addr: ', src_source_addr)
        # 判断是否找到字符串来源地址
        if src_source_addr == []:
            FELogger.info("未找到目标地址%s" % hexstr(xref_addr_t))
            vuln_flag = 1
        else:
            for src_addr in src_source_addr:
                addr1 = src_addr
                src_str = FEStrMgr.get_mem_string(src_addr)
                # 判断是否找到字符串
                if src_str == []:
                    FELogger.info('来源字符串未找到%s' % hexstr(xref_addr_t))
                    vuln_flag = 1
                else:
                    # 判断来源地址是否为内存
                    str1 = src_str[0]
                    if idc.get_operand_type(src_addr, 1) != ida_ua.o_mem:
                        vuln_flag = 1
                    else:
                        vuln_flag = 0

        data = AnalysisChooseData(vuln=vuln_flag,
                                  name=func_name_t,
                                  ea=xref_addr_t,
                                  addr1=addr1,
                                  str1=str1,
                                  other1=str_siz_addr)
        items.append(data)

    func_name_t = func_name
    xref_list_t = xref_list
    items = []
    vuln_rule = SINK_FUNC[func_name_t]['vuln_rule']
    vuln_regs = vuln_rule[0]['vuln_regs']
    src_reg = vuln_regs[0]
    siz_reg = None
    if len(vuln_regs) == 2:
        siz_reg = vuln_regs[1]

    FELogger.info('检测%s漏洞' % vuln_rule[0]['vuln_type'])
    for xref_addr_t in xref_list_t:
        # 判断是否有size参数
        if siz_reg != None:
            FELogger.info("从%s回溯字符串长度%s" % (hexstr(xref_addr_t), siz_reg))
            siz_tracer = FEArgsTracer(xref_addr_t, siz_reg, max_node=256)
            siz_source_addr = siz_tracer.run()
            print('siz_source_addr: ', siz_source_addr)
            # 判断是否找到size的地址
            if siz_source_addr == []:
                FELogger.info("未找到size地址%s" % hexstr(xref_addr_t))
                data = AnalysisChooseData(vuln=1,
                                          name=func_name_t,
                                          ea=xref_addr_t)
                items.append(data)
            else:
                for siz_addr_t in siz_source_addr:
                    # 判断size是否为立即数
                    if idc.get_operand_type(siz_addr_t, 1) != ida_ua.o_imm:
                        check_src_reg(xref_addr_t, src_reg, siz_addr_t)
                    else:
                        num = idc.print_operand(siz_addr_t, 1)
                        data = AnalysisChooseData(vuln=0,
                                                  name=func_name_t,
                                                  ea=xref_addr_t,
                                                  addr1=siz_addr_t,
                                                  str1='',
                                                  other1=num)
                        items.append(data)
        else:
            check_src_reg(xref_addr_t, src_reg)
    return items
Esempio n. 23
0
    def check_fmt_reg(xref_addr_t,
                      fmt_reg,
                      vuln_regs,
                      siz_addr_t=0,
                      parse=False):
        vuln_flag = 0
        addr1 = 0
        str1 = ''

        if siz_addr_t == 0:
            str_siz_addr = ''
        else:
            str_siz_addr = hexstr(siz_addr_t)

        FELogger.info("从%s回溯格式字符串%s" % (hexstr(xref_addr_t), fmt_reg))
        tracer = FEArgsTracer(xref_addr_t, fmt_reg)
        source_addr = tracer.run()
        print('source_addr: ', source_addr)
        # 判断是否找到字符串来源地址
        if source_addr == []:
            FELogger.info("未找到目标地址%s" % hexstr(xref_addr_t))
            vuln_flag = 1
        else:
            for fmt_addr in source_addr:
                addr1 = fmt_addr
                fmt_str = FEStrMgr.get_mem_string(fmt_addr)
                # 判断是否找到字符串
                if fmt_str == []:
                    FELogger.info('格式字符串未找到%s' % hexstr(xref_addr_t))
                    vuln_flag = 1
                    str1 = ''
                else:
                    FELogger.info('找到格式字符串%s' % hexstr(xref_addr_t))
                    str1 = fmt_str[0]
                    if parse == False:
                        vuln_flag = 0
                    else:
                        fmt_list = FEStrMgr.parse_format_string(str1)
                        # 判断字符串中的格式字符
                        if fmt_list != [] and 's' in ''.join(fmt_list):
                            if vuln_regs[-1] == '...':
                                args_num = len(fmt_list) + len(vuln_regs) - 1
                                if args_num > 4:
                                    fmt_list = fmt_list[:(
                                        4 - (len(vuln_regs) - 1))]

                                for idx in range(len(fmt_list)):
                                    if 's' in fmt_list[idx]:
                                        str_reg = 'R%s' % (len(vuln_regs) - 1 +
                                                           idx)
                                        FELogger.info(
                                            "从%s回溯字符串%s" %
                                            (hexstr(xref_addr_t), str_reg))
                                        str_tracer = FEArgsTracer(xref_addr_t,
                                                                  str_reg,
                                                                  max_node=256)
                                        str_source_addr = str_tracer.run()
                                        print('str_source_addr: ',
                                              str_source_addr)
                                        if str_source_addr == []:
                                            FELogger.info("未找到%s字符串地址" %
                                                          str_reg)
                                            vuln_flag = 1
                                            break
                                        else:
                                            for str_addr in str_source_addr:
                                                if idc.get_operand_type(
                                                        str_addr,
                                                        1) == ida_ua.o_mem:
                                                    vuln_flag = 0
                                                else:
                                                    vuln_flag = 1
                                                    break
                                    else:
                                        continue
                            else:
                                vuln_flag = 1
                        else:
                            FELogger.info("格式字符串不包含s转换符号")
                            vuln_flag = 0

        data = AnalysisChooseData(vuln=vuln_flag,
                                  name=func_name_t,
                                  ea=xref_addr_t,
                                  addr1=addr1,
                                  str1=str1,
                                  other1=str_siz_addr)
        items.append(data)
Esempio n. 24
0
def printf_func_analysis(func_name, xref_list):
    """
    printf系列函数漏洞分析
    """
    def check_fmt_reg(xref_addr_t,
                      fmt_reg,
                      vuln_regs,
                      siz_addr_t=0,
                      parse=False):
        vuln_flag = 0
        addr1 = 0
        str1 = ''

        if siz_addr_t == 0:
            str_siz_addr = ''
        else:
            str_siz_addr = hexstr(siz_addr_t)

        FELogger.info("从%s回溯格式字符串%s" % (hexstr(xref_addr_t), fmt_reg))
        tracer = FEArgsTracer(xref_addr_t, fmt_reg)
        source_addr = tracer.run()
        print('source_addr: ', source_addr)
        # 判断是否找到字符串来源地址
        if source_addr == []:
            FELogger.info("未找到目标地址%s" % hexstr(xref_addr_t))
            vuln_flag = 1
        else:
            for fmt_addr in source_addr:
                addr1 = fmt_addr
                fmt_str = FEStrMgr.get_mem_string(fmt_addr)
                # 判断是否找到字符串
                if fmt_str == []:
                    FELogger.info('格式字符串未找到%s' % hexstr(xref_addr_t))
                    vuln_flag = 1
                    str1 = ''
                else:
                    FELogger.info('找到格式字符串%s' % hexstr(xref_addr_t))
                    str1 = fmt_str[0]
                    if parse == False:
                        vuln_flag = 0
                    else:
                        fmt_list = FEStrMgr.parse_format_string(str1)
                        # 判断字符串中的格式字符
                        if fmt_list != [] and 's' in ''.join(fmt_list):
                            if vuln_regs[-1] == '...':
                                args_num = len(fmt_list) + len(vuln_regs) - 1
                                if args_num > 4:
                                    fmt_list = fmt_list[:(
                                        4 - (len(vuln_regs) - 1))]

                                for idx in range(len(fmt_list)):
                                    if 's' in fmt_list[idx]:
                                        str_reg = 'R%s' % (len(vuln_regs) - 1 +
                                                           idx)
                                        FELogger.info(
                                            "从%s回溯字符串%s" %
                                            (hexstr(xref_addr_t), str_reg))
                                        str_tracer = FEArgsTracer(xref_addr_t,
                                                                  str_reg,
                                                                  max_node=256)
                                        str_source_addr = str_tracer.run()
                                        print('str_source_addr: ',
                                              str_source_addr)
                                        if str_source_addr == []:
                                            FELogger.info("未找到%s字符串地址" %
                                                          str_reg)
                                            vuln_flag = 1
                                            break
                                        else:
                                            for str_addr in str_source_addr:
                                                if idc.get_operand_type(
                                                        str_addr,
                                                        1) == ida_ua.o_mem:
                                                    vuln_flag = 0
                                                else:
                                                    vuln_flag = 1
                                                    break
                                    else:
                                        continue
                            else:
                                vuln_flag = 1
                        else:
                            FELogger.info("格式字符串不包含s转换符号")
                            vuln_flag = 0

        data = AnalysisChooseData(vuln=vuln_flag,
                                  name=func_name_t,
                                  ea=xref_addr_t,
                                  addr1=addr1,
                                  str1=str1,
                                  other1=str_siz_addr)
        items.append(data)

    func_name_t = func_name
    xref_list_t = xref_list
    items = []
    vuln_rule = SINK_FUNC[func_name_t]['vuln_rule']
    args_rule = SINK_FUNC[func_name_t]['args_rule']
    for xref_addr_t in xref_list_t:
        for rule in vuln_rule:
            FELogger.info('检测%s漏洞' % rule['vuln_type'])

            if rule['vuln_type'] == 'format_string':
                fmt_reg = rule['vuln_regs'][0]
                check_fmt_reg(xref_addr_t, fmt_reg, args_rule, parse=False)
            else:
                vuln_regs = rule['vuln_regs']
                if vuln_regs[-1] == '...':
                    fmt_reg = vuln_regs[-2]
                    if len(vuln_regs) == 3:
                        siz_reg = vuln_regs[0]
                    else:
                        siz_reg = None
                else:
                    fmt_reg = vuln_regs[-1]
                    if len(vuln_regs) == 2:
                        siz_reg = vuln_regs[0]
                    else:
                        siz_reg = None

                # 判断是否有size参数
                if siz_reg != None:
                    FELogger.info("从%s回溯字符串长度%s" %
                                  (hexstr(xref_addr_t), siz_reg))
                    siz_tracer = FEArgsTracer(xref_addr_t,
                                              siz_reg,
                                              max_node=256)
                    siz_source_addr = siz_tracer.run()
                    print('siz_source_addr: ', siz_source_addr)
                    # 判断是否找到size的地址
                    if siz_source_addr == []:
                        FELogger.info("未找到size地址%s" % hexstr(xref_addr_t))
                        check_fmt_reg(xref_addr_t,
                                      fmt_reg,
                                      args_rule,
                                      parse=True)
                    else:
                        for siz_addr_t in siz_source_addr:
                            # 判断size是否为立即数
                            if idc.get_operand_type(siz_addr_t,
                                                    1) != ida_ua.o_imm:
                                check_fmt_reg(xref_addr_t,
                                              fmt_reg,
                                              args_rule,
                                              siz_addr_t,
                                              parse=True)
                            else:
                                num = idc.print_operand(siz_addr_t, 1)
                                data = AnalysisChooseData(vuln=0,
                                                          name=func_name_t,
                                                          ea=xref_addr_t,
                                                          addr1=siz_addr_t,
                                                          str1='',
                                                          other1=num)
                                items.append(data)
                else:
                    check_fmt_reg(xref_addr_t, fmt_reg, args_rule, parse=True)
    return items
Esempio n. 25
0
    def btn_get_one_vuln_func(self, code=0):
        """查看某个危险函数漏洞地址"""
        tgt_t = ida_kernwin.ask_str('', 0, '请输入要查看的危险函数名')
        if tgt_t in SINK_FUNC:
            mgr_t = FESinkFuncMgr()
            xref_list = mgr_t.get_one_func_xref(tgt_t)
            tag = SINK_FUNC[tgt_t]['tag']

            if not xref_list:
                FELogger.warn("未找到函数%s" % tgt_t)
                return

            # printf系列函数
            if tag == FUNC_TAG['PRINTF']:
                items = printf_func_analysis(tgt_t, xref_list)
                self.add_fast_dict_from_items(items)
                cols = [['可疑', 3 | ida_kernwin.Choose.CHCOL_DEC],
                        ['函数名', 10 | ida_kernwin.Choose.CHCOL_PLAIN],
                        ['函数地址', 10 | ida_kernwin.Choose.CHCOL_HEX],
                        ['格式字符串地址', 10 | ida_kernwin.Choose.CHCOL_HEX],
                        ['格式字符串', 15 | ida_kernwin.Choose.CHCOL_PLAIN],
                        ['长度', 10 | ida_kernwin.Choose.CHCOL_HEX]]
                chooser = AnalysisChooser(title='危险函数漏洞分析',
                                          cols=cols,
                                          item=items)
                chooser.Show()

            # str系列函数
            elif tag == FUNC_TAG['STRING']:
                items = str_func_analysis(tgt_t, xref_list)
                self.add_fast_dict_from_items(items)
                cols = [['可疑', 3 | ida_kernwin.Choose.CHCOL_DEC],
                        ['函数名', 10 | ida_kernwin.Choose.CHCOL_PLAIN],
                        ['函数地址', 10 | ida_kernwin.Choose.CHCOL_HEX],
                        ['来源地址', 10 | ida_kernwin.Choose.CHCOL_HEX],
                        ['字符串', 15 | ida_kernwin.Choose.CHCOL_PLAIN],
                        ['字符串长度', 10 | ida_kernwin.Choose.CHCOL_HEX]]
                chooser = AnalysisChooser(title='危险函数漏洞分析',
                                          cols=cols,
                                          item=items)
                chooser.Show()

            # scanf系列函数
            elif tag == FUNC_TAG['SCANF']:
                items = scanf_func_analysis(tgt_t, xref_list)
                self.add_fast_dict_from_items(items)
                cols = [['可疑', 3 | ida_kernwin.Choose.CHCOL_DEC],
                        ['函数名', 10 | ida_kernwin.Choose.CHCOL_PLAIN],
                        ['函数地址', 10 | ida_kernwin.Choose.CHCOL_HEX],
                        ['格式字符串地址', 10 | ida_kernwin.Choose.CHCOL_HEX],
                        ['格式字符串', 15 | ida_kernwin.Choose.CHCOL_PLAIN],
                        ['长度', 10 | ida_kernwin.Choose.CHCOL_HEX]]
                chooser = AnalysisChooser(title='危险函数漏洞分析',
                                          cols=cols,
                                          item=items)
                chooser.Show()

            # system函数
            elif tag == FUNC_TAG['SYSTEM']:
                items = system_func_analysis(tgt_t, xref_list)
                self.add_fast_dict_from_items(items)
                cols = [['可疑', 3 | ida_kernwin.Choose.CHCOL_DEC],
                        ['函数名', 10 | ida_kernwin.Choose.CHCOL_PLAIN],
                        ['函数地址', 10 | ida_kernwin.Choose.CHCOL_HEX],
                        ['来源地址', 10 | ida_kernwin.Choose.CHCOL_HEX],
                        ['命令语句', 15 | ida_kernwin.Choose.CHCOL_PLAIN]]
                chooser = AnalysisChooser(title='危险函数漏洞分析',
                                          cols=cols,
                                          item=items)
                chooser.Show()

            # mem系列函数
            elif tag == FUNC_TAG['MEMORY']:
                items = mem_func_analysis(tgt_t, xref_list)
                self.add_fast_dict_from_items(items)
                cols = [['可疑', 3 | ida_kernwin.Choose.CHCOL_DEC],
                        ['函数名', 10 | ida_kernwin.Choose.CHCOL_PLAIN],
                        ['函数地址', 10 | ida_kernwin.Choose.CHCOL_HEX],
                        ['来源地址', 10 | ida_kernwin.Choose.CHCOL_HEX],
                        ['', 0 | ida_kernwin.Choose.CHCOL_PLAIN],
                        ['字符串长度', 10 | ida_kernwin.Choose.CHCOL_HEX]]
                chooser = AnalysisChooser(title='危险函数漏洞分析',
                                          cols=cols,
                                          item=items)
                chooser.Show()
            else:
                FELogger.info("未支持函数%s" % tgt_t)
        else:
            FELogger.warn("未支持函数")
Esempio n. 26
0
    def get_next_reg(self, addr, reg):
        """
        寻找下一个赋值来源寄存器
        返回寄存器名或None
        """

        reg_t = reg
        addr_t = addr

        mnem = get_mnem(addr_t)
        line = idc.generate_disasm_line(addr_t, 0)
        if mnem.startswith('BLX') and addr_t != self.trace_addr:
            FELogger.info("途径函数\t"+hexstr(addr)+"\t"+line)
            func_name = idc.print_operand(addr_t, 0)
            func_addr = name_to_addr(func_name)
            if func_addr is not None:
                if reg_t == 'R0':
                    does_return = ida_funcs.get_func(func_addr).does_return()
                    if does_return == True:
                        FELogger.info("找到赋值点\t"+hexstr(addr)+"\t"+line)
                        return None
                else:
                    if func_name in SOURCE_FUNC and reg_t == SOURCE_FUNC[func_name]['dest']:
                        reg_t = SOURCE_FUNC[func_name]['src']
                        if reg_t == 'None':
                            FELogger.info("找到赋值点\t"+hexstr(addr)+"\t"+line)
                            return None
                        else:
                            FELogger.info("回溯"+reg_t+"\t"+hexstr(addr)+"\t"+line)

        inst_list_t = INST_LIST
        reg_re = re.compile(reg_t + '\\D|' + reg_t + '\\Z')
        if reg_re.search(line):
            if mnem in reduce(lambda x, y: x + y, [value for value in inst_list_t.values()]):
                op1 = idc.print_operand(addr_t, 0).split("!")[0]
                if mnem in inst_list_t['load_multi']:
                    # 找到      LDM R1, {R0-R3}
                    regs = self.parse_operands(mnem, addr_t)
                    if reg_t not in regs:
                        FELogger.info("回溯"+reg_t+"\t"+hexstr(addr)+"\t"+line)
                    else:
                        FELogger.info("找到赋值点\t"+hexstr(addr)+"\t"+line)
                        return None
                else:
                    if op1 != reg_t or mnem in inst_list_t['other']:
                        FELogger.info("回溯"+reg_t+"\t"+hexstr(addr)+"\t"+line)
                    elif mnem in inst_list_t['arithmetic']:
                        # 停止      ADD R0, SP; ADD R0, SP, #10
                        # 回溯R0    ADD R0, R1; ADD R0, #10
                        # 回溯R1    ADD R0, R1, #10; ADD R0, R1, R2
                        op2_tmp = idc.print_operand(addr_t, 1)
                        if idc.get_operand_type(addr_t, 2) == ida_ua.o_void:
                            if idc.get_operand_type(addr_t, 1) == ida_ua.o_reg:
                                if op2_tmp == 'SP':
                                    FELogger.info("取消回溯SP\t"+hexstr(addr)+"\t"+line)
                                    return None
                                else:
                                    FELogger.info("回溯"+reg_t+"\t"+hexstr(addr)+"\t"+line)
                            else:
                                FELogger.info("回溯"+reg_t+"\t"+hexstr(addr)+"\t"+line)
                        elif idc.get_operand_type(addr_t, 3) == ida_ua.o_void:
                            op3_tmp = idc.print_operand(addr_t, 2)
                            if op2_tmp == 'SP' or op3_tmp == 'SP':
                                FELogger.info("取消回溯SP\t"+hexstr(addr)+"\t"+line)
                                return None
                            elif reg_t == op2_tmp or reg_t == op3_tmp:
                                FELogger.info("复杂运算\t"+hexstr(addr)+"\t"+line)
                                return None
                            else:
                                reg_t = op2_tmp
                                FELogger.info("回溯"+reg_t+"\t"+hexstr(addr)+"\t"+line)
                        else:
                            op3_tmp = idc.print_operand(addr_t, 2)
                            op4_tmp = idc.print_operand(addr_t, 3)
                            if op2_tmp == 'SP' or op3_tmp == 'SP' or op4_tmp == 'SP':
                                FELogger.info("取消回溯SP\t"+hexstr(addr)+"\t"+line)
                                return None
                            elif reg_t == op2_tmp or reg_t == op3_tmp or reg_t == op4_tmp:
                                FELogger.info("复杂运算\t"+hexstr(addr)+"\t"+line)
                                return None
                            else:
                                reg_t = op2_tmp
                                FELogger.info("回溯"+reg_t+"\t"+hexstr(addr)+"\t"+line)
                    elif mnem in inst_list_t['move']:
                        # 停止      MOV R0, SP; MOV R0, SP, #10
                        # 找到      MOV R0, #10
                        # 回溯R1    MOV R0, R1
                        # 回溯D8    VMOV R0, R1, D16
                        if mnem.startswith('VMOV'):
                            op3_tmp = idc.print_operand(addr_t, 2)
                            reg_t = op3_tmp
                            FELogger.info("回溯"+reg_t+"\t"+hexstr(addr)+"\t"+line)
                        else:
                            op2_tmp = idc.print_operand(addr_t, 1)
                            if op2_tmp == 'SP':
                                FELogger.info("取消回溯SP\t"+hexstr(addr)+"\t"+line)
                                return None
                            elif idc.get_operand_type(addr_t, 1) == ida_ua.o_reg:
                                reg_t = op2_tmp
                                FELogger.info("回溯"+reg_t+"\t"+hexstr(addr)+"\t"+line)
                            elif mnem in ['MOVT', 'MOVTGT', 'MOVTLE']:
                                FELogger.info("回溯"+reg_t+"\t"+hexstr(addr)+"\t"+line)
                            else:
                                FELogger.info("找到赋值点\t"+hexstr(addr)+"\t"+line)
                                return None
                    elif mnem in inst_list_t['load']:
                        # 找到      LDR R0, =xxxxxxx
                        # 停止      LDR R0, [SP, #10]
                        # 回溯R1    LDR R0, [R1, #10]
                        # 回溯R0    LDR R0, [R0, R1, #10]
                        if idc.get_operand_type(addr_t, 1) == ida_ua.o_mem:
                            FELogger.info("找到赋值点\t"+hexstr(addr)+"\t"+line)
                            return None
                        else:
                            regs_tmp = self.parse_operands(mnem, addr_t)
                            if 'SP' in regs_tmp:
                                FELogger.info("取消回溯SP\t"+hexstr(addr)+"\t"+line)
                                return None
                            elif reg_t in regs_tmp:
                                FELogger.info("回溯"+reg_t+"\t"+hexstr(addr)+"\t"+line)
                            else:
                                reg_t = regs_tmp[0]
                                FELogger.info("回溯"+reg_t+"\t"+hexstr(addr)+"\t"+line)
                    else:
                        FELogger.info("未知指令\t"+hexstr(addr)+"\t"+line)
            else:
                FELogger.info("未知指令\t"+hexstr(addr)+"\t"+line)
        else:
            pass

        return reg_t
Esempio n. 27
0
 def btn_checksec(self, code=0):
     """
     ELF Checksec
     """
     elfpath = ida_nalt.get_input_file_path()
     if os.path.exists(elfpath):
         result = Checksec(elfpath)
         FELogger.info("-" * 10 + "Checksec" + "-" * 10 + elfpath +
                       "-" * 10)
         FELogger.info(result.sec)
     else:
         input_path = ida_kernwin.ask_str(elfpath, 0, "请输入原始Binary路径")
         if input_path and input_path != "":
             if os.path.exists(input_path):
                 result = Checksec(input_path)
                 FELogger.info("-" * 10 + "Checksec" + "-" * 10 +
                               input_path + "-" * 10)
                 FELogger.info(result.sec)
             else:
                 FELogger.info("原始Binary不存在:%s" % input_path)
         else:
             FELogger.info("原始Binary不存在:%s" % elfpath)