def cmd_cyclic_pattern(self, args, jid, is_muc): parser = ArgumentParserLite('cyclic_pattern', 'create and search a cyclic pattern') parser.add_argument('-s', '--size', dest='size', type=int, required=True, help='pattern size to create') parser.add_argument('-p', '--pattern', dest='pattern', help='pattern to find') parser.add_argument('--code', dest='code', action='store_true', help='format the pattern for code') if not len(args): return parser.format_help() results = parser.parse_args(args) size = results['size'] if size > MAX_PATTERN_SIZE: return 'size is too large, max is ' + str(MAX_PATTERN_SIZE) pattern = create_cyclic_pattern(size) if results['pattern'] is None: if results['code']: code = "# Cyclic Pattern Length: {0}\n".format(len(pattern)) code += 'pattern = ""\n' for idx in range(0, len(pattern), 32): code += "pattern += \"{0}\"\n".format(pattern[idx:idx + 32]) return code return pattern search_pattern = results['pattern'] if len(search_pattern) == 8: search_pattern = search_pattern.decode('hex') search_pattern = list(search_pattern) search_pattern.reverse() search_pattern = ''.join(search_pattern) if len(search_pattern) != 4: return 'the search pattern is invalid' index = pattern.find(search_pattern) if index == -1: return 'could not find the search pattern' return 'found exact match at ' + str(index)
def cmd_example(self, args, jid, is_muc): parser = ArgumentParserLite('example', 'an example module') if not len(args): return parser.format_help() results = parser.parse_args(args) if not results: return parser.get_last_error() return 'Hello World!'
def cmd_bot(self, args, jid, is_muc): parser = ArgumentParserLite('bot', 'control the bot') parser.add_argument('-l', '--log', dest='loglvl', action='store', default=None, help='set the bots logging level') parser.add_argument('--shutdown', dest='stop', action='store_true', default=False, help='stop the bot from running') parser.add_argument('--join', dest='chat_room_join', action='store', default=None, help='join a chat room') parser.add_argument('--leave', dest='chat_room_leave', action='store', default=None, help='leave a chat room') if not len(args): return parser.format_help() results = parser.parse_args(args) response = '' if results['loglvl']: results['loglvl'] = results['loglvl'].upper() if results['loglvl'] in ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'): log = logging.getLogger('') log.setLevel(getattr(logging, results['loglvl'])) self.logger.info('successfully set the logging level to: ' + results['loglvl']) response += 'Successfully set the logging level to: ' + results[ 'loglvl'] else: response += 'Invalid log level: ' + results['loglvl'] + '\n' if results['chat_room_join']: self.bot.chat_room_join(results['chat_room_join']) response += 'Joined chat room: ' + results['chat_room_join'] + '\n' if results['chat_room_leave']: self.bot.chat_room_leave(results['chat_room_leave']) response += 'Left chat room: ' + results['chat_room_leave'] + '\n' if results['stop']: self.bot.bot_request_stop() return response
def cmd_user(self, args, jid, is_muc): parser = ArgumentParserLite('user', 'add/delete/modify users') parser.add_argument('-a', '--add', dest='add user', action='store', default=None, help='add user') parser.add_argument('-d', '--del', dest='delete user', action='store', default=None, help='delete user') parser.add_argument('-l', '--lvl', dest='level', action='store', default='USER', help='permission level of user') parser.add_argument('-s', '--show', dest='show', action='store_true', default=False, help='show the user database') if not len(args): return parser.format_help() results = parser.parse_args(args) response = '' authorized_users = self.bot.authorized_users privilege_level = users.get_level_by_name(results['level']) if privilege_level is None: return 'Invalid privilege level' if results['add user']: if not results['add user'] in authorized_users: authorized_users[results['add user']] = users.User(results['add user'], privilege_level) response += 'Successfully Added User: '******'add user'] else: response += 'Can Not Add Already Authorized User' if results['delete user']: if not results['delete user'] in authorized_users: response += 'Can Not Delete Non-Authorized User' else: del authorized_users[results['delete user']] response += 'Successfully Deleted User: '******'delete user'] if results['show']: if not response: response += '\n' response += 'User Listing:\n' for user in authorized_users: response += user.type.upper() + ' ' + user.name + ' ' + user.level_name + '\n' response += '\n' if not response: return 'Missing Action' response += '\n' try: authorized_users.save() except Exception: self.logger.error('failed to save the user database', exc_info=True) response += 'Failed To Save User Database' return response
def cmd_github(self, args, jid, is_muc): parser = ArgumentParserLite( 'github', 'monitor new commits and pull requests to a github repository') parser.add_argument( 'action', required=True, help='github plugin action (disable, enable, status)') if not len(args): action = 'status' else: results = parser.parse_args(args) action = results['action'] if not action in ['disable', 'enable', 'status']: return 'action must be either disable, enable or status' response = [] job_manager = self.bot.job_manager if not job_manager.job_exists(self.job_id): self.job_start_time = datetime.datetime.utcnow() self.job_id = job_manager.job_add( self.check_github_repo_activity, seconds=self.check_frequency.seconds) if action == 'status': status = job_manager.job_is_enabled(self.job_id) response.append("github repository monitor is {0}running".format( ('' if status else 'not '))) if len(self.repositories): response.append( 'the following repositories are configured for monitoring') response.extend(' ' + repo for repo in self.repositories) else: response.append( 'no repositories are configured for monitoring') elif action == 'enable': job_manager.job_enable(self.job_id) response.append('enabled the github repository monitor') elif action == 'disable': job_manager.job_disable(self.job_id) response.append('disabled the github repository monitor') return '\n'.join(response)
def cmd_empire_shell_exec(self, args, jid, is_muc): parser = ArgumentParserLite('empire_shell_cmd', 'execute a shell command on empire agent') parser.add_argument('-a', '--agent', dest='emp_agent', help='run command on specified agent') parser.add_argument('-c', '--command', dest='emp_command', help='command to run') #parser.add_argument('-m', '--mimikatz', dest='emp_mimi', help='execute mimikatz on specified agent') if not len(args): return parser.format_help() results = parser.parse_args(args) user_jid = str(jid).split('/')[0] if not self.user_is_configured(user_jid): report = 'Sorry {0}, it looks like you do not have an Empire config yet. Create one with the "empire_setup" module.'.format(user_jid.split('@')[0]) return report empire_config = self.get_storage(user_jid) api = EmpireAPI(empire_config) token = api.get_api_token() exec_cmd = api.exec_shell_cmd(results['emp_agent'], results['emp_command']) report = 'Executing command "{0}" on agent: {1}\n'.format(results['emp_command'], results['emp_agent']) if exec_cmd['success'] is True: report += 'Success!\n' else: report += 'Command execution failed.\n' return report
def cmd_empire_list(self, args, jid, is_muc): parser = ArgumentParserLite('empire_list', 'list listeners/agents on an Empire server') parser.add_argument('-l', '--listeners', dest='list_listeners', help='list listeners', action='store_true', default=False) parser.add_argument('-a', '--agents', dest='list_agents', help='list agents', action='store_true', default=False) parser.add_argument('-c', '--creds', dest='list_creds', help='list credentials in the database', action='store_true', default=False) parser.add_argument('-v', '--verbose', dest='verbose', help='verbose output', action='store_true', default=False) if not len(args): return parser.format_help() results = parser.parse_args(args) user_jid = str(jid).split('/')[0] if not self.user_is_configured(user_jid): report = 'Sorry {0}, it looks like you do not have an Empire config yet. Create one with the "empire_setup" module.'.format(user_jid.split('@')[0]) return report empire_config = self.get_storage(user_jid) api = EmpireAPI(empire_config) token = api.get_api_token() if results['list_listeners']: listeners_dict = api.get_listeners() listeners = listeners_dict['listeners'] if len(listeners) > 1: report = 'There are {0} listeners available:\n'.format(str(len(listeners))) elif len(listeners) == 1: report = 'There is {0} listener available:\n'.format(str(len(listeners))) else: report = 'There are {0} listeners available:\n'.format(str(len(listeners))) for listener in listeners: report += 'Name: {0}\n'.format(listener['name']) for listener_property in listener.keys(): if listener_property != 'name': report += '{0}: {1}\n'.format(listener_property, listener[listener_property]) return report if results['list_agents']: desired_agent_properties = ['username', 'high_integrity', 'external_ip', 'internal_ip', 'os_details', 'lastseen_time'] agents_dict = api.get_agents() agents = agents_dict['agents'] if len(agents) > 1: report = 'There are {0} agents connected:\n'.format(str(len(agents))) elif len(agents) == 1: report = 'There is {0} agent connected:\n'.format(str(len(agents))) else: report = 'There are {0} agents connected:\n'.format(str(len(agents))) for agent in agents: report += 'Agent: {0}\n'.format(agent['name']) for agent_property in agent.keys(): if agent_property != 'name': if results['verbose']: report += '{0}: {1}\n'.format(agent_property, agent[agent_property]) else: for desired_prop in desired_agent_properties: if agent_property == desired_prop: report += '{0}: {1}\n'.format(agent_property, agent[agent_property]) report += '\n' return report if results['list_creds']: reported_creds = [] report = 'Harvested Credentials:\n' creds = api.get_creds()['creds'] for cred in creds: if cred['credtype'] == 'password': i = cred['domain'] + '\\' + cred['username'] if i not in reported_creds: report += 'Domain: {0}\nUser: {1}\nPassword: {2}\n\n'.format(cred['domain'], cred['username'], cred['password']) reported_creds.add(i) if not len(creds): report += 'No credentials are available.\n' return report
def cmd_empire_setup(self, args, jid, is_muc): """Create the Empire config file required by this module""" parser = ArgumentParserLite('empire_setup', 'Create an Empire config.') parser.add_argument('-s', '--server-url', dest='server_url', help='URL of Empire server (i.e. "https://127.0.0.1:1337/")', required=False) parser.add_argument('-u', '--username', dest='server_user', help='username for Empire API', required=False) parser.add_argument('-p', '--password', dest='server_pass', help='password for Empire API', required=False) parser.add_argument('-e', '--enable', dest='enable_server', help='enable automatic polling for your server', action='store_true', required=False, default=False) parser.add_argument('-d', '--disable', dest='disable_server', help='disable automatic polling for your server', action='store_true', required=False, default=False) parser.add_argument('-c', '--show-config', dest='show_config', help='displays your current Empire config', action='store_true', required=False, default=False) if not len(args): return parser.format_help() results = parser.parse_args(args) user_jid = str(jid).split('/')[0] user_storage = self.get_storage(user_jid) report_user = str(jid).split('@')[0] report = '' if results['enable_server'] and results['disable_server']: report = 'Automated polling cannot be both enabled and disabled.' return report if not self.polling_is_enabled(user_jid): user_storage['is_enabled'] = False if not self.user_is_configured and not all(results['server_user'], results['server_pass'], results['server_url']): report = "{0}: Your Empire config was not able to be updated successfully.\n".format(user_jid) report += 'You will not be able to leverage any Empire commands until your config is valid!\n' report += 'Please run the "!empire_setup" command again.' return report if results['enable_server'] and not self.polling_is_enabled(user_jid): user_storage['is_enabled'] = True report += ' Automatic polling has been enabled for your server.\n' if results['disable_server'] and self.polling_is_enabled(user_jid): user_storage['is_enabled'] = False user_storage['agents'] = [] report += ' Automatic polling has been disabled for your server.\n' if results['server_user'] is not None: user_storage['user'] = results['server_user'] if results['server_pass'] is not None: user_storage['pass'] = results['server_pass'] if results['server_url'] is not None: if self.url_is_valid(results['server_url']): user_storage['url'] = results['server_url'] else: report = '{0}: The specified URL is not valid. Please enter it in the form of "https://127.0.0.1:1337/"'.format(report_user) return report if results['show_config']: if not report: report = '' report += 'Current Empire Config:\n'.format(report_user) report += '\tUser: {0}\n'.format(user_storage.get('user', 'None')) report += '\tPassword: {0}\n'.format(user_storage.get('pass', 'None')) report += '\tURL: {0}\n'.format(user_storage.get('url', 'None')) report += '\tPolling Enabled: {0}'.format(user_storage.get('is_enabled', 'False')) return report
def cmd_frotz(self, args, jid, is_muc): parser = ArgumentParserLite( 'frotz', 'play z-machine games with frotz', 'each user can create one save file per game') parser.add_argument('-n', '--new', dest='new_game', action='store_true', help='start a new game') parser.add_argument('-r', '--restore', dest='restore_game', action='store_true', help='restore a previous game') parser.add_argument('-q', '--quit', dest='quit_game', action='store_true', help='quit playing the game') parser.add_argument('-s', '--save', dest='save_game', action='store_true', help='save the current game') parser.add_argument('-g', '--game', dest='game', action='store', help='game to play') parser.add_argument('--list-games', dest='list_games', action='store_true', help='list available games') if not len(args): return parser.format_help() results = parser.parse_args(args) user = str(jid.bare) if results['list_games']: resp = ['Available Games:'] games = list(self.options['games'].keys()) games.sort() resp.extend(games) return resp with self.frotz_instances_lock: if results['new_game'] or results['restore_game']: if not results['game'] in self.options['games']: if results['game'] is None: msg = 'Please select a game with the -g option' else: msg = 'Invalid game file' return msg + ', use --list-games to show available games' game_file = self.options['games'][results['game']] elif results['save_game'] or results['quit_game']: if results['game']: return 'Can\'t select a game with --save or --quit' if not user in self.frotz_instances: return 'Frotz is not currently running' frotz = self.frotz_instances[user]['frotz'] if not frotz.running: self.cleanup_game(user) return 'Frotz is not currently running' game_file = frotz.frotz_game_file save_file_name = user.replace( '@', '_at_') + '.' + os.path.splitext( os.path.basename(game_file))[0] + '.qzl' save_file_path = os.path.join(self.options['save_directory'], save_file_name) if results['new_game'] or results['restore_game']: if user in self.frotz_instances: self.cleanup_game(user) if results['new_game']: self.logger.info( str(jid.jid) + ' is starting a new game with frotz') elif results['restore_game']: self.logger.info( str(jid.jid) + ' is restoring a game with frotz') self.frotz_instances[user] = { 'frotz': Frotz(game_file, frotz_bin=self.options['binary']), 'handler_id': None } frotz = self.frotz_instances[user]['frotz'] if is_muc: handler_id = self.bot.custom_message_handler_add( jid.bare, self.callback_play_game, self.options['handler_timeout']) else: handler_id = self.bot.custom_message_handler_add( jid, self.callback_play_game, self.options['handler_timeout']) self.frotz_instances[user]['handler_id'] = handler_id output = frotz.game_start() if results['restore_game']: output = frotz.game_restore(save_file_path) return output if results['save_game']: self.logger.debug( str(jid.jid) + ' is saving a game with frotz') return frotz.game_save(save_file_path) if results['quit_game']: self.logger.debug( str(jid.jid) + ' is quitting a game with frotz') self.cleanup_game(user) return 'Ended Frotz game, thanks for playing'
def cmd_user(self, args, jid, is_muc): parser = ArgumentParserLite('user', 'add/delete/modify users') parser.add_argument('-a', '--add', dest='add user', action='store', default=None, help='add user') parser.add_argument('-d', '--del', dest='delete user', action='store', default=None, help='delete user') parser.add_argument('-l', '--lvl', dest='level', action='store', default='USER', help='permission level of user') parser.add_argument('-s', '--show', dest='show', action='store_true', default=False, help='show the user database') if not len(args): return parser.format_help() results = parser.parse_args(args) response = '' authorized_users = self.bot.authorized_users privilege_level = users.get_level_by_name(results['level']) if privilege_level is None: return 'Invalid privilege level' if results['add user']: if not results['add user'] in authorized_users: authorized_users[results['add user']] = users.User( results['add user'], privilege_level) response += 'Successfully Added User: '******'add user'] else: response += 'Can Not Add Already Authorized User' if results['delete user']: if not results['delete user'] in authorized_users: response += 'Can Not Delete Non-Authorized User' else: del authorized_users[results['delete user']] response += 'Successfully Deleted User: '******'delete user'] if results['show']: if not response: response += '\n' response += 'User Listing:\n' for user in authorized_users: response += user.type.upper( ) + ' ' + user.name + ' ' + user.level_name + '\n' response += '\n' if not response: return 'Missing Action' response += '\n' try: authorized_users.save() except Exception: self.logger.error('failed to save the user database', exc_info=True) response += 'Failed To Save User Database' return response
def cmd_frotz(self, args, jid, is_muc): parser = ArgumentParserLite('frotz', 'play z-machine games with frotz', 'each user can create one save file per game') parser.add_argument('-n', '--new', dest='new_game', action='store_true', help='start a new game') parser.add_argument('-r', '--restore', dest='restore_game', action='store_true', help='restore a previous game') parser.add_argument('-q', '--quit', dest='quit_game', action='store_true', help='quit playing the game') parser.add_argument('-s', '--save', dest='save_game', action='store_true', help='save the current game') parser.add_argument('-g', '--game', dest='game', action='store', help='game to play') parser.add_argument('--list-games', dest='list_games', action='store_true', help='list available games') if not len(args): return parser.format_help() results = parser.parse_args(args) user = str(jid.bare) if results['list_games']: resp = ['Available Games:'] games = list(self.options['games'].keys()) games.sort() resp.extend(games) return resp with self.frotz_instances_lock: if results['new_game'] or results['restore_game']: if not results['game'] in self.options['games']: if results['game'] is None: msg = 'Please select a game with the -g option' else: msg = 'Invalid game file' return msg + ', use --list-games to show available games' game_file = self.options['games'][results['game']] elif results['save_game'] or results['quit_game']: if results['game']: return 'Can\'t select a game with --save or --quit' if not user in self.frotz_instances: return 'Frotz is not currently running' frotz = self.frotz_instances[user]['frotz'] if not frotz.running: self.cleanup_game(user) return 'Frotz is not currently running' game_file = frotz.frotz_game_file save_file_name = user.replace('@', '_at_') + '.' + os.path.splitext(os.path.basename(game_file))[0] + '.qzl' save_file_path = os.path.join(self.options['save_directory'], save_file_name) if results['new_game'] or results['restore_game']: if user in self.frotz_instances: self.cleanup_game(user) if results['new_game']: self.logger.info(str(jid.jid) + ' is starting a new game with frotz') elif results['restore_game']: self.logger.info(str(jid.jid) + ' is restoring a game with frotz') self.frotz_instances[user] = {'frotz': Frotz(game_file, frotz_bin=self.options['binary']), 'handler_id': None} frotz = self.frotz_instances[user]['frotz'] if is_muc: handler_id = self.bot.custom_message_handler_add(jid.bare, self.callback_play_game, self.options['handler_timeout']) else: handler_id = self.bot.custom_message_handler_add(jid, self.callback_play_game, self.options['handler_timeout']) self.frotz_instances[user]['handler_id'] = handler_id output = frotz.game_start() if results['restore_game']: output = frotz.game_restore(save_file_path) return output if results['save_game']: self.logger.debug(str(jid.jid) + ' is saving a game with frotz') return frotz.game_save(save_file_path) if results['quit_game']: self.logger.debug(str(jid.jid) + ' is quitting a game with frotz') self.cleanup_game(user) return 'Ended Frotz game, thanks for playing'