Пример #1
0
 def exec(self, func_name, *args):
     print(utils.titlify('help'))
     print(
         utils.green_bold('usage: ') +
         self.command_map['executors']['usage'])
     r = []
     for key, value in self.executors_map.items():
         id = value['id']
         cmd_count = str(len(value['cmd_list']))
         r.append([str(id), key, cmd_count])
     h = [
         utils.white_bold_underline('id'),
         utils.white_bold_underline('name'),
         utils.white_bold_underline('commands')
     ]
     print(utils.titlify('executors'))
     print(tabulate(r, h, tablefmt="simple"))
Пример #2
0
    def resume_emulation(self, address=None, skip_bp=0):
        if address is not None:
            self.current_address = address

        self.skip_bp_count = skip_bp

        if self.exit_point is not None:
            print(
                utils.white_bold("emulation") + " started at " +
                utils.green_bold(hex(self.current_address)))

            if len(self.entry_context) == 0:
                # store the initial memory context for the restart
                self.entry_context = {'memory': {}, 'regs': {}}
                map_list = self.get_module('mappings_module').get_mappings()
                for map in map_list:
                    map_address = int(map[1], 16)
                    map_len = map[2]
                    self.entry_context['memory'][map_address] = bytes(
                        self.emu_instance.mem_read(map_address, map_len))
                # registers
                const = utils.get_arch_consts(self.arch)
                regs = [
                    k for k, v in const.__dict__.items()
                    if not k.startswith("__") and "_REG_" in k
                    and not "INVALID" in k
                ]
                for r in regs:
                    try:
                        self.entry_context['regs'][
                            r] = self.emu_instance.reg_read(getattr(const, r))
                    except Exception as ex:
                        pass
                        # print("Ignoring reg: {} ({})".format(r, ex)) -> Ignored UC_X86_REG_MSR

            start_addr = self.current_address
            if self.is_thumb:
                start_addr = start_addr | 1
            self.emu_instance.emu_start(start_addr, self.exit_point)
        else:
            print(
                'please use \'set exit_point *offset\' to define an exit point'
            )
Пример #3
0
 def new_exec(self, func_name, *args):
     key = input('executor name: ')
     id = len(self.executors_id_map)
     print('creating executor ' + utils.green_bold(str(id)) + '. add 1 command per line. type "end" to save')
     cmd_arr = []
     while True:
         p = input('')
         if p == 'end':
             break
         else:
             if p:
                 cmd_arr.append(p)
     if len(cmd_arr) > 0:
         executor = {
             'id': id,
             'cmd_list': cmd_arr
         }
         self.executors_map[key] = executor
         self.executors_id_map[id] = key
Пример #4
0
    def print_command_list(self, com_obj):
        """
        print the command list of the com_obj reference passed (could be root or even a sub_command reference)
        :param com_obj: command object reference
        :return:
        """
        try:
            com_array = []
            for com in com_obj:
                # if a short reference is present print (short)
                # if the command is a ref, ignore it
                if "ref" not in com_obj[com]:
                    com_array.append(com)

            # sort the list of commands and print it
            com_array.sort()
            command_table_arr = []
            for com in com_array:
                com_t = [utils.green_bold(com)]
                have_shorts = "short" in com_obj[com]
                if have_shorts:
                    com_t.append(com_obj[com]["short"])
                else:
                    com_t.append('')

                com_t.append(self.print_usage(com_obj[com], only_get=True))
                command_table_arr.append(com_t)

            print(utils.titlify('help'))
            print(
                tabulate(command_table_arr, [
                    utils.white_bold_underline('command'),
                    utils.white_bold_underline('short'),
                    utils.white_bold_underline('usage')
                ],
                         tablefmt="simple"))

        except Exception as e:
            print(utils.error_format('print_command_list', str(e)))
