Пример #1
0
	def generate_stats(self):
		stats = {
			'campaigns': [],
			'generated': datetime.datetime.utcnow(),
			'version': {
				'king_phisher': version.distutils_version,
				'stats': __version__
			}
		}
		rpc = self.rpc
		for campaign in rpc.remote_table('campaigns'):
			stats['campaigns'].append(self._campaign_stats(campaign))
		stats['hash'] = generate_signature(stats)
		return json_ex.dumps(stats)
Пример #2
0
def message_data_to_kpm(message_config, target_file, encoding='utf-8'):
    """
	Save details describing a message to the target file.

	:param dict message_config: The message details from the client configuration.
	:param str target_file: The file to write the data to.
	:param str encoding: The encoding to use for strings.
	"""
    message_config = copy.copy(message_config)
    kpm = archive.ArchiveFile(target_file, 'w')

    for config_name, file_name in KPM_ARCHIVE_FILES.items():
        if os.access(message_config.get(config_name, ''), os.R_OK):
            kpm.add_file(file_name, message_config[config_name])
            message_config[config_name] = os.path.basename(
                message_config[config_name])
            continue
        if len(message_config.get(config_name, '')):
            logger.info(
                "the specified {0} '{1}' is not readable, the setting will be removed"
                .format(config_name, message_config[config_name]))
        if config_name in message_config:
            del message_config[config_name]

    if os.access(message_config.get('html_file', ''), os.R_OK):
        with codecs.open(message_config['html_file'], 'r',
                         encoding=encoding) as file_h:
            template = file_h.read()
        message_config['html_file'] = os.path.basename(
            message_config['html_file'])
        template, attachments = message_template_to_kpm(template)
        logger.debug("identified {0} attachment file{1} to be archived".format(
            len(attachments), 's' if len(attachments) > 1 else ''))
        kpm.add_data('message_content.html', template)
        for attachment in attachments:
            if os.access(attachment, os.R_OK):
                kpm.add_file(
                    os.path.join('attachments', os.path.basename(attachment)),
                    attachment)
    else:
        if len(message_config.get('html_file', '')):
            logger.info(
                "the specified html_file '{0}' is not readable, the setting will be removed"
                .format(message_config['html_file']))
        if 'html_file' in message_config:
            del message_config['html_file']

    kpm.add_data('message_config.json', json_ex.dumps(message_config))
    kpm.close()
    return
Пример #3
0
 def generate_stats(self):
     stats = {
         'campaigns': [],
         'generated': datetime.datetime.utcnow(),
         'version': {
             'king_phisher': version.distutils_version,
             'stats': __version__
         }
     }
     rpc = self.rpc
     for campaign in rpc.remote_table('campaigns'):
         stats['campaigns'].append(self._campaign_stats(campaign))
     stats['hash'] = generate_signature(stats)
     return json_ex.dumps(stats)
Пример #4
0
def message_data_to_kpm(message_config, target_file, encoding='utf-8'):
	"""
	Save details describing a message to the target file.

	:param dict message_config: The message details from the client configuration.
	:param str target_file: The file to write the data to.
	:param str encoding: The encoding to use for strings.
	"""
	message_config = copy.copy(message_config)
	kpm = archive.ArchiveFile(target_file, 'w')

	for config_name, file_name in KPM_ARCHIVE_FILES.items():
		if os.access(message_config.get(config_name, ''), os.R_OK):
			kpm.add_file(file_name, message_config[config_name])
			message_config[config_name] = os.path.basename(message_config[config_name])
			continue
		if len(message_config.get(config_name, '')):
			logger.info("the specified {0} '{1}' is not readable, the setting will be removed".format(config_name, message_config[config_name]))
		if config_name in message_config:
			del message_config[config_name]

	if os.access(message_config.get('html_file', ''), os.R_OK):
		with codecs.open(message_config['html_file'], 'r', encoding=encoding) as file_h:
			template = file_h.read()
		message_config['html_file'] = os.path.basename(message_config['html_file'])
		template, attachments = message_template_to_kpm(template)
		logger.debug("identified {0} attachment file{1} to be archived".format(len(attachments), 's' if len(attachments) > 1 else ''))
		kpm.add_data('message_content.html', template)
		for attachment in attachments:
			if os.access(attachment, os.R_OK):
				kpm.add_file(os.path.join('attachments', os.path.basename(attachment)), attachment)
	else:
		if len(message_config.get('html_file', '')):
			logger.info("the specified html_file '{0}' is not readable, the setting will be removed".format(message_config['html_file']))
		if 'html_file' in message_config:
			del message_config['html_file']

	kpm.add_data('message_config.json', json_ex.dumps(message_config))
	kpm.close()
	return
