code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def export_message_data(self, path=None): """ Gather and prepare the components of the mailer tab to be exported into a King Phisher message (KPM) archive file suitable for restoring at a later point in time. If *path* is not specified, the user will be prompted to select one and failure to do so will prevent the message data from being exported. This function wraps the emission of the ``message-data-export`` signal. :param str path: An optional path of where to save the archive file to. :return: Whether or not the message archive file was written to disk. :rtype: bool """ config_tab = self.tabs.get('config') if not config_tab: self.logger.warning('attempted to export message data while the config tab was unavailable') return False if path is None: dialog = extras.FileChooserDialog('Export Message Configuration', self.parent) response = dialog.run_quick_save('message.kpm') dialog.destroy() if not response: return False path = response['target_path'] if not self.emit('message-data-export', path): return False gui_utilities.show_dialog_info('Success', self.parent, 'Successfully exported the message.') return True
Gather and prepare the components of the mailer tab to be exported into a King Phisher message (KPM) archive file suitable for restoring at a later point in time. If *path* is not specified, the user will be prompted to select one and failure to do so will prevent the message data from being exported. This function wraps the emission of the ``message-data-export`` signal. :param str path: An optional path of where to save the archive file to. :return: Whether or not the message archive file was written to disk. :rtype: bool
export_message_data
python
rsmusllp/king-phisher
king_phisher/client/tabs/mail.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/tabs/mail.py
BSD-3-Clause
def import_message_data(self): """ Process a previously exported message archive file and restore the message data, settings, and applicable files from it. This function wraps the emission of the ``message-data-import`` signal. :return: Whether or not the message archive file was loaded from disk. :rtype: bool """ config_tab = self.tabs.get('config') if not config_tab: self.logger.warning('attempted to import message data while the config tab was unavailable') return False config_tab.objects_save_to_config() dialog = extras.FileChooserDialog('Import Message Configuration', self.parent) dialog.quick_add_filter('King Phisher Message Files', '*.kpm') dialog.quick_add_filter('All Files', '*') response = dialog.run_quick_open() dialog.destroy() if not response: return False target_file = response['target_path'] dialog = extras.FileChooserDialog('Destination Directory', self.parent) response = dialog.run_quick_select_directory() dialog.destroy() if not response: return False dest_dir = response['target_path'] if not self.emit('message-data-import', target_file, dest_dir): return False gui_utilities.show_dialog_info('Success', self.parent, 'Successfully imported the message.') return True
Process a previously exported message archive file and restore the message data, settings, and applicable files from it. This function wraps the emission of the ``message-data-import`` signal. :return: Whether or not the message archive file was loaded from disk. :rtype: bool
import_message_data
python
rsmusllp/king-phisher
king_phisher/client/tabs/mail.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/tabs/mail.py
BSD-3-Clause
def do_populate(self, context): """ An automated function called by GtkSource.Completion, when :py:meth:`.do_match` returns True. This function is used to provide suggested completion words (referred to as proposals) for the context based on the match. This is done by creating a list of suggestions and adding them with :py:meth:`GtkSource.CompletionContext.add_proposals`. If :py:meth:`.extract` returns None, then :py:meth:`~.CustomCompletionProviderBase.populate` will not be called. :param context: The context for the completion. :type context: :py:class:`GtkSource.CompletionContext` """ match = self.extract(context) if match is None: # if extract returns none, return here without calling self.populate return proposals = [] try: matching_suggestions = self.populate(context, match) except Exception: self.logger.warning('encountered an exception in the completion populate routine', exc_info=True) return matching_suggestions.sort() for suggestion in matching_suggestions: if not suggestion: continue if isinstance(suggestion, str): item = GtkSource.CompletionItem(label=suggestion, text=suggestion) else: item = GtkSource.CompletionItem(label=suggestion[0], text=suggestion[1]) proposals.append(item) context.add_proposals(self, proposals, True)
An automated function called by GtkSource.Completion, when :py:meth:`.do_match` returns True. This function is used to provide suggested completion words (referred to as proposals) for the context based on the match. This is done by creating a list of suggestions and adding them with :py:meth:`GtkSource.CompletionContext.add_proposals`. If :py:meth:`.extract` returns None, then :py:meth:`~.CustomCompletionProviderBase.populate` will not be called. :param context: The context for the completion. :type context: :py:class:`GtkSource.CompletionContext`
do_populate
python
rsmusllp/king-phisher
king_phisher/client/widget/completion_providers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/completion_providers.py
BSD-3-Clause
def populate(self, context, match): """ Utilizes the match from the regular expression check to check for possible matches of :py:attr:`.jinja_vars`. :param context: The context for the completion. :type context: :py:class:`GtkSource.CompletionContext` :param match: The matching object. :types match: `re.MatchObject` :return: List of strings to be used for creation of proposals. :rtype: list """ proposal_terms = [] if match.group('is_filter'): jinja_filter = match.group('filter') or '' proposal_terms = [term for term in self.jinja_filters if term.startswith(jinja_filter)] elif match.group('is_test'): jinja_test = match.group('test') or '' proposal_terms = [term for term in self.jinja_tests if term.startswith(jinja_test)] elif match.group('var'): tokens = match.group('var') tokens = tokens.split('.') proposal_terms = get_proposal_terms(self.jinja_tokens, tokens) proposal_terms = [(term.split('(', 1)[0], term) for term in proposal_terms] return proposal_terms
Utilizes the match from the regular expression check to check for possible matches of :py:attr:`.jinja_vars`. :param context: The context for the completion. :type context: :py:class:`GtkSource.CompletionContext` :param match: The matching object. :types match: `re.MatchObject` :return: List of strings to be used for creation of proposals. :rtype: list
populate
python
rsmusllp/king-phisher
king_phisher/client/widget/completion_providers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/completion_providers.py
BSD-3-Clause
def __init__(self, title, parent, **kwargs): """ :param str title: The title for the file chooser dialog. :param parent: The parent window for the dialog. :type parent: :py:class:`Gtk.Window` """ utilities.assert_arg_type(parent, Gtk.Window, arg_pos=2) super(FileChooserDialog, self).__init__(title, parent, **kwargs) self.parent = self.get_parent_window()
:param str title: The title for the file chooser dialog. :param parent: The parent window for the dialog. :type parent: :py:class:`Gtk.Window`
__init__
python
rsmusllp/king-phisher
king_phisher/client/widget/extras.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/extras.py
BSD-3-Clause
def quick_add_filter(self, name, patterns): """ Add a filter for displaying files, this is useful in conjunction with :py:meth:`.run_quick_open`. :param str name: The name of the filter. :param patterns: The pattern(s) to match. :type patterns: list, str """ if not isinstance(patterns, (list, tuple)): patterns = (patterns,) new_filter = Gtk.FileFilter() new_filter.set_name(name) for pattern in patterns: new_filter.add_pattern(pattern) self.add_filter(new_filter)
Add a filter for displaying files, this is useful in conjunction with :py:meth:`.run_quick_open`. :param str name: The name of the filter. :param patterns: The pattern(s) to match. :type patterns: list, str
quick_add_filter
python
rsmusllp/king-phisher
king_phisher/client/widget/extras.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/extras.py
BSD-3-Clause
def run_quick_open(self): """ Display a dialog asking a user which file should be opened. The value of target_path in the returned dictionary is an absolute path. :return: A dictionary with target_uri and target_path keys representing the path chosen. :rtype: dict """ self.set_action(Gtk.FileChooserAction.OPEN) self.add_button(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL) self.add_button(Gtk.STOCK_OPEN, Gtk.ResponseType.ACCEPT) self.show_all() response = self.run() if response == Gtk.ResponseType.CANCEL: return None target_path = self.get_filename() if not os.access(target_path, os.R_OK): gui_utilities.show_dialog_error('Permissions Error', self.parent, 'Can not read the selected file.') return None target_uri = self.get_uri() return {'target_uri': target_uri, 'target_path': target_path}
Display a dialog asking a user which file should be opened. The value of target_path in the returned dictionary is an absolute path. :return: A dictionary with target_uri and target_path keys representing the path chosen. :rtype: dict
run_quick_open
python
rsmusllp/king-phisher
king_phisher/client/widget/extras.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/extras.py
BSD-3-Clause
def run_quick_save(self, current_name=None): """ Display a dialog which asks the user where a file should be saved. The value of target_path in the returned dictionary is an absolute path. :param set current_name: The name of the file to save. :return: A dictionary with target_uri and target_path keys representing the path chosen. :rtype: dict """ self.set_action(Gtk.FileChooserAction.SAVE) self.add_button(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL) self.add_button(Gtk.STOCK_SAVE, Gtk.ResponseType.ACCEPT) self.set_do_overwrite_confirmation(True) if current_name: self.set_current_name(current_name) self.show_all() response = self.run() if response == Gtk.ResponseType.CANCEL: return None target_path = self.get_filename() if os.path.isfile(target_path): if not os.access(target_path, os.W_OK): gui_utilities.show_dialog_error('Permissions Error', self.parent, 'Can not write to the selected file.') return None elif not os.access(os.path.dirname(target_path), os.W_OK): gui_utilities.show_dialog_error('Permissions Error', self.parent, 'Can not write to the selected path.') return None target_uri = self.get_uri() return {'target_uri': target_uri, 'target_path': target_path}
Display a dialog which asks the user where a file should be saved. The value of target_path in the returned dictionary is an absolute path. :param set current_name: The name of the file to save. :return: A dictionary with target_uri and target_path keys representing the path chosen. :rtype: dict
run_quick_save
python
rsmusllp/king-phisher
king_phisher/client/widget/extras.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/extras.py
BSD-3-Clause
def run_quick_select_directory(self): """ Display a dialog which asks the user to select a directory to use. The value of target_path in the returned dictionary is an absolute path. :return: A dictionary with target_uri and target_path keys representing the path chosen. :rtype: dict """ self.set_action(Gtk.FileChooserAction.SELECT_FOLDER) self.add_button(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL) self.add_button(Gtk.STOCK_OPEN, Gtk.ResponseType.ACCEPT) self.show_all() response = self.run() if response == Gtk.ResponseType.CANCEL: return None target_uri = self.get_uri() target_path = self.get_filename() return {'target_uri': target_uri, 'target_path': target_path}
Display a dialog which asks the user to select a directory to use. The value of target_path in the returned dictionary is an absolute path. :return: A dictionary with target_uri and target_path keys representing the path chosen. :rtype: dict
run_quick_select_directory
python
rsmusllp/king-phisher
king_phisher/client/widget/extras.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/extras.py
BSD-3-Clause
def load_html_data(self, html_data, html_file_uri=None): """ Load arbitrary HTML data into the WebKit engine to be rendered. :param str html_data: The HTML data to load into WebKit. :param str html_file_uri: The URI of the file where the HTML data came from. """ if isinstance(html_file_uri, str) and not html_file_uri.startswith('file://'): html_file_uri = 'file://' + html_file_uri if has_webkit2: self.load_html(html_data, html_file_uri) else: if html_file_uri is None: html_file_uri = 'file://' + os.getcwd() self.load_string(html_data, 'text/html', 'UTF-8', html_file_uri)
Load arbitrary HTML data into the WebKit engine to be rendered. :param str html_data: The HTML data to load into WebKit. :param str html_file_uri: The URI of the file where the HTML data came from.
load_html_data
python
rsmusllp/king-phisher
king_phisher/client/widget/extras.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/extras.py
BSD-3-Clause
def load_html_file(self, html_file): """ Load arbitrary HTML data from a file into the WebKit engine to be rendered. :param str html_file: The path to the file to load HTML data from. """ with codecs.open(html_file, 'r', encoding='utf-8') as file_h: html_data = file_h.read() self.load_html_data(html_data, html_file)
Load arbitrary HTML data from a file into the WebKit engine to be rendered. :param str html_file: The path to the file to load HTML data from.
load_html_file
python
rsmusllp/king-phisher
king_phisher/client/widget/extras.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/extras.py
BSD-3-Clause
def load_markdown_data(self, md_data, html_file_uri=None, gh_flavor=True, template=None, template_vars=None): """ Load markdown data, render it into HTML and then load it in to the WebKit engine. When *gh_flavor* is enabled, the markdown data is rendered using partial GitHub flavor support as provided by :py:class:`~mdx_partial_gfm.PartialGithubFlavoredMarkdownExtension`. If *template* is specified, it is used to load a Jinja2 template using :py:attr:`.template_env` into which the markdown data is passed in the variable ``markdown`` along with any others specified in the *template_vars* dictionary. :param str md_data: The markdown data to render into HTML for displaying. :param str html_file_uri: The URI of the file where the HTML data came from. :param bool gh_flavor: Whether or not to enable partial GitHub markdown syntax support. :param str template: The name of a Jinja2 HTML template to load for hosting the rendered markdown. :param template_vars: Additional variables to pass to the Jinja2 :py:class:`~jinja2.Template` when rendering it. :return: """ extensions = [] if gh_flavor: extensions = [mdx_partial_gfm.PartialGithubFlavoredMarkdownExtension()] md_data = markdown.markdown(md_data, extensions=extensions) if template: template = self.template_env.get_template(template) template_vars = template_vars or {} template_vars['markdown'] = jinja2.Markup(md_data) html = template.render(template_vars) else: html = md_data return self.load_html_data(html, html_file_uri=html_file_uri)
Load markdown data, render it into HTML and then load it in to the WebKit engine. When *gh_flavor* is enabled, the markdown data is rendered using partial GitHub flavor support as provided by :py:class:`~mdx_partial_gfm.PartialGithubFlavoredMarkdownExtension`. If *template* is specified, it is used to load a Jinja2 template using :py:attr:`.template_env` into which the markdown data is passed in the variable ``markdown`` along with any others specified in the *template_vars* dictionary. :param str md_data: The markdown data to render into HTML for displaying. :param str html_file_uri: The URI of the file where the HTML data came from. :param bool gh_flavor: Whether or not to enable partial GitHub markdown syntax support. :param str template: The name of a Jinja2 HTML template to load for hosting the rendered markdown. :param template_vars: Additional variables to pass to the Jinja2 :py:class:`~jinja2.Template` when rendering it. :return:
load_markdown_data
python
rsmusllp/king-phisher
king_phisher/client/widget/extras.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/extras.py
BSD-3-Clause
def load_markdown_file(self, md_file, **kwargs): """ Load markdown data from a file and render it using :py:meth:`~.load_markdown_data`. :param str md_file: The path to the file to load markdown data from. :param kwargs: Additional keyword arguments to pass to :py:meth:`~.load_markdown_data`. """ with codecs.open(md_file, 'r', encoding='utf-8') as file_h: md_data = file_h.read() return self.load_markdown_data(md_data, md_file, **kwargs)
Load markdown data from a file and render it using :py:meth:`~.load_markdown_data`. :param str md_file: The path to the file to load markdown data from. :param kwargs: Additional keyword arguments to pass to :py:meth:`~.load_markdown_data`.
load_markdown_file
python
rsmusllp/king-phisher
king_phisher/client/widget/extras.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/extras.py
BSD-3-Clause
def __init__(self, glade_gobject, widget_type, group_name): """ :param glade_gobject: The gobject which has the radio buttons set. :type glade_gobject: :py:class:`.GladeGObject` :param str group_name: The name of the group of buttons. """ utilities.assert_arg_type(glade_gobject, gui_utilities.GladeGObject) self.group_name = group_name name_prefix = widget_type + '_' + self.group_name + '_' self.buttons = utilities.FreezableDict() for gobj_name in glade_gobject.dependencies.children: if not gobj_name.startswith(name_prefix): continue button_name = gobj_name[len(name_prefix):] self.buttons[button_name] = glade_gobject.gobjects[gobj_name] if not len(self.buttons): raise ValueError('found no ' + widget_type + ' of group: ' + self.group_name) self.buttons.freeze()
:param glade_gobject: The gobject which has the radio buttons set. :type glade_gobject: :py:class:`.GladeGObject` :param str group_name: The name of the group of buttons.
__init__
python
rsmusllp/king-phisher
king_phisher/client/widget/managers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/managers.py
BSD-3-Clause
def get_active(self): """ Return the name of the active button if one in the group is active. If no button in the group is active, None is returned. :return: The name of the active button. :rtype: str """ for name, button in self.buttons.items(): if button.get_active(): return name return
Return the name of the active button if one in the group is active. If no button in the group is active, None is returned. :return: The name of the active button. :rtype: str
get_active
python
rsmusllp/king-phisher
king_phisher/client/widget/managers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/managers.py
BSD-3-Clause
def set_active(self, buttons): """ Set the specified buttons to active or not. :param dict buttons: A mapping of button names to boolean values. """ for name, active in buttons.items(): button = self.buttons.get(name) if button is None: raise ValueError('invalid button name: ' + name) button.set_active(active)
Set the specified buttons to active or not. :param dict buttons: A mapping of button names to boolean values.
set_active
python
rsmusllp/king-phisher
king_phisher/client/widget/managers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/managers.py
BSD-3-Clause
def __init__(self, menu=None): """ :param menu: An optional menu to start with. If a menu is specified it is used as is, otherwise a new instance is used and is set to be visible using :py:meth:`~Gtk.Widget.show`. :type menu: :py:class:`Gtk.Menu` """ if menu is None: menu = Gtk.Menu() menu.show() self.menu = menu self.items = collections.OrderedDict()
:param menu: An optional menu to start with. If a menu is specified it is used as is, otherwise a new instance is used and is set to be visible using :py:meth:`~Gtk.Widget.show`. :type menu: :py:class:`Gtk.Menu`
__init__
python
rsmusllp/king-phisher
king_phisher/client/widget/managers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/managers.py
BSD-3-Clause
def append(self, label, activate=None, activate_args=()): """ Create and append a new :py:class:`Gtk.MenuItem` with the specified label to the menu. :param str label: The label for the new menu item. :param activate: An optional callback function to connect to the new menu item's ``activate`` signal. :return: Returns the newly created and added menu item. :rtype: :py:class:`Gtk.MenuItem` """ if label in self.items: raise RuntimeError('label already exists in menu items') menu_item = Gtk.MenuItem.new_with_label(label) self.items[label] = menu_item self.append_item(menu_item) if activate: menu_item.connect('activate', activate, *activate_args) return menu_item
Create and append a new :py:class:`Gtk.MenuItem` with the specified label to the menu. :param str label: The label for the new menu item. :param activate: An optional callback function to connect to the new menu item's ``activate`` signal. :return: Returns the newly created and added menu item. :rtype: :py:class:`Gtk.MenuItem`
append
python
rsmusllp/king-phisher
king_phisher/client/widget/managers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/managers.py
BSD-3-Clause
def append_item(self, menu_item, set_show=True): """ Append the specified menu item to the menu. :param menu_item: The item to append to the menu. :type menu_item: :py:class:`Gtk.MenuItem` :param bool set_show: Whether to set the item to being visible or leave it as is. """ if set_show: menu_item.show() self.menu.append(menu_item) return menu_item
Append the specified menu item to the menu. :param menu_item: The item to append to the menu. :type menu_item: :py:class:`Gtk.MenuItem` :param bool set_show: Whether to set the item to being visible or leave it as is.
append_item
python
rsmusllp/king-phisher
king_phisher/client/widget/managers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/managers.py
BSD-3-Clause
def append_submenu(self, label): """ Create and append a submenu item, then return a new menu manager instance for it. :param str label: The label for the new menu item. :return: Returns the newly created and added menu item. :rtype: :py:class:`Gtk.MenuManager` """ submenu = self.__class__() submenu_item = Gtk.MenuItem.new_with_label(label) submenu_item.set_submenu(submenu.menu) self.append_item(submenu_item) return submenu
Create and append a submenu item, then return a new menu manager instance for it. :param str label: The label for the new menu item. :return: Returns the newly created and added menu item. :rtype: :py:class:`Gtk.MenuManager`
append_submenu
python
rsmusllp/king-phisher
king_phisher/client/widget/managers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/managers.py
BSD-3-Clause
def __init__(self, treeview, selection_mode=None, cb_delete=None, cb_refresh=None): """ :param treeview: The treeview to wrap and manage. :type treeview: :py:class:`Gtk.TreeView` :param selection_mode: The selection mode to set for the treeview. :type selection_mode: :py:class:`Gtk.SelectionMode` :param cb_delete: An optional callback that can be used to delete entries. :type cb_delete: function """ self.treeview = treeview """The :py:class:`Gtk.TreeView` instance being managed.""" self.cb_delete = cb_delete """An optional callback for deleting entries from the treeview's model.""" self.cb_refresh = cb_refresh """An optional callback for refreshing the data in the treeview's model.""" self.column_titles = collections.OrderedDict() """An ordered dictionary of storage data columns keyed by their respective column titles.""" self.column_views = {} """A dictionary of column treeview's keyed by their column titles.""" self.treeview.connect('key-press-event', self.signal_key_press_event) if selection_mode is None: selection_mode = Gtk.SelectionMode.SINGLE treeview.get_selection().set_mode(selection_mode) self._menu_items = {}
:param treeview: The treeview to wrap and manage. :type treeview: :py:class:`Gtk.TreeView` :param selection_mode: The selection mode to set for the treeview. :type selection_mode: :py:class:`Gtk.SelectionMode` :param cb_delete: An optional callback that can be used to delete entries. :type cb_delete: function
__init__
python
rsmusllp/king-phisher
king_phisher/client/widget/managers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/managers.py
BSD-3-Clause
def get_popup_menu(self, handle_button_press=True): """ Create a :py:class:`Gtk.Menu` with entries for copying and optionally delete cell data from within the treeview. The delete option will only be available if a delete callback was previously set. :param bool handle_button_press: Whether or not to connect a handler for displaying the popup menu. :return: The populated popup menu. :rtype: :py:class:`Gtk.Menu` """ popup_copy_submenu = self.get_popup_copy_submenu() popup_menu = Gtk.Menu.new() menu_item = Gtk.MenuItem.new_with_label('Copy') menu_item.set_submenu(popup_copy_submenu) popup_menu.append(menu_item) self._menu_items['Copy'] = menu_item if self.cb_delete: menu_item = Gtk.SeparatorMenuItem() popup_menu.append(menu_item) menu_item = Gtk.MenuItem.new_with_label('Delete') menu_item.connect('activate', self.signal_activate_popup_menu_delete) popup_menu.append(menu_item) self._menu_items['Delete'] = menu_item popup_menu.show_all() if handle_button_press: self.treeview.connect('button-press-event', self.signal_button_pressed, popup_menu) return popup_menu
Create a :py:class:`Gtk.Menu` with entries for copying and optionally delete cell data from within the treeview. The delete option will only be available if a delete callback was previously set. :param bool handle_button_press: Whether or not to connect a handler for displaying the popup menu. :return: The populated popup menu. :rtype: :py:class:`Gtk.Menu`
get_popup_menu
python
rsmusllp/king-phisher
king_phisher/client/widget/managers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/managers.py
BSD-3-Clause
def get_popup_copy_submenu(self): """ Create a :py:class:`Gtk.Menu` with entries for copying cell data from the treeview. :return: The populated copy popup menu. :rtype: :py:class:`Gtk.Menu` """ copy_menu = Gtk.Menu.new() for column_title, store_id in self.column_titles.items(): menu_item = Gtk.MenuItem.new_with_label(column_title) menu_item.connect('activate', self.signal_activate_popup_menu_copy, store_id) copy_menu.append(menu_item) if len(self.column_titles) > 1: menu_item = Gtk.SeparatorMenuItem() copy_menu.append(menu_item) menu_item = Gtk.MenuItem.new_with_label('All') menu_item.connect('activate', self.signal_activate_popup_menu_copy, self.column_titles.values()) copy_menu.append(menu_item) return copy_menu
Create a :py:class:`Gtk.Menu` with entries for copying cell data from the treeview. :return: The populated copy popup menu. :rtype: :py:class:`Gtk.Menu`
get_popup_copy_submenu
python
rsmusllp/king-phisher
king_phisher/client/widget/managers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/managers.py
BSD-3-Clause
def set_column_color(self, background=None, foreground=None, column_titles=None): """ Set a column in the model to be used as either the background or foreground RGBA color for a cell. :param int background: The column id of the model to use as the background color. :param int foreground: The column id of the model to use as the foreground color. :param column_titles: The columns to set the color for, if None is specified all columns will be set. :type column_titles: str, tuple """ if background is None and foreground is None: raise RuntimeError('either background of foreground must be set') if column_titles is None: column_titles = self.column_titles.keys() elif isinstance(column_titles, str): column_titles = (column_titles,) for column_title in column_titles: column = self.column_views[column_title] renderer = column.get_cells()[0] if background is not None: column.add_attribute(renderer, 'background-rgba', background) column.add_attribute(renderer, 'background-set', True) if foreground is not None: column.add_attribute(renderer, 'foreground-rgba', foreground) column.add_attribute(renderer, 'foreground-set', True)
Set a column in the model to be used as either the background or foreground RGBA color for a cell. :param int background: The column id of the model to use as the background color. :param int foreground: The column id of the model to use as the foreground color. :param column_titles: The columns to set the color for, if None is specified all columns will be set. :type column_titles: str, tuple
set_column_color
python
rsmusllp/king-phisher
king_phisher/client/widget/managers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/managers.py
BSD-3-Clause
def set_column_titles(self, column_titles, column_offset=0, renderers=None): """ Populate the column names of a GTK TreeView and set their sort IDs. This also populates the :py:attr:`.column_titles` attribute. :param list column_titles: The titles of the columns. :param int column_offset: The offset to start setting column names at. :param list renderers: A list containing custom renderers to use for each column. :return: A dict of all the :py:class:`Gtk.TreeViewColumn` objects keyed by their column id. :rtype: dict """ self.column_titles.update((v, k) for (k, v) in enumerate(column_titles, column_offset)) columns = gui_utilities.gtk_treeview_set_column_titles(self.treeview, column_titles, column_offset=column_offset, renderers=renderers) for store_id, column_title in enumerate(column_titles, column_offset): self.column_views[column_title] = columns[store_id] return columns
Populate the column names of a GTK TreeView and set their sort IDs. This also populates the :py:attr:`.column_titles` attribute. :param list column_titles: The titles of the columns. :param int column_offset: The offset to start setting column names at. :param list renderers: A list containing custom renderers to use for each column. :return: A dict of all the :py:class:`Gtk.TreeViewColumn` objects keyed by their column id. :rtype: dict
set_column_titles
python
rsmusllp/king-phisher
king_phisher/client/widget/managers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/managers.py
BSD-3-Clause
def __init__(self, application, button, value=None): """ :param button: The button used for activation. :type button: :py:class:`Gtk.ToggleButton` :param application: The application instance which owns this object. :param value: The present datetime value (defaults to 00:00). :type value: :py:class:`datetime.time` """ self.popover = _TimeSelector(application) self.button = button self.application = application self._time_format = "{time.hour:02}:{time.minute:02}" self._hour_spin = self.popover.gobjects['spinbutton_hour'] self._hour_spin.connect('value-changed', lambda _: self.button.set_label(self._time_format.format(time=self.time))) self._minute_spin = self.popover.gobjects['spinbutton_minute'] self._minute_spin.connect('value-changed', lambda _: self.button.set_label(self._time_format.format(time=self.time))) self.time = value or datetime.time(0, 0) self.popover.popover.set_relative_to(self.button) self.popover.popover.connect('closed', lambda _: self.button.set_active(False)) self.button.connect('toggled', self.signal_button_toggled)
:param button: The button used for activation. :type button: :py:class:`Gtk.ToggleButton` :param application: The application instance which owns this object. :param value: The present datetime value (defaults to 00:00). :type value: :py:class:`datetime.time`
__init__
python
rsmusllp/king-phisher
king_phisher/client/widget/managers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/managers.py
BSD-3-Clause
def time(self, value): """ :param value: value from self.popover.gobjects['spinbutton_xx'] :return: The new time value to self.time """ if not isinstance(value, datetime.time): raise TypeError('argument 1 must be a datetime.time instance') self._hour_spin.set_value(value.hour) self._minute_spin.set_value(value.minute) self.button.set_label(self._time_format.format(time=value))
:param value: value from self.popover.gobjects['spinbutton_xx'] :return: The new time value to self.time
time
python
rsmusllp/king-phisher
king_phisher/client/widget/managers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/widget/managers.py
BSD-3-Clause
def _update_id(self, element, id_fields, old_id, new_id): """ Iterates through the element and replaces the specified old ID with the new ID in the requested ID fields. :param element: Element to iterate over where the old id values can be found. :type element: :py:class:`xml.etree.ElementTree.Element` :param list id_fields: The list of fields to look for old_id. :param old_id: The old id value that has been changed :param new_id: The new id value to set. """ for nods in element.iter(): if nods.tag in id_fields and nods.text == old_id: nods.text = new_id # if new_id is none set type to null if new_id is None: nods.attrib['type'] = 'null'
Iterates through the element and replaces the specified old ID with the new ID in the requested ID fields. :param element: Element to iterate over where the old id values can be found. :type element: :py:class:`xml.etree.ElementTree.Element` :param list id_fields: The list of fields to look for old_id. :param old_id: The old id value that has been changed :param new_id: The new id value to set.
_update_id
python
rsmusllp/king-phisher
king_phisher/client/windows/campaign_import.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/windows/campaign_import.py
BSD-3-Clause
def signal_entry_change(self, _): """ When there is a change in the campaign entry field it will check to see if the name is already in use. If it is not in use it will change the sensitivity of the :py:attr:`.button_import_campaign` to allow the user to start the import process. """ if not self.campaign_info: return if not self._check_campaign_name(self.entry_campaign_name.get_text()): self.button_import_campaign.set_sensitive(False) return self.button_import_campaign.set_sensitive(True) return
When there is a change in the campaign entry field it will check to see if the name is already in use. If it is not in use it will change the sensitivity of the :py:attr:`.button_import_campaign` to allow the user to start the import process.
signal_entry_change
python
rsmusllp/king-phisher
king_phisher/client/windows/campaign_import.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/windows/campaign_import.py
BSD-3-Clause
def signal_window_delete_event(self, _, event): """ Checks to make sure the import campaign thread is closed before closing the window. """ if not self.campaign_info: return False if not self.thread_import_campaign: return False if not self.thread_import_campaign.is_alive(): return False response = gui_utilities.show_dialog_yes_no( 'Cancel Importing?', self.window, 'Do you want to cancel importing the campaign?' ) if not response: return True self.thread_import_campaign.stop() self.thread_import_campaign.join() self._import_cleanup(remove_campaign=True)
Checks to make sure the import campaign thread is closed before closing the window.
signal_window_delete_event
python
rsmusllp/king-phisher
king_phisher/client/windows/campaign_import.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/windows/campaign_import.py
BSD-3-Clause
def remove_import_campaign(self): """ Used to delete the imported campaign on failure or early exit of the import window, if the user selects to have it removed. """ campaign_id = self.campaign_info.find('id').text campaign_name = self.campaign_info.find('name').text campaign_check = self.rpc('db/table/get', 'campaigns', campaign_id) if not campaign_check: return if campaign_name == campaign_check['name']: self.rpc('db/table/delete', 'campaigns', campaign_id) self.logger.info("deleted campaign {}".format(campaign_id))
Used to delete the imported campaign on failure or early exit of the import window, if the user selects to have it removed.
remove_import_campaign
python
rsmusllp/king-phisher
king_phisher/client/windows/campaign_import.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/windows/campaign_import.py
BSD-3-Clause
def signal_import_button(self, _): """ This will check to see if the campaign information is present. If campaign information is present it will launch an py:class:`ImportThread` to import the campaign in the background, freeing up the GUI for the user to conduct other functions. """ if not self.campaign_info: self._update_text_view('No campaign information to import') self.button_import_campaign.set_sensitive(False) return self.thread_import_campaign = ImportThread(target=self._import_campaign) self.thread_import_campaign.start()
This will check to see if the campaign information is present. If campaign information is present it will launch an py:class:`ImportThread` to import the campaign in the background, freeing up the GUI for the user to conduct other functions.
signal_import_button
python
rsmusllp/king-phisher
king_phisher/client/windows/campaign_import.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/windows/campaign_import.py
BSD-3-Clause
def select_xml_campaign(self): """ Prompts the user with a file dialog window to select the King Phisher Campaign XML file to import. Validates the file to make sure it is a Campaign exported from King Phisher and is the correct version to import. """ dialog = extras.FileChooserDialog('Import Campaign from XML', self.window) dialog.quick_add_filter('King Phisher XML Campaign', '*.xml') dialog.quick_add_filter('All Files', '*') response = dialog.run_quick_open() dialog.destroy() if not response: return target_file = response['target_path'] self.entry_path.set_text(target_file) try: campaign_xml = ET.parse(target_file) except ET.ParseError as error: self.logger.error("cannot import campaign file: {0} (not a valid xml file)".format(target_file)) gui_utilities.show_dialog_error( 'Improper Format', self.window, 'File is not valid XML' ) return root = campaign_xml.getroot() if root.tag != 'king_phisher': self.logger.error("cannot import campaign file: {0} (invalid root xml tag)".format(target_file)) gui_utilities.show_dialog_error( 'Improper Format', self.window, 'File is not a valid King Phisher XML campaign file' ) return meta_data = root.find('metadata') if meta_data.find('version').text < '1.3': self.logger.error("cannot import campaign file: {0} (incompatible version)".format(target_file)) gui_utilities.show_dialog_error( 'Invalid Version', self.window, 'Cannot import XML campaign data less then version 1.3' ) return self.campaign_info = root.find('campaign') if not self.campaign_info: self.logger.error("cannot import campaign file: {0} (no campaign data found)".format(target_file)) gui_utilities.show_dialog_error( 'No Campaign Data', self.window, 'No campaign data to import' ) return self.db_campaigns = self.rpc.graphql("{ db { campaigns { edges { node { id, name } } } } }")['db']['campaigns']['edges'] self.entry_campaign_name.set_text(self.campaign_info.find('name').text) self.thread_import_campaign = None if not self._check_campaign_name(self.campaign_info.find('name').text, verbose=True): self.button_import_campaign.set_sensitive(False) return self.button_import_campaign.set_sensitive(True)
Prompts the user with a file dialog window to select the King Phisher Campaign XML file to import. Validates the file to make sure it is a Campaign exported from King Phisher and is the correct version to import.
select_xml_campaign
python
rsmusllp/king-phisher
king_phisher/client/windows/campaign_import.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/windows/campaign_import.py
BSD-3-Clause
def _check_campaign_name(self, campaign_name, verbose=False): """ Will check to see if the provided campaign name is safe to use. :param str campaign_name: campaign name to check :param bool verbose: If true will update output to text buffer. :return: True if campaign name can be used :rtype: bool """ if not self.campaign_info or not self.db_campaigns: return False if next((nodes for nodes in self.db_campaigns if nodes['node']['name'] == campaign_name), None): if verbose: self._update_text_view("Campaign name {} is already in use by another campaign.".format(campaign_name), idle=True) return False if verbose: self._update_text_view("Campaign Name {} is not in use, ready to import".format(campaign_name), idle=True) return True
Will check to see if the provided campaign name is safe to use. :param str campaign_name: campaign name to check :param bool verbose: If true will update output to text buffer. :return: True if campaign name can be used :rtype: bool
_check_campaign_name
python
rsmusllp/king-phisher
king_phisher/client/windows/campaign_import.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/windows/campaign_import.py
BSD-3-Clause
def preprep_xml_data(self): """ This function provides the actions required to see if required IDs are already in the database. If they are not it will clear them out and set subelement.attrib['type'] to null. If the element is required it will set it to a default value. This will normalize the data and ready it for import into the database. """ self._set_text_view('Normalizing Campaign Data') self.campaign_info.find('name').text = self.entry_campaign_name.get_text() campaign_type_check = self.rpc('db/table/get', 'campaign_types', self.campaign_info.find('campaign_type_id').text) if not campaign_type_check: temp_string = 'Campaign type not found, removing' self.logger.info(temp_string.lower()) self._update_text_view(temp_string, idle=True) reset_node = self.campaign_info.find('campaign_type_id') reset_node.clear() reset_node.attrib['type'] = 'null' if self.campaign_info.find('user_id').text != self.config['server_username']: temp_string = 'Setting the campaign owner to the current user' self.logger.info(temp_string.lower()) self._update_text_view(temp_string, idle=True) self.campaign_info.find('user_id').text = self.config['server_username'] company_id_check = self.rpc('db/table/get', 'companies', int(self.campaign_info.find('company_id').text)) if not company_id_check: temp_string = 'Company id not found, removing' self.logger.info(temp_string.lower()) self._update_text_view(temp_string, idle=True) reset_node = self.campaign_info.find('company_id') reset_node.clear() reset_node.attrib['type'] = 'null' for message in self.campaign_info.find('messages').getiterator(): if message.tag != 'company_department_id': continue if not message.text: continue self.logger.info("checking company_department_id {}".format(message.text)) company_department_id_check = self.rpc('db/table/get', 'company_departments', message.text) if not company_department_id_check: temp_string = "Company department id {} not found, removing it from campaign".format(message.text) self.logger.info(temp_string.lower()) self._update_text_view(temp_string, idle=True) self._update_id(self.campaign_info, ['company_department_id'], message.text, None)
This function provides the actions required to see if required IDs are already in the database. If they are not it will clear them out and set subelement.attrib['type'] to null. If the element is required it will set it to a default value. This will normalize the data and ready it for import into the database.
preprep_xml_data
python
rsmusllp/king-phisher
king_phisher/client/windows/campaign_import.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/windows/campaign_import.py
BSD-3-Clause
def _import_campaign(self): """ Used by the import thread to import the campaign into the database. Through this process after every major action, the thread will check to see if it has been requested to stop. """ self.logger.debug("import campaign running in tid: 0x{0:x}".format(threading.current_thread().ident)) if not self.campaign_info: return # prevent user from changing campaign info during import start_time = datetime.datetime.now() GLib.idle_add(self.button_import_campaign.set_sensitive, False) GLib.idle_add(self.button_select.set_sensitive, False) GLib.idle_add(self.spinner.start) batch_size = 100 if self.thread_import_campaign.stopped(): return self.preprep_xml_data() self.campaign_info.find('id').text = self.rpc( 'campaign/new', self.campaign_info.find('name').text, self.campaign_info.find('description').text ) self.logger.info("created new campaign id: {}".format(self.campaign_info.find('id').text)) nodes_completed = 0 node_count = float(len(self.campaign_info.findall('.//*'))) if self.thread_import_campaign.stopped(): return for nods in self.campaign_info.getiterator(): if nods.tag == 'campaign_id': nods.text = self.campaign_info.find('id').text self._update_text_view("Campaign created, ID set to {}".format(self.campaign_info.find('id').text), idle=True) keys = [] values = [] if self.thread_import_campaign.stopped(): return for elements in self.campaign_info: if elements.tag in ('id', 'landing_pages', 'messages', 'visits', 'credentials', 'deaddrop_deployments', 'deaddrop_connections'): continue keys.append(elements.tag) values.append(elements.text) self.rpc('db/table/set', 'campaigns', int(self.campaign_info.find('id').text), tuple(keys), tuple(values)) nodes_completed += float(len(values) + 1) percentage_completed = nodes_completed / node_count GLib.idle_add(self.import_progress.set_fraction, percentage_completed) if self.thread_import_campaign.stopped(): return for tables in ('landing_pages', 'messages', 'visits', 'credentials', 'deaddrop_deployments', 'deaddrop_connections'): inserted_ids = [] if self.thread_import_campaign.stopped(): return self._update_text_view("Serializing table {} data for import".format(tables), idle=True) keys, rows = self._get_keys_values(self.campaign_info.find(tables)) self._update_text_view("Working on table {} adding {} rows".format(tables, len(rows)), idle=True) if self.thread_import_campaign.stopped(): return # make table rows easy to manage for updating new ids returned table_rows = [] for row in rows: row = dict(zip(keys, row)) table_rows.append(row) while rows and not self.thread_import_campaign.stopped(): try: inserted_ids = inserted_ids + self.rpc('/db/table/insert/multi', tables, keys, rows[:batch_size], deconflict_ids=True) except advancedhttpserver.RPCError: response = gui_utilities.glib_idle_add_wait(self.failed_import_action) self._import_cleanup(remove_campaign=response) failed_string = 'Failed to import campaign, all partial campaign data ' + ('has been removed' if response else 'was left in place') self.logger.warning(failed_string.lower()) self._update_text_view(failed_string, idle=True) return rows = rows[batch_size:] nodes_completed += float(batch_size * len(keys)) percentage_completed = nodes_completed / node_count GLib.idle_add(self.import_progress.set_fraction, percentage_completed) if self.thread_import_campaign.stopped(): return # update id fields to maintain relationships self._update_text_view("Updating dependencies for table: {}".format(tables), idle=True) for id_ in inserted_ids: if id_ != table_rows[inserted_ids.index(id_)]['id']: self._update_id( self.campaign_info, ['id', "{}_id".format(tables[:-1])], table_rows[inserted_ids.index(id_)]['id'], id_ ) GLib.idle_add(self.import_progress.set_fraction, 1.0) self._import_cleanup() done_string = "Done importing campaign. Importing the campaign took {}".format(datetime.datetime.now() - start_time) self._update_text_view(done_string, idle=True) self.logger.info(done_string.lower())
Used by the import thread to import the campaign into the database. Through this process after every major action, the thread will check to see if it has been requested to stop.
_import_campaign
python
rsmusllp/king-phisher
king_phisher/client/windows/campaign_import.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/windows/campaign_import.py
BSD-3-Clause
def load_campaigns(self): """Load campaigns from the remote server and populate the :py:class:`Gtk.TreeView`.""" store = self._model store.clear() campaigns = self.application.rpc.graphql_find_file('get_campaigns.graphql') for campaign in campaigns['db']['campaigns']['edges']: campaign = campaign['node'] company = campaign['company']['name'] if campaign['company'] else None created_ts = utilities.datetime_utc_to_local(campaign['created']) created_ts = utilities.format_datetime(created_ts) campaign_type = campaign['campaignType']['name'] if campaign['campaignType'] else None expiration_ts = campaign['expiration'] if expiration_ts is not None: expiration_ts = utilities.datetime_utc_to_local(expiration_ts) expiration_ts = utilities.format_datetime(expiration_ts) store.append(( campaign['id'], False, campaign['name'], company, campaign_type, campaign['user']['name'], created_ts, expiration_ts ))
Load campaigns from the remote server and populate the :py:class:`Gtk.TreeView`.
load_campaigns
python
rsmusllp/king-phisher
king_phisher/client/windows/compare_campaigns.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/windows/compare_campaigns.py
BSD-3-Clause
def __init__(self, config, application): """ :param dict config: The main King Phisher client configuration. :param application: The application instance to which this window belongs. :type application: :py:class:`.KingPhisherClientApplication` """ utilities.assert_arg_type(application, Gtk.Application, arg_pos=2) super(MainAppWindow, self).__init__(application=application) self.set_property('hexpand', False) self.set_property('vexpand', False) self.set_property('window-position', Gtk.WindowPosition.NONE) self.application = application self.logger = logging.getLogger('KingPhisher.Client.MainWindow') self.config = config """The main King Phisher client configuration.""" self.set_property('role', 'main') self.set_property('title', 'King Phisher') vbox = Gtk.Box() vbox.set_property('orientation', Gtk.Orientation.VERTICAL) vbox.show() self.add(vbox) default_icon_file = find.data_file('king-phisher-icon.svg') if default_icon_file: icon_pixbuf = GdkPixbuf.Pixbuf.new_from_file(default_icon_file) self.set_default_icon(icon_pixbuf) self.accel_group = Gtk.AccelGroup() self.add_accel_group(self.accel_group) self.menu_bar = MainMenuBar(application, self) vbox.pack_start(self.menu_bar.menubar, False, False, 0) # create notebook and tabs self.notebook = Gtk.Notebook() """The primary :py:class:`Gtk.Notebook` that holds the top level taps of the client GUI.""" self.notebook.connect('switch-page', self.signal_notebook_switch_page) self.notebook.set_scrollable(True) vbox.pack_start(self.notebook, True, True, 0) self.tabs = {} current_page = self.notebook.get_current_page() self.last_page_id = current_page mailer_tab = MailSenderTab(self, self.application) self.tabs['mailer'] = mailer_tab self.notebook.insert_page(mailer_tab.box, mailer_tab.label, current_page + 1) self.notebook.set_current_page(current_page + 1) campaign_tab = CampaignViewTab(self, self.application) campaign_tab.box.show() self.tabs['campaign'] = campaign_tab self.notebook.insert_page(campaign_tab.box, campaign_tab.label, current_page + 2) self.set_size_request(800, 600) self.connect('delete-event', self.signal_delete_event) self.notebook.show() self.show() self.rpc = None # needs to be initialized last """The :py:class:`.KingPhisherRPCClient` instance.""" self.application.connect('server-connected', self.signal_kp_server_connected) self.login_dialog = dialogs.LoginDialog(self.application) self.login_dialog.dialog.connect('response', self.signal_login_dialog_response) self.login_dialog.show()
:param dict config: The main King Phisher client configuration. :param application: The application instance to which this window belongs. :type application: :py:class:`.KingPhisherClientApplication`
__init__
python
rsmusllp/king-phisher
king_phisher/client/windows/main.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/windows/main.py
BSD-3-Clause
def export_campaign_xlsx(self): """Export the current campaign to an Excel compatible XLSX workbook.""" dialog = extras.FileChooserDialog('Export Campaign To Excel', self) file_name = self.config['campaign_name'] + '.xlsx' response = dialog.run_quick_save(file_name) dialog.destroy() if not response: return destination_file = response['target_path'] campaign_tab = self.tabs['campaign'] workbook = xlsxwriter.Workbook(destination_file) title_format = workbook.add_format({'bold': True, 'size': 18}) for tab_name, tab in campaign_tab.tabs.items(): if not isinstance(tab, CampaignViewGenericTableTab): continue tab.export_table_to_xlsx_worksheet(workbook.add_worksheet(tab_name), title_format) workbook.close()
Export the current campaign to an Excel compatible XLSX workbook.
export_campaign_xlsx
python
rsmusllp/king-phisher
king_phisher/client/windows/main.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/windows/main.py
BSD-3-Clause
def export_campaign_xml(self): """Export the current campaign to an XML data file.""" dialog = extras.FileChooserDialog('Export Campaign XML Data', self) file_name = self.config['campaign_name'] + '.xml' response = dialog.run_quick_save(file_name) dialog.destroy() if not response: return destination_file = response['target_path'] export.campaign_to_xml(self.rpc, self.config['campaign_id'], destination_file)
Export the current campaign to an XML data file.
export_campaign_xml
python
rsmusllp/king-phisher
king_phisher/client/windows/main.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/windows/main.py
BSD-3-Clause
def export_campaign_visit_geojson(self): """ Export the current campaign visit information to a GeoJSON data file. """ dialog = extras.FileChooserDialog('Export Campaign Visit GeoJSON Data', self) file_name = self.config['campaign_name'] + '.geojson' response = dialog.run_quick_save(file_name) dialog.destroy() if not response: return destination_file = response['target_path'] export.campaign_visits_to_geojson(self.rpc, self.config['campaign_id'], destination_file)
Export the current campaign visit information to a GeoJSON data file.
export_campaign_visit_geojson
python
rsmusllp/king-phisher
king_phisher/client/windows/main.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/windows/main.py
BSD-3-Clause
def __init__(self, application, plugin_id): """ :param application: The parent application for this object. :type application: :py:class:`Gtk.Application` :param str plugin_id: The identifier of this plugin. """ super(PluginDocumentationWindow, self).__init__(application) plugin_path = self.application.plugin_manager.get_plugin_path(plugin_id) if plugin_path is None: raise FileNotFoundError(errno.ENOENT, "could not find the data path for plugin '{0}'".format(plugin_id)) md_file = os.path.join(plugin_path, 'README.md') if md_file is None or not os.path.isfile(md_file): self.window.destroy() raise FileNotFoundError(errno.ENOENT, "plugin '{0}' has no documentation".format(plugin_id), md_file) self._md_file = md_file self._plugin = self.application.plugin_manager[plugin_id] self.refresh() self.webview.connect('key-press-event', self.signal_key_press_event) self.webview.connect('open-remote-uri', self.signal_webview_open_remote_uri) self.window.set_title('Plugin Documentation')
:param application: The parent application for this object. :type application: :py:class:`Gtk.Application` :param str plugin_id: The identifier of this plugin.
__init__
python
rsmusllp/king-phisher
king_phisher/client/windows/plugin_manager.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/windows/plugin_manager.py
BSD-3-Clause
def __store_add_node(self, node, parent=None): """ Add a :py:class:`._ModelNode` to :py:attr:`._model`, recursively adding child :py:class:`._ModelNode` or :py:class:`._ModelNamedRow` instances as necessary. This is *not* tsafe. :param node: The node to add to the TreeView model. :type node: :py:class:`._ModelNode` :param parent: An optional parent for the node, used for recursion. """ row = self._model.append(parent, node.row) for child in node.children: if isinstance(child, _ModelNode): self.__store_add_node(child, parent=row) elif isinstance(child, _ModelNamedRow): self._model.append(row, child) else: raise TypeError('unsupported node child type')
Add a :py:class:`._ModelNode` to :py:attr:`._model`, recursively adding child :py:class:`._ModelNode` or :py:class:`._ModelNamedRow` instances as necessary. This is *not* tsafe. :param node: The node to add to the TreeView model. :type node: :py:class:`._ModelNode` :param parent: An optional parent for the node, used for recursion.
__store_add_node
python
rsmusllp/king-phisher
king_phisher/client/windows/plugin_manager.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/windows/plugin_manager.py
BSD-3-Clause
def _add_catalog_to_tree_tsafe(self, catalog): """ Create a :py:class:`._ModelNode` instance to representing the catalog, its data and add it to the TreeView model. :param catalog: The catalog to add to the TreeView. :type catalog: :py:class:`.Catalog` """ catalog_node = _ModelNode( id=catalog.id, installed=None, enabled=True, title=catalog.id, compatibility=None, version=None, visible_enabled=False, visible_installed=False, sensitive_installed=False, type=_ROW_TYPE_CATALOG ) for repo in catalog.repositories.values(): repo_node = _ModelNode( id=repo.id, installed=None, enabled=True, title=repo.title, compatibility=None, version=None, visible_enabled=False, visible_installed=False, sensitive_installed=False, type=_ROW_TYPE_REPOSITORY ) catalog_node.children.append(repo_node) plugin_collection = self.catalog_plugins.get_collection(catalog.id, repo.id) for plugin_info in plugin_collection.values(): installed = False enabled = False plugin_name = plugin_info['name'] install_src = self.config['plugins.installed'].get(plugin_name) if install_src and repo.id == install_src['repo_id'] and catalog.id == install_src['catalog_id']: installed = True # plugin was added to treeview so it is removed from the temporary tracking dict self._installed_plugins_treeview_tracker.pop(plugin_name) enabled = plugin_name in self.config['plugins.enabled'] repo_node.children.append(_ModelNamedRow( id=plugin_name, installed=installed, enabled=enabled, title=plugin_info['title'], compatibility='Yes' if self.catalog_plugins.is_compatible(catalog.id, repo.id, plugin_name) else 'No', version=plugin_info['version'], visible_enabled=True, visible_installed=True, sensitive_installed=True, type=_ROW_TYPE_PLUGIN )) gui_utilities.glib_idle_add_once(self.__store_add_node, catalog_node)
Create a :py:class:`._ModelNode` instance to representing the catalog, its data and add it to the TreeView model. :param catalog: The catalog to add to the TreeView. :type catalog: :py:class:`.Catalog`
_add_catalog_to_tree_tsafe
python
rsmusllp/king-phisher
king_phisher/client/windows/plugin_manager.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/windows/plugin_manager.py
BSD-3-Clause
def _worker_thread_start(self, target, *args, **kwargs): """ Start a worker thread. This must only be called from the main GUI thread and *target* must be a tsafe method. """ if not self._worker_thread_is_ready: self._show_dialog_busy() self.logger.debug('plugin manager worker thread is alive, can not start a new one') return False self._worker_thread = utilities.Thread(target=target, args=args, kwargs=kwargs) self._worker_thread.start() return True
Start a worker thread. This must only be called from the main GUI thread and *target* must be a tsafe method.
_worker_thread_start
python
rsmusllp/king-phisher
king_phisher/client/windows/plugin_manager.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/windows/plugin_manager.py
BSD-3-Clause
def _load_catalog_local_tsafe(self): """ Load the plugins which are available into the treeview to make them visible to the user. """ self.logger.debug('loading the local catalog') pm = self.application.plugin_manager self.__load_errors = {} pm.load_all(on_error=self._on_plugin_load_error_tsafe) node = _ModelNode( id=_LOCAL_REPOSITORY_ID, installed=None, enabled=True, title=_LOCAL_REPOSITORY_TITLE, compatibility=None, version=None, visible_enabled=False, visible_installed=False, sensitive_installed=False, type=_ROW_TYPE_CATALOG ) for name, plugin in pm.loaded_plugins.items(): if self.config['plugins.installed'].get(name): continue self.config['plugins.installed'][name] = None node.children.append(_ModelNamedRow( id=plugin.name, installed=True, enabled=plugin.name in pm.enabled_plugins, title=plugin.title, compatibility='Yes' if plugin.is_compatible else 'No', version=plugin.version, visible_enabled=True, visible_installed=True, sensitive_installed=False, type=_ROW_TYPE_PLUGIN )) for name in self.__load_errors.keys(): node.children.append(_ModelNamedRow( id=name, installed=True, enabled=False, title="{0} (Load Failed)".format(name), compatibility='No', version='Unknown', visible_enabled=True, visible_installed=True, sensitive_installed=False, type=_ROW_TYPE_PLUGIN )) gui_utilities.glib_idle_add_wait(self.__store_add_node, node)
Load the plugins which are available into the treeview to make them visible to the user.
_load_catalog_local_tsafe
python
rsmusllp/king-phisher
king_phisher/client/windows/plugin_manager.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/windows/plugin_manager.py
BSD-3-Clause
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 }, 'user_data_path': self.application.user_data_path, 'user_library_path': self.application.user_library_path } 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__, serializers.JSON.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=[ find.ENV_VAR + '=' + os.environ[find.ENV_VAR], 'DISPLAY=' + os.environ['DISPLAY'], 'PATH=' + os.environ['PATH'], 'PYTHONDONTWRITEBYTECODE=x', 'PYTHONPATH=' + module_path, 'TERM=' + os.environ.get('TERM', 'xterm') ], 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
:param application: The application instance to which this window belongs. :type application: :py:class:`.KingPhisherClientApplication`
__init__
python
rsmusllp/king-phisher
king_phisher/client/windows/rpc_terminal.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/windows/rpc_terminal.py
BSD-3-Clause
def __init__(self, user): """ :param user: The user object of the authenticated user. :type user: :py:class:`~king_phisher.server.database.models.User` """ self.user = user.id self.user_access_level = user.access_level self.user_is_admin = user.is_admin self.created = db_models.current_timestamp() self.last_seen = self.created self._event_socket = None
:param user: The user object of the authenticated user. :type user: :py:class:`~king_phisher.server.database.models.User`
__init__
python
rsmusllp/king-phisher
king_phisher/server/aaa.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/aaa.py
BSD-3-Clause
def event_socket(self): """ An optional :py:class:`~.EventSocket` associated with the client. If the client has not opened an event socket, this is None. """ if self._event_socket is None: return None return self._event_socket()
An optional :py:class:`~.EventSocket` associated with the client. If the client has not opened an event socket, this is None.
event_socket
python
rsmusllp/king-phisher
king_phisher/server/aaa.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/aaa.py
BSD-3-Clause
def from_db_authenticated_session(cls, stored_session): """ Load an instance from a record stored in the database. :param stored_session: The authenticated session from the database to load. :return: A new :py:class:`.AuthenticatedSession` instance. """ utilities.assert_arg_type(stored_session, db_models.AuthenticatedSession) session = cls(stored_session.user) session.created = stored_session.created session.last_seen = stored_session.last_seen return session
Load an instance from a record stored in the database. :param stored_session: The authenticated session from the database to load. :return: A new :py:class:`.AuthenticatedSession` instance.
from_db_authenticated_session
python
rsmusllp/king-phisher
king_phisher/server/aaa.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/aaa.py
BSD-3-Clause
def __init__(self, timeout='30m'): """ :param timeout: The length of time in seconds for which sessions are valid. :type timeout: int, str """ self.logger = logging.getLogger('KingPhisher.Server.SessionManager') timeout = smoke_zephyr.utilities.parse_timespan(timeout) self.session_timeout = datetime.timedelta(seconds=timeout) self._sessions = {} self._lock = threading.Lock() # get valid sessions from the database expired = 0 session = db_manager.Session() oldest = db_models.current_timestamp() - self.session_timeout for stored_session in session.query(db_models.AuthenticatedSession): if stored_session.last_seen < oldest: expired += 1 continue auth_session = AuthenticatedSession.from_db_authenticated_session(stored_session) self._sessions[stored_session.id] = auth_session session.query(db_models.AuthenticatedSession).delete() session.commit() self.logger.info("restored {0:,} valid session{1} and skipped {2:,} expired session{3} from the database".format( len(self._sessions), ('' if len(self._sessions) == 1 else 's'), expired, ('' if expired == 1 else 's') ))
:param timeout: The length of time in seconds for which sessions are valid. :type timeout: int, str
__init__
python
rsmusllp/king-phisher
king_phisher/server/aaa.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/aaa.py
BSD-3-Clause
def put(self, user): """ Create and store a new :py:class:`.AuthenticatedSession` object for the specified user id. Any previously existing sessions for the specified user are removed from the manager. :param user: The user object of the authenticated user. :type user: :py:class:`~king_phisher.server.database.models.User` :return: The unique identifier for this session. :rtype: str """ new_session = AuthenticatedSession(user) new_session_id = base64.b64encode(os.urandom(50)) if its.py_v3: new_session_id = new_session_id.decode('utf-8') with self._lock: self.clean() # limit users to one valid session remove = [] for old_session_id, old_session in self._sessions.items(): if old_session.user == user.id: remove.append(old_session_id) for old_session_id in remove: del self._sessions[old_session_id] if remove: self.logger.info("invalidated {0:,} previously existing session for user {1}".format(len(remove), user)) while new_session_id in self._sessions: new_session_id = base64.b64encode(os.urandom(50)) self._sessions[new_session_id] = new_session return new_session_id
Create and store a new :py:class:`.AuthenticatedSession` object for the specified user id. Any previously existing sessions for the specified user are removed from the manager. :param user: The user object of the authenticated user. :type user: :py:class:`~king_phisher.server.database.models.User` :return: The unique identifier for this session. :rtype: str
put
python
rsmusllp/king-phisher
king_phisher/server/aaa.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/aaa.py
BSD-3-Clause
def get(self, session_id, update_timestamp=True): """ Look up an :py:class:`.AuthenticatedSession` instance from it's unique identifier and optionally update the last seen timestamp. If the session is not found or has expired, None will be returned. :param str session_id: The unique identifier of the session to retrieve. :param bool update_timestamp: Whether or not to update the last seen timestamp for the session. :return: The session if it exists and is active. :rtype: :py:class:`.AuthenticatedSession` """ if session_id is None: return None now = db_models.current_timestamp() with self._lock: session = self._sessions.get(session_id) if session is None: return None if session.last_seen < now - self.session_timeout: del self._sessions[session_id] return None if update_timestamp: session.last_seen = now return session
Look up an :py:class:`.AuthenticatedSession` instance from it's unique identifier and optionally update the last seen timestamp. If the session is not found or has expired, None will be returned. :param str session_id: The unique identifier of the session to retrieve. :param bool update_timestamp: Whether or not to update the last seen timestamp for the session. :return: The session if it exists and is active. :rtype: :py:class:`.AuthenticatedSession`
get
python
rsmusllp/king-phisher
king_phisher/server/aaa.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/aaa.py
BSD-3-Clause
def __init__(self, pw_hash): """ :param bytes pw_hash: The salted hash of the password to cache. """ self.pw_hash = pw_hash self.time = time.time()
:param bytes pw_hash: The salted hash of the password to cache.
__init__
python
rsmusllp/king-phisher
king_phisher/server/aaa.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/aaa.py
BSD-3-Clause
def new_from_password(cls, password): """ Create a new instance from a plaintext password. :param str password: The password to cache in memory. """ password = (cls.salt + password).encode('utf-8') pw_hash = hashlib.new(cls.hash_algorithm, password).digest() for _ in range(cls.iterations - 1): pw_hash = hashlib.new(cls.hash_algorithm, pw_hash).digest() return cls(pw_hash)
Create a new instance from a plaintext password. :param str password: The password to cache in memory.
new_from_password
python
rsmusllp/king-phisher
king_phisher/server/aaa.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/aaa.py
BSD-3-Clause
def __init__(self, cache_timeout='10m', required_group=None, pam_service='sshd'): """ :param cache_timeout: The life time of cached credentials in seconds. :type cache_timeout: int, str :param str required_group: A group that if specified, users must be a member of to be authenticated. :param str pam_service: The service to use for identification to pam when authenticating. """ self.logger = logging.getLogger('KingPhisher.Server.Authenticator') self.cache_timeout = smoke_zephyr.utilities.parse_timespan(cache_timeout) """The timeout of the credential cache in seconds.""" self.response_timeout = 30 """The timeout for individual requests in seconds.""" self.service = pam_service self.logger.debug("use pam service '{0}' for authentication".format(self.service)) self.required_group = required_group if required_group: group = pylibc.getgrnam(required_group) if group is None: self.logger.warning('the specified group for authentication was not found') self.parent_rfile, self.child_wfile = os.pipe() self.child_rfile, self.parent_wfile = os.pipe() self.child_pid = os.fork() """The PID of the forked child.""" if not self.child_pid: self.rfile = self.child_rfile self.wfile = self.child_wfile else: self.rfile = self.parent_rfile self.wfile = self.parent_wfile self._lock = threading.Lock() self.rfile = os.fdopen(self.rfile, 'r', 1) self.wfile = os.fdopen(self.wfile, 'w', 1) if not self.child_pid: self.child_routine() self.rfile.close() self.wfile.close() logging.shutdown() os._exit(os.EX_OK) self.logger.debug('forked an authenticating process with pid: ' + str(self.child_pid)) # below this are attributes exclusive to the parent process self.cache = {} """The credential cache dictionary. Keys are usernames and values are tuples of password hashes and ages.""" self.sequence_number = 0 """A sequence number to use to align requests with responses.""" return
:param cache_timeout: The life time of cached credentials in seconds. :type cache_timeout: int, str :param str required_group: A group that if specified, users must be a member of to be authenticated. :param str pam_service: The service to use for identification to pam when authenticating.
__init__
python
rsmusllp/king-phisher
king_phisher/server/aaa.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/aaa.py
BSD-3-Clause
def send(self, request): """ Encode and send a request through the pipe to the opposite end. This also sets the 'sequence' member of the request and increments the stored value. :param dict request: A request. """ request['sequence'] = self.sequence_number self.sequence_number += 1 if self.sequence_number > 0xffffffff: self.sequence_number = 0 self._raw_send(request) log_msg = "sent request with sequence number {0}".format(request['sequence']) if 'action' in request: log_msg += " and action '{0}'".format(request['action']) self.logger.debug(log_msg)
Encode and send a request through the pipe to the opposite end. This also sets the 'sequence' member of the request and increments the stored value. :param dict request: A request.
send
python
rsmusllp/king-phisher
king_phisher/server/aaa.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/aaa.py
BSD-3-Clause
def _raw_recv(self, timeout=None): """ Receive a request from the other process and decode it. This makes no attempt to validate the 'sequence' member of the request. """ if timeout is not None: ready, _, _ = select.select([self.rfile], [], [], timeout) if not ready: raise errors.KingPhisherTimeoutError('a response was not received within the timeout') try: request = self.rfile.readline()[:-1] except KeyboardInterrupt: return {} return json.loads(request)
Receive a request from the other process and decode it. This makes no attempt to validate the 'sequence' member of the request.
_raw_recv
python
rsmusllp/king-phisher
king_phisher/server/aaa.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/aaa.py
BSD-3-Clause
def _seq_recv(self): """ Receive a response from the other process and decode it. This also ensures that 'sequence' member of the response is the expected value. """ timeout = self.response_timeout expected_sequence = self.sequence_number - 1 while timeout > 0: start_time = time.time() response = self._raw_recv(timeout) if response.get('sequence') == expected_sequence: break self.logger.warning("dropping response due to sequence number mismatch (received: {0} expected: {1})".format(response.get('sequence'), expected_sequence)) timeout -= time.time() - start_time else: raise errors.KingPhisherTimeoutError('a response was not received within the timeout') self.logger.debug("received response with sequence number {0}".format(response.get('sequence'))) return response
Receive a response from the other process and decode it. This also ensures that 'sequence' member of the response is the expected value.
_seq_recv
python
rsmusllp/king-phisher
king_phisher/server/aaa.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/aaa.py
BSD-3-Clause
def child_routine(self): """ The main routine that is executed by the child after the object forks. This loop does not exit unless a stop request is made. """ self.logger = logging.getLogger('KingPhisher.Server.Authenticator.Child') while True: request = self._raw_recv(timeout=None) if 'action' not in request: self.logger.warning('request received without a specified action') continue if not isinstance(request.get('sequence'), int): self.logger.warning('request received without a valid sequence number') continue action = request.get('action', 'UNKNOWN') self.logger.debug("received request with sequence number {0} and action '{1}'".format(request['sequence'], action)) if action == 'stop': break elif action != 'authenticate': continue username = str(request['username']) password = str(request['password']) start_time = time.time() pam_handle = pam.pam() try: with alarm_set(self.response_timeout): result = pam_handle.authenticate(username, password, service=self.service, resetcreds=False) except errors.KingPhisherTimeoutError: self.logger.warning("authentication failed for user: {0} reason: received timeout".format(username)) result = False elapsed_time = time.time() - start_time self.logger.debug("pam returned code: {0} reason: '{1}' for user {2} after {3:.2f} seconds".format(pam_handle.code, pam_handle.reason, username, elapsed_time)) result = { 'result': result, 'sequence': request['sequence'], 'username': username } if result['result']: if self.required_group: result['result'] = False self.logger.debug("checking group membership for user: {0}".format(username)) try: with alarm_set(int(round(self.response_timeout - elapsed_time))): groups = pylibc.getgrouplist(username) group = pylibc.getgrnam(self.required_group) except errors.KingPhisherTimeoutError: self.logger.warning("authentication failed for user: {0} reason: received timeout".format(username)) except KeyError: self.logger.error("encountered a KeyError while looking up group membership for user: {0}".format(username)) except Exception: self.logger.error("encountered an Exception while looking up group membership for user: {0}".format(username), exc_info=True) else: if group is None: self.logger.error('the specified group for authentication was not found, can not authenticate the user') elif group.gr_gid not in groups: self.logger.warning("authentication failed for user: {0} reason: lack of group membership".format(username)) else: result['result'] = True self.logger.debug("group requirement met for user: {0}".format(username)) else: self.logger.warning("authentication failed for user: {0} reason: bad username or password".format(username)) self._raw_send(result) self.logger.debug("sent response with sequence number {0}".format(request['sequence']))
The main routine that is executed by the child after the object forks. This loop does not exit unless a stop request is made.
child_routine
python
rsmusllp/king-phisher
king_phisher/server/aaa.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/aaa.py
BSD-3-Clause
def authenticate(self, username, password): """ Check if a username and password are valid. If they are, the password will be salted, hashed with SHA-512 and stored so the next call with the same values will not require sending a request to the forked child. :param str username: The username to check. :param str password: The password to check. :return: Whether the credentials are valid or not. :rtype: bool """ cached_password = self.cache.get(username) if cached_password is not None: if cached_password.time + self.cache_timeout >= time.time(): self.logger.debug("checking authentication for user {0} with cached password hash".format(username)) return cached_password == password self.logger.debug('removing expired hashed and cached password for user ' + username) del self.cache[username] request = { 'action': 'authenticate', 'password': password, 'username': username } self._lock.acquire() self.send(request) try: result = self._seq_recv() except errors.KingPhisherTimeoutError as error: self.logger.error(error.message) self._lock.release() return False if result['result'] and result.get('username') == username: self.logger.info("user {0} has successfully authenticated".format(username)) self.cache[username] = CachedPassword.new_from_password(password) self._lock.release() return result['result']
Check if a username and password are valid. If they are, the password will be salted, hashed with SHA-512 and stored so the next call with the same values will not require sending a request to the forked child. :param str username: The username to check. :param str password: The password to check. :return: Whether the credentials are valid or not. :rtype: bool
authenticate
python
rsmusllp/king-phisher
king_phisher/server/aaa.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/aaa.py
BSD-3-Clause
def stop(self): """ Send a stop request to the child process and wait for it to exit. """ if not os.path.exists("/proc/{0}".format(self.child_pid)): return request = {'action': 'stop'} with self._lock: self.send(request) os.waitpid(self.child_pid, 0) self.rfile.close() self.wfile.close()
Send a stop request to the child process and wait for it to exit.
stop
python
rsmusllp/king-phisher
king_phisher/server/aaa.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/aaa.py
BSD-3-Clause
def get_bind_addresses(config): """ Retrieve the addresses on which the server should bind to. Each of these addresses should be an IP address, port and optionally enable SSL. The returned list will contain tuples for each address found in the configuration. These tuples will be in the (host, port, use_ssl) format that is compatible with AdvancedHTTPServer. :param config: Configuration to retrieve settings from. :type config: :py:class:`smoke_zephyr.configuration.Configuration` :return: The specified addresses to bind to. :rtype: list """ addresses = [] for entry, address in enumerate(config.get('server.addresses')): port = address['port'] if not (0 <= port <= 0xffff): logger.critical("setting server.addresses[{0}] invalid port specified".format(entry)) raise errors.KingPhisherError("invalid port configuration for address #{0}".format(entry + 1)) addresses.append(_BindAddress(address['host'], port, address.get('ssl', False))) for host, port, use_ssl in addresses: if port in (443, 8443) and not use_ssl: logger.warning("running on port {0} without ssl, this is generally unintended behaviour".format(port)) elif port in (80, 8080) and use_ssl: logger.warning("running on port {0} with ssl, this is generally unintended behaviour".format(port)) return addresses
Retrieve the addresses on which the server should bind to. Each of these addresses should be an IP address, port and optionally enable SSL. The returned list will contain tuples for each address found in the configuration. These tuples will be in the (host, port, use_ssl) format that is compatible with AdvancedHTTPServer. :param config: Configuration to retrieve settings from. :type config: :py:class:`smoke_zephyr.configuration.Configuration` :return: The specified addresses to bind to. :rtype: list
get_bind_addresses
python
rsmusllp/king-phisher
king_phisher/server/build.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/build.py
BSD-3-Clause
def get_ssl_hostnames(config): """ Retrieve the SSL hosts that are specified within the configuration. This also ensures that the settings appear to be valid by ensuring that the necessary files are defined and readable. :param config: Configuration to retrieve settings from. :type config: :py:class:`smoke_zephyr.configuration.Configuration` :return: The specified SSH hosts. :rtype: list """ ssl_hostnames = [] for entry, ssl_host in enumerate(config.get_if_exists('server.ssl_hosts', [])): hostname = ssl_host.get('host') if hostname is None: logger.critical("setting server.ssl_hosts[{0}] host not specified".format(entry)) raise errors.KingPhisherError("invalid ssl host configuration #{0}, host must be specified".format(entry + 1)) ssl_certfile = ssl_host.get('ssl_cert') if ssl_certfile is None: logger.critical("setting server.ssl_hosts[{0}] cert file not specified".format(entry)) raise errors.KingPhisherError("invalid ssl host configuration #{0}, missing certificate file".format(entry + 1)) if not os.access(ssl_certfile, os.R_OK): logger.critical("setting server.ssl_hosts[{0}] file '{1}' not found".format(entry, ssl_certfile)) raise errors.KingPhisherError("invalid ssl host configuration #{0}, missing certificate file".format(entry + 1)) ssl_keyfile = ssl_host.get('ssl_key') if ssl_keyfile is not None and not os.access(ssl_keyfile, os.R_OK): logger.critical("setting server.ssl_hosts[{0}] file '{1}' not found".format(entry, ssl_keyfile)) raise errors.KingPhisherError("invalid ssl host configuration #{0}, missing key file".format(entry + 1)) ssl_hostnames.append(advancedhttpserver.SSLSNICertificate(hostname, ssl_certfile, ssl_keyfile)) return ssl_hostnames
Retrieve the SSL hosts that are specified within the configuration. This also ensures that the settings appear to be valid by ensuring that the necessary files are defined and readable. :param config: Configuration to retrieve settings from. :type config: :py:class:`smoke_zephyr.configuration.Configuration` :return: The specified SSH hosts. :rtype: list
get_ssl_hostnames
python
rsmusllp/king-phisher
king_phisher/server/build.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/build.py
BSD-3-Clause
def server_from_config(config, handler_klass=None, plugin_manager=None): """ Build a server from a provided configuration instance. If *handler_klass* is specified, then the object must inherit from the corresponding KingPhisherServer base class. :param config: Configuration to retrieve settings from. :type config: :py:class:`smoke_zephyr.configuration.Configuration` :param handler_klass: Alternative handler class to use. :type handler_klass: :py:class:`.KingPhisherRequestHandler` :param plugin_manager: The server's plugin manager instance. :type plugin_manager: :py:class:`~king_phisher.server.plugins.ServerPluginManager` :return: A configured server instance. :rtype: :py:class:`.KingPhisherServer` """ handler_klass = (handler_klass or KingPhisherRequestHandler) addresses = get_bind_addresses(config) if not len(addresses): raise errors.KingPhisherError('at least one address to listen on must be specified') ssl_certfile = None ssl_keyfile = None if config.has_option('server.ssl_cert'): ssl_certfile = config.get('server.ssl_cert') if not os.access(ssl_certfile, os.R_OK): logger.critical("setting server.ssl_cert file '{0}' not found".format(ssl_certfile)) raise errors.KingPhisherError('invalid ssl configuration, missing certificate file') logger.info("using default ssl cert file '{0}'".format(ssl_certfile)) if config.has_option('server.ssl_key'): ssl_keyfile = config.get('server.ssl_key') if not os.access(ssl_keyfile, os.R_OK): logger.critical("setting server.ssl_key file '{0}' not found".format(ssl_keyfile)) raise errors.KingPhisherError('invalid ssl configuration, missing key file') if any([address.ssl for address in addresses]): ssl_hostnames = get_ssl_hostnames(config) if ssl_certfile is None: if not ssl_hostnames: raise errors.KingPhisherError('an ssl certificate must be specified when ssl is enabled') sni_config = ssl_hostnames[0] logger.warning('no default certificate file was specified, using ssl host configuration: ' + sni_config.hostname) ssl_certfile = sni_config.certfile ssl_keyfile = sni_config.keyfile else: ssl_certfile = None ssl_keyfile = None ssl_hostnames = [] try: server = KingPhisherServer(config, plugin_manager, handler_klass, addresses=addresses, ssl_certfile=ssl_certfile, ssl_keyfile=ssl_keyfile) except socket.error as error: error_number, error_message = error.args error_message = "socket error #{0} ({1})".format((error_number or 'NOT-SET'), error_message) if error_number == 98: logger.error('failed to bind server to address (socket error #98)') logger.error(error_message, exc_info=True) raise errors.KingPhisherError(error_message) from None if config.has_option('server.server_header'): server.server_version = config.get('server.server_header') logger.info("setting the server version to the custom header: '{0}'".format(config.get('server.server_header'))) for hostname, ssl_certfile, ssl_keyfile in ssl_hostnames: sni_config = letsencrypt.get_sni_hostname_config(hostname, config) if sni_config is None: letsencrypt.set_sni_hostname(hostname, ssl_certfile, ssl_keyfile, enabled=True) for hostname, sni_config in letsencrypt.get_sni_hostnames(config, check_files=False).items(): if not sni_config.enabled: continue if not _server_add_sni_cert(server, hostname, sni_config): letsencrypt.set_sni_hostname(hostname, sni_config.certfile, sni_config.keyfile, enabled=False) signals.server_initialized.send(server) return server
Build a server from a provided configuration instance. If *handler_klass* is specified, then the object must inherit from the corresponding KingPhisherServer base class. :param config: Configuration to retrieve settings from. :type config: :py:class:`smoke_zephyr.configuration.Configuration` :param handler_klass: Alternative handler class to use. :type handler_klass: :py:class:`.KingPhisherRequestHandler` :param plugin_manager: The server's plugin manager instance. :type plugin_manager: :py:class:`~king_phisher.server.plugins.ServerPluginManager` :return: A configured server instance. :rtype: :py:class:`.KingPhisherServer`
server_from_config
python
rsmusllp/king-phisher
king_phisher/server/build.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/build.py
BSD-3-Clause
def iter_schema_errors(self, schema_file): """ Iterate over the :py:class:`~jsonschema.exceptions.ValidationError` instances for all errors found within the specified schema. :param str schema_file: The path to the schema file to use for validation. :return: Each of the validation errors. :rtype: :py:class:`~jsonschema.exceptions.ValidationError` """ with open(schema_file, 'r') as file_h: schema = json.load(file_h) validator = jsonschema.Draft4Validator(schema) for error in validator.iter_errors(self.get_storage()): yield error
Iterate over the :py:class:`~jsonschema.exceptions.ValidationError` instances for all errors found within the specified schema. :param str schema_file: The path to the schema file to use for validation. :return: Each of the validation errors. :rtype: :py:class:`~jsonschema.exceptions.ValidationError`
iter_schema_errors
python
rsmusllp/king-phisher
king_phisher/server/configuration.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/configuration.py
BSD-3-Clause
def ex_load_config(config_file, validate_schema=True): """ Load the server configuration from the specified file. This function is meant to be called early on during a scripts execution and if any error occurs, details will be printed and the process will exit. :param str config_file: The path to the configuration file to load. :param bool validate_schema: Whether or not to validate the schema of the configuration. :return: The loaded server configuration. :rtype: :py:class:`.Configuration` """ try: config = Configuration.from_file(config_file) except Exception as error: color.print_error('an error occurred while parsing the server configuration file') if isinstance(error, yaml.error.YAMLError): problem = getattr(error, 'problem', 'unknown yaml error') if hasattr(error, 'problem_mark'): prob_lineno = error.problem_mark.line + 1 color.print_error("{0} - {1}:{2} {3}".format(error.__class__.__name__, config_file, prob_lineno, problem)) lines = open(config_file, 'rU').readlines() for lineno, line in enumerate(lines[max(prob_lineno - 3, 0):(prob_lineno + 2)], max(prob_lineno - 3, 0) + 1): color.print_error(" {0} {1: <3}: {2}".format(('=>' if lineno == prob_lineno else ' '), lineno, line.rstrip())) else: color.print_error("{0} - {1}: {2}".format(error.__class__.__name__, config_file, problem)) color.print_error('fix the errors in the configuration file and restart the server') sys.exit(os.EX_CONFIG) # check the configuration for missing and incompatible options if validate_schema: find.init_data_path('server') config_schema = find.data_file(os.path.join('schemas', 'json', 'king-phisher.server.config.json')) if not config_schema: color.print_error('could not load server configuration schema data') sys.exit(os.EX_NOINPUT) schema_errors = config.schema_errors(config_schema) if schema_errors: color.print_error('the server configuration validation encountered the following errors:') for schema_error in schema_errors: color.print_error(" - {0} error: {1} ({2})".format(schema_error.validator, '.'.join(map(str, schema_error.path)), schema_error.message)) sys.exit(os.EX_CONFIG) return config
Load the server configuration from the specified file. This function is meant to be called early on during a scripts execution and if any error occurs, details will be printed and the process will exit. :param str config_file: The path to the configuration file to load. :param bool validate_schema: Whether or not to validate the schema of the configuration. :return: The loaded server configuration. :rtype: :py:class:`.Configuration`
ex_load_config
python
rsmusllp/king-phisher
king_phisher/server/configuration.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/configuration.py
BSD-3-Clause
def chown(path, user=None, group=constants.AUTOMATIC, recursive=True): """ This is a high-level wrapper around :py:func:`os.chown` to provide additional functionality. ``None`` can be specified as the *user* or *group* to leave the value unchanged. At least one of either *user* or *group* must be specified. .. versionadded:: 1.14.0 :param str path: The path to change the owner information for. :param user: The new owner to set for the path. If set to :py:class:`~king_phisher.constants.AUTOMATIC`, the process's current uid will be used. :type user: int, str, ``None``, :py:class:`~king_phisher.constants.AUTOMATIC` :param group: The new group to set for the path. If set to :py:class:`~king_phisher.constants.AUTOMATIC`, the group that *user* belongs too will be used. :type group: int, str, ``None``, :py:class:`~king_phisher.constants.AUTOMATIC` :param bool recursive: Whether or not to recurse into directories. """ uid, gid = _resolve_target_ids(user, group) if uid is None: uid = -1 if gid is None: gid = -1 if recursive: # set *filter_func* to skip paths that may have come from broken links iterator = smoke_zephyr.utilities.FileWalker(path, filter_func=os.path.exists) else: iterator = (path,) for path in iterator: os.chown(path, uid, gid)
This is a high-level wrapper around :py:func:`os.chown` to provide additional functionality. ``None`` can be specified as the *user* or *group* to leave the value unchanged. At least one of either *user* or *group* must be specified. .. versionadded:: 1.14.0 :param str path: The path to change the owner information for. :param user: The new owner to set for the path. If set to :py:class:`~king_phisher.constants.AUTOMATIC`, the process's current uid will be used. :type user: int, str, ``None``, :py:class:`~king_phisher.constants.AUTOMATIC` :param group: The new group to set for the path. If set to :py:class:`~king_phisher.constants.AUTOMATIC`, the group that *user* belongs too will be used. :type group: int, str, ``None``, :py:class:`~king_phisher.constants.AUTOMATIC` :param bool recursive: Whether or not to recurse into directories.
chown
python
rsmusllp/king-phisher
king_phisher/server/fs_utilities.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/fs_utilities.py
BSD-3-Clause
def access(path, mode, user=constants.AUTOMATIC, group=constants.AUTOMATIC): """ This is a high-level wrapper around :py:func:`os.access` to provide additional functionality. Similar to `os.access` this high-level wrapper will test the given path for a variety of access modes. Additionally *user* or *group* can be specified to test access for a specific user or group. .. versionadded:: 1.14.0 :param str path: The path to test access for. :param int mode: The mode to test access for. Set to `os.R_OK` to test for readability, `os.W_OK` for writability and `os.X_OK` to determine if path can be executed. :param user: The user to test permissions for. If set to :py:class:`~king_phisher.constants.AUTOMATIC`, the process's current uid will be used. :type user: int, str, ``None``, :py:class:`~king_phisher.constants.AUTOMATIC` :param group: The group to test permissions for. If set to :py:class:`~king_phisher.constants.AUTOMATIC`, the group that *user* belongs too will be used. :type group: int, str, ``None``, :py:class:`~king_phisher.constants.AUTOMATIC` :return: Returns ``True`` only if the user or group has the mode of permission specified else returns ``False``. :rtype: bool """ uid, gid = _resolve_target_ids(user, group) file_info = os.stat(path) # If there are no permissions to check for then yes the user has no more than no permissions. if not mode: return True __test_mode = functools.partial(_test_mode, file_info.st_mode, mode) # Other checks if __test_mode(stat.S_IROTH, stat.S_IWOTH, stat.S_IXOTH): return True # User Checks if file_info.st_uid == uid and __test_mode(stat.S_IRUSR, stat.S_IWUSR, stat.S_IXUSR): return True # Group checks if file_info.st_gid == gid and __test_mode(stat.S_IRGRP, stat.S_IWGRP, stat.S_IXGRP): return True # If there were no groups specified then enumerate all of the users gids and test them all. if group == constants.AUTOMATIC: if not isinstance(user, str): user = pylibc.getpwuid(uid).pw_name # Check all the groups if file_info.st_gid in pylibc.getgrouplist(user) and __test_mode(stat.S_IRGRP, stat.S_IWGRP, stat.S_IXGRP): return True return False
This is a high-level wrapper around :py:func:`os.access` to provide additional functionality. Similar to `os.access` this high-level wrapper will test the given path for a variety of access modes. Additionally *user* or *group* can be specified to test access for a specific user or group. .. versionadded:: 1.14.0 :param str path: The path to test access for. :param int mode: The mode to test access for. Set to `os.R_OK` to test for readability, `os.W_OK` for writability and `os.X_OK` to determine if path can be executed. :param user: The user to test permissions for. If set to :py:class:`~king_phisher.constants.AUTOMATIC`, the process's current uid will be used. :type user: int, str, ``None``, :py:class:`~king_phisher.constants.AUTOMATIC` :param group: The group to test permissions for. If set to :py:class:`~king_phisher.constants.AUTOMATIC`, the group that *user* belongs too will be used. :type group: int, str, ``None``, :py:class:`~king_phisher.constants.AUTOMATIC` :return: Returns ``True`` only if the user or group has the mode of permission specified else returns ``False``. :rtype: bool
access
python
rsmusllp/king-phisher
king_phisher/server/fs_utilities.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/fs_utilities.py
BSD-3-Clause
def certbot_issue(webroot, hostname, bin_path=None, unified_directory=None): """ Issue a certificate using Let's Encrypt's ``certbot`` utility. This function wraps the ``certbot`` binary and configures the parameters as appropriate. By default, the resulting certificate will be placed under :py:data:`.LETS_ENCRYPT_DEFAULT_DATA_PATH`, however if *unified_directory* is used then it will be under ``$unified_directory/etc``. :param str webroot: The webroot to use while requesting the certificate. :param str hostname: The hostname of the certificate to request. :param str bin_path: The optional path to the ``certbot`` binary. If not specified, then it will be searched for utilizing :py:func:`~king_phisher.startup.which`. :param str unified_directory: A single directory under which all the Let's Encrypt data should be stored. This is useful when not running the utility as root. :return: The exit status of the ``certbot`` utility. :rtype: int """ args = ['certonly'] if unified_directory: args.extend(['--config-dir', os.path.join(unified_directory, 'etc')]) args.extend(['--logs-dir', os.path.join(unified_directory, 'log')]) args.extend(['--work-dir', os.path.join(unified_directory, 'lib')]) args.extend(['--webroot', '--webroot-path', webroot, '-d', hostname]) proc = _run_certbot(args, bin_path=bin_path) return proc.status
Issue a certificate using Let's Encrypt's ``certbot`` utility. This function wraps the ``certbot`` binary and configures the parameters as appropriate. By default, the resulting certificate will be placed under :py:data:`.LETS_ENCRYPT_DEFAULT_DATA_PATH`, however if *unified_directory* is used then it will be under ``$unified_directory/etc``. :param str webroot: The webroot to use while requesting the certificate. :param str hostname: The hostname of the certificate to request. :param str bin_path: The optional path to the ``certbot`` binary. If not specified, then it will be searched for utilizing :py:func:`~king_phisher.startup.which`. :param str unified_directory: A single directory under which all the Let's Encrypt data should be stored. This is useful when not running the utility as root. :return: The exit status of the ``certbot`` utility. :rtype: int
certbot_issue
python
rsmusllp/king-phisher
king_phisher/server/letsencrypt.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/letsencrypt.py
BSD-3-Clause
def get_certbot_bin_path(config=None): """ Get the path to Let's Encrypt's ``certbot`` command line utility. If the path is found, it is verified to be both a file and executable. If the path verification fails, ``None`` is returned. .. versionadded:: 1.14.0 :param config: Configuration to retrieve settings from. :type config: :py:class:`smoke_zephyr.configuration.Configuration` :return: The path to the certbot binary. :rtype: str """ if config: letsencrypt_config = config.get_if_exists('server.letsencrypt', {}) else: letsencrypt_config = {} bin_path = letsencrypt_config.get('certbot_path') or startup.which('certbot') if bin_path is None: return None if not os.path.isfile(bin_path): return None if not os.access(bin_path, os.R_OK | os.X_OK): return None return bin_path
Get the path to Let's Encrypt's ``certbot`` command line utility. If the path is found, it is verified to be both a file and executable. If the path verification fails, ``None`` is returned. .. versionadded:: 1.14.0 :param config: Configuration to retrieve settings from. :type config: :py:class:`smoke_zephyr.configuration.Configuration` :return: The path to the certbot binary. :rtype: str
get_certbot_bin_path
python
rsmusllp/king-phisher
king_phisher/server/letsencrypt.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/letsencrypt.py
BSD-3-Clause
def get_sni_hostname_config(hostname, config=None): """ Search for and return the SNI configuration for the specified *hostname*. This method will first check to see if the entry exists in the database before searching the Let's Encrypt data directory (if ``data_path`` is present in the server configuration). If no configuration data is found, or the data file paths appear invalid, ``None`` is returned. :param str hostname: The hostname to retrieve the configuration for. :param config: Configuration to retrieve settings from. :type config: :py:class:`smoke_zephyr.configuration.Configuration` :return: The SNI configuration for the hostname if it was found. :rtype: :py:class:`.SNIHostnameConfiguration` """ unified_directory = config.get_if_exists('server.letsencrypt.data_path') if config else None if unified_directory: _sync_hostnames(unified_directory) sni_config = _sni_hostnames.get(hostname) if not sni_config: return None if not _check_files(sni_config['certfile'], sni_config['keyfile']): return None return SNIHostnameConfiguration(**sni_config)
Search for and return the SNI configuration for the specified *hostname*. This method will first check to see if the entry exists in the database before searching the Let's Encrypt data directory (if ``data_path`` is present in the server configuration). If no configuration data is found, or the data file paths appear invalid, ``None`` is returned. :param str hostname: The hostname to retrieve the configuration for. :param config: Configuration to retrieve settings from. :type config: :py:class:`smoke_zephyr.configuration.Configuration` :return: The SNI configuration for the hostname if it was found. :rtype: :py:class:`.SNIHostnameConfiguration`
get_sni_hostname_config
python
rsmusllp/king-phisher
king_phisher/server/letsencrypt.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/letsencrypt.py
BSD-3-Clause
def config(self): """ A dictionary that can be used by this plugin to access it's configuration. Any changes to this configuration will be lost with the server restarts. """ config = self.root_config.get('server.plugins').get(self.name) if config is None: config = {} self.root_config.get('server.plugins')[self.name] = config return config
A dictionary that can be used by this plugin to access it's configuration. Any changes to this configuration will be lost with the server restarts.
config
python
rsmusllp/king-phisher
king_phisher/server/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/plugins.py
BSD-3-Clause
def register_http(self, path, method): """ Register a new HTTP request handler at *path* that is handled by *method*. Two parameters are passed to the method. The first parameter is a :py:class:`~king_phisher.server.server.KingPhisherRequestHandler` instance and the second is a dictionary of the HTTP query parameters. The specified path is added within the plugins private HTTP handler namespace at ``_/plugins/$PLUGIN_NAME/$PATH`` .. warning:: This resource can be reached by any user whether or not they are authenticated and or associated with a campaign. .. versionadded:: 1.7.0 :param str path: The path to register the method at. :param method: The handler for the HTTP method. """ if path.startswith('/'): path = path[1:] path = "_/plugins/{0}/{1}".format(self.name, path) advancedhttpserver.RegisterPath(path)(method)
Register a new HTTP request handler at *path* that is handled by *method*. Two parameters are passed to the method. The first parameter is a :py:class:`~king_phisher.server.server.KingPhisherRequestHandler` instance and the second is a dictionary of the HTTP query parameters. The specified path is added within the plugins private HTTP handler namespace at ``_/plugins/$PLUGIN_NAME/$PATH`` .. warning:: This resource can be reached by any user whether or not they are authenticated and or associated with a campaign. .. versionadded:: 1.7.0 :param str path: The path to register the method at. :param method: The handler for the HTTP method.
register_http
python
rsmusllp/king-phisher
king_phisher/server/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/plugins.py
BSD-3-Clause
def register_rpc(self, path, method, database_access=False): """ Register a new RPC function at *path* that is handled by *method*. This RPC function can only be called by authenticated users. A single parameter of the :py:class:`~king_phisher.server.server.KingPhisherRequestHandler` instance is passed to *method* when the RPC function is invoked. The specified path is added within the plugins private RPC handler namespace at ``plugins/$PLUGIN_NAME/$PATH``. .. versionadded:: 1.7.0 .. versionchanged:: 1.12.0 Added the *database_access* parameter. :param str path: The path to register the method at. :param method: The handler for the RPC method. """ if path.startswith('/'): path = path[1:] path = "/plugins/{0}/{1}".format(self.name, path) server_rpc.register_rpc(path, database_access=database_access, log_call=True)(method)
Register a new RPC function at *path* that is handled by *method*. This RPC function can only be called by authenticated users. A single parameter of the :py:class:`~king_phisher.server.server.KingPhisherRequestHandler` instance is passed to *method* when the RPC function is invoked. The specified path is added within the plugins private RPC handler namespace at ``plugins/$PLUGIN_NAME/$PATH``. .. versionadded:: 1.7.0 .. versionchanged:: 1.12.0 Added the *database_access* parameter. :param str path: The path to register the method at. :param method: The handler for the RPC method.
register_rpc
python
rsmusllp/king-phisher
king_phisher/server/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/plugins.py
BSD-3-Clause
def getgrnam(name, encoding='utf-8'): """ Get the structure containing the fields from the specified entry in the group database. See `getgrnam(3) <http://man7.org/linux/man-pages/man3/getgrnam.3.html>`_ for more information. :param str name: The group name to look up. :param str encoding: The encoding to use for strings. :return: The entry from the group database or ``None`` if it was not found. :rtype: tuple """ name = _cbytes(name, encoding=encoding) c_pgroup = _libc_getgrnam(name) if not c_pgroup: return None return c_pgroup.contents.to_tuple()
Get the structure containing the fields from the specified entry in the group database. See `getgrnam(3) <http://man7.org/linux/man-pages/man3/getgrnam.3.html>`_ for more information. :param str name: The group name to look up. :param str encoding: The encoding to use for strings. :return: The entry from the group database or ``None`` if it was not found. :rtype: tuple
getgrnam
python
rsmusllp/king-phisher
king_phisher/server/pylibc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/pylibc.py
BSD-3-Clause
def getgrouplist(user, group=constants.AUTOMATIC, encoding='utf-8'): """ Get the groups that the specified user belongs to. If *group* is not specified, it will be looked up from the password record for *user*. See `getgrouplist(3) <http://man7.org/linux/man-pages/man3/getgrouplist.3.html>`_ for more information. :param str user: The user name to look up. :param int group: An optional group to add to the returned groups. :param str encoding: The encoding to use for strings. :return: The group IDs that *user* belongs to. :rtype: tuple """ user = _cbytes(user, encoding=encoding) ngroups = 20 ngrouplist = ctypes.c_int(ngroups) if group is constants.AUTOMATIC: group = getpwnam(user).pw_gid elif not isinstance(group, int): raise TypeError('group must be AUTOMATIC or an integer') grouplist = (ctypes.c_uint * ngroups)() ct = _libc_getgrouplist(user, group, ctypes.cast(ctypes.byref(grouplist), ctypes.POINTER(ctypes.c_uint)), ctypes.byref(ngrouplist)) if ct == -1: grouplist = (ctypes.c_uint * int(ngrouplist.value))() ct = _libc_getgrouplist(user, group, ctypes.cast(ctypes.byref(grouplist), ctypes.POINTER(ctypes.c_uint)), ctypes.byref(ngrouplist)) return tuple(grouplist[:ct])
Get the groups that the specified user belongs to. If *group* is not specified, it will be looked up from the password record for *user*. See `getgrouplist(3) <http://man7.org/linux/man-pages/man3/getgrouplist.3.html>`_ for more information. :param str user: The user name to look up. :param int group: An optional group to add to the returned groups. :param str encoding: The encoding to use for strings. :return: The group IDs that *user* belongs to. :rtype: tuple
getgrouplist
python
rsmusllp/king-phisher
king_phisher/server/pylibc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/pylibc.py
BSD-3-Clause
def getpwnam(name, encoding='utf-8'): """ Get the structure containing the fields from the specified entry in the password database. See `getpwnam(3) <http://man7.org/linux/man-pages/man3/getpwnam.3.html>`_ for more information. :param str name: The user name to look up. :param str encoding: The encoding to use for strings. :return: The entry from the user database or ``None`` if it was not found. :rtype: tuple """ name = _cbytes(name, encoding=encoding) c_ppasswd = _libc_getpwnam(name) if not c_ppasswd: return None return c_ppasswd.contents.to_tuple()
Get the structure containing the fields from the specified entry in the password database. See `getpwnam(3) <http://man7.org/linux/man-pages/man3/getpwnam.3.html>`_ for more information. :param str name: The user name to look up. :param str encoding: The encoding to use for strings. :return: The entry from the user database or ``None`` if it was not found. :rtype: tuple
getpwnam
python
rsmusllp/king-phisher
king_phisher/server/pylibc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/pylibc.py
BSD-3-Clause
def getpwuid(uid): """ Get the structure containing the fields from the specified entry in the password database. See `getpwuid(3) <http://man7.org/linux/man-pages/man3/getpwuid.3.html>`_ for more information. :param int uid: The user id to look up. :return: The entry from the user database or ``None`` if it was not found. :rtype: tuple """ c_ppasswd = _libc_getpwuid(uid) if not c_ppasswd: return None return c_ppasswd.contents.to_tuple()
Get the structure containing the fields from the specified entry in the password database. See `getpwuid(3) <http://man7.org/linux/man-pages/man3/getpwuid.3.html>`_ for more information. :param int uid: The user id to look up. :return: The entry from the user database or ``None`` if it was not found. :rtype: tuple
getpwuid
python
rsmusllp/king-phisher
king_phisher/server/pylibc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/pylibc.py
BSD-3-Clause
def rest_handler(handle_function): """ A function for decorating REST API handlers. The function checks the API token in the request and encodes the handler response in JSON to be sent to the client. :param handle_function: The REST API handler. """ def wrapped(handler, params): client_ip = ipaddress.ip_address(handler.client_address[0]) config = handler.config if not config.get('server.rest_api.enabled'): logger.warning("denying REST API request from {0} (REST API is disabled)".format(client_ip)) handler.respond_unauthorized() return networks = config.get_if_exists('server.rest_api.networks') if networks is not None: found = False for network in networks: if client_ip in ipaddress.ip_network(network, strict=False): found = True break if not found: logger.warning("denying REST API request from {0} (origin is from an unauthorized network)".format(client_ip)) handler.respond_unauthorized() return if not handler.config.get('server.rest_api.token'): logger.warning("denying REST API request from {0} (configured token is invalid)".format(client_ip)) handler.respond_unauthorized() return if config.get('server.rest_api.token') != handler.get_query('token'): logger.warning("denying REST API request from {0} (invalid authentication token)".format(client_ip)) handler.respond_unauthorized() return response = dict(result=handle_function(handler, params)) response = json.dumps(response, sort_keys=True, indent=2, separators=(',', ': ')) response = response.encode('utf-8') handler.send_response(200) handler.send_header('Content-Type', 'application/json') handler.send_header('Content-Length', str(len(response))) handler.end_headers() handler.wfile.write(response) return return wrapped
A function for decorating REST API handlers. The function checks the API token in the request and encodes the handler response in JSON to be sent to the client. :param handle_function: The REST API handler.
rest_handler
python
rsmusllp/king-phisher
king_phisher/server/rest_api.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/rest_api.py
BSD-3-Clause
def issue_alert(self, campaign_id, table, count): """ Send a campaign alert for the specified table. :param int campaign_id: The campaign subscribers to send the alert to. :param str table: The type of event to use as the sender when it is forwarded. :param int count: The number associated with the event alert. """ campaign = db_manager.get_row_by_id(self._session, db_models.Campaign, campaign_id) _send_safe_campaign_alerts(campaign, 'campaign-alert', table, count=count) return
Send a campaign alert for the specified table. :param int campaign_id: The campaign subscribers to send the alert to. :param str table: The type of event to use as the sender when it is forwarded. :param int count: The number associated with the event alert.
issue_alert
python
rsmusllp/king-phisher
king_phisher/server/server.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server.py
BSD-3-Clause
def adjust_path(self): """Adjust the :py:attr:`~.KingPhisherRequestHandler.path` attribute based on multiple factors.""" self.request_path = self.path.split('?', 1)[0] if not self.config.get('server.vhost_directories'): return if not self.vhost: raise errors.KingPhisherAbortRequestError() if self.vhost in ('localhost', '127.0.0.1') and self.client_address[0] != '127.0.0.1': raise errors.KingPhisherAbortRequestError() self.path = '/' + self.vhost + self.path
Adjust the :py:attr:`~.KingPhisherRequestHandler.path` attribute based on multiple factors.
adjust_path
python
rsmusllp/king-phisher
king_phisher/server/server.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server.py
BSD-3-Clause
def get_template_vars_client(self): """ Build a dictionary of variables for a client with an associated campaign. :return: The client specific template variables. :rtype: dict """ client_vars = { 'address': self.get_client_ip() } if not self.message_id: return client_vars credential_count = 0 expired_campaign = True visit_count = 0 result = None if self.message_id == self.config.get('server.secret_id'): client_vars['company_name'] = 'Wonderland Inc.' client_vars['company'] = {'name': 'Wonderland Inc.'} result = ('[email protected]', 'Alice', 'Liddle', 0) elif self.message_id: message = db_manager.get_row_by_id(self._session, db_models.Message, self.message_id) if message: campaign = message.campaign.to_dict() campaign['message_count'] = self._session.query(db_models.Message).filter_by(campaign_id=message.campaign.id).count() campaign['visit_count'] = self._session.query(db_models.Visit).filter_by(campaign_id=message.campaign.id).count() campaign['credential_count'] = self._session.query(db_models.Credential).filter_by(campaign_id=message.campaign.id).count() client_vars['campaign'] = campaign if message.campaign.company: client_vars['company_name'] = message.campaign.company.name client_vars['company'] = message.campaign.company.to_dict() result = (message.target_email, message.first_name, message.last_name, message.trained) query = self._session.query(db_models.Credential) query = query.filter_by(message_id=self.message_id) credential_count = query.count() expired_campaign = message.campaign.has_expired if not result: return client_vars client_vars['email_address'] = result[0] client_vars['first_name'] = result[1] client_vars['last_name'] = result[2] client_vars['is_trained'] = result[3] client_vars['message_id'] = self.message_id if self.visit_id: visit = db_manager.get_row_by_id(self._session, db_models.Visit, self.visit_id) client_vars['visit_id'] = visit.id visit_count = visit.count client_vars['credential_count'] = credential_count client_vars['visit_count'] = visit_count + (0 if expired_campaign else 1) return client_vars
Build a dictionary of variables for a client with an associated campaign. :return: The client specific template variables. :rtype: dict
get_template_vars_client
python
rsmusllp/king-phisher
king_phisher/server/server.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server.py
BSD-3-Clause
def _set_ids(self): """ Handle lazy resolution of the ``*_id`` properties necessary to track information. """ self._visit_id = None kp_cookie_name = self.config.get('server.cookie_name') if kp_cookie_name in self.cookies: value = self.cookies[kp_cookie_name].value if db_manager.get_row_by_id(self._session, db_models.Visit, value): self._visit_id = value self._message_id = None msg_id = self.get_query('id') if msg_id == self.config.get('server.secret_id'): self._message_id = msg_id elif msg_id and db_manager.get_row_by_id(self._session, db_models.Message, msg_id): self._message_id = msg_id elif self._visit_id: visit = db_manager.get_row_by_id(self._session, db_models.Visit, self._visit_id) self._message_id = visit.message_id self._campaign_id = None if self._message_id and self._message_id != self.config.get('server.secret_id'): message = db_manager.get_row_by_id(self._session, db_models.Message, self._message_id) if message: self._campaign_id = message.campaign_id
Handle lazy resolution of the ``*_id`` properties necessary to track information.
_set_ids
python
rsmusllp/king-phisher
king_phisher/server/server.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server.py
BSD-3-Clause
def campaign_id(self): """ The campaign id that is associated with the current request's visitor. This is retrieved by looking up the :py:attr:`~.KingPhisherRequestHandler.message_id` value in the database. If no campaign is associated, this value is None. """ if not hasattr(self, '_campaign_id'): self.logger.warning('using lazy resolution for the request campaign id') self._set_ids() return self._campaign_id
The campaign id that is associated with the current request's visitor. This is retrieved by looking up the :py:attr:`~.KingPhisherRequestHandler.message_id` value in the database. If no campaign is associated, this value is None.
campaign_id
python
rsmusllp/king-phisher
king_phisher/server/server.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server.py
BSD-3-Clause
def message_id(self): """ The message id that is associated with the current request's visitor. This is retrieved by looking at an 'id' parameter in the query and then by checking the :py:attr:`~.KingPhisherRequestHandler.visit_id` value in the database. If no message id is associated, this value is None. The resulting value will be either a confirmed valid value, or the value of the configurations server.secret_id for testing purposes. """ if not hasattr(self, '_message_id'): self.logger.warning('using lazy resolution for the request message id') self._set_ids() return self._message_id
The message id that is associated with the current request's visitor. This is retrieved by looking at an 'id' parameter in the query and then by checking the :py:attr:`~.KingPhisherRequestHandler.visit_id` value in the database. If no message id is associated, this value is None. The resulting value will be either a confirmed valid value, or the value of the configurations server.secret_id for testing purposes.
message_id
python
rsmusllp/king-phisher
king_phisher/server/server.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server.py
BSD-3-Clause
def visit_id(self): """ The visit id that is associated with the current request's visitor. This is retrieved by looking for the King Phisher cookie. If no cookie is set, this value is None. """ if not hasattr(self, '_visit_id'): self.logger.warning('using lazy resolution for the request visit id') self._set_ids() return self._visit_id
The visit id that is associated with the current request's visitor. This is retrieved by looking for the King Phisher cookie. If no cookie is set, this value is None.
visit_id
python
rsmusllp/king-phisher
king_phisher/server/server.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server.py
BSD-3-Clause
def get_client_ip(self): """ Intelligently get the IP address of the HTTP client, optionally accounting for proxies that may be in use. :return: The clients IP address. :rtype: str """ address = self.client_address[0] header_name = self.config.get_if_exists('server.client_ip_header') # new style header_name = header_name or self.config.get_if_exists('server.client_ip_cookie') # old style if not header_name: return address header_value = self.headers.get(header_name, '') if not header_value: return address header_value = header_value.split(',')[0] header_value = header_value.strip() if header_value.startswith('['): # header_value looks like an IPv6 address header_value = header_value.split(']:', 1)[0] else: # treat header_value as an IPv4 address header_value = header_value.split(':', 1)[0] if ipaddress.is_valid(header_value): address = header_value return address
Intelligently get the IP address of the HTTP client, optionally accounting for proxies that may be in use. :return: The clients IP address. :rtype: str
get_client_ip
python
rsmusllp/king-phisher
king_phisher/server/server.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server.py
BSD-3-Clause
def __init__(self, config, plugin_manager, handler_klass, *args, **kwargs): """ :param config: Configuration to retrieve settings from. :type config: :py:class:`smoke_zephyr.configuration.Configuration` """ # additional mime types to be treated as html because they're probably cloned pages handler_klass.extensions_map.update({ '': 'text/html', '.asp': 'text/html', '.aspx': 'text/html', '.cfm': 'text/html', '.cgi': 'text/html', '.do': 'text/html', '.jsp': 'text/html', '.nsf': 'text/html', '.php': 'text/html', '.srf': 'text/html' }) super(KingPhisherServer, self).__init__(handler_klass, *args, **kwargs) self.logger = logging.getLogger('KingPhisher.Server') self.config = config """A :py:class:`~smoke_zephyr.configuration.Configuration` instance used as the main King Phisher server configuration.""" self.headers = collections.OrderedDict() """A :py:class:`~collections.OrderedDict` containing additional headers specified from the server configuration to include in responses.""" self.plugin_manager = plugin_manager self.serve_files = True self.serve_files_root = config.get('server.web_root') self.serve_files_list_directories = False self.serve_robots_txt = True self.database_engine = db_manager.init_database(config.get('server.database'), extra_init=True) self.throttle_semaphore = threading.BoundedSemaphore() self.session_manager = aaa.AuthenticatedSessionManager( timeout=config.get_if_exists('server.authentication.session_timeout', '30m') ) self.forked_authenticator = aaa.ForkedAuthenticator( cache_timeout=config.get_if_exists('server.authentication.cache_timeout', '10m'), required_group=config.get_if_exists('server.authentication.group'), pam_service=config.get_if_exists('server.authentication.pam_service', 'sshd') ) self.job_manager = smoke_zephyr.job.JobManager(logger_name='KingPhisher.Server.JobManager') """A :py:class:`~smoke_zephyr.job.JobManager` instance for scheduling tasks.""" self.job_manager.start() maintenance_interval = 900 # 15 minutes self._maintenance_job = self.job_manager.job_add(self._maintenance, parameters=(maintenance_interval,), seconds=maintenance_interval) loader = jinja2.FileSystemLoader(config.get('server.web_root')) global_vars = {} if config.has_section('server.page_variables'): global_vars = config.get('server.page_variables') global_vars.update(template_extras.functions) self.template_env = templates.TemplateEnvironmentBase(loader=loader, global_vars=global_vars) self.ws_manager = web_sockets.WebSocketsManager(config, self.job_manager) self.tables_api = {} self._init_tables_api() for http_server in self.sub_servers: http_server.add_sni_cert = self.add_sni_cert http_server.config = config http_server.forked_authenticator = self.forked_authenticator http_server.get_sni_certs = lambda: self.sni_certs http_server.headers = self.headers http_server.job_manager = self.job_manager http_server.kp_shutdown = self.shutdown http_server.plugin_manager = plugin_manager http_server.remove_sni_cert = self.remove_sni_cert http_server.session_manager = self.session_manager http_server.tables_api = self.tables_api http_server.template_env = self.template_env http_server.throttle_semaphore = self.throttle_semaphore http_server.ws_manager = self.ws_manager if not config.has_option('server.secret_id'): test_id = rest_api.generate_token() config.set('server.secret_id', test_id) self.logger.debug('server request test id initialized with value: ' + test_id) if not config.get_if_exists('server.rest_api.token'): config.set('server.rest_api.token', rest_api.generate_token()) if config.get('server.rest_api.enabled'): self.logger.info('rest api token initialized with value: ' + config.get('server.rest_api.token')) self.__geoip_db = geoip.init_database(config.get('server.geoip.database')) self.__is_shutdown = threading.Event() self.__is_shutdown.clear() self.__shutdown_lock = threading.Lock() plugin_manager.server = weakref.proxy(self) headers = self.config.get_if_exists('server.headers', []) for header in headers: if ': ' not in header: self.logger.warning("header '{0}' is invalid and will not be included".format(header)) continue header, value = header.split(': ', 1) header = header.strip() self.headers[header] = value self.logger.info("including {0} custom http headers".format(len(self.headers)))
:param config: Configuration to retrieve settings from. :type config: :py:class:`smoke_zephyr.configuration.Configuration`
__init__
python
rsmusllp/king-phisher
king_phisher/server/server.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server.py
BSD-3-Clause
def _maintenance(self, interval): """ Execute periodic maintenance related tasks. :param int interval: The interval of time (in seconds) at which this method is being executed. """ self.logger.debug('running periodic maintenance tasks') now = db_models.current_timestamp() session = db_manager.Session() campaigns = session.query(db_models.Campaign).filter( db_models.Campaign.expiration != None ).filter( db_models.Campaign.expiration < now ).filter( db_models.Campaign.expiration >= now - datetime.timedelta(seconds=interval) ) for campaign in campaigns: signals.send_safe('campaign-expired', self.logger, campaign) _send_safe_campaign_alerts(campaign, 'campaign-alert-expired', campaign) session.close()
Execute periodic maintenance related tasks. :param int interval: The interval of time (in seconds) at which this method is being executed.
_maintenance
python
rsmusllp/king-phisher
king_phisher/server/server.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server.py
BSD-3-Clause
def shutdown(self, *args, **kwargs): """ Request that the server perform any cleanup necessary and then shut down. This will wait for the server to stop before it returns. """ with self.__shutdown_lock: if self.__is_shutdown.is_set(): return self.logger.warning('processing shutdown request') super(KingPhisherServer, self).shutdown(*args, **kwargs) self.ws_manager.stop() self.job_manager.stop() self.session_manager.stop() self.forked_authenticator.stop() self.logger.debug('stopped the forked authenticator process') self.__geoip_db.close() self.__is_shutdown.set()
Request that the server perform any cleanup necessary and then shut down. This will wait for the server to stop before it returns.
shutdown
python
rsmusllp/king-phisher
king_phisher/server/server.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server.py
BSD-3-Clause
def register_rpc(path, database_access=False, log_call=False): """ Register an RPC function with the HTTP request handler. This allows the method to be remotely invoked using King Phisher's standard RPC interface. If *database_access* is specified, a SQLAlchemy session will be passed as the second argument, after the standard :py:class:`~advancedhttpserver.RequestHandler` instance. :param str path: The path for the RPC function. :param bool database_access: Whether or not the function requires database access. :param bool log_call: Whether or not to log the arguments which the function is called with. """ path = '^' + path + '$' def decorator(function): @functools.wraps(function) def wrapper(handler_instance, *args, **kwargs): if log_call: _log_rpc_call(handler_instance, function.__name__, *args, **kwargs) signals.send_safe('rpc-method-call', rpc_logger, path[1:-1], request_handler=handler_instance, args=args, kwargs=kwargs) if database_access: session = db_manager.Session() try: result = function(handler_instance, session, *args, **kwargs) finally: session.close() else: result = function(handler_instance, *args, **kwargs) signals.send_safe('rpc-method-called', rpc_logger, path[1:-1], request_handler=handler_instance, args=args, kwargs=kwargs, retval=result) return result advancedhttpserver.RegisterPath(path, is_rpc=True)(wrapper) return wrapper return decorator
Register an RPC function with the HTTP request handler. This allows the method to be remotely invoked using King Phisher's standard RPC interface. If *database_access* is specified, a SQLAlchemy session will be passed as the second argument, after the standard :py:class:`~advancedhttpserver.RequestHandler` instance. :param str path: The path for the RPC function. :param bool database_access: Whether or not the function requires database access. :param bool log_call: Whether or not to log the arguments which the function is called with.
register_rpc
python
rsmusllp/king-phisher
king_phisher/server/server_rpc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server_rpc.py
BSD-3-Clause
def rpc_shutdown(handler): """ This method can be used to shut down the server. This function will return, however no subsequent requests will be processed. .. warning:: This action will stop the server process and there is no confirmation before it takes place. """ shutdown_thread = threading.Thread(target=handler.server.kp_shutdown) shutdown_thread.start() rpc_logger.debug("shutdown routine running in tid: 0x{0:x}".format(shutdown_thread.ident)) return
This method can be used to shut down the server. This function will return, however no subsequent requests will be processed. .. warning:: This action will stop the server process and there is no confirmation before it takes place.
rpc_shutdown
python
rsmusllp/king-phisher
king_phisher/server/server_rpc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server_rpc.py
BSD-3-Clause
def rpc_version(handler): """ Get the version information of the server. This returns a dictionary with keys of version, version_info and rpc_api_version. These values are provided for the client to determine compatibility. :return: A dictionary with version information. :rtype: dict """ if not ipaddress.ip_address(handler.client_address[0]).is_loopback: message = "an rpc request to /version was received from non-loopback IP address: {0}".format(handler.client_address[0]) rpc_logger.error(message) raise errors.KingPhisherAPIError(message) vinfo = { 'rpc_api_version': version.rpc_api_version, 'version': version.version, 'version_info': version.version_info._asdict() } return vinfo
Get the version information of the server. This returns a dictionary with keys of version, version_info and rpc_api_version. These values are provided for the client to determine compatibility. :return: A dictionary with version information. :rtype: dict
rpc_version
python
rsmusllp/king-phisher
king_phisher/server/server_rpc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server_rpc.py
BSD-3-Clause
def rpc_config_get(handler, option_name): """ Retrieve a value from the server's configuration. :param str option_name: The name of the configuration option. :return: The option's value. """ if isinstance(option_name, (list, tuple)): option_names = option_name option_values = {} for option_name in option_names: if not option_name in CONFIG_READABLE: raise errors.KingPhisherPermissionError('permission denied to read config option: ' + option_name) if handler.config.has_option(option_name): option_values[option_name] = handler.config.get(option_name) return option_values if not option_name in CONFIG_READABLE: raise errors.KingPhisherPermissionError('permission denied to read config option: ' + option_name) if handler.config.has_option(option_name): return handler.config.get(option_name) return
Retrieve a value from the server's configuration. :param str option_name: The name of the configuration option. :return: The option's value.
rpc_config_get
python
rsmusllp/king-phisher
king_phisher/server/server_rpc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server_rpc.py
BSD-3-Clause
def rpc_config_set(handler, options): """ Set options in the server's configuration. Any changes to the server's configuration are not written to disk. :param dict options: A dictionary of option names and values """ if rpc_logger.isEnabledFor(logging.DEBUG): _log_rpc_call(handler, 'rpc_config_set', dict((key, _REDACTED) for key in options.keys())) for key, value in options.items(): if key not in CONFIG_WRITEABLE: raise errors.KingPhisherPermissionError('permission denied to write config option: ' + key) handler.config.set(key, value) return
Set options in the server's configuration. Any changes to the server's configuration are not written to disk. :param dict options: A dictionary of option names and values
rpc_config_set
python
rsmusllp/king-phisher
king_phisher/server/server_rpc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server_rpc.py
BSD-3-Clause
def rpc_campaign_new(handler, session, name, description=None): """ Create a new King Phisher campaign and initialize the database information. :param str name: The new campaign's name. :param str description: The new campaign's description. :return: The ID of the new campaign. :rtype: int """ if session.query(db_models.Campaign).filter_by(name=name).count(): raise ValueError('the specified campaign name already exists') campaign = db_models.Campaign(name=name, description=description, user_id=handler.rpc_session.user) campaign.assert_session_has_permissions('c', handler.rpc_session) session.add(campaign) session.commit() return campaign.id
Create a new King Phisher campaign and initialize the database information. :param str name: The new campaign's name. :param str description: The new campaign's description. :return: The ID of the new campaign. :rtype: int
rpc_campaign_new
python
rsmusllp/king-phisher
king_phisher/server/server_rpc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server_rpc.py
BSD-3-Clause
def rpc_campaign_alerts_is_subscribed(handler, session, campaign_id): """ Check if the user is subscribed to alerts for the specified campaign. :param int campaign_id: The ID of the campaign. :return: The alert subscription status. :rtype: bool """ query = session.query(db_models.AlertSubscription) query = query.filter_by(campaign_id=campaign_id, user_id=handler.rpc_session.user) return query.count()
Check if the user is subscribed to alerts for the specified campaign. :param int campaign_id: The ID of the campaign. :return: The alert subscription status. :rtype: bool
rpc_campaign_alerts_is_subscribed
python
rsmusllp/king-phisher
king_phisher/server/server_rpc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server_rpc.py
BSD-3-Clause
def rpc_campaign_alerts_subscribe(handler, session, campaign_id): """ Subscribe to alerts for the specified campaign. :param int campaign_id: The ID of the campaign. """ user_id = handler.rpc_session.user query = session.query(db_models.AlertSubscription) query = query.filter_by(campaign_id=campaign_id, user_id=user_id) if query.count() == 0: subscription = db_models.AlertSubscription(campaign_id=campaign_id, user_id=user_id) subscription.assert_session_has_permissions('c', handler.rpc_session) session.add(subscription) session.commit()
Subscribe to alerts for the specified campaign. :param int campaign_id: The ID of the campaign.
rpc_campaign_alerts_subscribe
python
rsmusllp/king-phisher
king_phisher/server/server_rpc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server_rpc.py
BSD-3-Clause
def rpc_campaign_alerts_unsubscribe(handler, session, campaign_id): """ Unsubscribe to alerts for the specified campaign. :param int campaign_id: The ID of the campaign. """ user_id = handler.rpc_session.user query = session.query(db_models.AlertSubscription) query = query.filter_by(campaign_id=campaign_id, user_id=user_id) subscription = query.first() if subscription: subscription.assert_session_has_permissions('d', handler.rpc_session) session.delete(subscription) session.commit()
Unsubscribe to alerts for the specified campaign. :param int campaign_id: The ID of the campaign.
rpc_campaign_alerts_unsubscribe
python
rsmusllp/king-phisher
king_phisher/server/server_rpc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server_rpc.py
BSD-3-Clause