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 validate_record(ip, domain, sender=None):
"""
Check if an SPF record exists for the domain and can be parsed by this
module.
:return: Whether the record exists and is parsable or not.
:rtype: bool
"""
try:
result = check_host(ip, domain, sender)
except SPFPermError:
return False
return isinstance(result, str)
|
Check if an SPF record exists for the domain and can be parsed by this
module.
:return: Whether the record exists and is parsable or not.
:rtype: bool
|
validate_record
|
python
|
rsmusllp/king-phisher
|
king_phisher/spf.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/spf.py
|
BSD-3-Clause
|
def __init__(self, ip, domain, sender=None, timeout=DEFAULT_DNS_TIMEOUT):
"""
:param ip: The IP address of the host sending the message.
:type ip: str, :py:class:`ipaddress.IPv4Address`, :py:class:`ipaddress.IPv6Address`
:param str domain: The domain to check the SPF policy of.
:param str sender: The "MAIL FROM" identity of the message being sent.
:param int timeout: The timeout for DNS queries.
"""
if isinstance(ip, str):
ip = ipaddress.ip_address(ip)
self.ip_address = ip
self.domain = domain
self.helo_domain = 'unknown'
sender = (sender or 'postmaster')
if not '@' in sender:
sender = sender + '@' + self.domain
self.sender = sender
self.records = collections.OrderedDict()
"""
A :py:class:`collections.OrderedDict` of all the SPF records that were
resolved. This would be any records resolved due to an "include"
directive in addition to the top level domain.
"""
self.matches = []
"""
A list of :py:class:`.SPFMatch` instances showing the path traversed to
identify a matching directive. Multiple entries in this list are
present when include directives are used and a match is found within
the body of one. The list is ordered from the top level domain to the
matching record.
"""
# dns lookup limit per https://tools.ietf.org/html/rfc7208#section-4.6.4
self.query_limit = MAX_QUERIES
self.query_limit_void = MAX_QUERIES_VOID
self.policy = None
self.timeout = timeout
"""
The human readable policy result, one of the
:py:class:`.SPFResult` constants`.
"""
self._policy_checked = False
self.logger = logging.getLogger('KingPhisher.SPF.SenderPolicyFramework')
|
:param ip: The IP address of the host sending the message.
:type ip: str, :py:class:`ipaddress.IPv4Address`, :py:class:`ipaddress.IPv6Address`
:param str domain: The domain to check the SPF policy of.
:param str sender: The "MAIL FROM" identity of the message being sent.
:param int timeout: The timeout for DNS queries.
|
__init__
|
python
|
rsmusllp/king-phisher
|
king_phisher/spf.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/spf.py
|
BSD-3-Clause
|
def check_host(self):
"""
Check the SPF policy described by the object. The string representing the
matched policy is returned if an SPF policy exists, otherwise None will
be returned if no policy is defined.
:return: The result of the SPF policy described by the object.
:rtype: None, str
"""
if not self._policy_checked:
self.policy = self._check_host(self.ip_address, self.domain, self.sender)
self._policy_checked = True
return self.policy
|
Check the SPF policy described by the object. The string representing the
matched policy is returned if an SPF policy exists, otherwise None will
be returned if no policy is defined.
:return: The result of the SPF policy described by the object.
:rtype: None, str
|
check_host
|
python
|
rsmusllp/king-phisher
|
king_phisher/spf.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/spf.py
|
BSD-3-Clause
|
def _hostname_matches_additional(self, ip, name, additional):
"""
Search for *name* in *additional* and if it is found, check that it
includes *ip*.
:param ip: The IP address to search for.
:type ip: :py:class:`ipaddress.IPv4Address`, :py:class:`ipaddress.IPv6Address`
:param str name: The name to search for.
:param tuple additional: The additional data returned from a dns query to search in.
:return: The first value is whether or not *name* was found in *additional*, the second is if *ip* was also found.
:rtype: tuple
"""
rdtype = (1 if isinstance(ip, ipaddress.IPv4Address) else 28)
ip = str(ip)
additional = (entry for entry in additional if entry.rdtype == rdtype)
entry = next((entry for entry in additional if str(entry.name)[:-1] == name), None)
if entry is None:
return False, None
item = next((item for item in entry.items if item.address == ip), None)
return True, item is not None
|
Search for *name* in *additional* and if it is found, check that it
includes *ip*.
:param ip: The IP address to search for.
:type ip: :py:class:`ipaddress.IPv4Address`, :py:class:`ipaddress.IPv6Address`
:param str name: The name to search for.
:param tuple additional: The additional data returned from a dns query to search in.
:return: The first value is whether or not *name* was found in *additional*, the second is if *ip* was also found.
:rtype: tuple
|
_hostname_matches_additional
|
python
|
rsmusllp/king-phisher
|
king_phisher/spf.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/spf.py
|
BSD-3-Clause
|
def expand_macros(self, value, ip, domain, sender):
"""
Expand a string based on the macros it contains as specified by section
7 of :rfc:`7208`.
:param str value: The string containing macros to expand.
:param ip: The IP address to use when expanding macros.
:type ip: str, :py:class:`ipaddress.IPv4Address`, :py:class:`ipaddress.IPv6Address`
:param str domain: The domain name to use when expanding macros.
:param str sender: The email address of the sender to use when expanding macros.
:return: The string with the interpreted macros replaced within it.
:rtype: str
"""
if isinstance(ip, str):
ip = ipaddress.ip_address(ip)
macro_table = {
's': sender,
'l': sender.split('@', 1)[0],
'o': sender.split('@', 1)[1],
'd': domain,
'i': (str(ip) if isinstance(ip, ipaddress.IPv4Address) else '.'.join(ip.exploded.replace(':', ''))),
#'p'
'v': ('in-addr' if isinstance(ip, ipaddress.IPv4Address) else 'ip6'),
'h': self.helo_domain
}
for escape in (('%%', '%'), ('%-', '%20'), ('%_', ' ')):
value = value.replace(*escape)
end = 0
result = ''
for match in MACRO_REGEX.finditer(value):
result += value[end:match.start()]
macro_type = match.group(1)
macro_digit = int(match.group(2) or 128)
macro_reverse = (match.group(3) == 'r')
macro_delimiter = (match.group(4) or '.')
if not macro_type in macro_table:
raise SPFPermError("unsupported macro type: '{0}'".format(macro_type))
macro_value = macro_table[macro_type]
macro_value = macro_value.split(macro_delimiter)
if macro_reverse:
macro_value.reverse()
macro_value = macro_value[-macro_digit:]
macro_value = '.'.join(macro_value)
result += macro_value
end = match.end()
result += value[end:]
return result
|
Expand a string based on the macros it contains as specified by section
7 of :rfc:`7208`.
:param str value: The string containing macros to expand.
:param ip: The IP address to use when expanding macros.
:type ip: str, :py:class:`ipaddress.IPv4Address`, :py:class:`ipaddress.IPv6Address`
:param str domain: The domain name to use when expanding macros.
:param str sender: The email address of the sender to use when expanding macros.
:return: The string with the interpreted macros replaced within it.
:rtype: str
|
expand_macros
|
python
|
rsmusllp/king-phisher
|
king_phisher/spf.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/spf.py
|
BSD-3-Clause
|
def __init__(self, server, username, password, remote_server, local_port=0, private_key=None, missing_host_key_policy=None):
"""
:param tuple server: The SSH server to connect to.
:param str username: The username to authenticate with.
:param str password: The password to authenticate with.
:param tuple remote_server: The remote server to connect to through the specified SSH server.
:param int local_port: The local port to forward, if not set a random one will be used.
:param str private_key: An RSA key to prefer for authentication.
:param missing_host_key_policy: The policy to use for missing host keys.
"""
super(SSHTCPForwarder, self).__init__()
self.logger = logging.getLogger('KingPhisher.' + self.__class__.__name__)
self.server = (server[0], int(server[1]))
self.remote_server = (remote_server[0], int(remote_server[1]))
client = paramiko.SSHClient()
if missing_host_key_policy is None:
missing_host_key_policy = paramiko.AutoAddPolicy()
elif isinstance(missing_host_key_policy, paramiko.RejectPolicy):
self.logger.info('reject policy in place, loading system host keys')
client.load_system_host_keys()
client.set_missing_host_key_policy(missing_host_key_policy)
self.client = client
self.username = username
self.__connected = False
# an issue seems to exist in paramiko when multiple keys are present through the ssh-agent
agent_keys = paramiko.Agent().get_keys()
if not self.__connected and private_key:
private_key = self.__resolve_private_key(private_key, agent_keys)
if private_key:
self.logger.debug('attempting ssh authentication with user specified key')
self.__try_connect(look_for_keys=False, pkey=private_key)
else:
self.logger.warning('failed to identify the user specified key for ssh authentication')
if not self.__connected and agent_keys:
self.logger.debug("attempting ssh authentication with {:,} agent provided key{}".format(len(agent_keys), '' if len(agent_keys) == 1 else 's'))
for key in agent_keys:
if self.__try_connect(look_for_keys=False, pkey=key):
break
if not self.__connected:
self.logger.debug('attempting ssh authentication with user specified credentials')
self.__try_connect(password=password, look_for_keys=True, raise_error=True)
transport = self.client.get_transport()
self._forward_server = ForwardServer(self.remote_server, transport, ('127.0.0.1', local_port), ForwardHandler)
|
:param tuple server: The SSH server to connect to.
:param str username: The username to authenticate with.
:param str password: The password to authenticate with.
:param tuple remote_server: The remote server to connect to through the specified SSH server.
:param int local_port: The local port to forward, if not set a random one will be used.
:param str private_key: An RSA key to prefer for authentication.
:param missing_host_key_policy: The policy to use for missing host keys.
|
__init__
|
python
|
rsmusllp/king-phisher
|
king_phisher/ssh_forward.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/ssh_forward.py
|
BSD-3-Clause
|
def _run_pipenv(args, **kwargs):
"""
Execute Pipenv with the supplied arguments and return the
:py:class:`~.ProcessResults`. If the exit status is non-zero, then the
stdout buffer from the Pipenv execution will be written to stderr.
:param tuple args: The arguments for the Pipenv.
:param str cwd: An optional current working directory to use for the
process.
:return: The results of the execution.
:rtype: :py:class:`~.ProcessResults`
"""
path = which('pipenv')
if path is None:
return RuntimeError('pipenv could not be found')
args = (path,) + tuple(args)
results = run_process(args, **kwargs)
if results.status:
sys.stderr.write('pipenv encountered the following error:\n')
sys.stderr.write(results.stdout)
sys.stderr.flush()
return results
|
Execute Pipenv with the supplied arguments and return the
:py:class:`~.ProcessResults`. If the exit status is non-zero, then the
stdout buffer from the Pipenv execution will be written to stderr.
:param tuple args: The arguments for the Pipenv.
:param str cwd: An optional current working directory to use for the
process.
:return: The results of the execution.
:rtype: :py:class:`~.ProcessResults`
|
_run_pipenv
|
python
|
rsmusllp/king-phisher
|
king_phisher/startup.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/startup.py
|
BSD-3-Clause
|
def pipenv_entry(parser, entry_point):
"""
Run through startup logic for a Pipenv script (see Pipenv: `Custom Script
Shortcuts`_ for more information). This sets up a basic stream logging
configuration, establishes the Pipenv environment and finally calls the
actual entry point using :py:func:`os.execve`.
.. note::
Due to the use of :py:func:`os.execve`, this function does not return.
.. note::
Due to the use of :py:func:`os.execve` and ``os.EX_*`` exit codes, this
function is not available on Windows.
:param parser: The argument parser to use. Arguments are added to it and
extracted before passing the remainder to the entry point.
:param str entry_point: The name of the entry point using Pipenv.
.. _Custom Script Shortcuts: https://pipenv.readthedocs.io/en/latest/advanced/#custom-script-shortcuts
"""
if its.on_windows:
# this is because of the os.exec call and os.EX_* status codes
raise RuntimeError('pipenv_entry is incompatible with windows')
env_group = parser.add_argument_group('environment wrapper options')
env_action = env_group.add_mutually_exclusive_group()
env_action.add_argument('--env-install', dest='pipenv_install', default=False, action='store_true', help='install pipenv environment and exit')
env_action.add_argument('--env-update', dest='pipenv_update', default=False, action='store_true', help='update pipenv requirements and exit')
if its.on_windows:
env_group.set_defaults(pipenv_verbose=False)
else:
env_group.add_argument('--env-verbose', dest='pipenv_verbose', default=False, action='store_true', help='display pipenv output')
argp_add_default_args(parser)
arguments, _ = parser.parse_known_args()
sys_argv = sys.argv
sys_argv.pop(0)
if sys.version_info < (3, 4):
print('[-] the Python version is too old (minimum required is 3.4)')
return os.EX_SOFTWARE
# initialize basic stream logging
logger = logging.getLogger('KingPhisher.wrapper')
logger.setLevel(arguments.loglvl if arguments.loglvl else 'WARNING')
console_log_handler = logging.StreamHandler()
console_log_handler.setLevel(arguments.loglvl if arguments.loglvl else 'WARNING')
console_log_handler.setFormatter(logging.Formatter('%(levelname)-8s %(message)s'))
logger.addHandler(console_log_handler)
target_directory = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
logger.debug("target directory: {}".format(target_directory))
os.environ['PIPENV_VENV_IN_PROJECT'] = os.environ.get('PIPENV_VENV_IN_PROJECT', 'True')
os.environ['PIPENV_PIPFILE'] = os.environ.get('PIPENV_PIPFILE', os.path.join(target_directory, 'Pipfile'))
python_path = os.environ.get('PYTHONPATH')
python_path = [] if python_path is None else python_path.split(os.pathsep)
python_path.append(target_directory)
os.environ['PYTHONPATH'] = os.pathsep.join(python_path)
logger.info('checking for the pipenv environment')
if which('pipenv') is None:
logger.exception('pipenv not found, run tools/install.sh --update')
return os.EX_UNAVAILABLE
pipenv_path = which('pipenv')
logger.debug("pipenv path: {0!r}".format(pipenv_path))
pipenv_args = ['--site-packages', '--three']
if arguments.pipenv_verbose and logger.isEnabledFor(logging.DEBUG):
pipenv_args.append('--verbose')
if arguments.pipenv_install or not os.path.isdir(os.path.join(target_directory, '.venv')):
if arguments.pipenv_install:
logger.info('installing the pipenv environment')
else:
logger.warning('no pre-existing pipenv environment was found, installing it now')
results = _run_pipenv(pipenv_args + ['install'], cwd=target_directory, tee=arguments.pipenv_verbose)
if results.status:
logger.error('failed to install the pipenv environment')
logger.info('removing the incomplete .venv directory')
try:
shutil.rmtree(os.path.join(target_directory, '.venv'))
except OSError:
logger.error('failed to remove the incomplete .venv directory', exc_info=True)
return results.status
if arguments.pipenv_install:
return os.EX_OK
if arguments.pipenv_update:
logger.info('updating the pipenv environment')
results = _run_pipenv(pipenv_args + ['update'], cwd=target_directory, tee=arguments.pipenv_verbose)
if results.status:
logger.error('failed to update the pipenv environment')
return results.status
logger.info('the pipenv environment has been updated')
return os.EX_OK
logger.debug('pipenv Pipfile: {}'.format(os.environ['PIPENV_PIPFILE']))
# the blank arg being passed is required for pipenv
passing_argv = [' ', 'run', entry_point] + sys_argv
os.execve(pipenv_path, passing_argv, os.environ)
|
Run through startup logic for a Pipenv script (see Pipenv: `Custom Script
Shortcuts`_ for more information). This sets up a basic stream logging
configuration, establishes the Pipenv environment and finally calls the
actual entry point using :py:func:`os.execve`.
.. note::
Due to the use of :py:func:`os.execve`, this function does not return.
.. note::
Due to the use of :py:func:`os.execve` and ``os.EX_*`` exit codes, this
function is not available on Windows.
:param parser: The argument parser to use. Arguments are added to it and
extracted before passing the remainder to the entry point.
:param str entry_point: The name of the entry point using Pipenv.
.. _Custom Script Shortcuts: https://pipenv.readthedocs.io/en/latest/advanced/#custom-script-shortcuts
|
pipenv_entry
|
python
|
rsmusllp/king-phisher
|
king_phisher/startup.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/startup.py
|
BSD-3-Clause
|
def run_process(process_args, cwd=None, tee=False, encoding='utf-8'):
"""
Run a subprocess, wait for it to complete and return a
:py:class:`~.ProcessResults` object. This function differs from
:py:func:`.start_process` in the type it returns and the fact that it always
waits for the subprocess to finish before returning.
.. versionchanged:: 1.15.0
Added the *tee* parameter.
:param tuple process_args: The arguments for the processes including the binary.
:param bool cwd: An optional current working directory to use for the process.
:param bool tee: Whether or not to display the console output while the process is running.
:param str encoding: The encoding to use for strings.
:return: The results of the process including the status code and any text
printed to stdout or stderr.
:rtype: :py:class:`~.ProcessResults`
"""
process_handle = start_process(process_args, wait=False, cwd=cwd)
if tee:
if its.on_windows:
# this is because select() does not support file descriptors
raise RuntimeError('tee mode is not supported on Windows')
stdout = io.BytesIO()
stderr = io.BytesIO()
while process_handle.poll() is None:
_multistream(process_handle.stdout, stdout, sys.stdout.buffer, size=1)
_multistream(process_handle.stderr, stderr, sys.stderr.buffer, size=1)
_multistream(process_handle.stdout, stdout, sys.stdout.buffer)
_multistream(process_handle.stderr, stderr, sys.stderr.buffer)
stdout = stdout.getvalue()
stderr = stderr.getvalue()
else:
process_handle.wait()
stdout = process_handle.stdout.read()
stderr = process_handle.stderr.read()
results = ProcessResults(
stdout.decode(encoding),
stderr.decode(encoding),
process_handle.returncode
)
return results
|
Run a subprocess, wait for it to complete and return a
:py:class:`~.ProcessResults` object. This function differs from
:py:func:`.start_process` in the type it returns and the fact that it always
waits for the subprocess to finish before returning.
.. versionchanged:: 1.15.0
Added the *tee* parameter.
:param tuple process_args: The arguments for the processes including the binary.
:param bool cwd: An optional current working directory to use for the process.
:param bool tee: Whether or not to display the console output while the process is running.
:param str encoding: The encoding to use for strings.
:return: The results of the process including the status code and any text
printed to stdout or stderr.
:rtype: :py:class:`~.ProcessResults`
|
run_process
|
python
|
rsmusllp/king-phisher
|
king_phisher/startup.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/startup.py
|
BSD-3-Clause
|
def start_process(process_args, wait=True, cwd=None):
"""
Start a subprocess and optionally wait for it to finish. If not **wait**, a
handle to the subprocess is returned instead of ``True`` when it exits
successfully. This function differs from :py:func:`.run_process` in that it
optionally waits for the subprocess to finish, and can return a handle to
it.
:param tuple process_args: The arguments for the processes including the binary.
:param bool wait: Whether or not to wait for the subprocess to finish before returning.
:param str cwd: The optional current working directory.
:return: If **wait** is set to True, then a boolean indication success is returned, else a handle to the subprocess is returened.
"""
cwd = cwd or os.getcwd()
if isinstance(process_args, str):
process_args = shlex.split(process_args)
close_fds = True
startupinfo = None
preexec_fn = None if wait else getattr(os, 'setsid', None)
if sys.platform.startswith('win'):
close_fds = False
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
logger = logging.getLogger('KingPhisher.ExternalProcess')
logger.debug('starting external process: ' + ' '.join(process_args))
proc_h = subprocess.Popen(
process_args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
preexec_fn=preexec_fn,
close_fds=close_fds,
cwd=cwd,
startupinfo=startupinfo
)
if not wait:
return proc_h
return proc_h.wait() == 0
|
Start a subprocess and optionally wait for it to finish. If not **wait**, a
handle to the subprocess is returned instead of ``True`` when it exits
successfully. This function differs from :py:func:`.run_process` in that it
optionally waits for the subprocess to finish, and can return a handle to
it.
:param tuple process_args: The arguments for the processes including the binary.
:param bool wait: Whether or not to wait for the subprocess to finish before returning.
:param str cwd: The optional current working directory.
:return: If **wait** is set to True, then a boolean indication success is returned, else a handle to the subprocess is returened.
|
start_process
|
python
|
rsmusllp/king-phisher
|
king_phisher/startup.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/startup.py
|
BSD-3-Clause
|
def which(program):
"""
Examine the ``PATH`` environment variable to determine the location for the
specified program. If it can not be found None is returned. This is
fundamentally similar to the Unix utility of the same name.
:param str program: The name of the program to search for.
:return: The absolute path to the program if found.
:rtype: str
"""
is_exe = lambda fpath: (os.path.isfile(fpath) and os.access(fpath, os.X_OK))
for path in os.environ['PATH'].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
if is_exe(program):
return os.path.abspath(program)
return None
|
Examine the ``PATH`` environment variable to determine the location for the
specified program. If it can not be found None is returned. This is
fundamentally similar to the Unix utility of the same name.
:param str program: The name of the program to search for.
:return: The absolute path to the program if found.
:rtype: str
|
which
|
python
|
rsmusllp/king-phisher
|
king_phisher/startup.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/startup.py
|
BSD-3-Clause
|
def argp_add_default_args(parser, default_root=''):
"""
Add standard arguments to a new :py:class:`argparse.ArgumentParser`
instance. Used to add the utilities argparse options to the wrapper for
display.
:param parser: The parser to add arguments to.
:type parser: :py:class:`argparse.ArgumentParser`
:param str default_root: The default root logger to specify.
"""
parser.add_argument('-v', '--version', action='version', version=parser.prog + ' Version: ' + version.version)
log_group = parser.add_argument_group('logging options')
log_group.add_argument('-L', '--log', dest='loglvl', type=str.upper, choices=('DEBUG', 'INFO', 'WARNING', 'ERROR', 'FATAL'), help='set the logging level')
log_group.add_argument('--logger', default=default_root, help='specify the root logger')
gc_group = parser.add_argument_group('garbage collector options')
gc_group.add_argument('--gc-debug-leak', action='store_const', const=gc.DEBUG_LEAK, default=0, help='set the DEBUG_LEAK flag')
gc_group.add_argument('--gc-debug-stats', action='store_const', const=gc.DEBUG_STATS, default=0, help='set the DEBUG_STATS flag')
return parser
|
Add standard arguments to a new :py:class:`argparse.ArgumentParser`
instance. Used to add the utilities argparse options to the wrapper for
display.
:param parser: The parser to add arguments to.
:type parser: :py:class:`argparse.ArgumentParser`
:param str default_root: The default root logger to specify.
|
argp_add_default_args
|
python
|
rsmusllp/king-phisher
|
king_phisher/startup.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/startup.py
|
BSD-3-Clause
|
def argp_add_client(parser):
"""
Add client-specific arguments to a new :py:class:`argparse.ArgumentParser`
instance.
:param parser: The parser to add arguments to.
:type parser: :py:class:`argparse.ArgumentParser`
"""
kpc_group = parser.add_argument_group('client specific options')
kpc_group.add_argument('-c', '--config', dest='config_file', required=False, help='specify a configuration file to use')
kpc_group.add_argument('--no-plugins', dest='use_plugins', default=True, action='store_false', help='disable all plugins')
kpc_group.add_argument('--no-style', dest='use_style', default=True, action='store_false', help='disable interface styling')
return parser
|
Add client-specific arguments to a new :py:class:`argparse.ArgumentParser`
instance.
:param parser: The parser to add arguments to.
:type parser: :py:class:`argparse.ArgumentParser`
|
argp_add_client
|
python
|
rsmusllp/king-phisher
|
king_phisher/startup.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/startup.py
|
BSD-3-Clause
|
def argp_add_server(parser):
"""
Add server-specific arguments to a new :py:class:`argparse.ArgumentParser`
instance.
:param parser: The parser to add arguments to.
:type parser: :py:class:`argparse.ArgumentParser`
"""
kps_group = parser.add_argument_group('server specific options')
kps_group.add_argument('-f', '--foreground', dest='foreground', action='store_true', default=False, help='run in the foreground (do not fork)')
kps_group.add_argument('--verify-config', dest='verify_config', action='store_true', default=False, help='verify the configuration and exit')
kps_group.add_argument('config_file', action='store', help='configuration file to use')
return parser
|
Add server-specific arguments to a new :py:class:`argparse.ArgumentParser`
instance.
:param parser: The parser to add arguments to.
:type parser: :py:class:`argparse.ArgumentParser`
|
argp_add_server
|
python
|
rsmusllp/king-phisher
|
king_phisher/startup.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/startup.py
|
BSD-3-Clause
|
def __init__(self, loader=None, global_vars=None):
"""
:param loader: The loader to supply to the environment.
:type loader: :py:class:`jinja2.BaseLoader`
:param dict global_vars: Additional global variables for the environment.
"""
self.logger = logging.getLogger('KingPhisher.TemplateEnvironment')
autoescape = jinja2.select_autoescape(['html', 'htm', 'xml'], default_for_string=False)
extensions = ['jinja2.ext.autoescape', 'jinja2.ext.do']
super(TemplateEnvironmentBase, self).__init__(autoescape=autoescape, extensions=extensions, loader=loader, trim_blocks=True)
# misc. string filters
self.filters['cardinalize'] = boltons.strutils.cardinalize
self.filters['ordinalize'] = boltons.strutils.ordinalize
self.filters['pluralize'] = boltons.strutils.pluralize
self.filters['singularize'] = boltons.strutils.singularize
self.filters['possessive'] = lambda word: word + ('\'' if word.endswith('s') else '\'s')
self.filters['encode'] = self._filter_encode
self.filters['decode'] = self._filter_decode
self.filters['hash'] = self._filter_hash
# counter part to https://jinja.readthedocs.io/en/stable/templates.html#tojson
self.filters['fromjson'] = self._filter_json
# time filters
self.filters['strftime'] = self._filter_strftime
self.filters['timedelta'] = self._filter_timedelta
self.filters['tomorrow'] = lambda dt: dt + datetime.timedelta(days=1)
self.filters['next_week'] = lambda dt: dt + datetime.timedelta(weeks=1)
self.filters['next_month'] = lambda dt: dt + datetime.timedelta(days=30)
self.filters['next_year'] = lambda dt: dt + datetime.timedelta(days=365)
self.filters['yesterday'] = lambda dt: dt + datetime.timedelta(days=-1)
self.filters['last_week'] = lambda dt: dt + datetime.timedelta(weeks=-1)
self.filters['last_month'] = lambda dt: dt + datetime.timedelta(days=-30)
self.filters['last_year'] = lambda dt: dt + datetime.timedelta(days=-365)
# global variables
self.globals['version'] = version.version
# global functions
self.globals['fetch'] = self._func_fetch
self.globals['parse_user_agent'] = ua_parser.parse_user_agent
self.globals['password_is_complex'] = utilities.password_is_complex
self.globals['random_integer'] = random.randint
# additional globals
self.globals.update(global_vars or {})
|
:param loader: The loader to supply to the environment.
:type loader: :py:class:`jinja2.BaseLoader`
:param dict global_vars: Additional global variables for the environment.
|
__init__
|
python
|
rsmusllp/king-phisher
|
king_phisher/templates.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/templates.py
|
BSD-3-Clause
|
def from_file(self, path, **kwargs):
"""
A convenience method to load template data from a specified file,
passing it to :py:meth:`~jinja2.Environment.from_string`.
.. warning::
Because this method ultimately passes the template data to the
:py:meth:`~jinja2.Environment.from_string` method, the data will not
be automatically escaped based on the file extension as it would be
when using :py:meth:`~jinja2.Environment.get_template`.
:param str path: The path from which to load the template data.
:param kwargs: Additional keyword arguments to pass to :py:meth:`~jinja2.Environment.from_string`.
"""
with codecs.open(path, 'r', encoding='utf-8') as file_h:
source = file_h.read()
return self.from_string(source, **kwargs)
|
A convenience method to load template data from a specified file,
passing it to :py:meth:`~jinja2.Environment.from_string`.
.. warning::
Because this method ultimately passes the template data to the
:py:meth:`~jinja2.Environment.from_string` method, the data will not
be automatically escaped based on the file extension as it would be
when using :py:meth:`~jinja2.Environment.get_template`.
:param str path: The path from which to load the template data.
:param kwargs: Additional keyword arguments to pass to :py:meth:`~jinja2.Environment.from_string`.
|
from_file
|
python
|
rsmusllp/king-phisher
|
king_phisher/templates.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/templates.py
|
BSD-3-Clause
|
def join_path(self, template, parent):
"""
Over ride the default :py:meth:`jinja2.Environment.join_path` method to
explicitly specifying relative paths by prefixing the path with either
"./" or "../".
:param str template: The path of the requested template file.
:param str parent: The path of the template file which requested the load.
:return: The new path to the template.
:rtype: str
"""
if re.match(r'\.\.?/', template) is None:
return template
template = os.path.join(os.path.dirname(parent), template)
return os.path.normpath(template)
|
Over ride the default :py:meth:`jinja2.Environment.join_path` method to
explicitly specifying relative paths by prefixing the path with either
"./" or "../".
:param str template: The path of the requested template file.
:param str parent: The path of the template file which requested the load.
:return: The new path to the template.
:rtype: str
|
join_path
|
python
|
rsmusllp/king-phisher
|
king_phisher/templates.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/templates.py
|
BSD-3-Clause
|
def standard_variables(self):
"""
Additional standard variables that can optionally be used in templates.
"""
std_vars = {
'time': {
'local': datetime.datetime.now(),
'utc': datetime.datetime.utcnow()
}
}
return std_vars
|
Additional standard variables that can optionally be used in templates.
|
standard_variables
|
python
|
rsmusllp/king-phisher
|
king_phisher/templates.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/templates.py
|
BSD-3-Clause
|
def set_mode(self, mode):
"""
Set the operation mode for the environment. Valid values are the MODE_*
constants.
:param int mode: The operation mode.
"""
if mode not in (self.MODE_PREVIEW, self.MODE_ANALYZE, self.MODE_SEND):
raise ValueError('mode must be one of the MODE_* constants')
self._mode = mode
if mode == self.MODE_ANALYZE:
self.attachment_images = {}
|
Set the operation mode for the environment. Valid values are the MODE_*
constants.
:param int mode: The operation mode.
|
set_mode
|
python
|
rsmusllp/king-phisher
|
king_phisher/templates.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/templates.py
|
BSD-3-Clause
|
def skip_if_offline(test_method):
"""
A decorator to skip running tests when the KING_PHISHER_TEST_OFFLINE
environment variable is set. This allows unit tests which require a internet
connection to be skipped when network connectivity is known to be inactive.
"""
@functools.wraps(test_method)
def decorated(self, *args, **kwargs):
if os.environ.get('KING_PHISHER_TEST_OFFLINE'):
self.skipTest('due to running in offline mode')
return test_method(self, *args, **kwargs)
return decorated
|
A decorator to skip running tests when the KING_PHISHER_TEST_OFFLINE
environment variable is set. This allows unit tests which require a internet
connection to be skipped when network connectivity is known to be inactive.
|
skip_if_offline
|
python
|
rsmusllp/king-phisher
|
king_phisher/testing.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/testing.py
|
BSD-3-Clause
|
def skip_on_travis(test_method):
"""
A decorator to skip running a test when executing in the travis-ci environment.
"""
@functools.wraps(test_method)
def decorated(self, *args, **kwargs):
if os.environ.get('TRAVIS'):
self.skipTest('due to running in travis-ci environment')
return test_method(self, *args, **kwargs)
return decorated
|
A decorator to skip running a test when executing in the travis-ci environment.
|
skip_on_travis
|
python
|
rsmusllp/king-phisher
|
king_phisher/testing.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/testing.py
|
BSD-3-Clause
|
def assertIsEmpty(self, obj, msg=None):
"""Test that *obj* is empty as determined by :py:func:`len`."""
if len(obj):
self.fail(msg or 'the test object is not empty')
|
Test that *obj* is empty as determined by :py:func:`len`.
|
assertIsEmpty
|
python
|
rsmusllp/king-phisher
|
king_phisher/testing.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/testing.py
|
BSD-3-Clause
|
def assertIsNotEmpty(self, obj, msg=None):
"""Test that *obj* is not empty as determined by :py:func:`len`."""
if not len(obj):
self.fail(msg or 'the test object is empty')
|
Test that *obj* is not empty as determined by :py:func:`len`.
|
assertIsNotEmpty
|
python
|
rsmusllp/king-phisher
|
king_phisher/testing.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/testing.py
|
BSD-3-Clause
|
def assertIsSubclass(self, obj, cls, msg=None):
"""
Test that *obj* is a subclass of *cls* (which can be a class or a tuple
of classes as supported by :py:func:`issubclass`).
"""
if not issubclass(obj, cls):
self.fail(msg or "the test object is not a subclass of '{}'".format(cls.__name__))
|
Test that *obj* is a subclass of *cls* (which can be a class or a tuple
of classes as supported by :py:func:`issubclass`).
|
assertIsSubclass
|
python
|
rsmusllp/king-phisher
|
king_phisher/testing.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/testing.py
|
BSD-3-Clause
|
def assertHasAttribute(self, obj, attribute, msg=None):
"""Test that *obj* has the named *attribute*."""
if not hasattr(obj, attribute):
self.fail(msg or "the test object has no attribute '{}'".format(attribute))
|
Test that *obj* has the named *attribute*.
|
assertHasAttribute
|
python
|
rsmusllp/king-phisher
|
king_phisher/testing.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/testing.py
|
BSD-3-Clause
|
def assertHTTPStatus(self, http_response, status):
"""
Check an HTTP response to ensure that the correct HTTP status code is
specified.
:param http_response: The response object to check.
:type http_response: :py:class:`httplib.HTTPResponse`
:param int status: The status to check for.
"""
self.assertIsInstance(http_response, http.client.HTTPResponse)
error_message = "HTTP Response received status {0} when {1} was expected".format(http_response.status, status)
self.assertEqual(http_response.status, status, msg=error_message)
|
Check an HTTP response to ensure that the correct HTTP status code is
specified.
:param http_response: The response object to check.
:type http_response: :py:class:`httplib.HTTPResponse`
:param int status: The status to check for.
|
assertHTTPStatus
|
python
|
rsmusllp/king-phisher
|
king_phisher/testing.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/testing.py
|
BSD-3-Clause
|
def assertRPCPermissionDenied(self, method, *args, **kwargs):
"""
Assert that the specified RPC method fails with a
:py:exc:`~king_phisher.errors.KingPhisherPermissionError` exception.
:param method: The RPC method that is to be tested
"""
try:
self.rpc(method, *args, **kwargs)
except advancedhttpserver.RPCError as error:
name = error.remote_exception.get('name')
if name.endswith('.KingPhisherPermissionError'):
return
self.fail("the rpc method '{0}' failed".format(method))
self.fail("the rpc method '{0}' granted permissions".format(method))
|
Assert that the specified RPC method fails with a
:py:exc:`~king_phisher.errors.KingPhisherPermissionError` exception.
:param method: The RPC method that is to be tested
|
assertRPCPermissionDenied
|
python
|
rsmusllp/king-phisher
|
king_phisher/testing.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/testing.py
|
BSD-3-Clause
|
def http_request(self, resource, method='GET', include_id=True, body=None, headers=None):
"""
Make an HTTP request to the specified resource on the test server.
:param str resource: The resource to send the request to.
:param str method: The HTTP method to use for the request.
:param bool include_id: Whether to include the the id parameter.
:param body: The data to include in the body of the request.
:type body: dict, str
:param dict headers: The headers to include in the request.
:return: The servers HTTP response.
:rtype: :py:class:`httplib.HTTPResponse`
"""
if include_id:
if isinstance(include_id, str):
id_value = include_id
else:
id_value = self.config.get('server.secret_id')
resource += "{0}id={1}".format('&' if '?' in resource else '?', id_value)
server_address = self.config.get('server.addresses')[0]
conn = http.client.HTTPConnection('localhost', server_address['port'])
request_kwargs = {}
if isinstance(body, dict):
body = urllib.parse.urlencode(body)
if body:
request_kwargs['body'] = body
if headers:
request_kwargs['headers'] = headers
conn.request(method, resource, **request_kwargs)
time.sleep(0.025)
response = conn.getresponse()
conn.close()
return response
|
Make an HTTP request to the specified resource on the test server.
:param str resource: The resource to send the request to.
:param str method: The HTTP method to use for the request.
:param bool include_id: Whether to include the the id parameter.
:param body: The data to include in the body of the request.
:type body: dict, str
:param dict headers: The headers to include in the request.
:return: The servers HTTP response.
:rtype: :py:class:`httplib.HTTPResponse`
|
http_request
|
python
|
rsmusllp/king-phisher
|
king_phisher/testing.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/testing.py
|
BSD-3-Clause
|
def parse_user_agent(user_agent):
"""
Parse a user agent string and return normalized information regarding the
operating system.
:param str user_agent: The user agent to parse.
:return: A parsed user agent, None is returned if the data can not be processed.
:rtype: :py:class:`.UserAgent`
"""
os_parts = USER_AGENT_REGEX_OS.findall(user_agent)
if not os_parts:
return None
if len(os_parts) > 1:
os_parts = sorted(os_parts, key=lambda a: len(a[RE_POS_OS_NAME]) + len(a[RE_POS_OS_VERSION]), reverse=True)[0]
else:
os_parts = os_parts[0]
os_version = None
# os name
os_name = os_parts[RE_POS_OS_NAME].lower()
if os_name == 'android':
os_name = OSFamily.ANDROID
elif os_name == 'bb' or os_name.startswith('blackberry'):
os_name = OSFamily.BLACKBERRY
version_tag = USER_AGENT_REGEX_VERSION.findall(user_agent)
if version_tag:
os_version = version_tag[0][1]
elif 'ipad' in os_name or 'iphone' in os_name:
os_name = OSFamily.IOS
elif os_name == 'linux':
os_name = OSFamily.LINUX
elif os_name == 'mac os x':
os_name = OSFamily.OSX
elif os_name == 'windows nt':
os_name = OSFamily.WINDOWS
elif os_name == 'windows phone os':
os_name = OSFamily.WINDOWS_PHONE
else:
return None
# os version
os_version = (os_version or '').strip()
os_version = (os_version or os_parts[RE_POS_OS_VERSION])
os_version = re.sub(r'[_-]', r'.', os_version) if os_version else None
# os arch
os_arch = None
if USER_AGENT_REGEX_ARCH_X86_64.search(user_agent):
os_arch = OSArch.X86_64
elif USER_AGENT_REGEX_ARCH_X86.search(user_agent):
os_arch = OSArch.X86
elif USER_AGENT_REGEX_ARCH_PPC.search(user_agent):
os_arch = OSArch.PPC
return UserAgent(os_name, os_version, os_arch)
|
Parse a user agent string and return normalized information regarding the
operating system.
:param str user_agent: The user agent to parse.
:return: A parsed user agent, None is returned if the data can not be processed.
:rtype: :py:class:`.UserAgent`
|
parse_user_agent
|
python
|
rsmusllp/king-phisher
|
king_phisher/ua_parser.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/ua_parser.py
|
BSD-3-Clause
|
def argp_add_args(parser, default_root=''):
"""
Add standard arguments to a new :py:class:`argparse.ArgumentParser` instance
for configuring logging options from the command line and displaying the
version information.
.. note::
This function installs a hook to *parser.parse_args* to automatically
handle options which it adds. This includes setting up a stream logger
based on the added options.
:param parser: The parser to add arguments to.
:type parser: :py:class:`argparse.ArgumentParser`
:param str default_root: The default root logger to specify.
"""
startup.argp_add_default_args(parser, default_root=default_root)
@functools.wraps(parser.parse_args)
def parse_args_hook(*args, **kwargs):
arguments = parser._parse_args(*args, **kwargs)
configure_stream_logger(arguments.logger, arguments.loglvl)
gc.set_debug(arguments.gc_debug_stats | arguments.gc_debug_leak)
return arguments
parser._parse_args = parser.parse_args
parser.parse_args = parse_args_hook
return parser
|
Add standard arguments to a new :py:class:`argparse.ArgumentParser` instance
for configuring logging options from the command line and displaying the
version information.
.. note::
This function installs a hook to *parser.parse_args* to automatically
handle options which it adds. This includes setting up a stream logger
based on the added options.
:param parser: The parser to add arguments to.
:type parser: :py:class:`argparse.ArgumentParser`
:param str default_root: The default root logger to specify.
|
argp_add_args
|
python
|
rsmusllp/king-phisher
|
king_phisher/utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/utilities.py
|
BSD-3-Clause
|
def assert_arg_type(arg, arg_type, arg_pos=1, func_name=None):
"""
Check that an argument is an instance of the specified type and if not
raise a :py:exc:`TypeError` exception with a meaningful message. If
*func_name* is not specified, it will be determined by examining the stack.
:param arg: The argument to check.
:param arg_type: The type or sequence of types that *arg* can be.
:type arg_type: list, tuple, type
:param int arg_pos: The position of the argument in the function.
:param str func_name: The name of the function the argument is for.
"""
if isinstance(arg, arg_type):
return
if func_name is None:
parent_frame = inspect.stack()[1][0]
func_name = parent_frame.f_code.co_name
if isinstance(arg_type, (list, tuple)):
if len(arg_type) == 1:
arg_type = arg_type[0].__name__
else:
arg_type = tuple(at.__name__ for at in arg_type)
arg_type = ', '.join(arg_type[:-1]) + ' or ' + arg_type[-1]
else:
arg_type = arg_type.__name__
raise TypeError("{0}() argument {1} must be {2}, not {3}".format(func_name, arg_pos, arg_type, type(arg).__name__))
|
Check that an argument is an instance of the specified type and if not
raise a :py:exc:`TypeError` exception with a meaningful message. If
*func_name* is not specified, it will be determined by examining the stack.
:param arg: The argument to check.
:param arg_type: The type or sequence of types that *arg* can be.
:type arg_type: list, tuple, type
:param int arg_pos: The position of the argument in the function.
:param str func_name: The name of the function the argument is for.
|
assert_arg_type
|
python
|
rsmusllp/king-phisher
|
king_phisher/utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/utilities.py
|
BSD-3-Clause
|
def configure_stream_logger(logger, level=None):
"""
Configure the default stream handler for logging messages to the console.
This also configures the basic logging environment for the application.
:param str logger: The logger to add the stream handler for.
:param level: The level to set the logger to, will default to WARNING if no level is specified.
:type level: None, int, str
:return: The new configured stream handler.
:rtype: :py:class:`logging.StreamHandler`
"""
if level is None:
level = constants.DEFAULT_LOG_LEVEL
if isinstance(level, str):
level = getattr(logging, level)
root_logger = logging.getLogger('')
for handler in root_logger.handlers:
root_logger.removeHandler(handler)
logging.getLogger(logger).setLevel(logging.DEBUG)
console_log_handler = logging.StreamHandler()
console_log_handler.setLevel(level)
if its.on_linux:
console_log_handler.setFormatter(color.ColoredLogFormatter('%(levelname)s %(message)s'))
else:
console_log_handler.setFormatter(logging.Formatter('%(levelname)-8s %(message)s'))
logging.getLogger(logger).addHandler(console_log_handler)
logging.captureWarnings(True)
return console_log_handler
|
Configure the default stream handler for logging messages to the console.
This also configures the basic logging environment for the application.
:param str logger: The logger to add the stream handler for.
:param level: The level to set the logger to, will default to WARNING if no level is specified.
:type level: None, int, str
:return: The new configured stream handler.
:rtype: :py:class:`logging.StreamHandler`
|
configure_stream_logger
|
python
|
rsmusllp/king-phisher
|
king_phisher/utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/utilities.py
|
BSD-3-Clause
|
def datetime_local_to_utc(dt):
"""
Convert a :py:class:`datetime.datetime` instance from the local time to UTC
time.
:param dt: The time to convert from local to UTC.
:type dt: :py:class:`datetime.datetime`
:return: The time converted to the UTC timezone.
:rtype: :py:class:`datetime.datetime`
"""
dt = dt.replace(tzinfo=dateutil.tz.tzlocal())
dt = dt.astimezone(dateutil.tz.tzutc())
return dt.replace(tzinfo=None)
|
Convert a :py:class:`datetime.datetime` instance from the local time to UTC
time.
:param dt: The time to convert from local to UTC.
:type dt: :py:class:`datetime.datetime`
:return: The time converted to the UTC timezone.
:rtype: :py:class:`datetime.datetime`
|
datetime_local_to_utc
|
python
|
rsmusllp/king-phisher
|
king_phisher/utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/utilities.py
|
BSD-3-Clause
|
def datetime_utc_to_local(dt):
"""
Convert a :py:class:`datetime.datetime` instance from UTC time to the local
time.
:param dt: The time to convert from UTC to local.
:type dt: :py:class:`datetime.datetime`
:return: The time converted to the local timezone.
:rtype: :py:class:`datetime.datetime`
"""
dt = dt.replace(tzinfo=dateutil.tz.tzutc())
dt = dt.astimezone(dateutil.tz.tzlocal())
return dt.replace(tzinfo=None)
|
Convert a :py:class:`datetime.datetime` instance from UTC time to the local
time.
:param dt: The time to convert from UTC to local.
:type dt: :py:class:`datetime.datetime`
:return: The time converted to the local timezone.
:rtype: :py:class:`datetime.datetime`
|
datetime_utc_to_local
|
python
|
rsmusllp/king-phisher
|
king_phisher/utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/utilities.py
|
BSD-3-Clause
|
def format_datetime(dt, encoding='utf-8'):
"""
Format a date time object into a string. If the object *dt* is not an
instance of :py:class:`datetime.datetime` then an empty string will be
returned.
:param dt: The object to format.
:type dt: :py:class:`datetime.datetime`
:param str encoding: The encoding to use to coerce the return value into a unicode string.
:return: The string representing the formatted time.
:rtype: str
"""
if isinstance(dt, datetime.datetime):
formatted = dt.strftime(TIMESTAMP_FORMAT)
else:
formatted = ''
if isinstance(formatted, bytes):
formatted = formatted.decode(encoding)
return formatted
|
Format a date time object into a string. If the object *dt* is not an
instance of :py:class:`datetime.datetime` then an empty string will be
returned.
:param dt: The object to format.
:type dt: :py:class:`datetime.datetime`
:param str encoding: The encoding to use to coerce the return value into a unicode string.
:return: The string representing the formatted time.
:rtype: str
|
format_datetime
|
python
|
rsmusllp/king-phisher
|
king_phisher/utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/utilities.py
|
BSD-3-Clause
|
def is_valid_email_address(email_address):
"""
Check that the string specified appears to be a valid email address.
:param str email_address: The email address to validate.
:return: Whether the email address appears to be valid or not.
:rtype: bool
"""
if email_address is None:
return False
try:
email_validator.validate_email(email_address, allow_empty_local=False, check_deliverability=False)
except email_validator.EmailNotValidError:
return False
return True
|
Check that the string specified appears to be a valid email address.
:param str email_address: The email address to validate.
:return: Whether the email address appears to be valid or not.
:rtype: bool
|
is_valid_email_address
|
python
|
rsmusllp/king-phisher
|
king_phisher/utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/utilities.py
|
BSD-3-Clause
|
def open_uri(uri):
"""
Open a URI in a platform intelligent way. On Windows this will use
'cmd.exe /c start' and on Linux this will use gvfs-open or xdg-open
depending on which is available. If no suitable application can be
found to open the URI, a RuntimeError will be raised.
:param str uri: The URI to open.
"""
proc_args = []
if sys.platform.startswith('win'):
proc_args.append(smoke_zephyr.utilities.which('cmd.exe'))
proc_args.append('/c')
proc_args.append('start')
elif smoke_zephyr.utilities.which('gvfs-open'):
proc_args.append(smoke_zephyr.utilities.which('gvfs-open'))
elif smoke_zephyr.utilities.which('xdg-open'):
proc_args.append(smoke_zephyr.utilities.which('xdg-open'))
else:
raise RuntimeError('could not find suitable application to open uri')
proc_args.append(uri)
return startup.start_process(proc_args)
|
Open a URI in a platform intelligent way. On Windows this will use
'cmd.exe /c start' and on Linux this will use gvfs-open or xdg-open
depending on which is available. If no suitable application can be
found to open the URI, a RuntimeError will be raised.
:param str uri: The URI to open.
|
open_uri
|
python
|
rsmusllp/king-phisher
|
king_phisher/utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/utilities.py
|
BSD-3-Clause
|
def parse_datetime(ts):
"""
Parse a time stamp into a :py:class:`datetime.datetime` instance. The time
stamp must be in a compatible format, as would have been returned from the
:py:func:`.format_datetime` function.
:param str ts: The timestamp to parse.
:return: The parsed timestamp.
:rtype: :py:class:`datetime.datetime`
"""
assert_arg_type(ts, str)
return datetime.datetime.strptime(ts, TIMESTAMP_FORMAT)
|
Parse a time stamp into a :py:class:`datetime.datetime` instance. The time
stamp must be in a compatible format, as would have been returned from the
:py:func:`.format_datetime` function.
:param str ts: The timestamp to parse.
:return: The parsed timestamp.
:rtype: :py:class:`datetime.datetime`
|
parse_datetime
|
python
|
rsmusllp/king-phisher
|
king_phisher/utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/utilities.py
|
BSD-3-Clause
|
def password_is_complex(password, min_len=12):
"""
Check that the specified string meets standard password complexity
requirements.
:param str password: The password to validate.
:param int min_len: The minimum length the password should be.
:return: Whether the strings appears to be complex or not.
:rtype: bool
"""
has_upper = False
has_lower = False
has_digit = False
if len(password) < min_len:
return False
for char in password:
if char.isupper():
has_upper = True
if char.islower():
has_lower = True
if char.isdigit():
has_digit = True
if has_upper and has_lower and has_digit:
return True
return False
|
Check that the specified string meets standard password complexity
requirements.
:param str password: The password to validate.
:param int min_len: The minimum length the password should be.
:return: Whether the strings appears to be complex or not.
:rtype: bool
|
password_is_complex
|
python
|
rsmusllp/king-phisher
|
king_phisher/utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/utilities.py
|
BSD-3-Clause
|
def make_message_uid(upper=True, lower=True, digits=True):
"""
Creates a random string of specified character set to be used as a message
id. At least one of *upper*, *lower*, or *digits* must be ``True``.
:param bool upper: Include upper case characters in the UID.
:param bool lower: Include lower case characters in the UID.
:param bool digits: Include digits in the UID.
:return: String of characters from the random_string function.
:rtype: str
"""
charset = ''
if upper:
charset += string.ascii_uppercase
if lower:
charset += string.ascii_lowercase
if digits:
charset += string.digits
if not charset:
raise ValueError('at least one of upper, lower, or digits must be True')
return random_string(16, charset=charset)
|
Creates a random string of specified character set to be used as a message
id. At least one of *upper*, *lower*, or *digits* must be ``True``.
:param bool upper: Include upper case characters in the UID.
:param bool lower: Include lower case characters in the UID.
:param bool digits: Include digits in the UID.
:return: String of characters from the random_string function.
:rtype: str
|
make_message_uid
|
python
|
rsmusllp/king-phisher
|
king_phisher/utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/utilities.py
|
BSD-3-Clause
|
def make_webrelpath(path):
"""
Forcefully make *path* into a web-suitable relative path. This will strip
off leading and trailing directory separators.
.. versionadded:: 1.14.0
:param str path: The path to convert into a web-suitable relative path.
:return: The converted path.
:rtype: str
"""
if not path.startswith(webpath.sep):
path = webpath.sep + path
path = webpath.relpath(path, webpath.sep)
if path == webpath.curdir:
path = ''
return path
|
Forcefully make *path* into a web-suitable relative path. This will strip
off leading and trailing directory separators.
.. versionadded:: 1.14.0
:param str path: The path to convert into a web-suitable relative path.
:return: The converted path.
:rtype: str
|
make_webrelpath
|
python
|
rsmusllp/king-phisher
|
king_phisher/utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/utilities.py
|
BSD-3-Clause
|
def nonempty_string(value):
"""
Convert *value* into either a non-empty string or None. This will also
strip leading and trailing whitespace.
:param str value: The value to convert.
:return: Either the non-empty string or None.
"""
if not value:
return None
value = value.strip()
return value if value else None
|
Convert *value* into either a non-empty string or None. This will also
strip leading and trailing whitespace.
:param str value: The value to convert.
:return: Either the non-empty string or None.
|
nonempty_string
|
python
|
rsmusllp/king-phisher
|
king_phisher/utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/utilities.py
|
BSD-3-Clause
|
def random_string(size, charset=None):
"""
Generate a random string consisting of uppercase letters, lowercase letters
and numbers of the specified size.
:param int size: The size of the string to make.
:return: The string containing the random characters.
:rtype: str
"""
charset = charset or string.ascii_letters + string.digits
return ''.join(random.choice(charset) for _ in range(size))
|
Generate a random string consisting of uppercase letters, lowercase letters
and numbers of the specified size.
:param int size: The size of the string to make.
:return: The string containing the random characters.
:rtype: str
|
random_string
|
python
|
rsmusllp/king-phisher
|
king_phisher/utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/utilities.py
|
BSD-3-Clause
|
def switch(value, comp=operator.eq, swapped=False):
"""
A pure Python implementation of a switch case statement. *comp* will be used
as a comparison function and passed two arguments of *value* and the
provided case respectively.
Switch case example usage:
.. code-block:: python
for case in switch(2):
if case(1):
print('case 1 matched!')
break
if case(2):
print('case 2 matched!')
break
else:
print('no cases were matched')
:param value: The value to compare in each of the case statements.
:param comp: The function to use for comparison in the case statements.
:param swapped: Whether or not to swap the arguments to the *comp* function.
:return: A function to be called for each case statement.
"""
if swapped:
yield lambda case: comp(case, value)
else:
yield lambda case: comp(value, case)
|
A pure Python implementation of a switch case statement. *comp* will be used
as a comparison function and passed two arguments of *value* and the
provided case respectively.
Switch case example usage:
.. code-block:: python
for case in switch(2):
if case(1):
print('case 1 matched!')
break
if case(2):
print('case 2 matched!')
break
else:
print('no cases were matched')
:param value: The value to compare in each of the case statements.
:param comp: The function to use for comparison in the case statements.
:param swapped: Whether or not to swap the arguments to the *comp* function.
:return: A function to be called for each case statement.
|
switch
|
python
|
rsmusllp/king-phisher
|
king_phisher/utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/utilities.py
|
BSD-3-Clause
|
def validate_json_schema(data, schema_file_id):
"""
Validate the specified data against the specified schema. The schema file
will be searched for and loaded based on it's id. If the validation fails
a :py:class:`~jsonschema.exceptions.ValidationError` will be raised.
:param data: The data to validate against the schema.
:param schema_file_id: The id of the schema to load.
"""
schema_file_name = schema_file_id + '.json'
file_path = find.data_file(os.path.join('schemas', 'json', schema_file_name))
if file_path is None:
raise FileNotFoundError('the json schema file was not found')
with open(file_path, 'r') as file_h:
schema = json.load(file_h)
jsonschema.validate(data, schema)
|
Validate the specified data against the specified schema. The schema file
will be searched for and loaded based on it's id. If the validation fails
a :py:class:`~jsonschema.exceptions.ValidationError` will be raised.
:param data: The data to validate against the schema.
:param schema_file_id: The id of the schema to load.
|
validate_json_schema
|
python
|
rsmusllp/king-phisher
|
king_phisher/utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/utilities.py
|
BSD-3-Clause
|
def __init__(self, prefix, *args, **kwargs):
"""
:param str prefix: The string to prefix all messages with.
"""
self.prefix = prefix + ' '
super(PrefixLoggerAdapter, self).__init__(*args, **kwargs)
|
:param str prefix: The string to prefix all messages with.
|
__init__
|
python
|
rsmusllp/king-phisher
|
king_phisher/utilities.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/utilities.py
|
BSD-3-Clause
|
def get_revision(encoding='utf-8'):
"""
Retrieve the current git revision identifier. If the git binary can not be
found or the repository information is unavailable, None will be returned.
:param str encoding: The encoding to use for strings.
:return: The git revision tag if it's available.
:rtype: str
"""
# use error handling instead of startup.which to avoid a circular dependency
try:
proc_h = subprocess.Popen(
('git', 'rev-parse', 'HEAD'),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=False if its.on_windows else True,
cwd=os.path.dirname(os.path.abspath(__file__))
)
except OSError:
return None
rev = proc_h.stdout.read().strip()
proc_h.wait()
if not len(rev):
return None
return rev.decode(encoding)
|
Retrieve the current git revision identifier. If the git binary can not be
found or the repository information is unavailable, None will be returned.
:param str encoding: The encoding to use for strings.
:return: The git revision tag if it's available.
:rtype: str
|
get_revision
|
python
|
rsmusllp/king-phisher
|
king_phisher/version.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/version.py
|
BSD-3-Clause
|
def xor_encode(data, seed_key=None, encoding='utf-8'):
"""
Encode data using the XOR algorithm. This is not suitable for encryption
purposes and should only be used for light obfuscation. The key is
prepended to the data as the first byte which is required to be decoded
py the :py:func:`.xor_decode` function.
:param bytes data: The data to encode.
:param int seed_key: The optional value to use as the for XOR key.
:return: The encoded data.
:rtype: bytes
"""
if isinstance(data, str):
data = data.encode(encoding)
if seed_key is None:
seed_key = random.randint(0, 255)
else:
seed_key &= 0xff
encoded_data = collections.deque([seed_key])
last_key = seed_key
for byte in data:
e_byte = (byte ^ last_key)
last_key = e_byte
encoded_data.append(e_byte)
return bytes(encoded_data)
|
Encode data using the XOR algorithm. This is not suitable for encryption
purposes and should only be used for light obfuscation. The key is
prepended to the data as the first byte which is required to be decoded
py the :py:func:`.xor_decode` function.
:param bytes data: The data to encode.
:param int seed_key: The optional value to use as the for XOR key.
:return: The encoded data.
:rtype: bytes
|
xor_encode
|
python
|
rsmusllp/king-phisher
|
king_phisher/xor.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/xor.py
|
BSD-3-Clause
|
def xor_decode(data, encoding='utf-8'):
"""
Decode data using the XOR algorithm. This is not suitable for encryption
purposes and should only be used for light obfuscation. This function
requires the key to be set as the first byte of *data* as done in the
:py:func:`.xor_encode` function.
:param str data: The data to decode.
:return: The decoded data.
:rtype: str
"""
if isinstance(data, str):
data = data.encode(encoding)
data = collections.deque(data)
last_key = data.popleft()
decoded_data = collections.deque()
for b in data:
d = (b ^ last_key)
last_key = b
decoded_data.append(d)
return bytes(decoded_data)
|
Decode data using the XOR algorithm. This is not suitable for encryption
purposes and should only be used for light obfuscation. This function
requires the key to be set as the first byte of *data* as done in the
:py:func:`.xor_encode` function.
:param str data: The data to decode.
:return: The decoded data.
:rtype: str
|
xor_decode
|
python
|
rsmusllp/king-phisher
|
king_phisher/xor.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/xor.py
|
BSD-3-Clause
|
def _create_ssh_forwarder(self, server, username, password, window=None):
"""
Create and set the
:py:attr:`~.KingPhisherClientApplication._ssh_forwarder` attribute.
:param tuple server: The server information as a host and port tuple.
:param str username: The username to authenticate to the SSH server with.
:param str password: The password to authenticate to the SSH server with.
:param window: The GTK window to use as the parent for error dialogs.
:type window: :py:class:`Gtk.Window`
:rtype: int
:return: The local port that is forwarded to the remote server or None if the connection failed.
"""
window = window or self.get_active_window()
title_ssh_error = 'Failed To Connect To The SSH Service'
server_remote_port = self.config['server_remote_port']
try:
self._ssh_forwarder = ssh_forward.SSHTCPForwarder(
server,
username,
password,
('127.0.0.1', server_remote_port),
private_key=self.config.get('ssh_preferred_key'),
missing_host_key_policy=ssh_host_key.MissingHostKeyPolicy(self)
)
self._ssh_forwarder.start()
except ssh_forward.KingPhisherSSHKeyError as error:
gui_utilities.show_dialog_error('SSH Key Configuration Error', window, error.message)
except errors.KingPhisherAbortError as error:
self.logger.info("ssh connection aborted ({0})".format(error.message))
except paramiko.PasswordRequiredException:
gui_utilities.show_dialog_error(title_ssh_error, window, 'The specified SSH key requires a password.')
except paramiko.AuthenticationException:
self.logger.warning('failed to authenticate to the remote ssh server')
gui_utilities.show_dialog_error(title_ssh_error, window, 'The server responded that the credentials are invalid.')
except paramiko.SSHException as error:
self.logger.warning("failed with ssh exception '{0}'".format(error.args[0]))
except socket.error as error:
gui_utilities.show_dialog_exc_socket_error(error, window, title=title_ssh_error)
except Exception as error:
self.logger.warning('failed to connect to the remote ssh server', exc_info=True)
gui_utilities.show_dialog_error(title_ssh_error, window, "An {0}.{1} error occurred.".format(error.__class__.__module__, error.__class__.__name__))
else:
return self._ssh_forwarder.local_server
self.emit('server-disconnected')
return
|
Create and set the
:py:attr:`~.KingPhisherClientApplication._ssh_forwarder` attribute.
:param tuple server: The server information as a host and port tuple.
:param str username: The username to authenticate to the SSH server with.
:param str password: The password to authenticate to the SSH server with.
:param window: The GTK window to use as the parent for error dialogs.
:type window: :py:class:`Gtk.Window`
:rtype: int
:return: The local port that is forwarded to the remote server or None if the connection failed.
|
_create_ssh_forwarder
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/application.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/application.py
|
BSD-3-Clause
|
def add_reference(self, ref_object):
"""
Add *ref_object* to the :py:attr:`.references` so the object won't be
garbage collected. The object must either be a
:py:class:`.GladeGObject` or :py:class:`Gtk.Widget` instance so a
cleanup function can be attached to a ``destroy`` signal to remove the
reference automatically.
:param ref_object: The object to store a reference to.
:type ref_object: :py:class:`.GladeGObject`, :py:class:`Gtk.Widget`
"""
utilities.assert_arg_type(ref_object, (gui_utilities.GladeGObject, Gtk.Widget))
self.references.append(ref_object)
if isinstance(ref_object, gui_utilities.GladeGObject):
widget = getattr(ref_object, ref_object.top_gobject)
else:
widget = ref_object
widget.connect('destroy', self.signal_multi_destroy_remove_reference, ref_object)
|
Add *ref_object* to the :py:attr:`.references` so the object won't be
garbage collected. The object must either be a
:py:class:`.GladeGObject` or :py:class:`Gtk.Widget` instance so a
cleanup function can be attached to a ``destroy`` signal to remove the
reference automatically.
:param ref_object: The object to store a reference to.
:type ref_object: :py:class:`.GladeGObject`, :py:class:`Gtk.Widget`
|
add_reference
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/application.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/application.py
|
BSD-3-Clause
|
def do_campaign_delete(self, campaign_id):
"""
Delete the campaign on the server. A confirmation dialog will be
displayed before the operation is performed. If the campaign is deleted
and a new campaign is not selected with
:py:meth:`.show_campaign_selection`, the client will quit.
"""
self.rpc('db/table/delete', 'campaigns', campaign_id)
if campaign_id == self.config['campaign_id'] and not self.show_campaign_selection():
gui_utilities.show_dialog_error('Now Exiting', self.get_active_window(), 'A campaign must be selected.')
self.quit()
|
Delete the campaign on the server. A confirmation dialog will be
displayed before the operation is performed. If the campaign is deleted
and a new campaign is not selected with
:py:meth:`.show_campaign_selection`, the client will quit.
|
do_campaign_delete
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/application.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/application.py
|
BSD-3-Clause
|
def get_graphql_campaign(self, campaign_id=None):
"""
Retrieve the GraphQL representation of the specified campaign. If
*campaign_id* is not specified, then the data for the current campaign
is retrieved.
:param str campaign_id: The ID for the campaign whose information should be retrieved.
:return: The campaign's GraphQL representation.
:rtype: dict
"""
campaign_id = campaign_id or self.config['campaign_id']
campaign = self.rpc.graphql_find_file('get_campaign.graphql', id=campaign_id)
return campaign['db']['campaign']
|
Retrieve the GraphQL representation of the specified campaign. If
*campaign_id* is not specified, then the data for the current campaign
is retrieved.
:param str campaign_id: The ID for the campaign whose information should be retrieved.
:return: The campaign's GraphQL representation.
:rtype: dict
|
get_graphql_campaign
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/application.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/application.py
|
BSD-3-Clause
|
def do_server_disconnected(self):
"""
Clean up the connections to the server and disconnect. This logs out of
the RPC, closes the server event socket, and stops the SSH forwarder.
"""
if self.rpc is not None:
if self.server_events is not None:
self.server_events.reconnect = False
GLib.source_remove(self._rpc_ping_event)
try:
self.rpc.async_call('logout')
except advancedhttpserver.RPCError as error:
self.logger.warning('failed to logout, rpc error: ' + error.message)
else:
if self.server_events is not None:
self.server_events.shutdown()
self.server_events = None
self.rpc.shutdown()
self.rpc = None
if self._ssh_forwarder:
self._ssh_forwarder.stop()
self._ssh_forwarder = None
return
|
Clean up the connections to the server and disconnect. This logs out of
the RPC, closes the server event socket, and stops the SSH forwarder.
|
do_server_disconnected
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/application.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/application.py
|
BSD-3-Clause
|
def do_config_load(self, load_defaults):
"""
Load the client configuration from disk and set the
:py:attr:`~.KingPhisherClientApplication.config` attribute.
Check the proxy environment variable and set them appropriately.
:param bool load_defaults: Load missing options from the template configuration file.
"""
client_template = find.data_file('client_config.json')
self.logger.info('loading the config from: ' + self.config_file)
with open(self.config_file, 'r') as tmp_file:
self.config = serializers.JSON.load(tmp_file)
if load_defaults:
with open(client_template, 'r') as tmp_file:
client_template = serializers.JSON.load(tmp_file)
for key, value in client_template.items():
if not key in self.config:
self.config[key] = value
env_proxy = os.environ.get('HTTPS_PROXY')
if env_proxy is not None:
env_proxy = env_proxy.strip()
proxy_url = urllib.parse.urlparse(env_proxy)
if not (proxy_url.hostname and proxy_url.scheme):
self.logger.error('invalid proxy url (missing scheme or hostname)')
return
if self.config['proxy.url'] and env_proxy != self.config['proxy.url']:
self.logger.warning('setting proxy configuration via the environment, overriding the configuration')
else:
self.logger.info('setting proxy configuration via the environment')
self.config['proxy.url'] = env_proxy
elif self.config['proxy.url']:
self.logger.info('setting proxy configuration via the configuration')
os.environ['HTTPS_PROXY'] = self.config['proxy.url']
os.environ['HTTP_PROXY'] = self.config['proxy.url']
else:
os.environ.pop('HTTP_PROXY', None)
|
Load the client configuration from disk and set the
:py:attr:`~.KingPhisherClientApplication.config` attribute.
Check the proxy environment variable and set them appropriately.
:param bool load_defaults: Load missing options from the template configuration file.
|
do_config_load
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/application.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/application.py
|
BSD-3-Clause
|
def merge_config(self, config_file, strict=True):
"""
Merge the configuration information from the specified configuration
file. Only keys which exist in the currently loaded configuration are
copied over while non-existent keys are skipped. The contents of the new
configuration overwrites the existing.
:param bool strict: Do not try remove trailing commas from the JSON data.
:param str config_file: The path to the configuration file to merge.
"""
with open(config_file, 'r') as tmp_file:
config = serializers.JSON.load(tmp_file, strict=strict)
if not isinstance(config, dict):
self.logger.error("can not merge configuration file: {0} (invalid format)".format(config_file))
return
self.logger.debug('merging configuration information from source file: ' + config_file)
for key, value in config.items():
if not key in self.config:
self.logger.warning("skipped merging non-existent configuration key {0}".format(key))
continue
self.config[key] = value
return
|
Merge the configuration information from the specified configuration
file. Only keys which exist in the currently loaded configuration are
copied over while non-existent keys are skipped. The contents of the new
configuration overwrites the existing.
:param bool strict: Do not try remove trailing commas from the JSON data.
:param str config_file: The path to the configuration file to merge.
|
merge_config
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/application.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/application.py
|
BSD-3-Clause
|
def load_server_config(self):
"""Load the necessary values from the server's configuration."""
self.config['server_config'] = self.rpc(
'config/get',
[
'server.require_id',
'server.secret_id',
'server.tracking_image',
'server.web_root',
'server.addresses',
'server.vhost_directories'
]
)
return
|
Load the necessary values from the server's configuration.
|
load_server_config
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/application.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/application.py
|
BSD-3-Clause
|
def server_connect(self, username, password, otp=None, window=None):
"""
Initialize the connection to the King Phisher server.
:param str username: The username to authenticate with.
:param str password: The password to authenticate with.
:param str otp: The optional one-time password to authenticate with.
:param window: The GTK window to use as the parent for error dialogs.
:type window: :py:class:`Gtk.Window`
:rtype: tuple
"""
# pylint: disable=too-many-locals
server_version_info = None
title_rpc_error = 'Failed To Connect To The King Phisher RPC Service'
window = window or self.get_active_window()
server = parse_server(self.config['server'], 22)
if ipaddress.is_loopback(server[0]):
local_server = ('localhost', self.config['server_remote_port'])
self.logger.info("connecting to local king phisher instance")
else:
local_server = self._create_ssh_forwarder(server, username, password, window=window)
if not local_server:
return False, ConnectionErrorReason.ERROR_PORT_FORWARD
rpc = client_rpc.KingPhisherRPCClient(local_server, use_ssl=self.config.get('server_use_ssl'))
if self.config.get('rpc.serializer'):
try:
rpc.set_serializer(self.config['rpc.serializer'])
except ValueError as error:
self.logger.error("failed to set the rpc serializer, error: '{0}'".format(error.message))
generic_message = 'Can not contact the RPC HTTP service, ensure that the '
generic_message += "King Phisher Server is currently running on port {0}.".format(int(self.config['server_remote_port']))
connection_failed = True
try:
server_version_info = rpc('version')
if server_version_info is None:
rpc.shutdown()
raise RuntimeError('no version information was retrieved from the server')
except advancedhttpserver.RPCError as error:
self.logger.warning('failed to connect to the remote rpc service due to http status: ' + str(error.status))
gui_utilities.show_dialog_error(title_rpc_error, window, "The server responded with HTTP status: {0}.".format(str(error.status)))
except http.client.BadStatusLine as error:
self.logger.warning('failed to connect to the remote rpc service due to http bad status line: ' + error.line)
gui_utilities.show_dialog_error(title_rpc_error, window, generic_message)
except socket.error as error:
self.logger.debug('failed to connect to the remote rpc service due to a socket error', exc_info=True)
gui_utilities.show_dialog_exc_socket_error(error, window)
except ssl.CertificateError as error:
self.logger.warning('failed to connect to the remote rpc service with a https certificate error: ' + error.message)
gui_utilities.show_dialog_error(title_rpc_error, window, 'The server presented an invalid SSL certificate.')
except Exception:
self.logger.warning('failed to connect to the remote rpc service', exc_info=True)
gui_utilities.show_dialog_error(title_rpc_error, window, generic_message)
else:
connection_failed = False
if connection_failed:
rpc.shutdown()
self.emit('server-disconnected')
return False, ConnectionErrorReason.ERROR_CONNECTION
server_rpc_api_version = server_version_info.get('rpc_api_version', -1)
if isinstance(server_rpc_api_version, int):
# compatibility with pre-0.2.0 version
server_rpc_api_version = (server_rpc_api_version, 0)
self.logger.info(
"successfully connected to the king phisher server (version: {0} rpc api version: {1}.{2})".format(
server_version_info['version'],
server_rpc_api_version[0],
server_rpc_api_version[1]
)
)
error_text = None
if server_rpc_api_version[0] < version.rpc_api_version.major or (server_rpc_api_version[0] == version.rpc_api_version.major and server_rpc_api_version[1] < version.rpc_api_version.minor):
error_text = 'The server is running an old and incompatible version.'
error_text += '\nPlease update the remote server installation.'
elif server_rpc_api_version[0] > version.rpc_api_version.major:
error_text = 'The client is running an old and incompatible version.'
error_text += '\nPlease update the local client installation.'
if error_text:
gui_utilities.show_dialog_error('The RPC API Versions Are Incompatible', window, error_text)
rpc.shutdown()
self.emit('server-disconnected')
return False, ConnectionErrorReason.ERROR_INCOMPATIBLE_VERSIONS
login_result, login_reason = rpc.login(username, password, otp)
if not login_result:
self.logger.warning('failed to authenticate to the remote king phisher service, reason: ' + login_reason)
rpc.shutdown()
self.emit('server-disconnected')
return False, login_reason
rpc.username = username
self.logger.debug('successfully authenticated to the remote king phisher service')
server_str = self.config['server']
history = self.config['server.history']
if server_str in history:
history.remove(server_str)
history.insert(0, server_str)
self.config['server.history'] = history
event_subscriber = server_events.ServerEventSubscriber(rpc)
if not event_subscriber.is_connected:
event_subscriber.reconnect = False
event_subscriber.shutdown()
rpc.shutdown()
self.emit('server-disconnected')
return False, ConnectionErrorReason.ERROR_UNKNOWN
self.rpc = rpc
self.server_events = event_subscriber
self._rpc_ping_event = GLib.timeout_add_seconds(parse_timespan('5m'), functools.partial(_rpc_ping, rpc))
user = self.rpc.graphql(
"""\
query getUser($name: String!) {
db { user(name: $name) { id name } }
}""",
{'name': self.config['server_username']}
)['db']['user']
self.server_user = ServerUser(id=user['id'], name=user['name'])
self.emit('server-connected')
return True, ConnectionErrorReason.SUCCESS
|
Initialize the connection to the King Phisher server.
:param str username: The username to authenticate with.
:param str password: The password to authenticate with.
:param str otp: The optional one-time password to authenticate with.
:param window: The GTK window to use as the parent for error dialogs.
:type window: :py:class:`Gtk.Window`
:rtype: tuple
|
server_connect
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/application.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/application.py
|
BSD-3-Clause
|
def show_campaign_graph(self, graph_name):
"""
Create a new :py:class:`.CampaignGraph` instance and make it into
a window. *graph_name* must be the name of a valid, exported
graph provider.
:param str graph_name: The name of the graph to make a window of.
"""
cls = graphs.get_graph(graph_name)
graph_inst = cls(self, style_context=self.style_context)
graph_inst.load_graph()
window = graph_inst.make_window()
window.show()
|
Create a new :py:class:`.CampaignGraph` instance and make it into
a window. *graph_name* must be the name of a valid, exported
graph provider.
:param str graph_name: The name of the graph to make a window of.
|
show_campaign_graph
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/application.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/application.py
|
BSD-3-Clause
|
def show_campaign_selection(self):
"""
Display the campaign selection dialog in a new
:py:class:`.CampaignSelectionDialog` instance.
:return: Whether or not a campaign was selected.
:rtype: bool
"""
dialog = dialogs.CampaignSelectionDialog(self)
return dialog.interact() == Gtk.ResponseType.APPLY
|
Display the campaign selection dialog in a new
:py:class:`.CampaignSelectionDialog` instance.
:return: Whether or not a campaign was selected.
:rtype: bool
|
show_campaign_selection
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/application.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/application.py
|
BSD-3-Clause
|
def show_preferences(self):
"""
Display a
:py:class:`.dialogs.configuration.ConfigurationDialog`
instance and saves the configuration to disk if cancel is not selected.
"""
dialog = dialogs.ConfigurationDialog(self)
if dialog.interact() != Gtk.ResponseType.CANCEL:
self.emit('config-save')
|
Display a
:py:class:`.dialogs.configuration.ConfigurationDialog`
instance and saves the configuration to disk if cancel is not selected.
|
show_preferences
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/application.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/application.py
|
BSD-3-Clause
|
def do_sftp_client_start(self):
"""
Start the client's preferred sftp client application in a new process.
"""
if not self.config['sftp_client']:
gui_utilities.show_dialog_error('Invalid SFTP Configuration', self.get_active_window(), 'An SFTP client is not configured.\nOne can be configured in the Client Preferences.')
return False
command = str(self.config['sftp_client'])
sftp_bin = shlex.split(command)[0]
if not which(sftp_bin):
self.logger.error('could not locate the sftp binary: ' + sftp_bin)
gui_utilities.show_dialog_error('Invalid SFTP Configuration', self.get_active_window(), "Could not find the SFTP binary '{0}'".format(sftp_bin))
return False
try:
command = command.format(
server=self.config['server'],
username=self.config['server_username'],
web_root=self.config['server_config']['server.web_root']
)
except KeyError as error:
self.logger.error("key error while parsing the sftp command for token: {0}".format(error.args[0]))
gui_utilities.show_dialog_error('Invalid SFTP Configuration', self.get_active_window(), "Invalid token '{0}' in the SFTP command.".format(error.args[0]))
return False
self.logger.debug("starting sftp client command: {0}".format(command))
startup.start_process(command, wait=False)
return
|
Start the client's preferred sftp client application in a new process.
|
do_sftp_client_start
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/application.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/application.py
|
BSD-3-Clause
|
def stop_remote_service(self):
"""
Stop the remote King Phisher server. This will request that the
server stop processing new requests and exit. This will display
a confirmation dialog before performing the operation. If the
remote service is stopped, the client will quit.
"""
active_window = self.get_active_window()
if not gui_utilities.show_dialog_yes_no('Stop The Remote King Phisher Service?', active_window, 'This will stop the remote King Phisher service and\nnew incoming requests will not be processed.'):
return
self.rpc('shutdown')
self.logger.info('the remote king phisher service has been stopped')
gui_utilities.show_dialog_error('Now Exiting', active_window, 'The remote service has been stopped.')
self.quit()
return
|
Stop the remote King Phisher server. This will request that the
server stop processing new requests and exit. This will display
a confirmation dialog before performing the operation. If the
remote service is stopped, the client will quit.
|
stop_remote_service
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/application.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/application.py
|
BSD-3-Clause
|
def commit(self):
"""Send this object to the server to update the remote instance."""
values = tuple(getattr(self, attr) for attr in self.__slots__[1:])
values = collections.OrderedDict(((k, v) for (k, v) in zip(self.__slots__[1:], values) if v is not UNRESOLVED))
self.__rpc__('db/table/set', self.__table__, self.id, tuple(values.keys()), tuple(values.values()))
|
Send this object to the server to update the remote instance.
|
commit
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/client_rpc.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/client_rpc.py
|
BSD-3-Clause
|
def async_call(self, method, args=None, kwargs=None, on_success=None, on_error=None, when_idle=False, cb_args=None, cb_kwargs=None):
"""
Perform an asynchronous RPC call to the server. This will queue a work
item for a thread to issue the RPC call and then specifies the behavior
for completion. See :ref:`Asynchronous Methods
<client-rpc-async-methods>` for more information.
.. versionadded:: 1.14.0
:param str method: The RPC method name to call.
:param tuple args: The arguments to the RPC method.
:param tuple kwargs: The keyword arguments to the RPC method.
:param on_success: A callback function to be called after the RPC method
returns successfully.
:param on_error: A callback function to be called if the RPC method
raises an exception.
:param when_idle: Whether or not the *on_success* and *on_error*
callback functions should be called from the main GUI thread while
it is idle.
:param cb_args: The arguments to the *on_success* and *on_error*
callback functions.
:param cb_kwargs: The keyword arguments to the *on_success* and
*on_error* callback functions.
"""
self._async_queue.put(_WorkItem(
callback_on_success=on_success,
callback_on_error=on_error,
callback_when_idle=when_idle,
callback_args=cb_args,
callback_kwargs=cb_kwargs,
method=self.call,
args=(method,) + (args or ()),
kwargs=kwargs
))
|
Perform an asynchronous RPC call to the server. This will queue a work
item for a thread to issue the RPC call and then specifies the behavior
for completion. See :ref:`Asynchronous Methods
<client-rpc-async-methods>` for more information.
.. versionadded:: 1.14.0
:param str method: The RPC method name to call.
:param tuple args: The arguments to the RPC method.
:param tuple kwargs: The keyword arguments to the RPC method.
:param on_success: A callback function to be called after the RPC method
returns successfully.
:param on_error: A callback function to be called if the RPC method
raises an exception.
:param when_idle: Whether or not the *on_success* and *on_error*
callback functions should be called from the main GUI thread while
it is idle.
:param cb_args: The arguments to the *on_success* and *on_error*
callback functions.
:param cb_kwargs: The keyword arguments to the *on_success* and
*on_error* callback functions.
|
async_call
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/client_rpc.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/client_rpc.py
|
BSD-3-Clause
|
def async_graphql(self, query, query_vars=None, on_success=None, on_error=None, when_idle=False, cb_args=None, cb_kwargs=None):
"""
Perform an asynchronous RPC GraphQL query to the server. This will queue
a work item for a thread to issue the RPC call and then specifies the
behavior for completion. See :ref:`Asynchronous Methods
<client-rpc-async-methods>` for more information.
.. versionadded:: 1.14.0
:param str query: The GraphQL query string to execute asynchronously.
:param dict query_vars: Any variable definitions required by the GraphQL
query.
:param on_success: A callback function to be called after the RPC method
returns successfully.
:param on_error: A callback function to be called if the RPC method
raises an exception.
:param when_idle: Whether or not the *on_success* and *on_error*
callback functions should be called from the main GUI thread while
it is idle.
:param cb_args: The arguments to the *on_success* and *on_error*
callback functions.
:param cb_kwargs: The keyword arguments to the *on_success* and
*on_error* callback functions.
"""
self._async_queue.put(_WorkItem(
callback_on_success=on_success,
callback_on_error=on_error,
callback_when_idle=when_idle,
callback_args=cb_args,
callback_kwargs=cb_kwargs,
method=self.graphql,
args=(query,),
kwargs={'query_vars': query_vars}
))
|
Perform an asynchronous RPC GraphQL query to the server. This will queue
a work item for a thread to issue the RPC call and then specifies the
behavior for completion. See :ref:`Asynchronous Methods
<client-rpc-async-methods>` for more information.
.. versionadded:: 1.14.0
:param str query: The GraphQL query string to execute asynchronously.
:param dict query_vars: Any variable definitions required by the GraphQL
query.
:param on_success: A callback function to be called after the RPC method
returns successfully.
:param on_error: A callback function to be called if the RPC method
raises an exception.
:param when_idle: Whether or not the *on_success* and *on_error*
callback functions should be called from the main GUI thread while
it is idle.
:param cb_args: The arguments to the *on_success* and *on_error*
callback functions.
:param cb_kwargs: The keyword arguments to the *on_success* and
*on_error* callback functions.
|
async_graphql
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/client_rpc.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/client_rpc.py
|
BSD-3-Clause
|
def async_graphql_file(self, file_or_path, *args, **kwargs):
"""
Perform an asynchronous RPC GraphQL query from a file on the server.
This will queue a work item for a thread to issue the RPC call and then
specifies the behavior for completion. See :ref:`Asynchronous Methods
<client-rpc-async-methods>` for more information.
.. versionadded:: 1.14.0
:param file_or_path: The file object or path to the file from which to read.
"""
query = _graphql_file(file_or_path)
return self.async_graphql(query, *args, **kwargs)
|
Perform an asynchronous RPC GraphQL query from a file on the server.
This will queue a work item for a thread to issue the RPC call and then
specifies the behavior for completion. See :ref:`Asynchronous Methods
<client-rpc-async-methods>` for more information.
.. versionadded:: 1.14.0
:param file_or_path: The file object or path to the file from which to read.
|
async_graphql_file
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/client_rpc.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/client_rpc.py
|
BSD-3-Clause
|
def graphql(self, query, query_vars=None):
"""
Execute a GraphQL query on the server and return the results. This will
raise :py:exc:`~king_phisher.errors.KingPhisherGraphQLQueryError` if
the query fails.
:param str query: The GraphQL query string to execute.
:param query_vars: Any variable definitions required by the GraphQL
*query*.
:return: The query results.
:rtype: dict
"""
response = self.call('graphql', query, query_vars=query_vars)
if response['errors']:
raise errors.KingPhisherGraphQLQueryError(
'the query failed',
errors=response['errors'],
query=query,
query_vars=query_vars
)
return response['data']
|
Execute a GraphQL query on the server and return the results. This will
raise :py:exc:`~king_phisher.errors.KingPhisherGraphQLQueryError` if
the query fails.
:param str query: The GraphQL query string to execute.
:param query_vars: Any variable definitions required by the GraphQL
*query*.
:return: The query results.
:rtype: dict
|
graphql
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/client_rpc.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/client_rpc.py
|
BSD-3-Clause
|
def graphql_file(self, file_or_path, query_vars=None):
"""
This method wraps :py:meth:`~.graphql` to provide a convenient way to
execute GraphQL queries from files.
:param file_or_path: The file object or path to the file from which to read.
:param query_vars: The variables for *query*.
:return: The query results.
:rtype: dict
"""
query = _graphql_file(file_or_path)
return self.graphql(query, query_vars=query_vars)
|
This method wraps :py:meth:`~.graphql` to provide a convenient way to
execute GraphQL queries from files.
:param file_or_path: The file object or path to the file from which to read.
:param query_vars: The variables for *query*.
:return: The query results.
:rtype: dict
|
graphql_file
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/client_rpc.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/client_rpc.py
|
BSD-3-Clause
|
def graphql_find_file(self, query_file, **query_vars):
"""
This method is similar to :py:meth:`~.graphql_file`. The first argument
(*query_file*) is the name of a query file that will be located using
:py:func:`find.data_file`. Additional keyword arguments are passed as
the variables to the query.
:param str query_file: The name of the query file to locate.
:param query_vars: These keyword arguments are passed as the variables to the query.
:return: The query results.
:rtype: dict
"""
query = _graphql_find_file(query_file)
return self.graphql(query, query_vars=query_vars)
|
This method is similar to :py:meth:`~.graphql_file`. The first argument
(*query_file*) is the name of a query file that will be located using
:py:func:`find.data_file`. Additional keyword arguments are passed as
the variables to the query.
:param str query_file: The name of the query file to locate.
:param query_vars: These keyword arguments are passed as the variables to the query.
:return: The query results.
:rtype: dict
|
graphql_find_file
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/client_rpc.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/client_rpc.py
|
BSD-3-Clause
|
def remote_row_resolve(self, row):
"""
Take a :py:class:`~.RemoteRow` instance and load all fields which are
:py:data:`~.UNRESOLVED`. If all fields are present, no modifications
are made.
:param row: The row who's data is to be resolved.
:rtype: :py:class:`~.RemoteRow`
:return: The row with all of it's fields fully resolved.
:rtype: :py:class:`~.RemoteRow`
"""
utilities.assert_arg_type(row, RemoteRow)
slots = getattr(row, '__slots__')[1:]
if not any(prop for prop in slots if getattr(row, prop) is UNRESOLVED):
return row
for key, value in self.call('db/table/get', getattr(row, '__table__'), row.id).items():
setattr(row, key, value)
return row
|
Take a :py:class:`~.RemoteRow` instance and load all fields which are
:py:data:`~.UNRESOLVED`. If all fields are present, no modifications
are made.
:param row: The row who's data is to be resolved.
:rtype: :py:class:`~.RemoteRow`
:return: The row with all of it's fields fully resolved.
:rtype: :py:class:`~.RemoteRow`
|
remote_row_resolve
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/client_rpc.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/client_rpc.py
|
BSD-3-Clause
|
def remote_table(self, table, query_filter=None):
"""
Iterate over a remote database table hosted on the server. Rows are
yielded as named tuples whose fields are the columns of the specified
table.
:param str table: The table name to retrieve.
:return: A generator which yields rows of named tuples.
:rtype: tuple
"""
page = 0
results = self.call('db/table/view', table, page, query_filter=query_filter)
if results is None:
return
results_length = len(results['rows'])
row_cls = database_table_objects[table]
while results:
for row in results['rows']:
row = dict(zip(results['columns'], row))
yield row_cls(self, **row)
page += 1
if 'page_size' in results and 'total_rows' in results:
if results['page_size'] * page >= results['total_rows']:
break
if len(results['rows']) < results_length:
break
results = self.call('db/table/view', table, page, query_filter=query_filter)
|
Iterate over a remote database table hosted on the server. Rows are
yielded as named tuples whose fields are the columns of the specified
table.
:param str table: The table name to retrieve.
:return: A generator which yields rows of named tuples.
:rtype: tuple
|
remote_table
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/client_rpc.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/client_rpc.py
|
BSD-3-Clause
|
def remote_table_row(self, table, row_id, cache=False, refresh=False):
"""
Get a row from the specified table by it's id, optionally caching it.
:param str table: The table in which the row exists.
:param row_id: The value of the row's id column.
:param bool cache: Whether to use the cache for this row.
:param bool refresh: If *cache* is True, get the current row value and store it.
:return: The remote row as a named tuple of the specified table.
:rtype: tuple
"""
if cache and refresh:
row = self.cache_call_refresh('db/table/get', table, row_id)
elif cache and not refresh:
row = self.cache_call('db/table/get', table, row_id)
else:
row = self.call('db/table/get', table, row_id)
if row is None:
return None
row_cls = database_table_objects[table]
return row_cls(self, **row)
|
Get a row from the specified table by it's id, optionally caching it.
:param str table: The table in which the row exists.
:param row_id: The value of the row's id column.
:param bool cache: Whether to use the cache for this row.
:param bool refresh: If *cache* is True, get the current row value and store it.
:return: The remote row as a named tuple of the specified table.
:rtype: tuple
|
remote_table_row
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/client_rpc.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/client_rpc.py
|
BSD-3-Clause
|
def geoip_lookup(self, ip):
"""
Look up the geographic location information for the specified IP
address in the server's geoip database.
:param ip: The IP address to lookup.
:type ip: :py:class:`ipaddress.IPv4Address`, str
:return: The geographic location information for the specified IP address.
:rtype: :py:class:`~king_phisher.geoip.GeoLocation`
"""
result = self.cache_call('geoip/lookup', str(ip))
if result:
result = geoip.GeoLocation(ip, result=result)
return result
|
Look up the geographic location information for the specified IP
address in the server's geoip database.
:param ip: The IP address to lookup.
:type ip: :py:class:`ipaddress.IPv4Address`, str
:return: The geographic location information for the specified IP address.
:rtype: :py:class:`~king_phisher.geoip.GeoLocation`
|
geoip_lookup
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/client_rpc.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/client_rpc.py
|
BSD-3-Clause
|
def geoip_lookup_multi(self, ips):
"""
Look up the geographic location information for the specified IP
addresses in the server's geoip database. Because results are cached
for optimal performance, IP addresses to be queried should be grouped
and sorted in a way that is unlikely to change, i.e. by a timestamp.
:param ips: The IP addresses to lookup.
:type ips: list, set, tuple
:return: The geographic location information for the specified IP address.
:rtype: dict
"""
ips = [str(ip) for ip in ips]
results = self.cache_call('geoip/lookup/multi', ips)
for ip, data in results.items():
results[ip] = geoip.GeoLocation(ip, result=data)
return results
|
Look up the geographic location information for the specified IP
addresses in the server's geoip database. Because results are cached
for optimal performance, IP addresses to be queried should be grouped
and sorted in a way that is unlikely to change, i.e. by a timestamp.
:param ips: The IP addresses to lookup.
:type ips: list, set, tuple
:return: The geographic location information for the specified IP address.
:rtype: dict
|
geoip_lookup_multi
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/client_rpc.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/client_rpc.py
|
BSD-3-Clause
|
def get_tag_model(self, tag_table, model=None):
"""
Load tag information from a remote table into a
:py:class:`Gtk.ListStore` instance. Tables compatible with the tag
interface must have id, name and description fields. If no *model* is
provided a new one will be created, else the current model will be
cleared.
:param str tag_table: The name of the table to load tag information from.
:param model: The model to place the information into.
:type model: :py:class:`Gtk.ListStore`
:return: The model with the loaded data from the server.
:rtype: :py:class:`Gtk.ListStore`
"""
if tag_table not in _tag_tables:
raise ValueError('tag_table is not a valid tag interface exposing table')
tag_table = smoke_zephyr.utilities.parse_case_snake_to_camel(tag_table, upper_first=False)
if model is None:
model = Gtk.ListStore(str, str, str)
# sort by the name column, ascending
model.set_sort_column_id(1, Gtk.SortType.ASCENDING)
else:
model.clear()
graphql_query = 'query getTags { db { ' + tag_table + ' { edges { node { id name description } } } } }'
tags = self.graphql(graphql_query)['db'][tag_table]['edges']
for tag in tags:
tag = tag['node']
model.append((tag['id'], tag['name'], tag['description']))
return model
|
Load tag information from a remote table into a
:py:class:`Gtk.ListStore` instance. Tables compatible with the tag
interface must have id, name and description fields. If no *model* is
provided a new one will be created, else the current model will be
cleared.
:param str tag_table: The name of the table to load tag information from.
:param model: The model to place the information into.
:type model: :py:class:`Gtk.ListStore`
:return: The model with the loaded data from the server.
:rtype: :py:class:`Gtk.ListStore`
|
get_tag_model
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/client_rpc.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/client_rpc.py
|
BSD-3-Clause
|
def login(self, username, password, otp=None):
"""
Authenticate to the remote server. This is required before calling RPC
methods which require an authenticated session.
:param str username: The username to authenticate with.
:param str password: The password to authenticate with.
:param str otp: An optional one time password as a 6 digit string to provide if the account requires it.
:return: The login result and an accompanying reason.
:rtype: tuple
"""
login_result, login_reason, login_session = self.call('login', username, password, otp)
if login_result:
if self.headers is None:
self.headers = {}
self.headers['X-RPC-Auth'] = login_session
return login_result, login_reason
|
Authenticate to the remote server. This is required before calling RPC
methods which require an authenticated session.
:param str username: The username to authenticate with.
:param str password: The password to authenticate with.
:param str otp: An optional one time password as a 6 digit string to provide if the account requires it.
:return: The login result and an accompanying reason.
:rtype: tuple
|
login
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/client_rpc.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/client_rpc.py
|
BSD-3-Clause
|
def vte_child_routine(config):
"""
This is the method which is executed within the child process spawned
by VTE. It expects additional values to be set in the *config*
object so it can initialize a new :py:class:`.KingPhisherRPCClient`
instance. It will then drop into an interpreter where the user may directly
interact with the rpc object.
:param str config: A JSON encoded client configuration.
"""
config = serializers.JSON.loads(config)
try:
import readline
import rlcompleter # pylint: disable=unused-variable
except ImportError:
has_readline = False
else:
has_readline = True
try:
import IPython.terminal.embed
except ImportError:
has_ipython = False
else:
has_ipython = True
for plugins_directory in ('rpc_plugins', 'rpc-plugins'):
plugins_directory = find.data_directory(plugins_directory)
if not plugins_directory:
continue
sys.path.append(plugins_directory)
headers = config['rpc_data'].pop('headers')
rpc = KingPhisherRPCClient(**config['rpc_data'])
if rpc.headers is None:
rpc.headers = {}
for name, value in headers.items():
rpc.headers[str(name)] = str(value)
user_data_path = config['user_data_path']
sys.path.append(config['user_library_path'])
print("Python {0} on {1}".format(sys.version, sys.platform)) # pylint: disable=superfluous-parens
print("Campaign Name: '{0}' ID: {1}".format(config['campaign_name'], config['campaign_id'])) # pylint: disable=superfluous-parens
print('The \'rpc\' object holds the connected KingPhisherRPCClient instance')
console_vars = {
'CAMPAIGN_NAME': config['campaign_name'],
'CAMPAIGN_ID': config['campaign_id'],
'os': os,
'rpc': rpc,
'sys': sys
}
if has_ipython:
console = IPython.terminal.embed.InteractiveShellEmbed(ipython_dir=os.path.join(user_data_path, 'ipython'))
console.register_magic_function(functools.partial(_magic_graphql, rpc, 'query'), 'line', 'graphql')
console.register_magic_function(functools.partial(_magic_graphql, rpc, 'file'), 'line', 'graphql_file')
console.mainloop(console_vars)
else:
if has_readline:
readline.parse_and_bind('tab: complete')
console = code.InteractiveConsole(console_vars)
for var in tuple(console_vars.keys()):
console.push("__builtins__['{0}'] = {0}".format(var))
console.interact('')
return
|
This is the method which is executed within the child process spawned
by VTE. It expects additional values to be set in the *config*
object so it can initialize a new :py:class:`.KingPhisherRPCClient`
instance. It will then drop into an interpreter where the user may directly
interact with the rpc object.
:param str config: A JSON encoded client configuration.
|
vte_child_routine
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/client_rpc.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/client_rpc.py
|
BSD-3-Clause
|
def convert_value(table_name, key, value):
"""
Perform any conversions necessary to neatly display the data in XML format.
:param str table_name: The table name that the key and value pair are from.
:param str key: The data key.
:param value: The data value to convert.
:return: The converted value.
:rtype: str
"""
if isinstance(value, datetime.datetime):
value = value.isoformat()
if value is not None:
value = str(value)
return value
|
Perform any conversions necessary to neatly display the data in XML format.
:param str table_name: The table name that the key and value pair are from.
:param str key: The data key.
:param value: The data value to convert.
:return: The converted value.
:rtype: str
|
convert_value
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/export.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/export.py
|
BSD-3-Clause
|
def campaign_to_xml(rpc, campaign_id, xml_file, encoding='utf-8'):
"""
Load all information for a particular campaign and dump it to an XML file.
:param rpc: The connected RPC instance to load the information with.
:type rpc: :py:class:`.KingPhisherRPCClient`
:param campaign_id: The ID of the campaign to load the information for.
:param str xml_file: The destination file for the XML data.
:param str encoding: The encoding to use for strings.
"""
tzutc = dateutil.tz.tzutc()
root = ET.Element('king_phisher')
# Generate export metadata
metadata = ET.SubElement(root, 'metadata')
serializers.to_elementtree_subelement(
metadata,
'timestamp',
datetime.datetime.utcnow().replace(tzinfo=tzutc),
attrib={'utc': 'true'}
)
serializers.to_elementtree_subelement(metadata, 'version', '1.3')
campaign = ET.SubElement(root, 'campaign')
logger.info('gathering campaign information for export')
page_size = 1000
try:
campaign_info = rpc.graphql_find_file('get_campaign_export.graphql', id=campaign_id, page=page_size)['db']['campaign']
except errors.KingPhisherGraphQLQueryError as error:
logger.error('graphql error: ' + error.message)
raise
for key, value in campaign_info.items():
if key in ('landingPages', 'messages', 'visits', 'credentials', 'deaddropDeployments', 'deaddropConnections'):
continue
if isinstance(value, datetime.datetime):
value = value.replace(tzinfo=tzutc)
serializers.to_elementtree_subelement(campaign, key, value)
table_elements = {}
while True:
cursor = None # set later if any table hasNextPage
for table_name in ('landing_pages', 'messages', 'visits', 'credentials', 'deaddrop_deployments', 'deaddrop_connections'):
gql_table_name = parse_case_snake_to_camel(table_name, upper_first=False)
if campaign_info[gql_table_name]['pageInfo']['hasNextPage']:
cursor = campaign_info[gql_table_name]['pageInfo']['endCursor']
table = campaign_info[gql_table_name]['edges']
if table_name not in table_elements:
table_elements[table_name] = ET.SubElement(campaign, table_name)
for node in table:
table_row_element = ET.SubElement(table_elements[table_name], table_name[:-1])
for key, value in node['node'].items():
if isinstance(value, datetime.datetime):
value = value.replace(tzinfo=tzutc)
serializers.to_elementtree_subelement(table_row_element, key, value)
if cursor is None:
break
campaign_info = rpc.graphql_find_file('get_campaign_export.graphql', id=campaign_id, cursor=cursor, page=page_size)['db']['campaign']
logger.info('completed processing campaign information for export')
document = minidom.parseString(ET.tostring(root))
with open(xml_file, 'wb') as file_h:
file_h.write(document.toprettyxml(indent=' ', encoding=encoding))
logger.info('campaign export complete')
|
Load all information for a particular campaign and dump it to an XML file.
:param rpc: The connected RPC instance to load the information with.
:type rpc: :py:class:`.KingPhisherRPCClient`
:param campaign_id: The ID of the campaign to load the information for.
:param str xml_file: The destination file for the XML data.
:param str encoding: The encoding to use for strings.
|
campaign_to_xml
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/export.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/export.py
|
BSD-3-Clause
|
def campaign_credentials_to_msf_txt(rpc, campaign_id, target_file):
"""
Export credentials into a format that can easily be used with Metasploit's
USERPASS_FILE option.
:param rpc: The connected RPC instance to load the information with.
:type rpc: :py:class:`.KingPhisherRPCClient`
:param campaign_id: The ID of the campaign to load the information for.
:param str target_file: The destination file for the credential data.
"""
with open(target_file, 'w') as file_h:
for credential_node in _get_graphql_campaign_credentials(rpc, campaign_id):
credential = credential_node['node']
file_h.write("{0} {1}\n".format(credential['username'], credential['password']))
|
Export credentials into a format that can easily be used with Metasploit's
USERPASS_FILE option.
:param rpc: The connected RPC instance to load the information with.
:type rpc: :py:class:`.KingPhisherRPCClient`
:param campaign_id: The ID of the campaign to load the information for.
:param str target_file: The destination file for the credential data.
|
campaign_credentials_to_msf_txt
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/export.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/export.py
|
BSD-3-Clause
|
def campaign_visits_to_geojson(rpc, campaign_id, geojson_file):
"""
Export the geo location information for all the visits of a campaign into
the `GeoJSON <http://geojson.org/>`_ format.
:param rpc: The connected RPC instance to load the information with.
:type rpc: :py:class:`.KingPhisherRPCClient`
:param campaign_id: The ID of the campaign to load the information for.
:param str geojson_file: The destination file for the GeoJSON data.
"""
ips_for_georesolution = {}
ip_counter = collections.Counter()
for visit_node in _get_graphql_campaign_visits(rpc, campaign_id):
visit = visit_node['node']
ip_counter.update((visit['ip'],))
visitor_ip = ipaddress.ip_address(visit['ip'])
if not isinstance(visitor_ip, ipaddress.IPv4Address):
continue
if visitor_ip.is_loopback or visitor_ip.is_private:
continue
if not visitor_ip in ips_for_georesolution:
ips_for_georesolution[visitor_ip] = visit['firstSeen']
elif ips_for_georesolution[visitor_ip] > visit['firstSeen']:
ips_for_georesolution[visitor_ip] = visit['firstSeen']
ips_for_georesolution = [ip for (ip, _) in sorted(ips_for_georesolution.items(), key=lambda x: x[1])]
locations = {}
for ip_addresses in iterutils.chunked(ips_for_georesolution, 50):
locations.update(rpc.geoip_lookup_multi(ip_addresses))
points = []
for ip, location in locations.items():
if not (location.coordinates and location.coordinates[0] and location.coordinates[1]):
continue
points.append(geojson.Feature(geometry=location, properties={'count': ip_counter[ip], 'ip-address': ip}))
feature_collection = geojson.FeatureCollection(points)
with open(geojson_file, 'w') as file_h:
serializers.JSON.dump(feature_collection, file_h, pretty=True)
|
Export the geo location information for all the visits of a campaign into
the `GeoJSON <http://geojson.org/>`_ format.
:param rpc: The connected RPC instance to load the information with.
:type rpc: :py:class:`.KingPhisherRPCClient`
:param campaign_id: The ID of the campaign to load the information for.
:param str geojson_file: The destination file for the GeoJSON data.
|
campaign_visits_to_geojson
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/export.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/export.py
|
BSD-3-Clause
|
def message_data_from_kpm(target_file, dest_dir, encoding='utf-8'):
"""
Retrieve the stored details describing a message from a previously exported
file.
:param str target_file: The file to load as a message archive.
:param str dest_dir: The directory to extract data and attachment files to.
:param str encoding: The encoding to use for strings.
:return: The restored details from the message config.
:rtype: dict
"""
if not archive.is_archive(target_file):
logger.warning('the file is not recognized as a valid archive')
raise errors.KingPhisherInputValidationError('file is not in the correct format')
kpm = archive.ArchiveFile(target_file, 'r')
attachment_member_names = [n for n in kpm.file_names if n.startswith('attachments' + os.path.sep)]
attachments = []
if not kpm.has_file('message_config.json'):
logger.warning('the kpm archive is missing the message_config.json file')
raise errors.KingPhisherInputValidationError('data is missing from the message archive')
message_config = kpm.get_json('message_config.json')
message_config.pop('company_name', None)
if attachment_member_names:
attachment_dir = os.path.join(dest_dir, 'attachments')
if not os.path.isdir(attachment_dir):
os.mkdir(attachment_dir)
for file_name in attachment_member_names:
arcfile_h = kpm.get_file(file_name)
file_path = os.path.join(attachment_dir, os.path.basename(file_name))
with open(file_path, 'wb') as file_h:
shutil.copyfileobj(arcfile_h, file_h)
attachments.append(file_path)
logger.debug("extracted {0} attachment file{1} from the archive".format(len(attachments), 's' if len(attachments) > 1 else ''))
for config_name, file_name in KPM_ARCHIVE_FILES.items():
if not file_name in kpm.file_names:
if config_name in message_config:
logger.warning("the kpm archive is missing the {0} file".format(file_name))
raise errors.KingPhisherInputValidationError('data is missing from the message archive')
continue
if not message_config.get(config_name):
logger.warning("the kpm message configuration is missing the {0} setting".format(config_name))
raise errors.KingPhisherInputValidationError('data is missing from the message archive')
arcfile_h = kpm.get_file(file_name)
file_path = os.path.join(dest_dir, os.path.basename(message_config[config_name]))
with open(file_path, 'wb') as file_h:
shutil.copyfileobj(arcfile_h, file_h)
message_config[config_name] = file_path
if 'message_content.html' in kpm.file_names:
if 'html_file' not in message_config:
logger.warning('the kpm message configuration is missing the html_file setting')
raise errors.KingPhisherInputValidationError('data is missing from the message archive')
arcfile_h = kpm.get_file('message_content.html')
file_path = os.path.join(dest_dir, os.path.basename(message_config['html_file']))
with open(file_path, 'wb') as file_h:
file_h.write(message_template_from_kpm(arcfile_h.read().decode(encoding), attachments).encode(encoding))
message_config['html_file'] = file_path
elif 'html_file' in message_config:
logger.warning('the kpm archive is missing the message_content.html file')
raise errors.KingPhisherInputValidationError('data is missing from the message archive')
kpm.close()
return message_config
|
Retrieve the stored details describing a message from a previously exported
file.
:param str target_file: The file to load as a message archive.
:param str dest_dir: The directory to extract data and attachment files to.
:param str encoding: The encoding to use for strings.
:return: The restored details from the message config.
:rtype: dict
|
message_data_from_kpm
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/export.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/export.py
|
BSD-3-Clause
|
def message_data_to_kpm(message_config, target_file, encoding='utf-8'):
"""
Save details describing a message to the target file.
:param dict message_config: The message details from the client configuration.
:param str target_file: The file to write the data to.
:param str encoding: The encoding to use for strings.
"""
message_config = copy.copy(message_config)
kpm = archive.ArchiveFile(target_file, 'w')
for config_name, file_name in KPM_ARCHIVE_FILES.items():
if os.access(message_config.get(config_name, ''), os.R_OK):
kpm.add_file(file_name, message_config[config_name])
message_config[config_name] = os.path.basename(message_config[config_name])
continue
if len(message_config.get(config_name, '')):
logger.info("the specified {0} '{1}' is not readable, the setting will be removed".format(config_name, message_config[config_name]))
if config_name in message_config:
del message_config[config_name]
if os.access(message_config.get('html_file', ''), os.R_OK):
with codecs.open(message_config['html_file'], 'r', encoding=encoding) as file_h:
template = file_h.read()
message_config['html_file'] = os.path.basename(message_config['html_file'])
template, attachments = message_template_to_kpm(template)
logger.debug("identified {0} attachment file{1} to be archived".format(len(attachments), 's' if len(attachments) > 1 else ''))
kpm.add_data('message_content.html', template)
for attachment in attachments:
if os.access(attachment, os.R_OK):
kpm.add_file(os.path.join('attachments', os.path.basename(attachment)), attachment)
else:
if len(message_config.get('html_file', '')):
logger.info("the specified html_file '{0}' is not readable, the setting will be removed".format(message_config['html_file']))
if 'html_file' in message_config:
del message_config['html_file']
kpm.add_data('message_config.json', serializers.JSON.dumps(message_config, pretty=True))
kpm.close()
return
|
Save details describing a message to the target file.
:param dict message_config: The message details from the client configuration.
:param str target_file: The file to write the data to.
:param str encoding: The encoding to use for strings.
|
message_data_to_kpm
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/export.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/export.py
|
BSD-3-Clause
|
def liststore_export(store, columns, cb_write, cb_write_args, row_offset=0, write_columns=True):
"""
A function to facilitate writing values from a list store to an arbitrary
callback for exporting to different formats. The callback will be called
with the row number, the column values and the additional arguments
specified in *\\*cb_write_args*.
.. code-block:: python
cb_write(row, column_values, *cb_write_args).
:param store: The store to export the information from.
:type store: :py:class:`Gtk.ListStore`
:param dict columns: A dictionary mapping store column ids to the value names.
:param function cb_write: The callback function to be called for each row of data.
:param tuple cb_write_args: Additional arguments to pass to *cb_write*.
:param int row_offset: A modifier value to add to the row numbers passed to *cb_write*.
:param bool write_columns: Write the column names to the export.
:return: The number of rows that were written.
:rtype: int
"""
column_names, store_columns = _split_columns(columns)
if write_columns:
cb_write(0, column_names, *cb_write_args)
store_iter = store.get_iter_first()
rows_written = 0
while store_iter:
row = collections.deque()
for column in store_columns:
value = store.get_value(store_iter, column)
if isinstance(value, datetime.datetime):
value = utilities.format_datetime(value)
row.append(value)
cb_write(rows_written + 1 + row_offset, row, *cb_write_args)
rows_written += 1
store_iter = store.iter_next(store_iter)
return rows_written
|
A function to facilitate writing values from a list store to an arbitrary
callback for exporting to different formats. The callback will be called
with the row number, the column values and the additional arguments
specified in *\*cb_write_args*.
.. code-block:: python
cb_write(row, column_values, *cb_write_args).
:param store: The store to export the information from.
:type store: :py:class:`Gtk.ListStore`
:param dict columns: A dictionary mapping store column ids to the value names.
:param function cb_write: The callback function to be called for each row of data.
:param tuple cb_write_args: Additional arguments to pass to *cb_write*.
:param int row_offset: A modifier value to add to the row numbers passed to *cb_write*.
:param bool write_columns: Write the column names to the export.
:return: The number of rows that were written.
:rtype: int
|
liststore_export
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/export.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/export.py
|
BSD-3-Clause
|
def liststore_to_csv(store, target_file, columns):
"""
Write the contents of a :py:class:`Gtk.ListStore` to a csv file.
:param store: The store to export the information from.
:type store: :py:class:`Gtk.ListStore`
:param str target_file: The destination file for the CSV data.
:param dict columns: A dictionary mapping store column ids to the value names.
:return: The number of rows that were written.
:rtype: int
"""
target_file_h = open(target_file, 'w')
writer = csv.writer(target_file_h, quoting=csv.QUOTE_ALL)
rows = liststore_export(store, columns, _csv_write, (writer,))
target_file_h.close()
return rows
|
Write the contents of a :py:class:`Gtk.ListStore` to a csv file.
:param store: The store to export the information from.
:type store: :py:class:`Gtk.ListStore`
:param str target_file: The destination file for the CSV data.
:param dict columns: A dictionary mapping store column ids to the value names.
:return: The number of rows that were written.
:rtype: int
|
liststore_to_csv
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/export.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/export.py
|
BSD-3-Clause
|
def liststore_to_xlsx_worksheet(store, worksheet, columns, title_format, xlsx_options=None):
"""
Write the contents of a :py:class:`Gtk.ListStore` to an XLSX worksheet.
:param store: The store to export the information from.
:type store: :py:class:`Gtk.ListStore`
:param worksheet: The destination sheet for the store's data.
:type worksheet: :py:class:`xlsxwriter.worksheet.Worksheet`
:param dict columns: A dictionary mapping store column ids to the value names.
:param xlsx_options: A collection of additional options for formatting the Excel Worksheet.
:type xlsx_options: :py:class:`.XLSXWorksheetOptions`
:return: The number of rows that were written.
:rtype: int
"""
utilities.assert_arg_type(worksheet, xlsxwriter.worksheet.Worksheet, 2)
utilities.assert_arg_type(columns, dict, 3)
utilities.assert_arg_type(title_format, xlsxwriter.format.Format, 4)
utilities.assert_arg_type(xlsx_options, (type(None), XLSXWorksheetOptions), 5)
if xlsx_options is None:
worksheet.set_column(0, len(columns), 30)
else:
for column, width in enumerate(xlsx_options.column_widths):
worksheet.set_column(column, column, width)
column_names, _ = _split_columns(columns)
if xlsx_options is None:
start_row = 0
else:
start_row = 2
worksheet.merge_range(0, 0, 0, len(column_names) - 1, xlsx_options.title, title_format)
row_count = liststore_export(store, columns, _xlsx_write, (worksheet,), row_offset=start_row, write_columns=False)
if not row_count:
column_ = 0
for column_name in column_names:
worksheet.write(start_row, column_, column_name)
column_ += 1
return row_count
options = {
'columns': list({'header': column_name} for column_name in column_names),
'style': 'Table Style Medium 1'
}
worksheet.add_table(start_row, 0, row_count + start_row, len(column_names) - 1, options=options)
worksheet.freeze_panes(1 + start_row, 0)
return row_count
|
Write the contents of a :py:class:`Gtk.ListStore` to an XLSX worksheet.
:param store: The store to export the information from.
:type store: :py:class:`Gtk.ListStore`
:param worksheet: The destination sheet for the store's data.
:type worksheet: :py:class:`xlsxwriter.worksheet.Worksheet`
:param dict columns: A dictionary mapping store column ids to the value names.
:param xlsx_options: A collection of additional options for formatting the Excel Worksheet.
:type xlsx_options: :py:class:`.XLSXWorksheetOptions`
:return: The number of rows that were written.
:rtype: int
|
liststore_to_xlsx_worksheet
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/export.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/export.py
|
BSD-3-Clause
|
def export_graph_provider(cls):
"""
Decorator to mark classes as valid graph providers. This decorator also sets
the :py:attr:`~.CampaignGraph.name` attribute.
:param class cls: The class to mark as a graph provider.
:return: The *cls* parameter is returned.
"""
if not issubclass(cls, CampaignGraph):
raise RuntimeError("{0} is not a subclass of CampaignGraph".format(cls.__name__))
if not cls.is_available:
return None
graph_name = cls.__name__[13:]
cls.name = graph_name
EXPORTED_GRAPHS[graph_name] = cls
return cls
|
Decorator to mark classes as valid graph providers. This decorator also sets
the :py:attr:`~.CampaignGraph.name` attribute.
:param class cls: The class to mark as a graph provider.
:return: The *cls* parameter is returned.
|
export_graph_provider
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/graphs.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/graphs.py
|
BSD-3-Clause
|
def __init__(self, application, size_request=None, style_context=None):
"""
:param tuple size_request: The size to set for the canvas.
"""
self.logger = logging.getLogger('KingPhisher.Client.Graph.' + self.__class__.__name__[13:])
self.application = application
self.style_context = style_context
self.config = application.config
"""A reference to the King Phisher client configuration."""
self.figure, _ = pyplot.subplots()
self.figure.set_facecolor(self.get_color('bg', ColorHexCode.WHITE))
self.axes = self.figure.get_axes()
self.canvas = FigureCanvas(self.figure)
self.manager = None
self.minimum_size = (380, 200)
"""An absolute minimum size for the canvas."""
if size_request is not None:
self.resize(*size_request)
self.canvas.mpl_connect('button_press_event', self.mpl_signal_canvas_button_pressed)
self.canvas.show()
self.navigation_toolbar = NavigationToolbar(self.canvas, self.application.get_active_window())
self.popup_menu = managers.MenuManager()
self.popup_menu.append('Export', self.signal_activate_popup_menu_export)
self.popup_menu.append('Refresh', self.signal_activate_popup_refresh)
menu_item = Gtk.CheckMenuItem.new_with_label('Show Toolbar')
menu_item.connect('toggled', self.signal_toggled_popup_menu_show_toolbar)
self._menu_item_show_toolbar = menu_item
self.popup_menu.append_item(menu_item)
self.navigation_toolbar.hide()
self._legend = None
|
:param tuple size_request: The size to set for the canvas.
|
__init__
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/graphs.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/graphs.py
|
BSD-3-Clause
|
def get_color(self, color_name, default):
"""
Get a color by its style name such as 'fg' for foreground. If the
specified color does not exist, default will be returned. The underlying
logic for this function is provided by
:py:func:`~.gui_utilities.gtk_style_context_get_color`.
:param str color_name: The style name of the color.
:param default: The default color to return if the specified one was not found.
:return: The desired color if it was found.
:rtype: tuple
"""
color_name = 'theme_color_graph_' + color_name
sc_color = gui_utilities.gtk_style_context_get_color(self.style_context, color_name, default)
return (sc_color.red, sc_color.green, sc_color.blue)
|
Get a color by its style name such as 'fg' for foreground. If the
specified color does not exist, default will be returned. The underlying
logic for this function is provided by
:py:func:`~.gui_utilities.gtk_style_context_get_color`.
:param str color_name: The style name of the color.
:param default: The default color to return if the specified one was not found.
:return: The desired color if it was found.
:rtype: tuple
|
get_color
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/graphs.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/graphs.py
|
BSD-3-Clause
|
def make_window(self):
"""
Create a window from the figure manager.
:return: The graph in a new, dedicated window.
:rtype: :py:class:`Gtk.Window`
"""
if self.manager is None:
self.manager = FigureManager(self.canvas, 0)
self.navigation_toolbar.destroy()
self.navigation_toolbar = self.manager.toolbar
self._menu_item_show_toolbar.set_active(True)
window = self.manager.window
window.set_transient_for(self.application.get_active_window())
window.set_title(self.graph_title)
return window
|
Create a window from the figure manager.
:return: The graph in a new, dedicated window.
:rtype: :py:class:`Gtk.Window`
|
make_window
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/graphs.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/graphs.py
|
BSD-3-Clause
|
def resize(self, width=0, height=0):
"""
Attempt to resize the canvas. Regardless of the parameters the canvas
will never be resized to be smaller than :py:attr:`.minimum_size`.
:param int width: The desired width of the canvas.
:param int height: The desired height of the canvas.
"""
min_width, min_height = self.minimum_size
width = max(width, min_width)
height = max(height, min_height)
self.canvas.set_size_request(width, height)
|
Attempt to resize the canvas. Regardless of the parameters the canvas
will never be resized to be smaller than :py:attr:`.minimum_size`.
:param int width: The desired width of the canvas.
:param int height: The desired height of the canvas.
|
resize
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/graphs.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/graphs.py
|
BSD-3-Clause
|
def refresh(self, info_cache=None, stop_event=None):
"""
Refresh the graph data by retrieving the information from the
remote server.
:param dict info_cache: An optional cache of data tables.
:param stop_event: An optional object indicating that the operation should stop.
:type stop_event: :py:class:`threading.Event`
:return: A dictionary of cached tables from the server.
:rtype: dict
"""
info_cache = (info_cache or {})
if not self.rpc:
return info_cache
if stop_event and stop_event.is_set():
return info_cache
if not info_cache:
info_cache = self._get_graphql_campaign_cache(self.config['campaign_id'])
for ax in self.axes:
ax.clear()
if self._legend is not None:
self._legend.remove()
self._legend = None
self._load_graph(info_cache)
self.figure.suptitle(
self.graph_title,
color=self.get_color('fg', ColorHexCode.BLACK),
size=14,
weight='bold',
y=0.97
)
self.canvas.draw()
return info_cache
|
Refresh the graph data by retrieving the information from the
remote server.
:param dict info_cache: An optional cache of data tables.
:param stop_event: An optional object indicating that the operation should stop.
:type stop_event: :py:class:`threading.Event`
:return: A dictionary of cached tables from the server.
:rtype: dict
|
refresh
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/graphs.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/graphs.py
|
BSD-3-Clause
|
def _barh_stacked(self, ax, bars, bar_colors, height):
"""
:param ax: This axis to use for the graph.
:param tuple bars: A two dimensional array of bars, and their respective stack sizes.
:param tuple bar_colors: A one dimensional array of colors for each of the stacks.
:param float height: The height of the bars.
:return:
"""
# define the necessary colors
ax.set_facecolor(self.get_color('bg', ColorHexCode.WHITE))
self.resize(height=60 + 20 * len(bars))
bar_count = len(bars)
columns = []
left_subbars = [0] * bar_count
columns.extend(zip(*bars))
for right_subbars, color, in zip(columns, bar_colors):
bar_container = ax.barh(
range(len(bars)),
right_subbars,
color=color,
height=height,
left=left_subbars,
linewidth=0,
)
left_subbars = _matrices_add(left_subbars, right_subbars)
return bar_container
|
:param ax: This axis to use for the graph.
:param tuple bars: A two dimensional array of bars, and their respective stack sizes.
:param tuple bar_colors: A one dimensional array of colors for each of the stacks.
:param float height: The height of the bars.
:return:
|
_barh_stacked
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/graphs.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/graphs.py
|
BSD-3-Clause
|
def graph_bar(self, bars, yticklabels, xlabel=None):
"""
Create a horizontal bar graph with better defaults for the standard use
cases.
:param list bars: The values of the bars to graph.
:param list yticklabels: The labels to use on the x-axis.
:param str xlabel: The label to give to the y-axis.
:return: The bars created using :py:mod:`matplotlib`
:rtype: `matplotlib.container.BarContainer`
"""
largest = (max(bars) if len(bars) else 0)
bars = [[cell, largest - cell] for cell in bars]
bar_colors = (self.get_color('bar_fg', ColorHexCode.BLACK), self.get_color('bar_bg', ColorHexCode.GRAY))
return self.graph_bar_stacked(bars, bar_colors, yticklabels, xlabel=xlabel)
|
Create a horizontal bar graph with better defaults for the standard use
cases.
:param list bars: The values of the bars to graph.
:param list yticklabels: The labels to use on the x-axis.
:param str xlabel: The label to give to the y-axis.
:return: The bars created using :py:mod:`matplotlib`
:rtype: `matplotlib.container.BarContainer`
|
graph_bar
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/graphs.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/graphs.py
|
BSD-3-Clause
|
def load_graph(self, campaigns):
"""
Load the information to compare the specified and paint it to the
canvas. Campaigns are graphed on the X-axis in the order that they are
provided. No sorting of campaigns is done by this method.
:param tuple campaigns: A tuple containing campaign IDs to compare.
"""
ax = self.axes[0]
ax2 = self.axes[1]
ax.clear()
ax2.clear()
self._config_axes(ax, ax2)
rpc = self.rpc
ellipsize = lambda text: (text if len(text) < 20 else text[:17] + '...')
visits_line_color = self.get_color('line_fg', ColorHexCode.RED)
creds_line_color = self.get_color('map_marker1', ColorHexCode.BLACK)
messages_color = '#046D8B'
trained_color = '#77c67f'
ax.grid(True)
ax.set_xticks(range(len(campaigns)))
ax.set_xticklabels([ellipsize(self._get_graphql_campaign_name(cid)) for cid in campaigns])
for tick in ax.xaxis.get_major_ticks():
tick.label.set_fontsize(self.markersize_scale * 1.25)
labels = ax.get_xticklabels()
pyplot.setp(labels, rotation=15)
self._campaigns = campaigns
campaigns = [rpc('/campaign/stats', cid) for cid in campaigns]
ax2.plot([stats['messages'] for stats in campaigns], label='Messages', color=messages_color, lw=3)
if sum(stats['messages-trained'] for stats in campaigns):
ax.plot([self._calc(stats, 'messages-trained', 'visits-unique') for stats in campaigns], label='Trained (Visited)', color=trained_color, lw=3)
ax.plot([self._calc(stats, 'messages-trained') for stats in campaigns], label='Trained (All)', color=trained_color, lw=3, ls='dashed')
ax.plot([self._calc(stats, 'visits') for stats in campaigns], label='Visits', color=visits_line_color, lw=3)
ax.plot([self._calc(stats, 'visits-unique') for stats in campaigns], label='Unique Visits', color=visits_line_color, lw=3, ls='dashed')
if sum(stats['credentials'] for stats in campaigns):
ax.plot([self._calc(stats, 'credentials') for stats in campaigns], label='Credentials', color=creds_line_color, lw=3)
ax.plot([self._calc(stats, 'credentials-unique') for stats in campaigns], label='Unique Credentials', color=creds_line_color, lw=3, ls='dashed')
ax.set_ylim((0, 100))
ax2.set_ylim(bottom=0)
self.canvas.set_size_request(500 + 50 * (len(campaigns) - 1), 500)
legend_patch = [
(visits_line_color, 'solid', 'Visits'),
(visits_line_color, 'dotted', 'Unique Visits')
]
if sum(stats['credentials'] for stats in campaigns):
legend_patch.extend([
(creds_line_color, 'solid', 'Credentials'),
(creds_line_color, 'dotted', 'Unique Credentials')
])
if sum(stats['messages-trained'] for stats in campaigns):
legend_patch.extend([
(trained_color, 'solid', 'Trained (Visited)'),
(trained_color, 'dotted', 'Trained (All)')
])
legend_patch.append(
(messages_color, 'solid', 'Messages')
)
self.add_legend_patch(legend_patch)
pyplot.tight_layout()
|
Load the information to compare the specified and paint it to the
canvas. Campaigns are graphed on the X-axis in the order that they are
provided. No sorting of campaigns is done by this method.
:param tuple campaigns: A tuple containing campaign IDs to compare.
|
load_graph
|
python
|
rsmusllp/king-phisher
|
king_phisher/client/graphs.py
|
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/client/graphs.py
|
BSD-3-Clause
|
def _cmp(item1, item2):
"""
Compare two arbitrary Python objects. The object types should either be the
same or one or both may be ``None``.
:rtype: int
:return: ``-1`` if *item1* is less than *item2*, ``0`` if they are equal or
``1`` if *item1* is greater than *item2*.
"""
if item1 is None:
return 0 if item2 is None else -1
if item2 is None:
return 1
return (item1 > item2) - (item1 < item2)
|
Compare two arbitrary Python objects. The object types should either be the
same or one or both may be ``None``.
:rtype: int
:return: ``-1`` if *item1* is less than *item2*, ``0`` if they are equal or
``1`` if *item1* is greater than *item2*.
|
_cmp
|
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 glib_idle_add_store_extend(store, things, clear=False, wait=False):
"""
Extend a GTK store object (either :py:class:`Gtk.ListStore` or
:py:class:`Gtk.TreeStore`) object using :py:func:`GLib.idle_add`. This
function is suitable for use in non-main GUI threads for synchronizing data.
:param store: The GTK storage object to add *things* to.
:type store: :py:class:`Gtk.ListStore`, :py:class:`Gtk.TreeStore`
:param tuple things: The array of things to add to *store*.
:param bool clear: Whether or not to clear the storage object before adding *things* to it.
:param bool wait: Whether or not to wait for the operation to complete before returning.
:return: Regardless of the *wait* parameter, ``None`` is returned.
:rtype: None
"""
if not isinstance(store, Gtk.ListStore):
raise TypeError('store must be a Gtk.ListStore instance')
idle_add = glib_idle_add_wait if wait else glib_idle_add_once
idle_add(_store_extend, store, things, clear)
|
Extend a GTK store object (either :py:class:`Gtk.ListStore` or
:py:class:`Gtk.TreeStore`) object using :py:func:`GLib.idle_add`. This
function is suitable for use in non-main GUI threads for synchronizing data.
:param store: The GTK storage object to add *things* to.
:type store: :py:class:`Gtk.ListStore`, :py:class:`Gtk.TreeStore`
:param tuple things: The array of things to add to *store*.
:param bool clear: Whether or not to clear the storage object before adding *things* to it.
:param bool wait: Whether or not to wait for the operation to complete before returning.
:return: Regardless of the *wait* parameter, ``None`` is returned.
:rtype: None
|
glib_idle_add_store_extend
|
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 glib_idle_add_once(function, *args, **kwargs):
"""
Execute *function* in the main GTK loop using :py:func:`GLib.idle_add`
one time. This is useful for threads that need to update GUI data.
:param function function: The function to call.
:param args: The positional arguments to *function*.
:param kwargs: The key word arguments to *function*.
:return: The result of the function call.
"""
@functools.wraps(function)
def wrapper():
function(*args, **kwargs)
return False
return GLib.idle_add(wrapper)
|
Execute *function* in the main GTK loop using :py:func:`GLib.idle_add`
one time. This is useful for threads that need to update GUI data.
:param function function: The function to call.
:param args: The positional arguments to *function*.
:param kwargs: The key word arguments to *function*.
:return: The result of the function call.
|
glib_idle_add_once
|
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 glib_idle_add_wait(function, *args, **kwargs):
"""
Execute *function* in the main GTK loop using :py:func:`GLib.idle_add`
and block until it has completed. This is useful for threads that need
to update GUI data.
:param function function: The function to call.
:param args: The positional arguments to *function*.
:param kwargs: The key word arguments to *function*.
:return: The result of the function call.
"""
gsource_completed = threading.Event()
results = []
@functools.wraps(function)
def wrapper():
results.append(function(*args, **kwargs))
gsource_completed.set()
return False
GLib.idle_add(wrapper)
gsource_completed.wait()
return results.pop()
|
Execute *function* in the main GTK loop using :py:func:`GLib.idle_add`
and block until it has completed. This is useful for threads that need
to update GUI data.
:param function function: The function to call.
:param args: The positional arguments to *function*.
:param kwargs: The key word arguments to *function*.
:return: The result of the function call.
|
glib_idle_add_wait
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.