Пример #5
0
	def __init__(self, application):
		"""
		:param application: The application instance to which this window belongs.
		:type application: :py:class:`.KingPhisherClientApplication`
		"""
		utilities.assert_arg_type(application, Gtk.Application, arg_pos=1)
		self.application = application
		self.logger = logging.getLogger('KingPhisher.Client.' + self.__class__.__name__)
		if not has_vte:
			gui_utilities.show_dialog_error('RPC Terminal Is Unavailable', self.application.get_active_window(), 'VTE is not installed')
			return
		config = application.config

		self.terminal = Vte.Terminal()
		self.rpc_window = RPCTerminalAppWindow(self.terminal, self.application)

		rpc = self.application.rpc
		config = {
			'campaign_id': config['campaign_id'],
			'campaign_name': config['campaign_name'],
			'rpc_data': {
				'address': (rpc.host, rpc.port),
				'use_ssl': rpc.use_ssl,
				'username': rpc.username,
				'uri_base': rpc.uri_base,
				'headers': rpc.headers
			}
		}

		module_path = os.path.dirname(client_rpc.__file__) + ((os.path.sep + '..') * client_rpc.__name__.count('.'))
		module_path = os.path.normpath(module_path)

		python_command = [
			"import {0}".format(client_rpc.__name__),
			"{0}.vte_child_routine('{1}')".format(client_rpc.__name__, json_ex.dumps(config, pretty=False))
		]
		python_command = '; '.join(python_command)

		if hasattr(self.terminal, 'pty_new_sync'):
			# Vte._version >= 2.91
			vte_pty = self.terminal.pty_new_sync(Vte.PtyFlags.DEFAULT)
			self.terminal.set_pty(vte_pty)
			self.terminal.connect('child-exited', lambda vt, status: self.rpc_window.window.destroy())
		else:
			# Vte._version <= 2.90
			vte_pty = self.terminal.pty_new(Vte.PtyFlags.DEFAULT)
			self.terminal.set_pty_object(vte_pty)
			self.terminal.connect('child-exited', lambda vt: self.rpc_window.window.destroy())

		child_pid, _, _, _ = GLib.spawn_async(
			working_directory=os.getcwd(),
			argv=[sys.executable, '-c', python_command],
			envp=[
				'PATH=' + os.environ['PATH'],
				'PYTHONPATH=' + module_path, find.ENV_VAR + '=' + os.environ[find.ENV_VAR]
			],
			flags=(GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD),
			child_setup=self._child_setup,
			user_data=vte_pty
		)

		self.logger.info("vte spawned child process with pid: {0}".format(child_pid))
		self.child_pid = child_pid
		self.terminal.watch_child(child_pid)
		GLib.spawn_close_pid(child_pid)
		self.rpc_window.window.show_all()
		self.rpc_window.child_pid = child_pid
		return
Пример #6
0
	def close(self):
		"""Close the handle to the archive."""
		if 'w' in self.mode:
			self.add_data(self.metadata_file_name, json_ex.dumps(self.metadata))
		self._tar_h.close()
Пример #7
0
    def __init__(self, application):
        """
		:param application: The application instance to which this window belongs.
		:type application: :py:class:`.KingPhisherClientApplication`
		"""
        assert isinstance(application, Gtk.Application)
        self.application = application
        self.logger = logging.getLogger('KingPhisher.Client.' +
                                        self.__class__.__name__)
        if not has_vte:
            gui_utilities.show_dialog_error(
                'RPC Terminal Is Unavailable',
                self.application.get_active_window(), 'VTE is not installed')
            return
        config = application.config

        self.terminal = Vte.Terminal()
        self.rpc_window = RPCTerminalAppWindow(self.terminal, self.application)

        rpc = self.application.rpc
        config = {
            'campaign_id': config['campaign_id'],
            'campaign_name': config['campaign_name'],
            'rpc_data': {
                'address': (rpc.host, rpc.port),
                'use_ssl': rpc.use_ssl,
                'username': rpc.username,
                'uri_base': rpc.uri_base,
                'headers': rpc.headers
            }
        }

        module_path = os.path.dirname(client_rpc.__file__) + (
            (os.path.sep + '..') * client_rpc.__name__.count('.'))
        module_path = os.path.normpath(module_path)

        python_command = [
            "import {0}".format(client_rpc.__name__),
            "{0}.vte_child_routine('{1}')".format(
                client_rpc.__name__, json_ex.dumps(config, pretty=False))
        ]
        python_command = '; '.join(python_command)

        if hasattr(self.terminal, 'pty_new_sync'):
            # Vte._version >= 2.91
            vte_pty = self.terminal.pty_new_sync(Vte.PtyFlags.DEFAULT)
            self.terminal.set_pty(vte_pty)
            self.terminal.connect(
                'child-exited',
                lambda vt, status: self.rpc_window.window.destroy())
        else:
            # Vte._version <= 2.90
            vte_pty = self.terminal.pty_new(Vte.PtyFlags.DEFAULT)
            self.terminal.set_pty_object(vte_pty)
            self.terminal.connect('child-exited',
                                  lambda vt: self.rpc_window.window.destroy())

        child_pid, _, _, _ = GLib.spawn_async(
            working_directory=os.getcwd(),
            argv=[sys.executable, '-c', python_command],
            envp=[
                'PATH=' + os.environ['PATH'], 'PYTHONPATH=' + module_path,
                find.ENV_VAR + '=' + os.environ[find.ENV_VAR]
            ],
            flags=(GLib.SpawnFlags.SEARCH_PATH
                   | GLib.SpawnFlags.DO_NOT_REAP_CHILD),
            child_setup=self._child_setup,
            user_data=vte_pty)

        self.logger.info(
            "vte spawned child process with pid: {0}".format(child_pid))
        self.child_pid = child_pid
        self.terminal.watch_child(child_pid)
        GLib.spawn_close_pid(child_pid)
        self.rpc_window.window.show_all()
        self.rpc_window.child_pid = child_pid
        return
