Ejemplo n.º 1
0
    def run(self, args: Cmdline) -> int:
        args = self.parse.parse_args(args.options)
        webshell = self.session.client
        if webshell is None:
            logger.error('No webshell client is using.')
            return self.STOP
        if args.webshell_help:
            print(colour(webshell.help))
        elif args.options_help:
            old = webshell.options.option_list()
            tmp = []
            tmp.append([old[0][0], old[0][4]])
            for l in old[1:]:
                tmp.append([l[0], l[4]])
            print(
                tablor(tmp,
                       border=False,
                       title="Options",
                       max_width="30-1, 80-2"))
        else:
            old = webshell.options.option_list()
            tmp = []
            tmp.append([old[0][0], old[0][1], old[0][2], old[0][3]])
            for l in old[1:]:
                tmp.append([l[0], l[1], l[2], l[3]])
            print(
                tablor(tmp,
                       border=False,
                       title="Options",
                       max_width="30-1, 10-3"))

        return self.SUCCESS
Ejemplo n.º 2
0
    def run(self, args: Cmdline) -> int:
        args = self.parse.parse_args(args.options)
        if args.format:
            self.format = args.format
            logger.info("Update command format successful!")
        if args.code is not None:
            self.code = args.code
            logger.info("Update command handle code successful!")
        if args.exec_type:
            self.exec_type = self.session.command_map.get(args.exec_type)
            logger.info("Update command execute type successful!")
        if args.verbose:
            self.verbose = True if args.verbose == 'true' else False
            logger.info("Update verbose successful!")
        if args.show:
            info = []
            info.append(['Format', self.format])
            info.append(['Executor', self.exec_type.name])
            info.append(['Handle Code', self.code])
            info.append(['verbose', self.verbose])
            print(tablor(info, header=False, max_width="100-2"))
        elif args.cmd:
            print(self.exec_command_on_server(args.cmd))

        return self.SUCCESS
Ejemplo n.º 3
0
 def show_last_result(self):
     if self._scan_result:
         hosts = [['Host', 'Opened Ports Count']]
         ports_list = []
         for ip in self._scan_result:
             hosts.append([ip, len(self._scan_result[ip])])
             ports = {'ip': ip, 'ports': [['Port', 'Note']]}
             for p in self._scan_result[ip]:
                 ports['ports'].append([f"{p.port}/{p.type}", p.note])
             ports_list.append(ports)
         print(tablor(hosts, border=False, title="Alive Host"))
         for p in ports_list:
             if len(p['ports']) > 1:
                 print(tablor(p['ports'], border=False, title=p['ip']))
         return
     print(colour.colorize('No scan result info!', ['bold', 'note'], 'red'))
Ejemplo n.º 4
0
    def _command_info(self, command=None) -> str:
        '''获取当前command的信息,若指定command则返回对应命令的帮助信息'''
        result = ''
        if command is None:
            for title, cmdmap in self.session['Command List'].items():
                info = []
                if len(cmdmap) > 0:
                    info.append(['Command', 'Description'])
                    for cmd, func in cmdmap.items():
                        des = func.help
                        if des is None:
                            des = colour.colorize('No description.', 'note')
                        else:
                            des = des.lstrip('\t\n\r ').split('\n')[0]

                        info.append([cmd, des])
                    result += tablor(info,
                                     title=title,
                                     border=False,
                                     max_width="30-1, 100-2") + '\n'
            info = [['Command', 'Description', 'Value']]
            if len(self.session.alias_command) > 0:
                for cmd, func in self.session.alias_command.items():
                    des = func.help
                    if des is None:
                        des = colour.colorize('No description.', 'note')
                    else:
                        des = des.lstrip('\t\n\r ').split('\n')[0]

                    info.append([cmd, des, func.value])
                result += tablor(info,
                                 title="Alias Commands",
                                 border=False,
                                 max_width="30-1, 50-2, 50-3") + '\n'
        else:
            for cmd, func in self.session.command_map.items():
                if cmd == command:
                    des = func.help
                    return colour.colorize('No description.',
                                           'note') if des is None else des
            return colour.colorize('No description.', 'note')

        return result
Ejemplo n.º 5
0
    def _query(self, sql: str) -> int:
        ret = self.evalfile('payload/query',
                            host=self._host,
                            port=self._port,
                            user=self._user,
                            password=self._password,
                            database=self._current_database,
                            sql=sql)
        ret = ret.data
        if ret is None:
            return self.STOP
        ret = json.loads(ret)
        encoding = self.session.client.options.encoding
        if ret['code'] in (0, -1):
            msg = base64.b64decode(ret['msg'].encode()).decode(
                encoding, 'ignore')
            print(msg)
            if ret['code'] == -1:
                self._last_connect_status = False
                return self.STOP
            return self.ERROR
        elif ret['code'] == 1:
            result = []
            fields = []
            for row in ret['result']:
                if not fields:
                    fields = [
                        base64.b64decode(i.encode()).decode(
                            encoding, 'ignore') for i in row.keys()
                    ]
                tmp = []
                for val in row.values():
                    val = base64.b64decode(val.encode()).decode(
                        encoding, 'ignore')
                    tmp.append(val)
                result.append(tmp)
            table = [
                fields,
            ] + result
            print(tablor(table, indent=''))
            logger.info(colour.colorize(f"{len(result)} rows in set.", 'bold'))
        elif ret['code'] == 2:
            affected = ret['affected']
            logger.info(
                colour.colorize(f"Query OK, {affected} row affected.", 'bold'))
        elif ret['code'] == -2:
            logger.error(
                "Can't find function `oci_connect`, the server may not have the OCI extension installed."
            )
            self._last_connect_status = False
            return self.STOP

        self._last_connect_status = True
        return self.SUCCESS
