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 gobject_get_value(gobject, gtype=None):
"""
Retrieve the value of a GObject widget. Only objects with corresponding
entries present in the :py:data:`.GOBJECT_PROPERTY_MAP` can be processed by
this function.
:param gobject: The object to retrieve the value for.
:type gobject: :py:class:`GObject.Object`
:param str gtype: An explicit type to treat *gobject* as.
:return: The value of *gobject*.
:rtype: str
"""
gtype = (gtype or gobject.__class__.__name__)
gtype = gtype.lower()
if isinstance(GOBJECT_PROPERTY_MAP[gtype], (list, tuple)):
try:
value = GOBJECT_PROPERTY_MAP[gtype][1](gobject)
except AttributeError:
return None
else:
value = gobject.get_property(GOBJECT_PROPERTY_MAP[gtype])
return value
|
Retrieve the value of a GObject widget. Only objects with corresponding
entries present in the :py:data:`.GOBJECT_PROPERTY_MAP` can be processed by
this function.
:param gobject: The object to retrieve the value for.
:type gobject: :py:class:`GObject.Object`
:param str gtype: An explicit type to treat *gobject* as.
:return: The value of *gobject*.
:rtype: str
|
gobject_get_value
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def gobject_set_value(gobject, value, gtype=None):
"""
Set the value of a GObject widget. Only objects with corresponding entries
present in the :py:data:`.GOBJECT_PROPERTY_MAP` can be processed by this
function.
:param gobject: The object to set the value for.
:type gobject: :py:class:`GObject.Object`
:param value: The value to set for the object.
:param str gtype: An explicit type to treat *gobject* as.
"""
gtype = (gtype or gobject.__class__.__name__)
gtype = gtype.lower()
if gtype not in GOBJECT_PROPERTY_MAP:
raise ValueError('unsupported gtype: ' + gtype)
if isinstance(GOBJECT_PROPERTY_MAP[gtype], (list, tuple)):
GOBJECT_PROPERTY_MAP[gtype][0](gobject, value)
else:
gobject.set_property(GOBJECT_PROPERTY_MAP[gtype], value)
|
Set the value of a GObject widget. Only objects with corresponding entries
present in the :py:data:`.GOBJECT_PROPERTY_MAP` can be processed by this
function.
:param gobject: The object to set the value for.
:type gobject: :py:class:`GObject.Object`
:param value: The value to set for the object.
:param str gtype: An explicit type to treat *gobject* as.
|
gobject_set_value
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def gobject_signal_blocked(gobject, signal_name):
"""
This is a context manager that can be used with the 'with' statement
to execute a block of code while *signal_name* is blocked.
:param gobject: The object to block the signal on.
:type gobject: :py:class:`GObject.Object`
:param str signal_name: The name of the signal to block.
"""
signal_id = GObject.signal_lookup(signal_name, gobject.__class__)
handler_id = GObject.signal_handler_find(gobject, GObject.SignalMatchType.ID, signal_id, 0, None, 0, 0)
GObject.signal_handler_block(gobject, handler_id)
yield
GObject.signal_handler_unblock(gobject, handler_id)
|
This is a context manager that can be used with the 'with' statement
to execute a block of code while *signal_name* is blocked.
:param gobject: The object to block the signal on.
:type gobject: :py:class:`GObject.Object`
:param str signal_name: The name of the signal to block.
|
gobject_signal_blocked
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def gobject_signal_accumulator(test=None):
"""
Create an accumulator function for use with GObject signals. All return
values will be collected and returned in a list. If provided, *test* is a
callback that will be called with two arguments, the return value from the
handler and the list of accumulated return values.
.. code-block:: python
stop = test(retval, accumulated)
:param test: A callback to test whether additional handler should be executed.
"""
if test is None:
test = lambda retval, accumulated: True
def _accumulator(_, accumulated, retval):
if accumulated is None:
accumulated = []
stop = test(retval, accumulated)
accumulated.append(retval)
return (stop, accumulated)
return _accumulator
|
Create an accumulator function for use with GObject signals. All return
values will be collected and returned in a list. If provided, *test* is a
callback that will be called with two arguments, the return value from the
handler and the list of accumulated return values.
.. code-block:: python
stop = test(retval, accumulated)
:param test: A callback to test whether additional handler should be executed.
|
gobject_signal_accumulator
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def gtk_calendar_get_pydate(gtk_calendar):
"""
Get the Python date from a :py:class:`Gtk.Calendar` instance. If the day
in *gtk_calendar* is not within the valid range for the specified month, it
will be rounded to the closest value (i.e. 0 for unset will become 1 etc.).
:param gtk_calendar: The calendar to get the date from.
:type gtk_calendar: :py:class:`Gtk.Calendar`
:return: The date as returned by the calendar's :py:meth:`~Gtk.Calendar.get_date` method.
:rtype: :py:class:`datetime.date`
"""
if not isinstance(gtk_calendar, Gtk.Calendar):
raise ValueError('calendar must be a Gtk.Calendar instance')
year, month, day = gtk_calendar.get_date()
month += 1 # account for Gtk.Calendar starting at 0
_, last_day_of_month = calendar.monthrange(year, month)
day = max(1, min(day, last_day_of_month))
return datetime.date(year, month, day)
|
Get the Python date from a :py:class:`Gtk.Calendar` instance. If the day
in *gtk_calendar* is not within the valid range for the specified month, it
will be rounded to the closest value (i.e. 0 for unset will become 1 etc.).
:param gtk_calendar: The calendar to get the date from.
:type gtk_calendar: :py:class:`Gtk.Calendar`
:return: The date as returned by the calendar's :py:meth:`~Gtk.Calendar.get_date` method.
:rtype: :py:class:`datetime.date`
|
gtk_calendar_get_pydate
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def gtk_combobox_get_active_cell(combobox, column=None):
"""
Get the active value from a GTK combobox and it's respective model. If
nothing is selected, ``None`` is returned.
.. versionadded:: 1.14.0
:param combobox: The combobox to retrieve the active model value for.
:param int column: The column ID to retrieve from the selected row. If not
specified, the combobox's ``id-column`` property will be used.
:return: The selected model row's value.
"""
row = gtk_combobox_get_active_row(combobox)
if row is None:
return None
if column is None:
column = combobox.get_property('id-column')
return row[column]
|
Get the active value from a GTK combobox and it's respective model. If
nothing is selected, ``None`` is returned.
.. versionadded:: 1.14.0
:param combobox: The combobox to retrieve the active model value for.
:param int column: The column ID to retrieve from the selected row. If not
specified, the combobox's ``id-column`` property will be used.
:return: The selected model row's value.
|
gtk_combobox_get_active_cell
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def gtk_combobox_get_active_row(combobox):
"""
Get the active row from a GTK combobox and it's respective model. If
nothing is selected, ``None`` is returned.
.. versionadded:: 1.14.0
:param combobox: The combobox to retrieve the active model row for.
:return: The selected model row.
"""
active = combobox.get_active()
if active == -1:
return None
model = combobox.get_model()
return model[active]
|
Get the active row from a GTK combobox and it's respective model. If
nothing is selected, ``None`` is returned.
.. versionadded:: 1.14.0
:param combobox: The combobox to retrieve the active model row for.
:return: The selected model row.
|
gtk_combobox_get_active_row
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def gtk_combobox_get_entry_text(combobox):
"""
Get the text from a combobox's entry widget.
.. versionadded:: 1.14.0
:param combobox: The combobox to retrieve the entry text for.
:return: The value of the entry text.
:rtype: str
"""
if not combobox.get_has_entry():
raise ValueError('the specified combobox does not have an entry')
entry = combobox.get_child()
return entry.get_text()
|
Get the text from a combobox's entry widget.
.. versionadded:: 1.14.0
:param combobox: The combobox to retrieve the entry text for.
:return: The value of the entry text.
:rtype: str
|
gtk_combobox_get_entry_text
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def gtk_combobox_set_entry_completion(combobox):
"""
Add completion for a :py:class:`Gtk.ComboBox` widget which contains an
entry. They combobox's ``entry-text-column`` property it used to determine
which column in its model contains the strings to suggest for completion.
.. versionadded:: 1.14.0
:param combobox: The combobox to add completion for.
:type: :py:class:`Gtk.ComboBox`
"""
utilities.assert_arg_type(combobox, Gtk.ComboBox)
completion = Gtk.EntryCompletion()
completion.set_model(combobox.get_model())
completion.set_text_column(combobox.get_entry_text_column())
entry = combobox.get_child()
entry.set_completion(completion)
|
Add completion for a :py:class:`Gtk.ComboBox` widget which contains an
entry. They combobox's ``entry-text-column`` property it used to determine
which column in its model contains the strings to suggest for completion.
.. versionadded:: 1.14.0
:param combobox: The combobox to add completion for.
:type: :py:class:`Gtk.ComboBox`
|
gtk_combobox_set_entry_completion
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def gtk_list_store_search(list_store, value, column=0):
"""
Search a :py:class:`Gtk.ListStore` for a value and return a
:py:class:`Gtk.TreeIter` to the first match.
:param list_store: The list store to search.
:type list_store: :py:class:`Gtk.ListStore`
:param value: The value to search for.
:param int column: The column in the row to check.
:return: The row on which the value was found.
:rtype: :py:class:`Gtk.TreeIter`
"""
for row in list_store:
if row[column] == value:
return row.iter
return None
|
Search a :py:class:`Gtk.ListStore` for a value and return a
:py:class:`Gtk.TreeIter` to the first match.
:param list_store: The list store to search.
:type list_store: :py:class:`Gtk.ListStore`
:param value: The value to search for.
:param int column: The column in the row to check.
:return: The row on which the value was found.
:rtype: :py:class:`Gtk.TreeIter`
|
gtk_list_store_search
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def gtk_listbox_populate_labels(listbox, label_strings):
"""
Formats and adds labels to a listbox. Each label is styled and added as a
separate entry.
.. versionadded:: 1.13.0
:param listbox: Gtk Listbox to put the labels in.
:type listbox: :py:class:`Gtk.listbox`
:param list label_strings: List of strings to add to the Gtk Listbox as labels.
"""
gtk_widget_destroy_children(listbox)
for label_text in label_strings:
label = Gtk.Label()
label.set_markup("<span font=\"smaller\"><tt>{0}</tt></span>".format(saxutils.escape(label_text)))
label.set_property('halign', Gtk.Align.START)
label.set_property('use-markup', True)
label.set_property('valign', Gtk.Align.START)
label.set_property('visible', True)
listbox.add(label)
|
Formats and adds labels to a listbox. Each label is styled and added as a
separate entry.
.. versionadded:: 1.13.0
:param listbox: Gtk Listbox to put the labels in.
:type listbox: :py:class:`Gtk.listbox`
:param list label_strings: List of strings to add to the Gtk Listbox as labels.
|
gtk_listbox_populate_labels
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def gtk_listbox_populate_urls(listbox, url_strings, signals=None):
"""
Format and adds URLs to a list box. Each URL is styled and added as a
separate entry.
.. versionadded:: 1.14.0
:param listbox: Gtk Listbox to put the labels in.
:type listbox: :py:class:`Gtk.listbox`
:param list url_strings: List of URL strings to add to the Gtk Listbox as labels.
:param dict signals: A dictionary, keyed by signal names to signal handler
functions for the labels added to the listbox.
"""
gtk_widget_destroy_children(listbox)
signals = signals or {}
for url in url_strings:
label = Gtk.Label()
for signal, handler in signals.items():
label.connect(signal, handler)
label.set_markup("<a href=\"{0}\">{1}</a>".format(url.replace('"', '"'), saxutils.escape(url)))
label.set_property('halign', Gtk.Align.START)
label.set_property('track-visited-links', False)
label.set_property('use-markup', True)
label.set_property('valign', Gtk.Align.START)
label.set_property('visible', True)
listbox.add(label)
|
Format and adds URLs to a list box. Each URL is styled and added as a
separate entry.
.. versionadded:: 1.14.0
:param listbox: Gtk Listbox to put the labels in.
:type listbox: :py:class:`Gtk.listbox`
:param list url_strings: List of URL strings to add to the Gtk Listbox as labels.
:param dict signals: A dictionary, keyed by signal names to signal handler
functions for the labels added to the listbox.
|
gtk_listbox_populate_urls
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def gtk_menu_get_item_by_label(menu, label):
"""
Retrieve a menu item from a menu by it's label. If more than one items share
the same label, only the first is returned.
:param menu: The menu to search for the item in.
:type menu: :py:class:`Gtk.Menu`
:param str label: The label to search for in *menu*.
:return: The identified menu item if it could be found, otherwise None is returned.
:rtype: :py:class:`Gtk.MenuItem`
"""
for item in menu:
if item.get_label() == label:
return item
|
Retrieve a menu item from a menu by it's label. If more than one items share
the same label, only the first is returned.
:param menu: The menu to search for the item in.
:type menu: :py:class:`Gtk.Menu`
:param str label: The label to search for in *menu*.
:return: The identified menu item if it could be found, otherwise None is returned.
:rtype: :py:class:`Gtk.MenuItem`
|
gtk_menu_get_item_by_label
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def gtk_menu_insert_by_path(menu, menu_path, menu_item):
"""
Add a new menu item into the existing menu at the path specified in
*menu_path*.
:param menu: The existing menu to add the new item to.
:type menu: :py:class:`Gtk.Menu` :py:class:`Gtk.MenuBar`
:param list menu_path: The labels of submenus to traverse to insert the new item.
:param menu_item: The new menu item to insert.
:type menu_item: :py:class:`Gtk.MenuItem`
"""
utilities.assert_arg_type(menu, (Gtk.Menu, Gtk.MenuBar), 1)
utilities.assert_arg_type(menu_path, list, 2)
utilities.assert_arg_type(menu_item, Gtk.MenuItem, 3)
while len(menu_path):
label = menu_path.pop(0)
menu_cursor = gtk_menu_get_item_by_label(menu, label)
if menu_cursor is None:
raise ValueError('missing node labeled: ' + label)
menu = menu_cursor.get_submenu()
menu.append(menu_item)
|
Add a new menu item into the existing menu at the path specified in
*menu_path*.
:param menu: The existing menu to add the new item to.
:type menu: :py:class:`Gtk.Menu` :py:class:`Gtk.MenuBar`
:param list menu_path: The labels of submenus to traverse to insert the new item.
:param menu_item: The new menu item to insert.
:type menu_item: :py:class:`Gtk.MenuItem`
|
gtk_menu_insert_by_path
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def gtk_menu_position(event, *args):
"""
Create a menu at the given location for an event. This function is meant to
be used as the *func* parameter for the :py:meth:`Gtk.Menu.popup` method.
The *event* object must be passed in as the first parameter, which can be
accomplished using :py:func:`functools.partial`.
:param event: The event to retrieve the coordinates for.
"""
if not hasattr(event, 'get_root_coords'):
raise TypeError('event object has no get_root_coords method')
coords = event.get_root_coords()
return (coords[0], coords[1], True)
|
Create a menu at the given location for an event. This function is meant to
be used as the *func* parameter for the :py:meth:`Gtk.Menu.popup` method.
The *event* object must be passed in as the first parameter, which can be
accomplished using :py:func:`functools.partial`.
:param event: The event to retrieve the coordinates for.
|
gtk_menu_position
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def gtk_style_context_get_color(sc, color_name, default=None):
"""
Look up a color by it's name in the :py:class:`Gtk.StyleContext` specified
in *sc*, and return it as an :py:class:`Gdk.RGBA` instance if the color is
defined. If the color is not found, *default* will be returned.
:param sc: The style context to use.
:type sc: :py:class:`Gtk.StyleContext`
:param str color_name: The name of the color to lookup.
:param default: The default color to return if the specified color was not found.
:type default: str, :py:class:`Gdk.RGBA`
:return: The color as an RGBA instance.
:rtype: :py:class:`Gdk.RGBA`
"""
found, color_rgba = sc.lookup_color(color_name)
if found:
return color_rgba
if isinstance(default, str):
color_rgba = Gdk.RGBA()
color_rgba.parse(default)
return color_rgba
elif isinstance(default, Gdk.RGBA):
return default
return
|
Look up a color by it's name in the :py:class:`Gtk.StyleContext` specified
in *sc*, and return it as an :py:class:`Gdk.RGBA` instance if the color is
defined. If the color is not found, *default* will be returned.
:param sc: The style context to use.
:type sc: :py:class:`Gtk.StyleContext`
:param str color_name: The name of the color to lookup.
:param default: The default color to return if the specified color was not found.
:type default: str, :py:class:`Gdk.RGBA`
:return: The color as an RGBA instance.
:rtype: :py:class:`Gdk.RGBA`
|
gtk_style_context_get_color
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def gtk_treesortable_sort_func_numeric(model, iter1, iter2, column_id):
"""
Sort the model by comparing text numeric values with place holders such as
1,337. This is meant to be set as a sorting function using
:py:meth:`Gtk.TreeSortable.set_sort_func`. The user_data parameter must be
the column id which contains the numeric values to be sorted.
:param model: The model that is being sorted.
:type model: :py:class:`Gtk.TreeSortable`
:param iter1: The iterator of the first item to compare.
:type iter1: :py:class:`Gtk.TreeIter`
:param iter2: The iterator of the second item to compare.
:type iter2: :py:class:`Gtk.TreeIter`
:param column_id: The ID of the column containing numeric values.
:return: An integer, -1 if item1 should come before item2, 0 if they are the same and 1 if item1 should come after item2.
:rtype: int
"""
column_id = column_id or 0
item1 = model.get_value(iter1, column_id).replace(',', '')
item2 = model.get_value(iter2, column_id).replace(',', '')
if item1.isdigit() and item2.isdigit():
return _cmp(int(item1), int(item2))
if item1.isdigit():
return -1
elif item2.isdigit():
return 1
item1 = model.get_value(iter1, column_id)
item2 = model.get_value(iter2, column_id)
return _cmp(item1, item2)
|
Sort the model by comparing text numeric values with place holders such as
1,337. This is meant to be set as a sorting function using
:py:meth:`Gtk.TreeSortable.set_sort_func`. The user_data parameter must be
the column id which contains the numeric values to be sorted.
:param model: The model that is being sorted.
:type model: :py:class:`Gtk.TreeSortable`
:param iter1: The iterator of the first item to compare.
:type iter1: :py:class:`Gtk.TreeIter`
:param iter2: The iterator of the second item to compare.
:type iter2: :py:class:`Gtk.TreeIter`
:param column_id: The ID of the column containing numeric values.
:return: An integer, -1 if item1 should come before item2, 0 if they are the same and 1 if item1 should come after item2.
:rtype: int
|
gtk_treesortable_sort_func_numeric
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def gtk_treeview_selection_iterate(treeview):
"""
Iterate over the a treeview's selected rows.
:param treeview: The treeview for which to iterate over.
:type treeview: :py:class:`Gtk.TreeView`
:return: The rows which are selected within the treeview.
:rtype: :py:class:`Gtk.TreeIter`
"""
selection = treeview.get_selection()
(model, tree_paths) = selection.get_selected_rows()
if not tree_paths:
return
for tree_path in tree_paths:
yield model.get_iter(tree_path)
|
Iterate over the a treeview's selected rows.
:param treeview: The treeview for which to iterate over.
:type treeview: :py:class:`Gtk.TreeView`
:return: The rows which are selected within the treeview.
:rtype: :py:class:`Gtk.TreeIter`
|
gtk_treeview_selection_iterate
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def gtk_treeview_selection_to_clipboard(treeview, columns=0):
"""
Copy the currently selected values from the specified columns in the
treeview to the users clipboard. If no value is selected in the treeview,
then the clipboard is left unmodified. If multiple values are selected, they
will all be placed in the clipboard on separate lines.
:param treeview: The treeview instance to get the selection from.
:type treeview: :py:class:`Gtk.TreeView`
:param column: The column numbers to retrieve the value for.
:type column: int, list, tuple
"""
treeview_selection = treeview.get_selection()
(model, tree_paths) = treeview_selection.get_selected_rows()
if not tree_paths:
return
if isinstance(columns, int):
columns = (columns,)
tree_iters = map(model.get_iter, tree_paths)
selection_lines = []
for ti in tree_iters:
values = (model.get_value(ti, column) for column in columns)
values = (('' if value is None else str(value)) for value in values)
selection_lines.append(' '.join(values).strip())
selection_lines = os.linesep.join(selection_lines)
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
clipboard.set_text(selection_lines, -1)
|
Copy the currently selected values from the specified columns in the
treeview to the users clipboard. If no value is selected in the treeview,
then the clipboard is left unmodified. If multiple values are selected, they
will all be placed in the clipboard on separate lines.
:param treeview: The treeview instance to get the selection from.
:type treeview: :py:class:`Gtk.TreeView`
:param column: The column numbers to retrieve the value for.
:type column: int, list, tuple
|
gtk_treeview_selection_to_clipboard
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def gtk_treeview_get_column_titles(treeview):
"""
Iterate over a GTK TreeView and return a tuple containing the id and title
of each of it's columns.
:param treeview: The treeview instance to retrieve columns from.
:type treeview: :py:class:`Gtk.TreeView`
"""
for column_id, column in enumerate(treeview.get_columns()):
column_name = column.get_title()
yield (column_id, column_name)
|
Iterate over a GTK TreeView and return a tuple containing the id and title
of each of it's columns.
:param treeview: The treeview instance to retrieve columns from.
:type treeview: :py:class:`Gtk.TreeView`
|
gtk_treeview_get_column_titles
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def gtk_treeview_set_column_titles(treeview, column_titles, column_offset=0, renderers=None):
"""
Populate the column names of a GTK TreeView and set their sort IDs.
:param treeview: The treeview to set column names for.
:type treeview: :py:class:`Gtk.TreeView`
:param list column_titles: The names 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
"""
columns = {}
for column_id, column_title in enumerate(column_titles, column_offset):
renderer = renderers[column_id - column_offset] if renderers else Gtk.CellRendererText()
if isinstance(renderer, Gtk.CellRendererToggle):
column = Gtk.TreeViewColumn(column_title, renderer, active=column_id)
elif hasattr(renderer.props, 'python_value'):
column = Gtk.TreeViewColumn(column_title, renderer, python_value=column_id)
else:
column = Gtk.TreeViewColumn(column_title, renderer, text=column_id)
column.set_property('min-width', 25)
column.set_property('reorderable', True)
column.set_property('resizable', True)
column.set_sort_column_id(column_id)
treeview.append_column(column)
columns[column_id] = column
return columns
|
Populate the column names of a GTK TreeView and set their sort IDs.
:param treeview: The treeview to set column names for.
:type treeview: :py:class:`Gtk.TreeView`
:param list column_titles: The names 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
|
gtk_treeview_set_column_titles
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def show_dialog(message_type, message, parent, secondary_text=None, message_buttons=Gtk.ButtonsType.OK, use_markup=False, secondary_use_markup=False):
"""
Display a dialog and return the response. The response is dependent on
the value of *message_buttons*.
:param message_type: The GTK message type to display.
:type message_type: :py:class:`Gtk.MessageType`
:param str message: The text to display in the dialog.
:param parent: The parent window that the dialog should belong to.
:type parent: :py:class:`Gtk.Window`
:param str secondary_text: Optional subtext for the dialog.
:param message_buttons: The buttons to display in the dialog box.
:type message_buttons: :py:class:`Gtk.ButtonsType`
:param bool use_markup: Whether or not to treat the message text as markup.
:param bool secondary_use_markup: Whether or not to treat the secondary text as markup.
:return: The response of the dialog.
:rtype: int
"""
dialog = Gtk.MessageDialog(parent, Gtk.DialogFlags.DESTROY_WITH_PARENT, message_type, message_buttons)
dialog.set_property('text', message)
dialog.set_property('use-markup', use_markup)
dialog.set_property('secondary-text', secondary_text)
dialog.set_property('secondary-use-markup', secondary_use_markup)
if secondary_use_markup:
signal_label_activate_link = lambda _, uri: utilities.open_uri(uri)
for label in dialog.get_message_area().get_children():
if not isinstance(label, Gtk.Label):
continue
label.connect('activate-link', signal_label_activate_link)
dialog.show_all()
response = dialog.run()
dialog.destroy()
return response
|
Display a dialog and return the response. The response is dependent on
the value of *message_buttons*.
:param message_type: The GTK message type to display.
:type message_type: :py:class:`Gtk.MessageType`
:param str message: The text to display in the dialog.
:param parent: The parent window that the dialog should belong to.
:type parent: :py:class:`Gtk.Window`
:param str secondary_text: Optional subtext for the dialog.
:param message_buttons: The buttons to display in the dialog box.
:type message_buttons: :py:class:`Gtk.ButtonsType`
:param bool use_markup: Whether or not to treat the message text as markup.
:param bool secondary_use_markup: Whether or not to treat the secondary text as markup.
:return: The response of the dialog.
:rtype: int
|
show_dialog
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def show_dialog_exc_socket_error(error, parent, title=None):
"""
Display an error dialog with details regarding a :py:exc:`socket.error`
exception that has been raised.
:param error: The exception instance that has been raised.
:type error: :py:exc:`socket.error`
:param parent: The parent window that the dialog should belong to.
:type parent: :py:class:`Gtk.Window`
:param title: The title of the error dialog that is displayed.
"""
title = title or 'Connection Error'
if isinstance(error, socket.timeout):
description = 'The connection to the server timed out.'
elif len(error.args) > 1:
error_number, error_message = error.args[:2]
if error_number == 111:
description = 'The server refused the connection.'
else:
description = "Socket error #{0} ({1}).".format((error_number or 'N/A'), error_message)
return show_dialog(Gtk.MessageType.ERROR, title, parent, secondary_text=description)
|
Display an error dialog with details regarding a :py:exc:`socket.error`
exception that has been raised.
:param error: The exception instance that has been raised.
:type error: :py:exc:`socket.error`
:param parent: The parent window that the dialog should belong to.
:type parent: :py:class:`Gtk.Window`
:param title: The title of the error dialog that is displayed.
|
show_dialog_exc_socket_error
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def show_dialog_yes_no(*args, **kwargs):
"""
Display a dialog which asks a yes or no question with
:py:func:`.show_dialog`.
:return: True if the response is Yes.
:rtype: bool
"""
kwargs['message_buttons'] = Gtk.ButtonsType.YES_NO
return show_dialog(Gtk.MessageType.QUESTION, *args, **kwargs) == Gtk.ResponseType.YES
|
Display a dialog which asks a yes or no question with
:py:func:`.show_dialog`.
:return: True if the response is Yes.
:rtype: bool
|
show_dialog_yes_no
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def __init__(self, method, widget=None, args=None, kwargs=None):
"""
:param str method: The method of the container *widget* to use to add
the proxied widget.
:param str widget: The widget name to add the proxied widget to. If this
value is ``None``, the proxied widget is added to the top level
widget.
:param tuple args: Position arguments to provide when calling *method*.
:param dict kwargs: Key word arguments to provide when calling *method*.
"""
utilities.assert_arg_type(method, str, 1)
utilities.assert_arg_type(widget, (type(None), str), 2)
self.widget = widget
"""The name of the parent widget for this proxied child."""
self.method = method
"""The method of the parent widget that should be called to add the proxied child."""
self.args = args or ()
"""Arguments to append after the proxied child instance when calling :py:attr:`~.GladeProxyDestination.method`."""
self.kwargs = kwargs or {}
"""Key word arguments to append after the proxied child instance when calling :py:attr:`~.GladeProxyDestination.method`."""
|
:param str method: The method of the container *widget* to use to add
the proxied widget.
:param str widget: The widget name to add the proxied widget to. If this
value is ``None``, the proxied widget is added to the top level
widget.
:param tuple args: Position arguments to provide when calling *method*.
:param dict kwargs: Key word arguments to provide when calling *method*.
|
__init__
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def __init__(self, application):
"""
:param application: The parent application for this object.
:type application: :py:class:`Gtk.Application`
"""
utilities.assert_arg_type(application, Gtk.Application, arg_pos=1)
self.config = application.config
"""A reference to the King Phisher client configuration."""
self.application = application
"""The parent :py:class:`Gtk.Application` instance."""
self.logger = logging.getLogger('KingPhisher.Client.' + self.__class__.__name__)
builder = Gtk.Builder()
self.gtk_builder = builder
"""A :py:class:`Gtk.Builder` instance used to load Glade data with."""
top_level_dependencies = [gobject.name for gobject in self.dependencies.children if isinstance(gobject, GladeProxy)]
top_level_dependencies.append(self.dependencies.name)
if self.dependencies.top_level is not None:
top_level_dependencies.extend(self.dependencies.top_level)
builder.add_objects_from_file(which_glade(), top_level_dependencies)
builder.connect_signals(self)
gobject = builder.get_object(self.dependencies.name)
setattr(self, self.top_gobject, gobject)
if isinstance(gobject, Gtk.Window):
gobject.set_transient_for(self.application.get_active_window())
self.application.add_reference(self)
if isinstance(gobject, Gtk.ApplicationWindow):
application.add_window(gobject)
if isinstance(gobject, Gtk.Dialog):
gobject.set_modal(True)
self.gobjects = utilities.FreezableDict()
"""A :py:class:`~king_phisher.utilities.FreezableDict` which maps gobjects to their unique GTK Builder id."""
self._load_child_dependencies(self.dependencies)
self.gobjects.freeze()
self._load_child_proxies()
if self.objects_persist:
self.objects_load_from_config()
|
:param application: The parent application for this object.
:type application: :py:class:`Gtk.Application`
|
__init__
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def get_entry_value(self, entry_name):
"""
Get the value of the specified entry then remove leading and trailing
white space and finally determine if the string is empty, in which case
return None.
:param str entry_name: The name of the entry to retrieve text from.
:return: Either the non-empty string or None.
:rtype: None, str
"""
text = self.gobjects['entry_' + entry_name].get_text()
text = text.strip()
if not text:
return None
return text
|
Get the value of the specified entry then remove leading and trailing
white space and finally determine if the string is empty, in which case
return None.
:param str entry_name: The name of the entry to retrieve text from.
:return: Either the non-empty string or None.
:rtype: None, str
|
get_entry_value
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def gtk_builder_get(self, gobject_id, parent_name=None):
"""
Find the child GObject with name *gobject_id* from the GTK builder.
:param str gobject_id: The object name to look for.
:param str parent_name: The name of the parent object in the builder data file.
:return: The GObject as found by the GTK builder.
:rtype: :py:class:`GObject.Object`
"""
parent_name = parent_name or self.dependencies.name
gtkbuilder_id = "{0}.{1}".format(parent_name, gobject_id)
self.logger.debug('loading GTK builder object with id: ' + gtkbuilder_id)
return self.gtk_builder.get_object(gtkbuilder_id)
|
Find the child GObject with name *gobject_id* from the GTK builder.
:param str gobject_id: The object name to look for.
:param str parent_name: The name of the parent object in the builder data file.
:return: The GObject as found by the GTK builder.
:rtype: :py:class:`GObject.Object`
|
gtk_builder_get
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def objects_load_from_config(self):
"""
Iterate through :py:attr:`.gobjects` and set the GObject's value
from the corresponding value in the :py:attr:`~.GladeGObject.config`.
"""
for gobject_id, gobject in self.gobjects.items():
if '_' not in gobject_id:
continue
gtype, config_name = gobject_id.split('_', 1)
config_name = self.config_prefix + config_name
if gtype not in GOBJECT_PROPERTY_MAP:
continue
value = self.config.get(config_name)
if value is None:
continue
if isinstance(GOBJECT_PROPERTY_MAP[gtype], (list, tuple)):
GOBJECT_PROPERTY_MAP[gtype][0](gobject, value)
else:
gobject.set_property(GOBJECT_PROPERTY_MAP[gtype], value)
|
Iterate through :py:attr:`.gobjects` and set the GObject's value
from the corresponding value in the :py:attr:`~.GladeGObject.config`.
|
objects_load_from_config
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def __init__(self, path, on_changed):
"""
:param str path: The path to monitor for changes.
:param on_changed: The callback function to be called when changes are detected.
:type on_changed: function
"""
self.logger = logging.getLogger('KingPhisher.Utility.FileMonitor')
self.on_changed = on_changed
self.path = path
self._gfile = Gio.file_new_for_path(path)
self._gfile_monitor = self._gfile.monitor(Gio.FileMonitorFlags.NONE, None)
self._gfile_monitor.connect('changed', self.cb_changed)
self.logger.debug('starting file monitor for: ' + path)
|
:param str path: The path to monitor for changes.
:param on_changed: The callback function to be called when changes are detected.
:type on_changed: function
|
__init__
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/gui_utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/gui_utilities.py
|
BSD-3-Clause
|
def count_targets_file(target_file):
"""
Count the number of valid targets that the specified file contains. This
skips lines which are missing fields or where the email address is invalid.
:param str target_file: The path the the target CSV file on disk.
:return: The number of valid targets.
:rtype: int
"""
count = 0
for target in _iterate_targets_file(target_file):
if target.missing_fields:
continue
if not utilities.is_valid_email_address(target.email_address):
continue
count += 1
return count
|
Count the number of valid targets that the specified file contains. This
skips lines which are missing fields or where the email address is invalid.
:param str target_file: The path the the target CSV file on disk.
:return: The number of valid targets.
:rtype: int
|
count_targets_file
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/mailer.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/mailer.py
|
BSD-3-Clause
|
def get_invite_start_from_config(config):
"""
Get the start time for an invite from the configuration. This takes into
account whether the invite is for all day or starts at a specific time.
:param dict config: The King Phisher client configuration.
:return: The timestamp of when the invite is to start.
:rtype: :py:class:`datetime.datetime`
"""
if config['mailer.calendar_invite_all_day']:
start_time = datetime.datetime.combine(
config['mailer.calendar_invite_date'],
datetime.time(0, 0)
)
else:
start_time = datetime.datetime.combine(
config['mailer.calendar_invite_date'],
datetime.time(
int(config['mailer.calendar_invite_start_hour']),
int(config['mailer.calendar_invite_start_minute'])
)
)
return start_time
|
Get the start time for an invite from the configuration. This takes into
account whether the invite is for all day or starts at a specific time.
:param dict config: The King Phisher client configuration.
:return: The timestamp of when the invite is to start.
:rtype: :py:class:`datetime.datetime`
|
get_invite_start_from_config
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/mailer.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/mailer.py
|
BSD-3-Clause
|
def guess_smtp_server_address(host, forward_host=None):
"""
Guess the IP address of the SMTP server that will be connected to given the
SMTP host information and an optional SSH forwarding host. If a hostname is
in use it will be resolved to an IP address, either IPv4 or IPv6 and in that
order. If a hostname resolves to multiple IP addresses, None will be
returned. This function is intended to guess the SMTP servers IP address
given the client configuration so it can be used for SPF record checks.
:param str host: The SMTP server that is being connected to.
:param str forward_host: An optional host that is being used to tunnel the connection.
:return: The IP address of the SMTP server.
:rtype: None, :py:class:`ipaddress.IPv4Address`, :py:class:`ipaddress.IPv6Address`
"""
host = host.rsplit(':', 1)[0]
if ipaddress.is_valid(host):
ip = ipaddress.ip_address(host)
if not ip.is_loopback:
return ip
else:
info = None
for family in (socket.AF_INET, socket.AF_INET6):
try:
info = socket.getaddrinfo(host, 1, family)
except socket.gaierror:
continue
info = set(list([r[4][0] for r in info]))
if len(info) != 1:
return
break
if info:
ip = ipaddress.ip_address(info.pop())
if not ip.is_loopback:
return ip
if forward_host:
return guess_smtp_server_address(forward_host)
return
|
Guess the IP address of the SMTP server that will be connected to given the
SMTP host information and an optional SSH forwarding host. If a hostname is
in use it will be resolved to an IP address, either IPv4 or IPv6 and in that
order. If a hostname resolves to multiple IP addresses, None will be
returned. This function is intended to guess the SMTP servers IP address
given the client configuration so it can be used for SPF record checks.
:param str host: The SMTP server that is being connected to.
:param str forward_host: An optional host that is being used to tunnel the connection.
:return: The IP address of the SMTP server.
:rtype: None, :py:class:`ipaddress.IPv4Address`, :py:class:`ipaddress.IPv6Address`
|
guess_smtp_server_address
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/mailer.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/mailer.py
|
BSD-3-Clause
|
def render_message_template(template, config, target=None, analyze=False):
"""
Take a message from a template and format it to be sent by replacing
variables and processing other template directives. If the *target*
parameter is not set, a placeholder will be created and the message will be
formatted to be previewed.
:param str template: The message template.
:param dict config: The King Phisher client configuration.
:param target: The messages intended target information.
:type target: :py:class:`.MessageTarget`
:param bool analyze: Set the template environment to analyze mode.
:return: The formatted message.
:rtype: str
"""
if target is None:
target = MessageTargetPlaceholder(uid=config['server_config'].get('server.secret_id'))
template_environment.set_mode(template_environment.MODE_PREVIEW)
if analyze:
template_environment.set_mode(template_environment.MODE_ANALYZE)
template = template_environment.from_string(template)
template_vars = {}
template_vars['campaign'] = dict(
id=str(config['campaign_id']),
name=config['campaign_name']
)
template_vars['client'] = dict(
first_name=target.first_name,
last_name=target.last_name,
email_address=target.email_address,
department=target.department,
company_name=config.get('mailer.company_name'),
message_id=target.uid
)
template_vars['sender'] = dict(
email=config.get('mailer.source_email'),
friendly_alias=config.get('mailer.source_email_alias'),
reply_to=config.get('mailer.reply_to_email')
)
template_vars['uid'] = target.uid
message_type = config.get('mailer.message_type', 'email')
template_vars['message_type'] = message_type
if message_type == 'calendar_invite':
template_vars['calendar_invite'] = dict(
all_day=config.get('mailer.calendar_invite_all_day'),
location=config.get('mailer.calendar_invite_location'),
start=get_invite_start_from_config(config),
summary=config.get('mailer.calendar_invite_summary')
)
template_vars['message'] = dict(
attachment=config.get('mailer.attachment_file'),
importance=config.get('mailer.importance'),
recipient=dict(
field=config.get('mailer.target_field', 'to'),
to=(target.email_address if config.get('mailer.target_field') == 'to' else config.get('mailer.recipient_email_to', '')),
cc=(target.email_address if config.get('mailer.target_field') == 'cc' else config.get('mailer.recipient_email_cc', '')),
bcc=(target.email_address if config.get('mailer.target_field') == 'bcc' else '')
),
sensitivity=config.get('mailer.sensitivity'),
subject=config.get('mailer.subject'),
template=config.get('mailer.html_file'),
type=message_type
)
webserver_url = config.get('mailer.webserver_url', '')
webserver_url = urllib.parse.urlparse(webserver_url)
tracking_image = config['server_config']['server.tracking_image']
template_vars['webserver'] = webserver_url.netloc
tracking_url = urllib.parse.urlunparse((webserver_url.scheme, webserver_url.netloc, tracking_image, '', 'id=' + target.uid, ''))
webserver_url = urllib.parse.urlunparse((webserver_url.scheme, webserver_url.netloc, webserver_url.path, '', '', ''))
template_vars['tracking_dot_image_tag'] = "<img src=\"{0}\" style=\"display:none\" alt=\"\" />".format(tracking_url)
template_vars_url = {}
template_vars_url['rickroll'] = 'http://www.youtube.com/watch?v=oHg5SJYRHA0'
template_vars_url['webserver'] = webserver_url + '?id=' + target.uid
template_vars_url['webserver_raw'] = webserver_url
template_vars_url['tracking_dot'] = tracking_url
template_vars['url'] = template_vars_url
template_vars.update(template_environment.standard_variables)
return template.render(template_vars)
|
Take a message from a template and format it to be sent by replacing
variables and processing other template directives. If the *target*
parameter is not set, a placeholder will be created and the message will be
formatted to be previewed.
:param str template: The message template.
:param dict config: The King Phisher client configuration.
:param target: The messages intended target information.
:type target: :py:class:`.MessageTarget`
:param bool analyze: Set the template environment to analyze mode.
:return: The formatted message.
:rtype: str
|
render_message_template
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/mailer.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/mailer.py
|
BSD-3-Clause
|
def rfc2282_timestamp(dt=None, utc=False):
"""
Convert a :py:class:`datetime.datetime` instance into an :rfc:`2282`
compliant timestamp suitable for use in MIME-encoded messages.
:param dt: A time to use for the timestamp otherwise the current time is used.
:type dt: :py:class:`datetime.datetime`
:param utc: Whether to return the timestamp as a UTC offset or from the local timezone.
:return: The timestamp.
:rtype: str
"""
dt = dt or datetime.datetime.utcnow()
# email.utils.formatdate wants the time to be in the local timezone
dt = utilities.datetime_utc_to_local(dt)
return email.utils.formatdate(time.mktime(dt.timetuple()), not utc)
|
Convert a :py:class:`datetime.datetime` instance into an :rfc:`2282`
compliant timestamp suitable for use in MIME-encoded messages.
:param dt: A time to use for the timestamp otherwise the current time is used.
:type dt: :py:class:`datetime.datetime`
:param utc: Whether to return the timestamp as a UTC offset or from the local timezone.
:return: The timestamp.
:rtype: str
|
rfc2282_timestamp
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/mailer.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/mailer.py
|
BSD-3-Clause
|
def __init__(self, mime_type, config, target):
"""
:param str mime_type: The type of this part such as related or alternative.
:param dict config: The King Phisher client configuration.
:param target: The target information for the messages intended recipient.
:type target: :py:class:`.MessageTarget`
"""
mime.multipart.MIMEMultipart.__init__(self, mime_type, charset='utf-8')
self['Subject'] = render_message_template(config['mailer.subject'], config, target)
if config.get('mailer.reply_to_email'):
self.add_header('reply-to', config['mailer.reply_to_email'])
if config.get('mailer.source_email_alias'):
self['From'] = "\"{0}\" <{1}>".format(config['mailer.source_email_alias'], config['mailer.source_email'])
else:
self['From'] = config['mailer.source_email']
self['Date'] = rfc2282_timestamp()
self.preamble = 'This is a multi-part message in MIME format.'
|
:param str mime_type: The type of this part such as related or alternative.
:param dict config: The King Phisher client configuration.
:param target: The target information for the messages intended recipient.
:type target: :py:class:`.MessageTarget`
|
__init__
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/mailer.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/mailer.py
|
BSD-3-Clause
|
def __init__(self, application, target_file, rpc, tab=None):
"""
:param application: The GTK application that the thread is associated with.
:type application: :py:class:`.KingPhisherClientApplication`
:param str target_file: The CSV formatted file to read message targets from.
:param tab: The GUI tab to report information to.
:type tab: :py:class:`.MailSenderSendTab`
:param rpc: The client's connected RPC instance.
:type rpc: :py:class:`.KingPhisherRPCClient`
"""
super(MailSenderThread, self).__init__()
self.daemon = True
self.logger = logging.getLogger('KingPhisher.Client.' + self.__class__.__name__)
self.application = application
self.config = self.application.config
self.target_file = target_file
"""The name of the target file in CSV format."""
self.tab = tab
"""The optional :py:class:`.MailSenderSendTab` instance for reporting status messages to the GUI."""
self.rpc = rpc
self._ssh_forwarder = None
self.smtp_connection = None
"""The :py:class:`smtplib.SMTP` connection instance."""
self.smtp_server = smoke_zephyr.utilities.parse_server(self.config['smtp_server'], 25)
self.running = threading.Event()
"""A :py:class:`threading.Event` object indicating if emails are being sent."""
self.paused = threading.Event()
"""A :py:class:`threading.Event` object indicating if the email sending operation is or should be paused."""
self.should_stop = threading.Event()
self.max_messages_per_minute = float(self.config.get('smtp_max_send_rate', 0.0))
self.mail_options = []
|
:param application: The GTK application that the thread is associated with.
:type application: :py:class:`.KingPhisherClientApplication`
:param str target_file: The CSV formatted file to read message targets from.
:param tab: The GUI tab to report information to.
:type tab: :py:class:`.MailSenderSendTab`
:param rpc: The client's connected RPC instance.
:type rpc: :py:class:`.KingPhisherRPCClient`
|
__init__
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/mailer.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/mailer.py
|
BSD-3-Clause
|
def tab_notify_sent(self, emails_done, emails_total):
"""
Notify the tab that messages have been sent.
:param int emails_done: The number of emails that have been sent.
:param int emails_total: The total number of emails that are going to be sent.
"""
if isinstance(self.tab, gui_utilities.GladeGObject):
GLib.idle_add(lambda x: self.tab.notify_sent(*x), (emails_done, emails_total))
|
Notify the tab that messages have been sent.
:param int emails_done: The number of emails that have been sent.
:param int emails_total: The total number of emails that are going to be sent.
|
tab_notify_sent
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/mailer.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/mailer.py
|
BSD-3-Clause
|
def tab_notify_status(self, message):
"""
Handle a status message regarding the message sending operation.
:param str message: The notification message.
"""
self.logger.info(message.lower())
if isinstance(self.tab, gui_utilities.GladeGObject):
GLib.idle_add(self.tab.notify_status, message + '\n')
|
Handle a status message regarding the message sending operation.
:param str message: The notification message.
|
tab_notify_status
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/mailer.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/mailer.py
|
BSD-3-Clause
|
def server_ssh_connect(self):
"""
Connect to the remote SMTP server over SSH and configure port forwarding
with :py:class:`.SSHTCPForwarder` for tunneling SMTP traffic.
:return: The connection status as one of the :py:class:`.ConnectionErrorReason` constants.
"""
server = smoke_zephyr.utilities.parse_server(self.config['ssh_server'], 22)
username = self.config['ssh_username']
password = self.config['ssh_password']
remote_server = smoke_zephyr.utilities.parse_server(self.config['smtp_server'], 25)
try:
self._ssh_forwarder = SSHTCPForwarder(
server,
username,
password,
remote_server,
private_key=self.config.get('ssh_preferred_key'),
missing_host_key_policy=ssh_host_key.MissingHostKeyPolicy(self.application)
)
self._ssh_forwarder.start()
except errors.KingPhisherAbortError as error:
self.logger.info("ssh connection aborted ({0})".format(error.message))
except paramiko.AuthenticationException:
self.logger.warning('failed to authenticate to the remote ssh server')
return ConnectionErrorReason.ERROR_AUTHENTICATION_FAILED
except paramiko.SSHException as error:
self.logger.warning("failed with: {0!r}".format(error))
except socket.timeout:
self.logger.warning('the connection to the ssh server timed out')
except Exception:
self.logger.warning('failed to connect to the remote ssh server', exc_info=True)
else:
self.smtp_server = self._ssh_forwarder.local_server
return ConnectionErrorReason.SUCCESS
return ConnectionErrorReason.ERROR_UNKNOWN
|
Connect to the remote SMTP server over SSH and configure port forwarding
with :py:class:`.SSHTCPForwarder` for tunneling SMTP traffic.
:return: The connection status as one of the :py:class:`.ConnectionErrorReason` constants.
|
server_ssh_connect
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/mailer.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/mailer.py
|
BSD-3-Clause
|
def server_smtp_connect(self):
"""
Connect and optionally authenticate to the configured SMTP server.
:return: The connection status as one of the :py:class:`.ConnectionErrorReason` constants.
"""
if self.config.get('smtp_ssl_enable', False):
SmtpClass = smtplib.SMTP_SSL
else:
SmtpClass = smtplib.SMTP
self.logger.debug('opening a new connection to the SMTP server')
try:
self.smtp_connection = SmtpClass(*self.smtp_server, timeout=15)
self.smtp_connection.ehlo()
except smtplib.SMTPException:
self.logger.warning('received an SMTPException while connecting to the SMTP server', exc_info=True)
return ConnectionErrorReason.ERROR_UNKNOWN
except socket.error:
self.logger.warning('received a socket.error while connecting to the SMTP server')
return ConnectionErrorReason.ERROR_CONNECTION
if not self.config.get('smtp_ssl_enable', False) and 'starttls' in self.smtp_connection.esmtp_features:
self.logger.debug('target SMTP server supports the STARTTLS extension')
try:
self.smtp_connection.starttls()
self.smtp_connection.ehlo()
except smtplib.SMTPException:
self.logger.warning('received an SMTPException while negotiating STARTTLS with the SMTP server', exc_info=True)
return ConnectionErrorReason.ERROR_UNKNOWN
except socket.error:
self.logger.warning('received a socket.error while negotiating STARTTLS with the SMTP server')
return ConnectionErrorReason.ERROR_CONNECTION
username = self.config.get('smtp_username', '')
if username:
password = self.config.get('smtp_password', '')
try:
self.smtp_connection.login(username, password)
except smtplib.SMTPException as error:
self.logger.warning('received an {0} while authenticating to the SMTP server'.format(error.__class__.__name__))
self.smtp_connection.quit()
return ConnectionErrorReason.ERROR_AUTHENTICATION_FAILED
if self.smtp_connection.has_extn('SMTPUTF8'):
self.logger.debug('target SMTP server supports the SMTPUTF8 extension')
self.mail_options.append('SMTPUTF8')
return ConnectionErrorReason.SUCCESS
|
Connect and optionally authenticate to the configured SMTP server.
:return: The connection status as one of the :py:class:`.ConnectionErrorReason` constants.
|
server_smtp_connect
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/mailer.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/mailer.py
|
BSD-3-Clause
|
def server_smtp_disconnect(self):
"""Clean up and close the connection to the remote SMTP server."""
if self.smtp_connection:
self.logger.debug('closing the connection to the SMTP server')
try:
self.smtp_connection.quit()
except smtplib.SMTPServerDisconnected:
pass
self.smtp_connection = None
self.tab_notify_status('Disconnected from the SMTP server')
|
Clean up and close the connection to the remote SMTP server.
|
server_smtp_disconnect
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/mailer.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/mailer.py
|
BSD-3-Clause
|
def server_smtp_reconnect(self):
"""
Disconnect from the remote SMTP server and then attempt to open
a new connection to it.
:return: The reconnection status.
:rtype: bool
"""
if self.smtp_connection:
try:
self.smtp_connection.quit()
except smtplib.SMTPServerDisconnected:
pass
self.smtp_connection = None
while self.server_smtp_connect() != ConnectionErrorReason.SUCCESS:
self.tab_notify_status('Failed to reconnect to the SMTP server')
if not self.process_pause(True):
return False
return True
|
Disconnect from the remote SMTP server and then attempt to open
a new connection to it.
:return: The reconnection status.
:rtype: bool
|
server_smtp_reconnect
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/mailer.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/mailer.py
|
BSD-3-Clause
|
def iterate_targets(self, counting=False):
"""
Iterate over each of the targets as defined within the configuration.
If *counting* is ``False``, messages will not be displayed to the end
user through the notification tab.
:param bool counting: Whether or not to iterate strictly for counting purposes.
:return: Each message target.
:rtype: :py:class:`~.MessageTarget`
"""
mailer_tab = self.application.main_tabs['mailer']
target_type = self.config['mailer.target_type']
if target_type == 'single':
target_name = self.config['mailer.target_name'].split(' ')
while len(target_name) < 2:
target_name.append('')
uid_charset = self.config['mailer.message_uid.charset']
target = MessageTarget(
first_name=target_name[0].strip(),
last_name=target_name[1].strip(),
email_address=self.config['mailer.target_email_address'].strip(),
uid=utilities.make_message_uid(
upper=uid_charset['upper'],
lower=uid_charset['lower'],
digits=uid_charset['digits']
)
)
if not counting:
mailer_tab.emit('target-create', target)
yield target
elif target_type == 'file':
for target in _iterate_targets_file(self.target_file, config=self.config):
missing_fields = target.missing_fields
if missing_fields:
if counting:
msg = "Target CSV line {0} skipped due to missing field{1}".format(target.line, ('' if len(missing_fields) == 1 else 's'))
msg += ':' + ', '.join(field.replace('_', ' ') for field in missing_fields)
self.tab_notify_status(msg)
continue
if not utilities.is_valid_email_address(target.email_address):
self.logger.warning("skipping line {0} in target csv file due to invalid email address: {1}".format(target.line, target.email_address))
continue
if not counting:
mailer_tab.emit('target-create', target)
yield target
else:
self.logger.error("the configured target type '{0}' is unsupported".format(target_type))
|
Iterate over each of the targets as defined within the configuration.
If *counting* is ``False``, messages will not be displayed to the end
user through the notification tab.
:param bool counting: Whether or not to iterate strictly for counting purposes.
:return: Each message target.
:rtype: :py:class:`~.MessageTarget`
|
iterate_targets
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/mailer.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/mailer.py
|
BSD-3-Clause
|
def run(self):
"""The entry point of the thread."""
self.logger.debug("mailer routine running in tid: 0x{0:x}".format(threading.current_thread().ident))
self.running.set()
self.should_stop.clear()
self.paused.clear()
try:
self._prepare_env()
emails_done = self._send_messages()
except UnicodeDecodeError as error:
self.logger.error("a unicode error occurred, {0} at position: {1}-{2}".format(error.reason, error.start, error.end))
self.tab_notify_status("A unicode error occurred, {0} at position: {1}-{2}".format(error.reason, error.start, error.end))
except Exception:
self.logger.error('an error occurred while sending messages', exc_info=True)
self.tab_notify_status('An error occurred while sending messages.')
else:
self.tab_notify_status("Finished sending, successfully sent {0:,} messages".format(emails_done))
self.server_smtp_disconnect()
if self._ssh_forwarder:
self._ssh_forwarder.stop()
self._ssh_forwarder = None
self.tab_notify_status('Disconnected from the SSH server')
self.tab_notify_stopped()
return
|
The entry point of the thread.
|
run
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/mailer.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/mailer.py
|
BSD-3-Clause
|
def process_pause(self, set_pause=False):
"""
Pause sending emails if a pause request has been set.
:param bool set_pause: Whether to request a pause before processing it.
:return: Whether or not the sending operation was cancelled during the pause.
:rtype: bool
"""
if set_pause:
if isinstance(self.tab, gui_utilities.GladeGObject):
gui_utilities.glib_idle_add_wait(lambda: self.tab.pause_button.set_property('active', True))
else:
self.pause()
if self.paused.is_set():
self.tab_notify_status('Paused sending emails, waiting to resume')
self.running.wait()
self.paused.clear()
if self.should_stop.is_set():
self.tab_notify_status('Sending emails cancelled')
return False
self.tab_notify_status('Resuming sending emails')
self.max_messages_per_minute = float(self.config.get('smtp_max_send_rate', 0.0))
return True
|
Pause sending emails if a pause request has been set.
:param bool set_pause: Whether to request a pause before processing it.
:return: Whether or not the sending operation was cancelled during the pause.
:rtype: bool
|
process_pause
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/mailer.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/mailer.py
|
BSD-3-Clause
|
def create_message_calendar_invite(self, target, attachments):
"""
Create a MIME calendar invite to be sent from a set of parameters.
:param target: The information for the messages intended recipient.
:type target: :py:class:`.MessageTarget`
:param str uid: The message's unique identifier.
:param attachments: The attachments to add to the created message.
:type attachments: :py:class:`Attachments`
:return: The new MIME message.
:rtype: :py:class:`email.mime.multipart.MIMEMultipart`
"""
top_msg = TopMIMEMultipart('mixed', self.config, target)
top_msg['To'] = target.email_address
related_msg = mime.multipart.MIMEMultipart('related')
top_msg.attach(related_msg)
alt_msg = mime.multipart.MIMEMultipart('alternative')
related_msg.attach(alt_msg)
part = mime.base.MIMEBase('text', 'plain', charset='utf-8')
part.set_payload(MIME_TEXT_PLAIN)
encoders.encode_base64(part)
alt_msg.attach(part)
with codecs.open(self.config['mailer.html_file'], 'r', encoding='utf-8') as file_h:
msg_template = file_h.read()
formatted_msg = render_message_template(msg_template, self.config, target=target)
part = MIMEText(formatted_msg, 'html')
alt_msg.attach(part)
start_time = get_invite_start_from_config(self.config)
if self.config['mailer.calendar_invite_all_day']:
duration = ics.DurationAllDay()
else:
duration = int(self.config['mailer.calendar_invite_duration']) * 60
ical = ics.Calendar(
self.config['mailer.source_email'],
start_time,
self.config.get('mailer.calendar_invite_summary'),
duration=duration,
location=self.config.get('mailer.calendar_invite_location')
)
ical.add_attendee(target.email_address, rsvp=self.config.get('mailer.calendar_request_rsvp', False))
part = mime.base.MIMEBase('text', 'calendar', charset='utf-8', method='REQUEST')
part.set_payload(ical.to_ical(encoding='utf-8'))
encoders.encode_base64(part)
alt_msg.attach(part)
for attach in attachments.images:
related_msg.attach(attach)
for attach in attachments.files:
top_msg.attach(attach)
return top_msg
|
Create a MIME calendar invite to be sent from a set of parameters.
:param target: The information for the messages intended recipient.
:type target: :py:class:`.MessageTarget`
:param str uid: The message's unique identifier.
:param attachments: The attachments to add to the created message.
:type attachments: :py:class:`Attachments`
:return: The new MIME message.
:rtype: :py:class:`email.mime.multipart.MIMEMultipart`
|
create_message_calendar_invite
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/mailer.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/mailer.py
|
BSD-3-Clause
|
def create_message_email(self, target, attachments):
"""
Create a MIME email to be sent from a set of parameters.
:param target: The information for the messages intended recipient.
:type target: :py:class:`.MessageTarget`
:param str uid: The message's unique identifier.
:param attachments: The attachments to add to the created message.
:type attachments: :py:class:`MessageAttachments`
:return: The new MIME message.
:rtype: :py:class:`email.mime.multipart.MIMEMultipart`
"""
msg = TopMIMEMultipart('related', self.config, target)
target_field = self.config.get('mailer.target_field', 'to').lower()
for header in ('To', 'CC', 'BCC'):
if header.lower() == target_field:
msg[header] = '<' + target.email_address + '>'
continue
value = self.config.get('mailer.recipient_email_' + header.lower())
if value:
msg[header] = '<' + value + '>'
importance = self.config.get('mailer.importance', 'Normal')
if importance != 'Normal':
msg['Importance'] = importance
sensitivity = self.config.get('mailer.sensitivity', 'Normal')
if sensitivity != 'Normal':
msg['Sensitivity'] = sensitivity
msg_alt = mime.multipart.MIMEMultipart('alternative')
msg.attach(msg_alt)
with codecs.open(self.config['mailer.html_file'], 'r', encoding='utf-8') as file_h:
msg_template = file_h.read()
formatted_msg = render_message_template(msg_template, self.config, target=target)
# RFC-1341 page 35 states friendliest part must be attached first
msg_body = MIMEText(MIME_TEXT_PLAIN, 'plain')
msg_alt.attach(msg_body)
msg_body = MIMEText(formatted_msg, 'html')
msg_alt.attach(msg_body)
msg_alt.set_default_type('html')
# process attachments
for attach in attachments.files:
msg.attach(attach)
for attach in attachments.images:
msg.attach(attach)
return msg
|
Create a MIME email to be sent from a set of parameters.
:param target: The information for the messages intended recipient.
:type target: :py:class:`.MessageTarget`
:param str uid: The message's unique identifier.
:param attachments: The attachments to add to the created message.
:type attachments: :py:class:`MessageAttachments`
:return: The new MIME message.
:rtype: :py:class:`email.mime.multipart.MIMEMultipart`
|
create_message_email
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/mailer.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/mailer.py
|
BSD-3-Clause
|
def get_mime_attachments(self):
"""
Return a :py:class:`.MessageAttachments` object containing both the images and
raw files to be included in sent messages.
:return: A namedtuple of both files and images in their MIME containers.
:rtype: :py:class:`.MessageAttachments`
"""
files = []
# allow the attachment_file.post_processing to be attached instead of
# attachment_file so attachment_file can be used as an input for
# arbitrary operations to modify without over writing the original
attachment_file = self.config.get('mailer.attachment_file.post_processing')
delete_attachment_file = False
if attachment_file is not None:
if not isinstance(attachment_file, str):
raise TypeError('config option mailer.attachment_file.post_processing is not a readable file')
if not os.path.isfile(attachment_file) and os.access(attachment_file, os.R_OK):
raise ValueError('config option mailer.attachment_file.post_processing is not a readable file')
self.config['mailer.attachment_file.post_processing'] = None
delete_attachment_file = True
else:
attachment_file = self.config.get('mailer.attachment_file')
if attachment_file:
attachfile = mime.base.MIMEBase(*mimetypes.guess_type(attachment_file))
attachfile.set_payload(open(attachment_file, 'rb').read())
encoders.encode_base64(attachfile)
attachfile.add_header('Content-Disposition', "attachment; filename=\"{0}\"".format(os.path.basename(attachment_file)))
files.append(attachfile)
if delete_attachment_file and os.access(attachment_file, os.W_OK):
os.remove(attachment_file)
images = []
for attachment_file, attachment_name in template_environment.attachment_images.items():
attachfile = mime.image.MIMEImage(open(attachment_file, 'rb').read())
attachfile.add_header('Content-ID', "<{0}>".format(attachment_name))
attachfile.add_header('Content-Disposition', "inline; filename=\"{0}\"".format(attachment_name))
images.append(attachfile)
return MessageAttachments(tuple(files), tuple(images))
|
Return a :py:class:`.MessageAttachments` object containing both the images and
raw files to be included in sent messages.
:return: A namedtuple of both files and images in their MIME containers.
:rtype: :py:class:`.MessageAttachments`
|
get_mime_attachments
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/mailer.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/mailer.py
|
BSD-3-Clause
|
def send_message(self, target_email, msg):
"""
Send an email using the connected SMTP server.
:param str target_email: The email address to send the message to.
:param msg: The formatted message to be sent.
:type msg: :py:class:`.mime.multipart.MIMEMultipart`
"""
source_email = self.config['mailer.source_email_smtp']
self.smtp_connection.sendmail(source_email, target_email, msg.as_string(), self.mail_options)
|
Send an email using the connected SMTP server.
:param str target_email: The email address to send the message to.
:param msg: The formatted message to be sent.
:type msg: :py:class:`.mime.multipart.MIMEMultipart`
|
send_message
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/mailer.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/mailer.py
|
BSD-3-Clause
|
def stop(self):
"""
Requests that the email sending operation stop. It can not be
resumed from the same position. This function blocks until the
stop request has been processed and the thread exits.
"""
self.should_stop.set()
self.unpause()
if self.is_alive():
self.join()
|
Requests that the email sending operation stop. It can not be
resumed from the same position. This function blocks until the
stop request has been processed and the thread exits.
|
stop
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/mailer.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/mailer.py
|
BSD-3-Clause
|
def missing_files(self):
"""
Return a list of all missing or unreadable files which are referenced by
the message template.
:return: The list of unusable files.
:rtype: list
"""
missing = []
attachment = self.config.get('mailer.attachment_file')
if attachment and not os.access(attachment, os.R_OK):
missing.append(attachment)
msg_template = self.config['mailer.html_file']
if not os.access(msg_template, os.R_OK):
missing.append(msg_template)
return missing
self._prepare_env()
for attachment in template_environment.attachment_images.keys():
if not os.access(attachment, os.R_OK):
missing.append(attachment)
return missing
|
Return a list of all missing or unreadable files which are referenced by
the message template.
:return: The list of unusable files.
:rtype: list
|
missing_files
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/mailer.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/mailer.py
|
BSD-3-Clause
|
def __init__(self, name, *args, **kwargs):
"""
:param str name: The name of this option.
:param str description: The description of this option.
:param default: The default value of this option.
:param str display_name: The name to display in the UI to the user for this option.
"""
self.display_name = kwargs.pop('display_name', name)
super(ClientOptionMixin, self).__init__(name, *args, **kwargs)
|
:param str name: The name of this option.
:param str description: The description of this option.
:param default: The default value of this option.
:param str display_name: The name to display in the UI to the user for this option.
|
__init__
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/plugins.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/plugins.py
|
BSD-3-Clause
|
def __init__(self, name, *args, **kwargs):
"""
:param str name: The name of this option.
:param str description: The description of this option.
:param default: The default value of this option.
:param str display_name: The name to display in the UI to the user for this option.
:param adjustment: The adjustment details of the options value.
:type adjustment: :py:class:`Gtk.Adjustment`
"""
self.adjustment = kwargs.pop('adjustment', Gtk.Adjustment(0, -0x7fffffff, 0x7fffffff, 1, 10, 0))
super(ClientOptionInteger, self).__init__(name, *args, **kwargs)
|
:param str name: The name of this option.
:param str description: The description of this option.
:param default: The default value of this option.
:param str display_name: The name to display in the UI to the user for this option.
:param adjustment: The adjustment details of the options value.
:type adjustment: :py:class:`Gtk.Adjustment`
|
__init__
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/plugins.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/plugins.py
|
BSD-3-Clause
|
def __init__(self, name, *args, **kwargs):
"""
.. versionchanged:: 1.9.0b5
Added the *multiline* parameter.
:param str name: The name of this option.
:param str description: The description of this option.
:param default: The default value of this option.
:param str display_name: The name to display in the UI to the user for this option.
:param bool multiline: Whether or not this option allows multiple lines of input.
"""
self.multiline = bool(kwargs.pop('multiline', False))
super(ClientOptionString, self).__init__(name, *args, **kwargs)
|
.. versionchanged:: 1.9.0b5
Added the *multiline* parameter.
:param str name: The name of this option.
:param str description: The description of this option.
:param default: The default value of this option.
:param str display_name: The name to display in the UI to the user for this option.
:param bool multiline: Whether or not this option allows multiple lines of input.
|
__init__
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/plugins.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/plugins.py
|
BSD-3-Clause
|
def __init__(self, name, *args, **kwargs):
"""
:param str name: The name of this option.
:param str description: The description of this option.
:param default: The default value of this option.
:param str display_name: The name to display in the UI to the user for this option.
:param str path_type: The type of the path to select, either 'directory', 'file-open' or 'file-save'.
"""
self.path_type = kwargs.pop('path_type', 'file-open').lower()
if self.path_type not in ('directory', 'file-open', 'file-save'):
raise ValueError('path_type must be either \'directory\', \'file-open\', or \'file-save\'')
self.file_filters = kwargs.pop('file_filters', None)
super(ClientOptionPath, self).__init__(name, *args, **kwargs)
|
:param str name: The name of this option.
:param str description: The description of this option.
:param default: The default value of this option.
:param str display_name: The name to display in the UI to the user for this option.
:param str path_type: The type of the path to select, either 'directory', 'file-open' or 'file-save'.
|
__init__
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/plugins.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/plugins.py
|
BSD-3-Clause
|
def __init__(self, *args, **kwargs):
"""
:param str name: The name of this option.
:param str description: The description of this option.
:param default: The default value of this option.
:param str display_name: The name to display in the UI to the user for this option.
"""
kwargs['adjustment'] = Gtk.Adjustment(1, 1, 0xffff, 1, 10, 0)
super(ClientOptionPort, self).__init__(*args, **kwargs)
|
:param str name: The name of this option.
:param str description: The description of this option.
:param default: The default value of this option.
:param str display_name: The name to display in the UI to the user for this option.
|
__init__
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/plugins.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/plugins.py
|
BSD-3-Clause
|
def config(self):
"""
A dictionary that can be used by this plugin for persistent storage of
it's configuration.
"""
config = self.application.config['plugins'].get(self.name)
if config is None:
config = {}
self.application.config['plugins'][self.name] = config
return config
|
A dictionary that can be used by this plugin for persistent storage of
it's configuration.
|
config
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/plugins.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/plugins.py
|
BSD-3-Clause
|
def render_template_string(self, template_string, target=None, description='string', log_to_mailer=True):
"""
Render the specified *template_string* in the message environment. If
an error occurs during the rendering process, a message will be logged
and ``None`` will be returned. If *log_to_mailer* is set to ``True``
then a message will also be displayed in the message send tab of the
client.
.. versionadded:: 1.9.0b5
:param str template_string: The string to render as a template.
:param target: An optional target to pass to the rendering environment.
:type target: :py:class:`~king_phisher.client.mailer.MessageTarget`
:param str description: A keyword to use to identify the template string in error messages.
:param bool log_to_mailer: Whether or not to log to the message send tab as well.
:return: The rendered string or ``None`` if an error occurred.
:rtype: str
"""
mailer_tab = self.application.main_tabs['mailer']
text_insert = mailer_tab.tabs['send_messages'].text_insert
try:
template_string = mailer.render_message_template(template_string, self.application.config, target=target)
except jinja2.exceptions.TemplateSyntaxError as error:
self.logger.error("jinja2 syntax error ({0}) in {1}: {2}".format(error.message, description, template_string))
if log_to_mailer:
text_insert("Jinja2 syntax error ({0}) in {1}: {2}\n".format(error.message, description, template_string))
return None
except jinja2.exceptions.UndefinedError as error:
self.logger.error("jinj2 undefined error ({0}) in {1}: {2}".format(error.message, description, template_string))
if log_to_mailer:
text_insert("Jinja2 undefined error ({0}) in {1}: {2}".format(error.message, description, template_string))
return None
except ValueError as error:
self.logger.error("value error ({0}) in {1}: {2}".format(error, description, template_string))
if log_to_mailer:
text_insert("Value error ({0}) in {1}: {2}\n".format(error, description, template_string))
return None
return template_string
|
Render the specified *template_string* in the message environment. If
an error occurs during the rendering process, a message will be logged
and ``None`` will be returned. If *log_to_mailer* is set to ``True``
then a message will also be displayed in the message send tab of the
client.
.. versionadded:: 1.9.0b5
:param str template_string: The string to render as a template.
:param target: An optional target to pass to the rendering environment.
:type target: :py:class:`~king_phisher.client.mailer.MessageTarget`
:param str description: A keyword to use to identify the template string in error messages.
:param bool log_to_mailer: Whether or not to log to the message send tab as well.
:return: The rendered string or ``None`` if an error occurred.
:rtype: str
|
render_template_string
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/plugins.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/plugins.py
|
BSD-3-Clause
|
def save_cache(self, catalog, catalog_url):
"""
Saves the catalog or catalogs in the manager to the cache.
:param catalog: The :py:class:`~king_phisher.catalog.Catalog` to save.
"""
self._catalog_cache[catalog.id] = {
'created': datetime.datetime.utcnow(),
'id': catalog.id,
'url': catalog_url,
'value': catalog.to_dict()
}
self._catalog_cache.save()
|
Saves the catalog or catalogs in the manager to the cache.
:param catalog: The :py:class:`~king_phisher.catalog.Catalog` to save.
|
save_cache
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/plugins.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/plugins.py
|
BSD-3-Clause
|
def add_catalog(self, catalog, catalog_url, cache=False):
"""
Adds the specified catalog to the manager and stores the associated
source URL for caching.
:param catalog: The catalog to add to the cache manager.
:type catalog: :py:class:`~king_phisher.catalog.Catalog`
:param str catalog_url: The URL from which the catalog was loaded.
:param bool cache: Whether or not the catalog should be saved to the cache.
:return: The catalog.
:rtype: :py:class:`~king_phisher.catalog.Catalog`
"""
self.catalogs[catalog.id] = catalog
if cache and catalog_url:
self.save_cache(catalog=catalog, catalog_url=catalog_url)
return catalog
|
Adds the specified catalog to the manager and stores the associated
source URL for caching.
:param catalog: The catalog to add to the cache manager.
:type catalog: :py:class:`~king_phisher.catalog.Catalog`
:param str catalog_url: The URL from which the catalog was loaded.
:param bool cache: Whether or not the catalog should be saved to the cache.
:return: The catalog.
:rtype: :py:class:`~king_phisher.catalog.Catalog`
|
add_catalog
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/plugins.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/plugins.py
|
BSD-3-Clause
|
def event_type_filter(event_types, is_method=False):
"""
A decorator to filter a signal handler by the specified event types. Using
this will ensure that the decorated function is only called for the
specified event types and not others which may have been subscribed to
elsewhere in the application.
:param event_types: A single event type as a string or a list of event type strings.
:type event_types: list, str
:param bool is_method: Whether or not the function being decorated is a class method.
"""
utilities.assert_arg_type(event_types, (list, set, str, tuple))
if isinstance(event_types, str):
event_types = (event_types,)
def decorator(function):
@functools.wraps(function)
def wrapper(*args):
if is_method:
_, _, event_type, _ = args
else:
_, event_type, _ = args
if event_type in event_types:
function(*args)
return
return wrapper
return decorator
|
A decorator to filter a signal handler by the specified event types. Using
this will ensure that the decorated function is only called for the
specified event types and not others which may have been subscribed to
elsewhere in the application.
:param event_types: A single event type as a string or a list of event type strings.
:type event_types: list, str
:param bool is_method: Whether or not the function being decorated is a class method.
|
event_type_filter
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/server_events.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/server_events.py
|
BSD-3-Clause
|
def __init__(self, rpc):
"""
:param rpc: The client's connected RPC instance.
:type rpc: :py:class:`.KingPhisherRPCClient`
"""
super(ServerEventSubscriber, self).__init__()
self._encoding = 'utf-8'
self.__is_shutdown = threading.Event()
self.__is_shutdown.clear()
self._reconnect_event_id = None
self.reconnect = True
"""Whether or not the socket should attempt to reconnect itself when it has been closed."""
self.rpc = rpc
self._connect_event = threading.Event()
self._subscriptions = collections.defaultdict(lambda: collections.defaultdict(int))
self._worker_thread = None
self.logger.info('connecting to the server event socket')
self._ws_connect()
|
:param rpc: The client's connected RPC instance.
:type rpc: :py:class:`.KingPhisherRPCClient`
|
__init__
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/server_events.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/server_events.py
|
BSD-3-Clause
|
def shutdown(self):
"""
Disconnect the event socket from the remote server. After the object is
shutdown, remove events will no longer be published.
:param int timeout: An optional timeout for how long to wait on the worker thread.
"""
self.__is_shutdown.set()
self.logger.debug('shutting down the server event socket')
worker = self._worker_thread
if worker:
worker.join()
self._worker_thread = None
|
Disconnect the event socket from the remote server. After the object is
shutdown, remove events will no longer be published.
:param int timeout: An optional timeout for how long to wait on the worker thread.
|
shutdown
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/server_events.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/server_events.py
|
BSD-3-Clause
|
def subscribe(self, event_id, event_types, attributes):
"""
Subscribe the client to the specified event published by the server.
When the event is published the specified *attributes* of it and it's
corresponding id and type information will be sent to the client.
:param str event_id: The identifier of the event to subscribe to.
:param list event_types: A list of sub-types for the corresponding event.
:param list attributes: A list of attributes of the event object to be sent to the client.
"""
utilities.assert_arg_type(event_id, str, arg_pos=1)
utilities.assert_arg_type(event_types, (list, set, tuple), arg_pos=2)
utilities.assert_arg_type(event_types, (list, set, tuple), arg_pos=3)
new_event_types = set(event_types)
new_attributes = set(attributes)
subscription_table = self._subscriptions[event_id]
for subscription in itertools.product(event_types, attributes):
subscription = _SubscriptionStub(*subscription)
subscription_table[subscription] += 1
if subscription_table[subscription] > 1:
new_event_types.discard(subscription.event_type)
new_attributes.discard(subscription.attribute)
if new_event_types or new_attributes:
self._subscribe(event_id, event_types, attributes)
|
Subscribe the client to the specified event published by the server.
When the event is published the specified *attributes* of it and it's
corresponding id and type information will be sent to the client.
:param str event_id: The identifier of the event to subscribe to.
:param list event_types: A list of sub-types for the corresponding event.
:param list attributes: A list of attributes of the event object to be sent to the client.
|
subscribe
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/server_events.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/server_events.py
|
BSD-3-Clause
|
def unsubscribe(self, event_id, event_types, attributes):
"""
Unsubscribe from an event published by the server that the client
previously subscribed to.
:param str event_id: The identifier of the event to subscribe to.
:param list event_types: A list of sub-types for the corresponding event.
:param list attributes: A list of attributes of the event object to be sent to the client.
"""
utilities.assert_arg_type(event_id, str, arg_pos=1)
utilities.assert_arg_type(event_types, (list, set, tuple), arg_pos=2)
utilities.assert_arg_type(event_types, (list, set, tuple), arg_pos=3)
event_types = set(event_types)
attributes = set(attributes)
freeable_subsriptions = collections.deque()
subscription_table = self._subscriptions[event_id]
for subscription in itertools.product(event_types, attributes):
subscription = _SubscriptionStub(*subscription)
subscription_table[subscription] -= 1
if subscription_table[subscription] < 1:
freeable_subsriptions.append(subscription)
for subscription in freeable_subsriptions:
del subscription_table[subscription]
# to do, delete the subscription table from _subscriptions if it's empty
remaining_event_types = [sub.event_type for sub in subscription_table]
remaining_attributes = [sub.attribute for sub in subscription_table]
freeable_event_types = [sub.event_type for sub in freeable_subsriptions if not sub.event_type in remaining_event_types]
freeable_attributes = [sub.attribute for sub in freeable_subsriptions if not sub.attribute in remaining_attributes]
if freeable_event_types or freeable_attributes:
self._unsubscribe(event_id, freeable_event_types, freeable_attributes)
|
Unsubscribe from an event published by the server that the client
previously subscribed to.
:param str event_id: The identifier of the event to subscribe to.
:param list event_types: A list of sub-types for the corresponding event.
:param list attributes: A list of attributes of the event object to be sent to the client.
|
unsubscribe
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/server_events.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/server_events.py
|
BSD-3-Clause
|
def __init__(self, target_url, dest_dir):
"""
:param str target_url: The URL of the target web page to clone.
:param str dest_dir: The path of a directory to write the resources to.
"""
if not has_webkit2:
raise RuntimeError('cloning requires WebKit2GTK+')
self.target_url = urllib.parse.urlparse(target_url)
dest_dir = os.path.abspath(dest_dir)
if not os.path.exists(dest_dir):
os.mkdir(dest_dir)
self.dest_dir = os.path.abspath(os.path.normpath(dest_dir))
self.logger = logging.getLogger('KingPhisher.Client.WebPageScraper')
self.cloned_resources = collections.OrderedDict()
"""A :py:class:`collections.OrderedDict` instance of :py:class:`.ClonedResourceDetails` keyed by the web resource they describe."""
self.load_started = False
self.load_failed_event = None
self.__web_resources = []
self.webview = WebKit2.WebView()
web_context = self.webview.get_context()
web_context.set_cache_model(WebKit2.CacheModel.DOCUMENT_VIEWER)
web_context.set_tls_errors_policy(WebKit2.TLSErrorsPolicy.IGNORE)
self.webview.connect('decide-policy', self.signal_decide_policy)
self.webview.connect('load-changed', self.signal_load_changed)
self.webview.connect('load-failed', self.signal_load_failed)
self.webview.connect('resource-load-started', self.signal_resource_load_started)
self.webview.load_uri(self.target_url_str)
|
:param str target_url: The URL of the target web page to clone.
:param str dest_dir: The path of a directory to write the resources to.
|
__init__
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/web_cloner.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/web_cloner.py
|
BSD-3-Clause
|
def _webkit_empty_resource_bug_workaround(self, url, expected_len):
"""
This works around an issue in WebKit2GTK+ that will hopefully be
resolved eventually. Sometimes the resource data that is returned is
an empty string so attempt to re-request it with Python.
"""
try:
response = requests.get(url, timeout=10)
except requests.exceptions.RequestException:
self.logger.warning('failed to request the empty resource with python')
return ''
if response.status_code < 200 or response.status_code > 299:
self.logger.warning("requested the empty resource with python, but received status: {0} ({1})".format(response.status_code, response.reason))
return ''
data = response.content
if len(data) != expected_len:
self.logger.warning('requested the empty resource with python, but the length appears invalid')
return data
|
This works around an issue in WebKit2GTK+ that will hopefully be
resolved eventually. Sometimes the resource data that is returned is
an empty string so attempt to re-request it with Python.
|
_webkit_empty_resource_bug_workaround
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/web_cloner.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/web_cloner.py
|
BSD-3-Clause
|
def copy_resource_data(self, resource, data):
"""
Copy the data from a loaded resource to a local file.
:param resource: The resource whose data is being copied.
:type resource: :py:class:`WebKit2.WebResource`
:param data: The raw data of the represented resource.
:type data: bytes, str
"""
resource_url_str = resource.get_property('uri')
resource_url = urllib.parse.urlparse(resource_url_str)
resource_path = os.path.split(resource_url.path)[0].lstrip('/')
resource_path = urllib.parse.unquote(resource_path)
directory = self.dest_dir
for part in resource_path.split('/'):
directory = os.path.join(directory, part)
if not os.path.exists(directory):
os.mkdir(directory)
mime_type = None
charset = 'utf-8'
response = resource.get_response()
# WebKit2.URIResponse.get_http_headers is available since v2.6
# see http://webkitgtk.org/reference/webkit2gtk/stable/WebKitURIResponse.html#webkit-uri-response-get-http-headers
if response and hasattr(response, 'get_http_headers'):
mime_type = response.get_http_headers().get('content-type')
if mime_type and ';' in mime_type:
mime_type, charset = mime_type.split(';', 1)
charset = charset.strip()
if charset.startswith('charset='):
charset = charset[8:].strip()
resource_path = urllib.parse.unquote(resource_url.path)
if resource_path.endswith('/'):
resource_path += 'index.html'
resource_path = resource_path.lstrip('/')
resource_path = os.path.join(self.dest_dir, resource_path)
if mime_type == 'text/html':
data = self.patch_html(data, charset)
with open(resource_path, 'wb') as file_h:
file_h.write(data)
crd = ClonedResourceDetails(urllib.parse.unquote(resource_url.path), mime_type, len(data), resource_path)
self.cloned_resources[resource_url.path] = crd
self.logger.debug("wrote {0:,} bytes to {1}".format(crd.size, resource_path))
|
Copy the data from a loaded resource to a local file.
:param resource: The resource whose data is being copied.
:type resource: :py:class:`WebKit2.WebResource`
:param data: The raw data of the represented resource.
:type data: bytes, str
|
copy_resource_data
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/web_cloner.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/web_cloner.py
|
BSD-3-Clause
|
def patch_html(self, data, encoding='utf-8'):
"""
Patch the HTML data to include the King Phisher javascript resource.
The script tag is inserted just before the closing head tag. If no head
tag is present, the data is left unmodified.
:param str data: The HTML data to patch.
:return: The patched HTML data.
:rtype: str
"""
try:
codec = codecs.lookup(encoding)
except LookupError as error:
self.logger.warning('failed to decode data from web response, ' + error.args[0])
return data
try:
data = codec.decode(data)[0]
except Exception as error:
self.logger.error("failed to decode data from web response ({0}) using encoding {1}".format(error.__class__.__name__, encoding))
return data
match = re.search(r'</head>', data, flags=re.IGNORECASE)
if not match:
return codec.encode(data)[0]
end_head = match.start(0)
patched = ''
patched += data[:end_head]
patched += '<script src="/kp.js" type="text/javascript"></script>'
ws_cursor = end_head - 1
while ws_cursor > 0 and data[ws_cursor] in string.whitespace:
ws_cursor -= 1
patched += data[ws_cursor + 1:end_head]
patched += data[end_head:]
return codec.encode(patched)[0]
|
Patch the HTML data to include the King Phisher javascript resource.
The script tag is inserted just before the closing head tag. If no head
tag is present, the data is left unmodified.
:param str data: The HTML data to patch.
:return: The patched HTML data.
:rtype: str
|
patch_html
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/web_cloner.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/web_cloner.py
|
BSD-3-Clause
|
def resource_is_on_target(self, resource):
"""
Test whether the resource is on the target system. This tries to match
the hostname, scheme and port number of the resource's URI against the
target URI.
:return: Whether the resource is on the target or not.
:rtype: bool
"""
resource_url = urllib.parse.urlparse(resource.get_property('uri'))
if resource_url.netloc.lower() != self.target_url.netloc.lower():
return False
if resource_url.scheme.lower() != self.target_url.scheme.lower():
return False
rport = resource_url.port or (443 if resource_url.scheme == 'https' else 80)
tport = self.target_url.port or (443 if self.target_url.scheme == 'https' else 80)
if rport != tport:
return False
return True
|
Test whether the resource is on the target system. This tries to match
the hostname, scheme and port number of the resource's URI against the
target URI.
:return: Whether the resource is on the target or not.
:rtype: bool
|
resource_is_on_target
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/web_cloner.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/web_cloner.py
|
BSD-3-Clause
|
def wait(self):
"""
Wait for the cloning operation to complete and return whether the
operation was successful or not.
:return: True if the operation was successful.
:rtype: bool
"""
while not self.load_started:
gui_utilities.gtk_sync()
while self.webview.get_property('is-loading') or len(self.__web_resources):
gui_utilities.gtk_sync()
self.webview.destroy()
return not self.load_failed
|
Wait for the cloning operation to complete and return whether the
operation was successful or not.
:return: True if the operation was successful.
:rtype: bool
|
wait
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/web_cloner.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/web_cloner.py
|
BSD-3-Clause
|
def __init__(self, application, campaign_id=None):
"""
:param application: The application instance which this object belongs to.
:type application: :py:class:`~king_phisher.client.application.KingPhisherClientApplication`
:param campaign_id: The ID of the campaign to edit.
"""
super(CampaignAssistant, self).__init__(application)
if campaign_id is not None:
campaign_id = str(campaign_id)
self.campaign_id = campaign_id
self._close_ready = True
self._page_titles = {}
for page_n in range(self.assistant.get_n_pages()):
page = self.assistant.get_nth_page(page_n)
page_title = self.assistant.get_page_title(page)
if page_title:
self._page_titles[page_title] = page_n
campaign_edges = self.application.rpc.graphql(
'{ db { campaigns { edges { node { id name } } } } }',
)['db']['campaigns']['edges']
self._campaign_names = dict((edge['node']['name'], edge['node']['id']) for edge in campaign_edges)
self._cache_hostname = {}
self._cache_site_template = {}
self._can_issue_certs = False
self._ssl_status = {}
self._expiration_time = managers.TimeSelectorButtonManager(self.application, self.gobjects['togglebutton_expiration_time'])
self._set_comboboxes()
self._set_defaults()
self._set_page_complete(False, page='Web Server URL')
self.application.rpc.async_graphql(
'{ ssl { status { enabled hasLetsencrypt hasSni } } }',
on_success=self.__async_rpc_cb_ssl_status
)
_homogenous_label_width((
self.gobjects['label_url_for_scheme'],
self.gobjects['label_url_ssl_for_status'],
self.gobjects['label_url_info_for_authors']
))
if not self.config['server_config']['server.require_id']:
self.gobjects['checkbutton_reject_after_credentials'].set_sensitive(False)
self.gobjects['checkbutton_reject_after_credentials'].set_property('active', False)
confirm_preamble = 'Verify all settings are correct in the previous sections'
if campaign_id:
# re-configuring an existing campaign
self.gobjects['label_confirm_body'].set_text(confirm_preamble + ', then hit "Apply" to update the King Phisher campaign with the new settings.')
self.gobjects['label_intro_body'].set_text('This assistant will walk you through reconfiguring the selected King Phisher campaign.')
self.gobjects['label_intro_title'].set_text('Configure Campaign')
self._set_webserver_url(self.config['mailer.webserver_url'])
else:
# creating a new campaign
self.gobjects['label_confirm_body'].set_text(confirm_preamble + ', then hit "Apply" to create the new King Phisher campaign.')
self.gobjects['label_intro_body'].set_text('This assistant will walk you through creating and configuring a new King Phisher campaign.')
self.gobjects['label_intro_title'].set_text('New Campaign')
|
:param application: The application instance which this object belongs to.
:type application: :py:class:`~king_phisher.client.application.KingPhisherClientApplication`
:param campaign_id: The ID of the campaign to edit.
|
__init__
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/assistants/campaign.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/assistants/campaign.py
|
BSD-3-Clause
|
def _set_comboboxes(self):
"""Set up all the comboboxes and load the data for their models."""
renderer = resources.renderer_text_desc
rpc = self.application.rpc
for tag_name, tag_table in (('campaign_type', 'campaign_types'), ('company_existing', 'companies'), ('company_industry', 'industries')):
combobox = self.gobjects['combobox_' + tag_name]
model = combobox.get_model()
if model is None:
combobox.pack_start(renderer, True)
combobox.add_attribute(renderer, 'text', 2)
combobox.set_model(rpc.get_tag_model(tag_table, model=model))
gui_utilities.gtk_combobox_set_entry_completion(combobox)
# setup the URL scheme combobox asynchronously
model = Gtk.ListStore(str, str, str, int)
combobox = self.gobjects['combobox_url_scheme']
combobox.set_model(model)
combobox.pack_start(renderer, True)
combobox.add_attribute(renderer, 'text', 2)
rpc.async_call('config/get', ('server.addresses',), on_success=self.__async_rpc_cb_populate_url_scheme_combobox, when_idle=True)
# setup the URL hostname combobox asynchronously
model = Gtk.ListStore(str)
combobox = self.gobjects['combobox_url_hostname']
combobox.set_model(model)
gui_utilities.gtk_combobox_set_entry_completion(combobox)
rpc.async_call('hostnames/get', on_success=self.__async_rpc_cb_populate_url_hostname_combobox, when_idle=True)
# setup the URL path combobox model, but don't populate it until a hostname is selected
model = Gtk.ListStore(str, str)
combobox = self.gobjects['combobox_url_path']
combobox.set_model(model)
gui_utilities.gtk_combobox_set_entry_completion(combobox)
|
Set up all the comboboxes and load the data for their models.
|
_set_comboboxes
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/assistants/campaign.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/assistants/campaign.py
|
BSD-3-Clause
|
def _set_defaults(self):
"""
Set any default values for widgets. Also load settings from the existing
campaign if one was specified.
"""
calendar = self.gobjects['calendar_campaign_expiration']
default_day = datetime.datetime.today() + datetime.timedelta(days=31)
gui_utilities.gtk_calendar_set_pydate(calendar, default_day)
if self.is_new_campaign:
return
campaign = self.application.get_graphql_campaign()
# set entries
self.gobjects['entry_campaign_name'].set_text(campaign['name'])
self.gobjects['entry_validation_regex_username'].set_text(campaign['credentialRegexUsername'] or '')
self.gobjects['entry_validation_regex_password'].set_text(campaign['credentialRegexPassword'] or '')
self.gobjects['entry_validation_regex_mfa_token'].set_text(campaign['credentialRegexMfaToken'] or '')
if campaign['description'] is not None:
self.gobjects['entry_campaign_description'].set_text(campaign['description'])
if campaign['campaignType'] is not None:
combobox = self.gobjects['combobox_campaign_type']
model = combobox.get_model()
model_iter = gui_utilities.gtk_list_store_search(model, campaign['campaignType']['id'], column=0)
if model_iter is not None:
combobox.set_active_iter(model_iter)
self.gobjects['checkbutton_alert_subscribe'].set_property('active', self.application.rpc('campaign/alerts/is_subscribed', self.campaign_id))
self.gobjects['checkbutton_reject_after_credentials'].set_property('active', bool(campaign['maxCredentials']))
if campaign['company'] is not None:
self.gobjects['radiobutton_company_existing'].set_active(True)
combobox = self.gobjects['combobox_company_existing']
model = combobox.get_model()
model_iter = gui_utilities.gtk_list_store_search(model, campaign['company']['id'], column=0)
if model_iter is not None:
combobox.set_active_iter(model_iter)
if campaign['expiration'] is not None:
expiration = utilities.datetime_utc_to_local(campaign['expiration'])
self.gobjects['checkbutton_expire_campaign'].set_active(True)
self._expiration_time.time = expiration.time()
gui_utilities.gtk_calendar_set_pydate(self.gobjects['calendar_campaign_expiration'], expiration.date())
|
Set any default values for widgets. Also load settings from the existing
campaign if one was specified.
|
_set_defaults
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/assistants/campaign.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/assistants/campaign.py
|
BSD-3-Clause
|
def load_campaigns(self, cursor=None):
"""Load campaigns from the remote server and populate the :py:class:`Gtk.TreeView`."""
if cursor is None:
self._tv_model.clear()
self.gobjects['revealer_loading'].set_reveal_child(True)
self.gobjects['progressbar_loading'].set_fraction(0.0)
path = find.data_file(os.path.join('queries', 'get_campaigns.graphql'))
if path is None:
raise errors.KingPhisherResourceError('could not find GraphQL query file: get_campaigns.graphql')
self.application.rpc.async_graphql_file(path, query_vars={'cursor': cursor, 'page': _QUERY_PAGE_SIZE}, on_success=self.__async_rpc_cb_load_campaigns, when_idle=True)
|
Load campaigns from the remote server and populate the :py:class:`Gtk.TreeView`.
|
load_campaigns
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/dialogs/campaign_selection.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/dialogs/campaign_selection.py
|
BSD-3-Clause
|
def _set_comboboxes(self):
"""Set up all the comboboxes and load the data for their models."""
renderer = resources.renderer_text_desc
rpc = self.application.rpc
for tag_name, tag_table in (('company_existing', 'companies'), ('company_industry', 'industries')):
combobox = self.gobjects['combobox_' + tag_name]
model = combobox.get_model()
if model is None:
combobox.pack_start(renderer, True)
combobox.add_attribute(renderer, 'text', 2)
combobox.set_model(rpc.get_tag_model(tag_table, model=model))
|
Set up all the comboboxes and load the data for their models.
|
_set_comboboxes
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/dialogs/company_editor.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/dialogs/company_editor.py
|
BSD-3-Clause
|
def format_exception_details(exc_type, exc_value, exc_traceback, error_uid=None):
"""
Format exception details to be show to a human. This should include enough
information about the type of error that occurred and the system on which
it was triggered to allow someone to attempt to debug and fix it. The first
three parameters to this function directly correspond to the values
returned from the :py:func:`sys.exc_info` function.
:param exc_type: The type of the exception.
:param exc_value: The exception instance.
:param exc_traceback: The traceback object corresponding to the exception.
:param error_uid: A unique identifier for this exception.
:type error_uid: str, :py:class:`uuid.UUID`
:return: A formatted message containing the details about the exception and environment.
:rtype: str
"""
if isinstance(error_uid, uuid.UUID):
error_uid = str(error_uid)
elif error_uid is None:
error_uid = 'N/A'
elif not isinstance(error_uid, str):
raise TypeError('error_uid must be an instance of either str, uuid.UUID or None')
pversion = 'UNKNOWN'
if its.on_linux:
# todo: platform.linux_distribution will be removed in Python 3.8, see:
# https://docs.python.org/3/library/platform.html#platform.linux_distribution
pversion = 'Linux: ' + ' '.join(platform.linux_distribution())
elif its.on_windows:
pversion = 'Windows: ' + ' '.join(platform.win32_ver())
if its.frozen:
pversion += ' (Frozen=True)'
else:
pversion += ' (Frozen=False)'
exc_name = format_exception_name(exc_type)
rpc_error_details = 'N/A (Not an RPC error)'
if isinstance(exc_value, advancedhttpserver.RPCError) and exc_value.is_remote_exception:
rpc_error_details = "Name: {0}".format(exc_value.remote_exception['name'])
if exc_value.remote_exception.get('message'):
rpc_error_details += " Message: '{0}'".format(exc_value.remote_exception['message'])
current_tid = threading.current_thread().ident
thread_info = (
"{0: >4}{1} (alive={2} daemon={3})".format(('=> ' if thread.ident == current_tid else ''), thread.name, thread.is_alive(), thread.daemon) for thread in threading.enumerate()
)
thread_info = '\n'.join(thread_info)
details = EXCEPTION_DETAILS_TEMPLATE.format(
error_details=repr(exc_value),
error_type=exc_name,
error_uid=error_uid,
rpc_error_details=rpc_error_details,
king_phisher_version=version.version,
platform_version=pversion,
python_version="{0}.{1}.{2}".format(*sys.version_info),
gtk_version="{0}.{1}.{2}".format(Gtk.get_major_version(), Gtk.get_minor_version(), Gtk.get_micro_version()),
stack_trace=''.join(traceback.format_exception(exc_type, exc_value, exc_traceback)),
thread_info=thread_info,
timezone=tzlocal.get_localzone().zone
)
details = details.strip() + '\n'
# add on additional details for context as necessary
if isinstance(exc_value, errors.KingPhisherGraphQLQueryError):
details += '\nGraphQL Exception Information:\n=============================\n\n'
if exc_value.errors:
details += 'GraphQL Errors:\n---------------\n'
details += '\n'.join(error.strip() for error in exc_value.errors) + '\n\n'
details += 'GraphQL Query:\n--------------\n'
details += textwrap.dedent(exc_value.query) + '\n'
return details
|
Format exception details to be show to a human. This should include enough
information about the type of error that occurred and the system on which
it was triggered to allow someone to attempt to debug and fix it. The first
three parameters to this function directly correspond to the values
returned from the :py:func:`sys.exc_info` function.
:param exc_type: The type of the exception.
:param exc_value: The exception instance.
:param exc_traceback: The traceback object corresponding to the exception.
:param error_uid: A unique identifier for this exception.
:type error_uid: str, :py:class:`uuid.UUID`
:return: A formatted message containing the details about the exception and environment.
:rtype: str
|
format_exception_details
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/dialogs/exception.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/dialogs/exception.py
|
BSD-3-Clause
|
def __init__(self, application, exc_info=None, error_uid=None):
"""
:param application: The parent application for this object.
:type application: :py:class:`Gtk.Application`
:param tuple exc_info: The exception information as provided by :py:func:`sys.exc_info`.
:param str error_uid: An optional unique identifier for the exception that can be provided for tracking purposes.
"""
super(ExceptionDialog, self).__init__(application)
self.error_description = self.gtk_builder_get('label_error_description')
self.error_details = self.gtk_builder_get('textview_error_details')
self.error_details.modify_font(Pango.FontDescription('monospace 9'))
self.exc_info = exc_info or sys.exc_info()
self.error_uid = error_uid
linkbutton = self.gobjects['linkbutton_github_issues']
linkbutton.set_label('Project Issue Tracker')
linkbutton.connect('activate-link', lambda _: utilities.open_uri(linkbutton.get_property('uri')))
|
:param application: The parent application for this object.
:type application: :py:class:`Gtk.Application`
:param tuple exc_info: The exception information as provided by :py:func:`sys.exc_info`.
:param str error_uid: An optional unique identifier for the exception that can be provided for tracking purposes.
|
__init__
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/dialogs/exception.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/dialogs/exception.py
|
BSD-3-Clause
|
def __init__(self, application, hostname, key):
"""
:param application: The application to associate this popup dialog with.
:type application: :py:class:`.KingPhisherClientApplication`
:param str hostname: The hostname associated with the key.
:param key: The host's SSH key.
:type key: :py:class:`paramiko.pkey.PKey`
"""
super(BaseHostKeyDialog, self).__init__(application)
self.hostname = hostname
self.key = key
textview = self.gobjects['textview_key_details']
textview.modify_font(Pango.FontDescription('monospace 9'))
textview.get_buffer().set_text(self.key_details)
if self.default_response is not None:
button = self.dialog.get_widget_for_response(response_id=self.default_response)
button.grab_default()
|
:param application: The application to associate this popup dialog with.
:type application: :py:class:`.KingPhisherClientApplication`
:param str hostname: The hostname associated with the key.
:param key: The host's SSH key.
:type key: :py:class:`paramiko.pkey.PKey`
|
__init__
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/dialogs/ssh_host_key.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/dialogs/ssh_host_key.py
|
BSD-3-Clause
|
def __init__(self, application):
"""
:param application: The application which is using this policy.
:type application: :py:class:`.KingPhisherClientApplication`
"""
self.application = application
self.logger = logging.getLogger('KingPhisher.Client.' + self.__class__.__name__)
super(MissingHostKeyPolicy, self).__init__()
|
:param application: The application which is using this policy.
:type application: :py:class:`.KingPhisherClientApplication`
|
__init__
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/dialogs/ssh_host_key.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/dialogs/ssh_host_key.py
|
BSD-3-Clause
|
def _sync_loader_thread(self):
"""
Synchronize the loader thread by ensuring that it is stopped. If it is
currently running, this will use :py:attr:`~.loader_thread_stop` to
request that the loader stops early.
"""
if not self.loader_thread_is_running:
return
# it's alive so tell it to stop, wait for it, then proceed
self.loader_thread_stop.set()
while self.loader_thread.is_alive():
gui_utilities.gtk_sync()
self.loader_thread.join(1)
|
Synchronize the loader thread by ensuring that it is stopped. If it is
currently running, this will use :py:attr:`~.loader_thread_stop` to
request that the loader stops early.
|
_sync_loader_thread
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/tabs/campaign.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/tabs/campaign.py
|
BSD-3-Clause
|
def load_campaign_information(self, force=True):
"""
Load the necessary campaign information from the remote server.
Unless *force* is True, the
:py:attr:`~.CampaignViewGenericTab.last_load_time` is compared
with the :py:attr:`~.CampaignViewGenericTab.refresh_frequency` to
check if the information is stale. If the local data is not stale,
this function will return without updating the table.
:param bool force: Ignore the load life time and force loading the remote data.
"""
if not force and ((time.time() - self.last_load_time) < self.refresh_frequency):
return
with self.loader_thread_lock:
self._sync_loader_thread()
self.loader_thread_stop.clear()
self._tv_model.clear()
self.loader_thread = utilities.Thread(target=self.loader_thread_routine, args=(self._tv_model,))
self.loader_thread.daemon = True
self.loader_thread.start()
return
|
Load the necessary campaign information from the remote server.
Unless *force* is True, the
:py:attr:`~.CampaignViewGenericTab.last_load_time` is compared
with the :py:attr:`~.CampaignViewGenericTab.refresh_frequency` to
check if the information is stale. If the local data is not stale,
this function will return without updating the table.
:param bool force: Ignore the load life time and force loading the remote data.
|
load_campaign_information
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/tabs/campaign.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/tabs/campaign.py
|
BSD-3-Clause
|
def loader_thread_routine(self, store):
"""
The loading routine to be executed within a thread.
:param store: The store object to place the new data.
:type store: :py:class:`Gtk.ListStore`
"""
gui_utilities.glib_idle_add_wait(lambda: self.gobjects['treeview_campaign'].set_property('sensitive', False))
campaign_id = self.config['campaign_id']
count = 500
page_info = {'endCursor': None, 'hasNextPage': True}
while page_info['hasNextPage']:
if self.rpc is None:
break
try:
results = self.rpc.graphql(self.table_query, {'campaign': campaign_id, 'count': count, 'cursor': page_info['endCursor']})
except errors.KingPhisherGraphQLQueryError as error:
self.logger.error('graphql error: ' + error.message)
raise
if self.loader_thread_stop.is_set():
break
if self.is_destroyed.is_set():
break
for edge in results['db']['campaign'][self.table_name]['edges']:
node = edge['node']
row_data = (str(node['id']),) + tuple(self.format_node_data(node))
gui_utilities.glib_idle_add_wait(store.append, row_data)
page_info = results['db']['campaign'][self.table_name]['pageInfo']
if self.is_destroyed.is_set():
return
gui_utilities.glib_idle_add_wait(lambda: self.gobjects['treeview_campaign'].set_property('sensitive', True))
self.last_load_time = time.time()
|
The loading routine to be executed within a thread.
:param store: The store object to place the new data.
:type store: :py:class:`Gtk.ListStore`
|
loader_thread_routine
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/tabs/campaign.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/tabs/campaign.py
|
BSD-3-Clause
|
def export_table_to_csv(self, filtered=False):
"""Export the data represented by the view to a CSV file."""
if not self._export_lock():
return
dialog = extras.FileChooserDialog('Export Data', self.parent)
file_name = self.config['campaign_name'] + '.csv'
response = dialog.run_quick_save(file_name)
dialog.destroy()
if not response:
self.loader_thread_lock.release()
return
destination_file = response['target_path']
if filtered:
store = self._tv_model_filter
else:
store = self._tv_model
columns = dict(enumerate(('UID',) + self.view_column_titles))
export.liststore_to_csv(store, destination_file, columns)
self.loader_thread_lock.release()
|
Export the data represented by the view to a CSV file.
|
export_table_to_csv
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/tabs/campaign.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/tabs/campaign.py
|
BSD-3-Clause
|
def export_table_to_xlsx_worksheet(self, worksheet, title_format):
"""
Export the data represented by the view to an XLSX worksheet.
:param worksheet: The destination sheet for the store's data.
:type worksheet: :py:class:`xlsxwriter.worksheet.Worksheet`
:param title_format: The formatting to use for the title row.
:type title_format: :py:class:`xlsxwriter.format.Format`
"""
if not self._export_lock():
return
store = self._tv_model
columns = dict(enumerate(('UID',) + self.view_column_titles))
xlsx_worksheet_options = export.XLSXWorksheetOptions(
column_widths=(20,) + tuple(column.width for column in self.view_columns),
title=self.label_text
)
export.liststore_to_xlsx_worksheet(store, worksheet, columns, title_format, xlsx_options=xlsx_worksheet_options)
self.loader_thread_lock.release()
|
Export the data represented by the view to an XLSX worksheet.
:param worksheet: The destination sheet for the store's data.
:type worksheet: :py:class:`xlsxwriter.worksheet.Worksheet`
:param title_format: The formatting to use for the title row.
:type title_format: :py:class:`xlsxwriter.format.Format`
|
export_table_to_xlsx_worksheet
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/tabs/campaign.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/tabs/campaign.py
|
BSD-3-Clause
|
def load_campaign_information(self, force=True):
"""
Load the necessary campaign information from the remote server.
Unless *force* is True, the :py:attr:`~.last_load_time` is compared with
the :py:attr:`~.refresh_frequency` to check if the information is stale.
If the local data is not stale, this function will return without
updating the table.
:param bool force: Ignore the load life time and force loading the remote data.
"""
if not force and ((time.time() - self.last_load_time) < self.refresh_frequency):
return
if not self.application.rpc:
self.logger.warning('skipping load_campaign_information because rpc is not initialized')
return
with self.loader_thread_lock:
self._sync_loader_thread()
self.loader_thread_stop.clear()
self.loader_thread = utilities.Thread(target=self.loader_thread_routine)
self.loader_thread.daemon = True
self.loader_thread.start()
|
Load the necessary campaign information from the remote server.
Unless *force* is True, the :py:attr:`~.last_load_time` is compared with
the :py:attr:`~.refresh_frequency` to check if the information is stale.
If the local data is not stale, this function will return without
updating the table.
:param bool force: Ignore the load life time and force loading the remote data.
|
load_campaign_information
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/tabs/campaign.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/tabs/campaign.py
|
BSD-3-Clause
|
def loader_idle_routine(self):
"""The routine which refreshes the campaign data at a regular interval."""
if self.rpc and not self.loader_thread_is_running:
self.logger.debug('idle loader routine called')
self.load_campaign_information()
return True
|
The routine which refreshes the campaign data at a regular interval.
|
loader_idle_routine
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/tabs/campaign.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/tabs/campaign.py
|
BSD-3-Clause
|
def loader_thread_routine(self):
"""The loading routine to be executed within a thread."""
if not 'campaign_id' in self.config:
return
try:
campaign = self.application.get_graphql_campaign()
except (ConnectionError, advancedhttpserver.RPCConnectionError):
return
if campaign is None:
return
info_cache = {}
for graph in self.graphs:
if self.loader_thread_stop.is_set():
break
if self.is_destroyed.is_set():
break
info_cache.update(gui_utilities.glib_idle_add_wait(lambda g=graph: g.refresh(info_cache, self.loader_thread_stop)))
else:
self.last_load_time = time.time()
|
The loading routine to be executed within a thread.
|
loader_thread_routine
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/tabs/campaign.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/tabs/campaign.py
|
BSD-3-Clause
|
def __init__(self, parent, application):
"""
:param parent: The parent window for this object.
:type parent: :py:class:`Gtk.Window`
:param application: The main client application instance.
:type application: :py:class:`Gtk.Application`
"""
self.parent = parent
self.application = application
self.config = application.config
self.logger = logging.getLogger('KingPhisher.Client.' + self.__class__.__name__)
self.box = Gtk.Box()
self.box.set_property('orientation', Gtk.Orientation.VERTICAL)
self.box.show()
self.label = Gtk.Label(label='View Campaign')
"""The :py:class:`Gtk.Label` representing this tabs name."""
self.notebook = Gtk.Notebook()
""" The :py:class:`Gtk.Notebook` for holding sub-tabs."""
self.notebook.connect('switch-page', self.signal_notebook_switch_page)
self.notebook.set_scrollable(True)
self.box.pack_start(self.notebook, True, True, 0)
self.tabs = utilities.FreezableDict()
"""A dict object holding the sub tabs managed by this object."""
current_page = self.notebook.get_current_page()
self.last_page_id = current_page
if graphs.has_matplotlib:
self.logger.info('matplotlib is installed, dashboard will be available')
dashboard_tab = CampaignViewDashboardTab(application)
self.tabs['dashboard'] = dashboard_tab
self.notebook.append_page(dashboard_tab.box, dashboard_tab.label)
else:
self.logger.warning('matplotlib is not installed, dashboard will not be available')
messages_tab = CampaignViewMessagesTab(application)
self.tabs['messages'] = messages_tab
self.notebook.append_page(messages_tab.box, messages_tab.label)
visits_tab = CampaignViewVisitsTab(application)
self.tabs['visits'] = visits_tab
self.notebook.append_page(visits_tab.box, visits_tab.label)
credentials_tab = CampaignViewCredentialsTab(application)
self.tabs['credentials'] = credentials_tab
self.notebook.append_page(credentials_tab.box, credentials_tab.label)
if self.config.get('gui.show_deaddrop', False):
deaddrop_connections_tab = CampaignViewDeaddropTab(application)
self.tabs['deaddrop_connections'] = deaddrop_connections_tab
self.notebook.append_page(deaddrop_connections_tab.box, deaddrop_connections_tab.label)
self.tabs.freeze()
for tab in self.tabs.values():
tab.box.show()
self.notebook.show()
|
:param parent: The parent window for this object.
:type parent: :py:class:`Gtk.Window`
:param application: The main client application instance.
:type application: :py:class:`Gtk.Application`
|
__init__
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/tabs/campaign.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/tabs/campaign.py
|
BSD-3-Clause
|
def test_webserver_url(target_url, secret_id):
"""
Test the target URL to ensure that it is valid and the server is responding.
:param str target_url: The URL to make a test request to.
:param str secret_id: The King Phisher Server secret id to include in the test request.
"""
parsed_url = urllib.parse.urlparse(target_url)
query = urllib.parse.parse_qs(parsed_url.query)
query['id'] = [secret_id]
query = urllib.parse.urlencode(query, True)
target_url = urllib.parse.urlunparse((parsed_url.scheme, parsed_url.netloc, parsed_url.path, parsed_url.params, query, parsed_url.fragment))
return requests.get(target_url, timeout=6.0)
|
Test the target URL to ensure that it is valid and the server is responding.
:param str target_url: The URL to make a test request to.
:param str secret_id: The King Phisher Server secret id to include in the test request.
|
test_webserver_url
|
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 sender_start_failure(self, message=None, text=None, retry=False):
"""
Handle a failure in starting the message sender thread and
perform any necessary clean up.
:param message: A message to shown in an error popup dialog.
:type message: str, tuple
:param text message: A message to be inserted into the text buffer.
:param bool retry: The operation will be attempted again.
"""
if text:
self.text_insert(text)
self.gobjects['button_mail_sender_stop'].set_sensitive(False)
self.gobjects['button_mail_sender_start'].set_sensitive(True)
if isinstance(message, str):
gui_utilities.show_dialog_error(message, self.parent)
elif isinstance(message, tuple) and len(message) == 2:
gui_utilities.show_dialog_error(message[0], self.parent, message[1])
if not retry:
self.sender_thread = None
|
Handle a failure in starting the message sender thread and
perform any necessary clean up.
:param message: A message to shown in an error popup dialog.
:type message: str, tuple
:param text message: A message to be inserted into the text buffer.
:param bool retry: The operation will be attempted again.
|
sender_start_failure
|
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 notify_stopped(self):
"""
A callback used by :py:class:`.MailSenderThread` to notify when the
thread has stopped.
"""
self.progressbar.set_fraction(1)
self.gobjects['button_mail_sender_stop'].set_sensitive(False)
self.gobjects['togglebutton_mail_sender_pause'].set_property('active', False)
self.gobjects['togglebutton_mail_sender_pause'].set_sensitive(False)
self.gobjects['button_mail_sender_start'].set_sensitive(True)
self.sender_thread = None
self.application.main_tabs['mailer'].emit('send-finished')
|
A callback used by :py:class:`.MailSenderThread` to notify when the
thread has stopped.
|
notify_stopped
|
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 __init__(self, application):
"""
:param application: The application instance.
:type application: :py:class:`.KingPhisherClientApplication`
"""
self.label = Gtk.Label(label='Preview')
"""The :py:class:`Gtk.Label` representing this tabs name."""
self.application = application
self.config = application.config
self.box = Gtk.Box()
self.box.set_property('orientation', Gtk.Orientation.VERTICAL)
self.box.show()
self.webview = extras.WebKitHTMLView()
"""The :py:class:`~.extras.WebKitHTMLView` object used to render the message HTML."""
self.webview.show()
scrolled_window = Gtk.ScrolledWindow()
scrolled_window.add(self.webview)
scrolled_window.show()
self.info_bar = Gtk.InfoBar()
self.info_bar.set_no_show_all(True)
self.info_bar_label = Gtk.Label('Template Error!')
self.info_bar_label.show()
image = Gtk.Image.new_from_stock('gtk-dialog-error', Gtk.IconSize.DIALOG)
image.show()
self.info_bar.get_content_area().add(image)
self.info_bar.get_content_area().add(self.info_bar_label)
self.info_bar.add_button('OK', Gtk.ResponseType.OK)
self.info_bar.connect('response', lambda x, y: self.info_bar.hide())
self.box.pack_start(self.info_bar, False, True, 0)
self.box.pack_start(scrolled_window, True, True, 0)
self.file_monitor = None
|
:param application: The application instance.
:type application: :py:class:`.KingPhisherClientApplication`
|
__init__
|
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 load_html_file(self):
"""
Load the configured HTML file into the WebKit engine so the contents can
be previewed.
"""
html_file = self.config.get('mailer.html_file')
if not (html_file and os.path.isfile(html_file) and os.access(html_file, os.R_OK)):
return
try:
with codecs.open(html_file, 'r', encoding='utf-8') as file_h:
html_data = file_h.read()
except UnicodeDecodeError:
self.info_bar_label.set_text("Source file is not UTF-8 encoded.")
return
try:
html_data = mailer.render_message_template(html_data, self.config)
except jinja2.TemplateSyntaxError as error:
self.info_bar_label.set_text("Template syntax error: {error.message} on line {error.lineno}.".format(error=error))
self.info_bar.show()
except jinja2.UndefinedError as error:
self.info_bar_label.set_text("Template undefined error: {error.message}.".format(error=error))
self.info_bar.show()
except TypeError as error:
self.info_bar_label.set_text("Template type error: {0}.".format(error.args[0]))
self.info_bar.show()
else:
html_file_uri = urllib.parse.urlparse(html_file, 'file').geturl()
self.webview.load_html_data(html_data, html_file_uri)
self.info_bar.hide()
|
Load the configured HTML file into the WebKit engine so the contents can
be previewed.
|
load_html_file
|
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 show_tab(self):
"""Configure the webview to preview the the message HTML file."""
if not self.config['mailer.html_file']:
if self.file_monitor:
self.file_monitor.stop()
self.file_monitor = None
self.webview.load_html_data('')
return
self.load_html_file()
if self.file_monitor and self.file_monitor.path != self.config['mailer.html_file']:
self.file_monitor.stop()
self.file_monitor = None
if not self.file_monitor:
self.file_monitor = gui_utilities.FileMonitor(self.config['mailer.html_file'], self._html_file_changed)
|
Configure the webview to preview the the message HTML file.
|
show_tab
|
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 load_html_file(self):
"""Load the contents of the configured HTML file into the editor."""
html_file = self.config.get('mailer.html_file')
if not (html_file and os.path.isfile(html_file) and os.access(html_file, os.R_OK)):
self.toolbutton_save_html_file.set_sensitive(False)
return
self.toolbutton_save_html_file.set_sensitive(True)
try:
with codecs.open(html_file, 'r', encoding='utf-8') as file_h:
html_data = file_h.read()
except UnicodeDecodeError:
gui_utilities.show_dialog_error(
"Error Opening File",
self.parent,
"Source file is not UTF-8 encoded"
)
return
current_text = self.textbuffer.get_text(self.textbuffer.get_start_iter(), self.textbuffer.get_end_iter(), False)
if html_data == current_text:
return
self.textbuffer.begin_not_undoable_action()
self.textbuffer.set_text(html_data)
self.textbuffer.end_not_undoable_action()
|
Load the contents of the configured HTML file into the editor.
|
load_html_file
|
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 save_html_file(self, force_prompt=False):
"""
Save the contents from the editor into an HTML file if one is configured
otherwise prompt to user to select a file to save as. The user may abort
the operation by declining to select a file to save as if they are
prompted to do so.
:param force_prompt: Force prompting the user to select the file to save as.
:rtype: bool
:return: Whether the contents were saved or not.
"""
html_file = self.config.get('mailer.html_file')
force_prompt = force_prompt or not html_file
if html_file and not os.path.isdir(os.path.dirname(html_file)):
force_prompt = True
if force_prompt:
if html_file:
current_name = os.path.basename(html_file)
else:
current_name = 'message.html'
dialog = extras.FileChooserDialog('Save HTML File', self.parent)
response = dialog.run_quick_save(current_name=current_name)
dialog.destroy()
if not response:
return False
html_file = response['target_path']
self.config['mailer.html_file'] = html_file
text = self.textbuffer.get_text(self.textbuffer.get_start_iter(), self.textbuffer.get_end_iter(), False)
with open(html_file, 'w') as file_h:
file_h.write(text)
self.toolbutton_save_html_file.set_sensitive(True)
return True
|
Save the contents from the editor into an HTML file if one is configured
otherwise prompt to user to select a file to save as. The user may abort
the operation by declining to select a file to save as if they are
prompted to do so.
:param force_prompt: Force prompting the user to select the file to save as.
:rtype: bool
:return: Whether the contents were saved or not.
|
save_html_file
|
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 show_tab(self):
"""Load the message HTML file from disk and configure the tab for editing."""
if self.file_monitor and self.file_monitor.path == self.config['mailer.html_file']:
return
if not self.config['mailer.html_file']:
if self.file_monitor:
self.file_monitor.stop()
self.file_monitor = None
self.toolbutton_save_html_file.set_sensitive(False)
return
self.load_html_file()
self.file_monitor = gui_utilities.FileMonitor(self.config['mailer.html_file'], self._html_file_changed)
|
Load the message HTML file from disk and configure the tab for editing.
|
show_tab
|
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 __init__(self, parent, application):
"""
:param parent: The parent window for this object.
:type parent: :py:class:`Gtk.Window`
:param application: The main client application instance.
:type application: :py:class:`Gtk.Application`
"""
super(MailSenderTab, self).__init__()
self.parent = parent
self.application = application
self.config = application.config
self.box = Gtk.Box()
self.box.set_property('orientation', Gtk.Orientation.VERTICAL)
self.box.show()
self.label = Gtk.Label(label='Send Messages')
"""The :py:class:`Gtk.Label` representing this tabs name."""
self.notebook = Gtk.Notebook()
""" The :py:class:`Gtk.Notebook` for holding sub-tabs."""
self.notebook.connect('switch-page', self.signal_notebook_switch_page)
self.notebook.set_scrollable(True)
self.box.pack_start(self.notebook, True, True, 0)
self.status_bar = Gtk.Statusbar()
self.status_bar.show()
self.box.pack_end(self.status_bar, False, False, 0)
self.tabs = utilities.FreezableDict()
"""A dict object holding the sub tabs managed by this object."""
current_page = self.notebook.get_current_page()
self.last_page_id = current_page
config_tab = MailSenderConfigurationTab(self.application)
self.tabs['config'] = config_tab
self.notebook.append_page(config_tab.box, config_tab.label)
edit_tab = MailSenderEditTab(self.application)
self.tabs['edit'] = edit_tab
self.notebook.append_page(edit_tab.box, edit_tab.label)
preview_tab = MailSenderPreviewTab(self.application)
self.tabs['preview'] = preview_tab
self.notebook.append_page(preview_tab.box, preview_tab.label)
send_messages_tab = MailSenderSendTab(self.application)
self.tabs['send_messages'] = send_messages_tab
self.notebook.append_page(send_messages_tab.box, send_messages_tab.label)
self.tabs.freeze()
for tab in self.tabs.values():
tab.box.show()
self.notebook.show()
self.application.connect('campaign-set', self.signal_kpc_campaign_set)
|
:param parent: The parent window for this object.
:type parent: :py:class:`Gtk.Window`
:param application: The main client application instance.
:type application: :py:class:`Gtk.Application`
|
__init__
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.