Пример #8
0
	def test_json_ex_loads(self):
		try:
			json_ex.loads(json_ex.dumps('test'))
		except ValueError:
			self.fail('Invalid data type for json_ex.loads()')
Пример #9
0
	def test_json_ex_dumps(self):
		self.assertIsInstance(json_ex.dumps('test'), str)
		self.assertIsInstance(json_ex.dumps(True), str)
		self.assertIsInstance(json_ex.dumps(100), str)
Пример #10
0
def generate_signature(data):
	data = copy.deepcopy(data)
	data['hash'] = None
	return generate_hash(json_ex.dumps(data))
Пример #11
0
 def close(self):
     """Close the handle to the archive."""
     if 'w' in self.mode:
         self.add_data(self.metadata_file_name,
                       json_ex.dumps(self.metadata))
     self._tar_h.close()
Пример #12
0
    def __init__(self, application):
        """
		:param application: The application instance to which this window belongs.
		:type application: :py:class:`.KingPhisherClientApplication`
		"""
        assert isinstance(application, Gtk.Application)
        self.application = application
        self.logger = logging.getLogger("KingPhisher.Client." + self.__class__.__name__)
        if not has_vte:
            gui_utilities.show_dialog_error(
                "RPC Terminal Is Unavailable", self.application.get_active_window(), "VTE is not installed"
            )
            return
        config = application.config

        self.terminal = Vte.Terminal()
        self.rpc_window = RPCTerminalAppWindow(self.terminal, self.application)

        rpc = self.application.rpc
        config = {
            "campaign_id": config["campaign_id"],
            "campaign_name": config["campaign_name"],
            "rpc_data": {
                "address": (rpc.host, rpc.port),
                "use_ssl": rpc.use_ssl,
                "username": rpc.username,
                "uri_base": rpc.uri_base,
                "headers": rpc.headers,
                "hmac_key": rpc.hmac_key,
            },
        }

        module_path = os.path.dirname(client_rpc.__file__) + ((os.path.sep + "..") * client_rpc.__name__.count("."))
        module_path = os.path.normpath(module_path)

        python_command = [
            "import {0}".format(client_rpc.__name__),
            "{0}.vte_child_routine('{1}')".format(client_rpc.__name__, json_ex.dumps(config, pretty=False)),
        ]
        python_command = "; ".join(python_command)

        if hasattr(self.terminal, "pty_new_sync"):
            # Vte._version >= 2.91
            vte_pty = self.terminal.pty_new_sync(Vte.PtyFlags.DEFAULT)
            self.terminal.set_pty(vte_pty)
            self.terminal.connect("child-exited", lambda vt, status: self.rpc_window.window.destroy())
        else:
            # Vte._version <= 2.90
            vte_pty = self.terminal.pty_new(Vte.PtyFlags.DEFAULT)
            self.terminal.set_pty_object(vte_pty)
            self.terminal.connect("child-exited", lambda vt: self.rpc_window.window.destroy())

        child_pid, _, _, _ = GLib.spawn_async(
            working_directory=os.getcwd(),
            argv=[sys.executable, "-c", python_command],
            envp=[
                "PATH=" + os.environ["PATH"],
                "PYTHONPATH=" + module_path,
                find.ENV_VAR + "=" + os.environ[find.ENV_VAR],
            ],
            flags=(GLib.SpawnFlags.SEARCH_PATH | GLib.SpawnFlags.DO_NOT_REAP_CHILD),
            child_setup=self._child_setup,
            user_data=vte_pty,
        )

        self.logger.info("vte spawned child process with pid: {0}".format(child_pid))
        self.child_pid = child_pid
        self.terminal.watch_child(child_pid)
        GLib.spawn_close_pid(child_pid)
        self.rpc_window.window.show_all()
        self.rpc_window.child_pid = child_pid
        return
Пример #13
0
def generate_signature(data):
    data = copy.deepcopy(data)
    data['hash'] = None
    return generate_hash(json_ex.dumps(data))