Пример #5
0
 def batch_execute(self, commands_arr):
     """
     batch execute a list of commands
     :param commands_arr: array with commands
     :return:
     """
     try:
         l = len(commands_arr)
         if l > 0:
             for com in commands_arr:
                 self.parse_command(com)
             print('executed ' + utils.green_bold(str(l) + ' commands') +
                   '.')
         else:
             raise Exception
     except Exception as e:
         print(MENU_APIX + " " +
               colored("FAILED", 'red', attrs=['underline', 'bold']) + " " +
               colored("batch execution of " + str(len(commands_arr)) +
                       " commands",
                       'white',
                       attrs=['underline', 'bold']))
Пример #6
0
    def resume_emulation(self, address=0x0, skip_bp=0):
        if address > 0x0:
            self.current_address = address

        self.skip_bp_count = skip_bp

        if self.exit_point > 0x0:
            print(
                utils.white_bold("emulation") + " started at " +
                utils.green_bold(hex(self.current_address)))

            if len(self.entry_context) == 0:
                # store the initial memory context for the restart
                self.entry_context = {'memory': {}, 'regs': {}}
                map_list = self.get_module('mappings_module').get_mappings()
                for map in map_list:
                    map_address = int(map[1], 16)
                    map_len = map[2]
                    self.entry_context['memory'][map_address] = bytes(
                        self.emu_instance.mem_read(map_address, map_len))
                # registers
                const = utils.get_arch_consts(self.arch)
                regs = [
                    k for k, v in const.__dict__.items()
                    if not k.startswith("__") and k.index("_REG_") > 0
                ]
                for r in regs:
                    self.entry_context['regs'][r] = \
                        self.emu_instance.reg_read(getattr(const, r))

            start_addr = self.current_address
            if self.is_thumb:
                start_addr = start_addr | 1
            self.emu_instance.emu_start(start_addr, self.exit_point)
        else:
            print(
                'please use \'set exit_point *offset\' to define an exit point'
            )
Пример #7
0
    def print_usage(self, command, only_get=False):
        """
        utils function to check (if exist) and print the command usage

        :param command: command of which to print usage description
        :param only_get: if True he will not print the usage but only returns it
        :return:
        """

        if isinstance(command, dict):
            com = command
        else:
            com = self.core_instance.commands_map[command]

        try:
            if "usage" in com:
                if only_get is False:
                    print(utils.green_bold("usage: ") + com["usage"])
                return com["usage"]
            else:
                return None
        except Exception as e:
            return None
Пример #8
0
 def disassemble(self, func_name, *args):
     p = bytes.fromhex(args[0])
     off = 0x00
     if len(args) == 1:
         self.internal_disassemble(p, off)
     else:
         try:
             arch = getattr(capstone.__all__,
                            'CS_ARCH_' + str(args[0]).upper())
         except Exception as e:
             raise Exception('arch not found')
         mode = self.core_instance.get_cs_mode()
         if len(args) > 2:
             try:
                 arch = getattr(capstone.__all__,
                                'CS_MODE_' + str(args[0]).upper())
             except Exception as e:
                 raise Exception('mode not found')
         cs = capstone.Cs(arch, mode)
         for i in cs.disasm(p, off):
             a = hex(i.address)
             print(
                 utils.green_bold(a) + "\t%s\t%s" % (i.mnemonic, i.op_str))