Ejemplo n.º 6
0
 def _show(self) -> int:
     table = [['Host', self._host], ['Port', self._port],
              ['User', self._user], ['Password', self._password],
              ['Current database', self._current_database],
              [
                  'Last connection',
                  colour.colorize('Success', 'bold', 'green')
                  if self._last_connect_status else colour.colorize(
                      'Failed', 'bold', 'red')
              ]]
     print(tablor(table, False, indent=''))
     return self.SUCCESS
Ejemplo n.º 7
0
    def _list(self) -> int:
        table = [['ID', 'Webshell Type', 'Target']]
        try:
            tree = ET.parse(config.webshell_save_path)
            root = tree.getroot()
            for c in root:
                l = []
                l.append(c.attrib.get('id', 1))
                l.append(c.find("./webshell").attrib.get("value"))
                l.append(
                    c.find("./options/option[@name='target']").attrib.get(
                        'value'))
                table.append(l)
        except (FileNotFoundError, ET.ParseError):
            logger.warning(
                f"Load or parse file `{config.webshell_save_path}` failed!")
            return self.STOP

        print(tablor(table, border=False, title="Saved Webshell Connections"))
        return self.SUCCESS
Ejemplo n.º 8
0
 def _list(self):
     table = [['ID', 'Forwarding Rule', 'Upload limit', 'Alive Connections Count', 'State']]
     for ID, rule in self._forward_list.items():
         tmp = []
         tmp.append(ID)
         tmp.append(f"{rule['lhost']}:{rule['lport']} {'<=' if rule['lf'] else '=>'} {rule['rhost']}:{rule['rport']}")
         tmp.append(f"{'Unlimited' if rule['uploadsize'] == 0 else rule['uploadsize']}")
         cc = 0
         if rule['forwd']:
             if rule['lf']:
                 cc = len(rule['forwd'].connections)
             else:
                 if rule['forwd'].is_alive() and rule['forwd'].connections and list(rule['forwd'].connections.values())[0]:
                     cc = 1
         tmp.append(cc)
         state = colour.colorize('Stopped', 'bold', 'red')
         if rule['forwd'] and rule['forwd'].is_alive():
             state = colour.colorize('Running', 'bold', 'green')
         tmp.append(state)
         table.append(tmp)
     print(tablor(table, border=False, title="Forwarding Rule Table", aligning="right-3"))
     return self.SUCCESS
Ejemplo n.º 9
0
    def run(self, args: Cmdline) -> int:
        args = self.parse.parse_args(args.options)
        if args.path:
            ret = self.evalfile('ls', pwd=self.session.pwd, path=args.path)
            ret = ret.data
            if ret is None:
                logger.error("Listing error!")
                return self.STOP
            ret = json.loads(ret)
            if ret['code'] == 1:
                table = [[
                    'Permissions', 'Owner', 'Group', 'Size', 'Mtime', 'Name'
                ]]
                for item in ret['msg']:
                    l = []
                    l.append(item[0])
                    l.append(item[1] if item[1] != '(Unknown)' else colour.
                             colorize(item[1], 'note'))
                    l.append(item[2] if item[2] != '(Unknown)' else colour.
                             colorize(item[2], 'note'))
                    l.append(self._format_size(item[3]))
                    l.append(self._format_time(item[4]))
                    tmp = base64.b64decode(item[5].encode()).decode(
                        self.session.client.options.encoding, 'ignore')
                    l.append(self._format_filename(tmp, item[0]))
                    table.append(l)
                print(
                    tablor(table,
                           border=False,
                           autocolor=False,
                           aligning='right-4',
                           indent=' '))
                return self.SUCCESS
            elif ret['code'] == -1:
                logger.error(f"Path `{args.path}` not found or access denied!")
            elif ret['code'] == -2:
                logger.error(f"Path `{args.path}` cannot list directory")

        return self.STOP
Ejemplo n.º 10
0
    def _list(self) -> int:
        session_list = [['ID', 'Session Type', 'Target', 'Origin']]
        pos = 0
        j = 0
        for i, s in self.manager.session_map.items():
            j += 1
            if isinstance(self.session,
                          WebshellSession) and self.session.id == i:
                pos = j
            origin = 'create by exploit'
            if 'save_id' in s.state:
                origin = f'create by saved connection `{s.state.get("save_id")}`'
            session_list.append(
                [i, s.state.get('type'), s.client.options.target, origin])

        print(
            tablor(session_list,
                   border=False,
                   title="Active Sessions",
                   pos=pos,
                   max_width="30-4, 30-3"))
        return self.SUCCESS