Пример #9
0
 def print_arm_registers(self):
     r0 = self.core_instance.get_emu_instance() \
         .reg_read(arm_const.UC_ARM_REG_R0)
     r1 = self.core_instance.get_emu_instance() \
         .reg_read(arm_const.UC_ARM_REG_R1)
     r2 = self.core_instance.get_emu_instance() \
         .reg_read(arm_const.UC_ARM_REG_R2)
     r3 = self.core_instance.get_emu_instance() \
         .reg_read(arm_const.UC_ARM_REG_R3)
     r4 = self.core_instance.get_emu_instance() \
         .reg_read(arm_const.UC_ARM_REG_R4)
     r5 = self.core_instance.get_emu_instance() \
         .reg_read(arm_const.UC_ARM_REG_R5)
     r6 = self.core_instance.get_emu_instance() \
         .reg_read(arm_const.UC_ARM_REG_R6)
     r7 = self.core_instance.get_emu_instance() \
         .reg_read(arm_const.UC_ARM_REG_R7)
     r8 = self.core_instance.get_emu_instance() \
         .reg_read(arm_const.UC_ARM_REG_R8)
     r9 = self.core_instance.get_emu_instance() \
         .reg_read(arm_const.UC_ARM_REG_R9)
     r10 = self.core_instance.get_emu_instance() \
         .reg_read(arm_const.UC_ARM_REG_R10)
     r11 = self.core_instance.get_emu_instance() \
         .reg_read(arm_const.UC_ARM_REG_R11)
     r12 = self.core_instance.get_emu_instance() \
         .reg_read(arm_const.UC_ARM_REG_R12)
     sp = self.core_instance.get_emu_instance() \
         .reg_read(arm_const.UC_ARM_REG_SP)
     pc = self.core_instance.get_emu_instance() \
         .reg_read(arm_const.UC_ARM_REG_PC)
     lr = self.core_instance.get_emu_instance() \
         .reg_read(arm_const.UC_ARM_REG_LR)
     r = [[utils.green_bold("r0"), hex(r0), r0],
          [utils.green_bold("r1"), hex(r1), r1],
          [utils.green_bold("r2"), hex(r2), r2],
          [utils.green_bold("r3"), hex(r3), r3],
          [utils.green_bold("r4"), hex(r4), r4],
          [utils.green_bold("r5"), hex(r5), r5],
          [utils.green_bold("r6"), hex(r6), r6],
          [utils.green_bold("r7"), hex(r7), r7],
          [utils.green_bold("r8"), hex(r8), r8],
          [utils.green_bold("r9"), hex(r9), r9],
          [utils.green_bold("r10"), hex(r10), r10],
          [utils.green_bold("r11"), hex(r11), r11],
          [utils.green_bold("r12"), hex(r12), r12],
          [utils.green_bold("sp"), hex(sp), sp],
          [utils.green_bold("pc"), hex(pc), pc],
          [utils.green_bold("lr"), hex(lr), lr]]
     h = [
         utils.white_bold_underline('register'),
         utils.white_bold_underline('hex'),
         utils.white_bold_underline('decimal')
     ]
     print(tabulate(r, h, tablefmt="simple"))
Пример #10
0
      utils.error("found multiple (%d) machines for searchkey \"%s\"" % (len(matches), searchkey))
    else:
      for entry in matches:
        utils.to_json(self.htbapi.vm_vip_remove(entry["id"]))

  def htb_todo(self, searchkey):
    for entry in [x["id"] for x in self._filter_machines([searchkey], infrastructure="htb")]:
      self.htbapi.machines_todo_update(entry)
    self.htb_todos()

  def thm_stats(self):
    utils.to_json(self.thmapi.stats_global())


if __name__ == "__main__":
  parser = argparse.ArgumentParser(description="%s (v%s): Command-line interface for %s, %s and %s machines." % (utils.blue_bold("machinescli"), utils.green_bold("0.1"), utils.magenta_bold("HackTheBox"), utils.cyan_bold("TryHackMe"), utils.yellow_bold("VulnHub")))

  # global flag to switch output mode; useful for debugging with jq
  ggroup = parser.add_mutually_exclusive_group()
  ggroup.add_argument('-j', '--jsonify', required=False, action='store_true', default=False, help='show raw json output (disable default tabular output)')
  ggroup.add_argument('-g', '--gsheet', required=False, action='store_true', default=False, help='show ghseet csv output (disable default tabular output)')
  ggroup.add_argument('-t', '--showttps', required=False, action='store_true', default=False, help='show ttps if machine writeup is available')

  mcgroup = parser.add_mutually_exclusive_group()

  # update htb|vh|oscplike stats
  # will perform live api querying for htb, web crawls for vh and oscplike lists
  mcgroup.add_argument('--update', required=False, action='store_true', default=False, help='update local stats file %s' % (utils.black_bold("(takes time)")))

  # localized querying and listing of results from stats file (covers all supported platforms and lists (htb|vh and oscplike as of v0.1)
  # results could differ from htbgroup calls if local stats file has not been updated in a while