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 image_to_pdf_or_hocr( image, lang=None, config='', nice=0, extension='pdf', timeout=0, ): """ Returns the result of a Tesseract OCR run on the provided image to pdf/hocr """ if extension not in {'pdf', 'hocr'}: raise ValueError(f'Unsupported extension: {extension}') if extension == 'hocr': config = f'-c tessedit_create_hocr=1 {config.strip()}' args = [image, extension, lang, config, nice, timeout, True] return run_and_get_output(*args)
Returns the result of a Tesseract OCR run on the provided image to pdf/hocr
image_to_pdf_or_hocr
python
madmaze/pytesseract
pytesseract/pytesseract.py
https://github.com/madmaze/pytesseract/blob/master/pytesseract/pytesseract.py
Apache-2.0
def image_to_alto_xml( image, lang=None, config='', nice=0, timeout=0, ): """ Returns the result of a Tesseract OCR run on the provided image to ALTO XML """ if get_tesseract_version(cached=True) < TESSERACT_ALTO_VERSION: raise ALTONotSupported() config = f'-c tessedit_create_alto=1 {config.strip()}' args = [image, 'xml', lang, config, nice, timeout, True] return run_and_get_output(*args)
Returns the result of a Tesseract OCR run on the provided image to ALTO XML
image_to_alto_xml
python
madmaze/pytesseract
pytesseract/pytesseract.py
https://github.com/madmaze/pytesseract/blob/master/pytesseract/pytesseract.py
Apache-2.0
def image_to_boxes( image, lang=None, config='', nice=0, output_type=Output.STRING, timeout=0, ): """ Returns string containing recognized characters and their box boundaries """ config = ( f'{config.strip()} -c tessedit_create_boxfile=1 batch.nochop makebox' ) args = [image, 'box', lang, config, nice, timeout] return { Output.BYTES: lambda: run_and_get_output(*(args + [True])), Output.DICT: lambda: file_to_dict( f'char left bottom right top page\n{run_and_get_output(*args)}', ' ', 0, ), Output.STRING: lambda: run_and_get_output(*args), }[output_type]()
Returns string containing recognized characters and their box boundaries
image_to_boxes
python
madmaze/pytesseract
pytesseract/pytesseract.py
https://github.com/madmaze/pytesseract/blob/master/pytesseract/pytesseract.py
Apache-2.0
def image_to_data( image, lang=None, config='', nice=0, output_type=Output.STRING, timeout=0, pandas_config=None, ): """ Returns string containing box boundaries, confidences, and other information. Requires Tesseract 3.05+ """ if get_tesseract_version(cached=True) < TESSERACT_MIN_VERSION: raise TSVNotSupported() config = f'-c tessedit_create_tsv=1 {config.strip()}' args = [image, 'tsv', lang, config, nice, timeout] return { Output.BYTES: lambda: run_and_get_output(*(args + [True])), Output.DATAFRAME: lambda: get_pandas_output( args + [True], pandas_config, ), Output.DICT: lambda: file_to_dict(run_and_get_output(*args), '\t', -1), Output.STRING: lambda: run_and_get_output(*args), }[output_type]()
Returns string containing box boundaries, confidences, and other information. Requires Tesseract 3.05+
image_to_data
python
madmaze/pytesseract
pytesseract/pytesseract.py
https://github.com/madmaze/pytesseract/blob/master/pytesseract/pytesseract.py
Apache-2.0
def image_to_osd( image, lang='osd', config='', nice=0, output_type=Output.STRING, timeout=0, ): """ Returns string containing the orientation and script detection (OSD) """ config = f'--psm 0 {config.strip()}' args = [image, 'osd', lang, config, nice, timeout] return { Output.BYTES: lambda: run_and_get_output(*(args + [True])), Output.DICT: lambda: osd_to_dict(run_and_get_output(*args)), Output.STRING: lambda: run_and_get_output(*args), }[output_type]()
Returns string containing the orientation and script detection (OSD)
image_to_osd
python
madmaze/pytesseract
pytesseract/pytesseract.py
https://github.com/madmaze/pytesseract/blob/master/pytesseract/pytesseract.py
Apache-2.0
def test_image_to_data_pandas_output(test_file_small): """Test and compare the type and meta information of the result.""" result = image_to_data(test_file_small, output_type=Output.DATAFRAME) assert isinstance(result, pandas.DataFrame) expected_columns = [ 'level', 'page_num', 'block_num', 'par_num', 'line_num', 'word_num', 'left', 'top', 'width', 'height', 'conf', 'text', ] assert bool(set(result.columns).intersection(expected_columns))
Test and compare the type and meta information of the result.
test_image_to_data_pandas_output
python
madmaze/pytesseract
tests/pytesseract_test.py
https://github.com/madmaze/pytesseract/blob/master/tests/pytesseract_test.py
Apache-2.0
def test_image_to_data_common_output(test_file_small, output): """Test and compare the type of the result.""" result = image_to_data(test_file_small, output_type=output) expected_dict_result = { 'level': [1, 2, 3, 4, 5], 'page_num': [1, 1, 1, 1, 1], 'block_num': [0, 1, 1, 1, 1], 'par_num': [0, 0, 1, 1, 1], 'line_num': [0, 0, 0, 1, 1], 'word_num': [0, 0, 0, 0, 1], 'left': [0, 11, 11, 11, 11], 'top': [0, 11, 11, 11, 11], 'width': [79, 60, 60, 60, 60], 'height': [47, 24, 24, 24, 24], # 'conf': ['-1', '-1', '-1', '-1', 96], 'text': ['', '', '', '', 'This'], } if output is Output.BYTES: assert isinstance(result, bytes) elif output is Output.DICT: confidence_values = result.pop('conf', None) assert confidence_values is not None assert 0 <= confidence_values[-1] <= 100 assert result == expected_dict_result elif output is Output.STRING: assert isinstance(result, string_type) for key in expected_dict_result.keys(): assert key in result
Test and compare the type of the result.
test_image_to_data_common_output
python
madmaze/pytesseract
tests/pytesseract_test.py
https://github.com/madmaze/pytesseract/blob/master/tests/pytesseract_test.py
Apache-2.0
def test_wrong_tesseract_cmd(monkeypatch, test_file, test_path): """Test wrong or missing tesseract command.""" import pytesseract monkeypatch.setattr('pytesseract.pytesseract.tesseract_cmd', test_path) with pytest.raises(TesseractNotFoundError): pytesseract.get_languages.__wrapped__() with pytest.raises(TesseractNotFoundError): pytesseract.get_tesseract_version.__wrapped__() with pytest.raises(TesseractNotFoundError): pytesseract.image_to_string(test_file)
Test wrong or missing tesseract command.
test_wrong_tesseract_cmd
python
madmaze/pytesseract
tests/pytesseract_test.py
https://github.com/madmaze/pytesseract/blob/master/tests/pytesseract_test.py
Apache-2.0
def test_main_not_found_cases( capsys, monkeypatch, test_file, test_invalid_file, ): """Test wrong or missing tesseract command in main.""" import pytesseract monkeypatch.setattr('sys.argv', ['', test_invalid_file]) assert pytesseract.pytesseract.main() == 1 captured = capsys.readouterr() assert ( 'No such file or directory' in captured.err and repr(test_invalid_file) in captured.err ) monkeypatch.setattr( 'pytesseract.pytesseract.tesseract_cmd', 'wrong_tesseract', ) monkeypatch.setattr('sys.argv', ['', test_file]) assert pytesseract.pytesseract.main() == 1 assert ( "wrong_tesseract is not installed or it's not in your PATH. " 'See README file for more information.' in capsys.readouterr().err ) monkeypatch.setattr('sys.argv', ['']) assert pytesseract.pytesseract.main() == 2 assert 'Usage: pytesseract [-l lang] input_file' in capsys.readouterr().err
Test wrong or missing tesseract command in main.
test_main_not_found_cases
python
madmaze/pytesseract
tests/pytesseract_test.py
https://github.com/madmaze/pytesseract/blob/master/tests/pytesseract_test.py
Apache-2.0
def test_proper_oserror_exception_handling(monkeypatch, test_file, test_path): """ "Test for bubbling up OSError exceptions.""" import pytesseract monkeypatch.setattr( 'pytesseract.pytesseract.tesseract_cmd', test_path, ) with pytest.raises( TesseractNotFoundError if IS_PYTHON_2 and test_path else OSError, ): pytesseract.image_to_string(test_file)
"Test for bubbling up OSError exceptions.
test_proper_oserror_exception_handling
python
madmaze/pytesseract
tests/pytesseract_test.py
https://github.com/madmaze/pytesseract/blob/master/tests/pytesseract_test.py
Apache-2.0
def __init__(self, n_vocab=None, vectors=None, residual_embeddings=False, layer0=False, layer1=True, trainable=False, model_cache=MODEL_CACHE): """Initialize an MTLSTM. If layer0 and layer1 are True, they are concatenated along the last dimension so that layer0 outputs contribute the first 600 entries and layer1 contributes the second 600 entries. If residual embeddings is also true, inputs are also concatenated along the last dimension with any outputs such that they form the first 300 entries. Arguments: n_vocab (int): If not None, initialize MTLSTM with an embedding matrix with n_vocab vectors vectors (Float Tensor): If not None, initialize embedding matrix with specified vectors (These should be 300d CommonCrawl GloVe vectors) residual_embedding (bool): If True, concatenate the input GloVe embeddings with contextualized word vectors as final output layer0 (bool): If True, return the outputs of the first layer of the MTLSTM layer1 (bool): If True, return the outputs of the second layer of the MTLSTM trainable (bool): If True, do not detach outputs; i.e. train the MTLSTM (recommended to leave False) model_cache (str): path to the model file for the MTLSTM to load pretrained weights (defaults to the best MTLSTM from (McCann et al. 2017) -- that MTLSTM was trained with 300d 840B GloVe on the WMT 2017 machine translation dataset. """ super(MTLSTM, self).__init__() self.layer0 = layer0 self.layer1 = layer1 self.residual_embeddings = residual_embeddings self.trainable = trainable self.embed = False if n_vocab is not None: self.embed = True self.vectors = nn.Embedding(n_vocab, 300) if vectors is not None: self.vectors.weight.data = vectors state_dict = model_zoo.load_url(model_urls['wmt-lstm'], model_dir=model_cache) if layer0: layer0_dict = {k: v for k, v in state_dict.items() if 'l0' in k} self.rnn0 = nn.LSTM(300, 300, num_layers=1, bidirectional=True, batch_first=True) self.rnn0.load_state_dict(layer0_dict) if layer1: layer1_dict = {k.replace('l1', 'l0'): v for k, v in state_dict.items() if 'l1' in k} self.rnn1 = nn.LSTM(600, 300, num_layers=1, bidirectional=True, batch_first=True) self.rnn1.load_state_dict(layer1_dict) elif layer1: self.rnn1 = nn.LSTM(300, 300, num_layers=2, bidirectional=True, batch_first=True) self.rnn1.load_state_dict(model_zoo.load_url(model_urls['wmt-lstm'], model_dir=model_cache)) else: raise ValueError('At least one of layer0 and layer1 must be True.')
Initialize an MTLSTM. If layer0 and layer1 are True, they are concatenated along the last dimension so that layer0 outputs contribute the first 600 entries and layer1 contributes the second 600 entries. If residual embeddings is also true, inputs are also concatenated along the last dimension with any outputs such that they form the first 300 entries. Arguments: n_vocab (int): If not None, initialize MTLSTM with an embedding matrix with n_vocab vectors vectors (Float Tensor): If not None, initialize embedding matrix with specified vectors (These should be 300d CommonCrawl GloVe vectors) residual_embedding (bool): If True, concatenate the input GloVe embeddings with contextualized word vectors as final output layer0 (bool): If True, return the outputs of the first layer of the MTLSTM layer1 (bool): If True, return the outputs of the second layer of the MTLSTM trainable (bool): If True, do not detach outputs; i.e. train the MTLSTM (recommended to leave False) model_cache (str): path to the model file for the MTLSTM to load pretrained weights (defaults to the best MTLSTM from (McCann et al. 2017) -- that MTLSTM was trained with 300d 840B GloVe on the WMT 2017 machine translation dataset.
__init__
python
salesforce/cove
cove/encoder.py
https://github.com/salesforce/cove/blob/master/cove/encoder.py
BSD-3-Clause
def forward(self, inputs, lengths, hidden=None): """ Arguments: inputs (Tensor): If MTLSTM handles embedding, a Long Tensor of size (batch_size, timesteps). Otherwise, a Float Tensor of size (batch_size, timesteps, features). lengths (Long Tensor): lenghts of each sequence for handling padding hidden (Float Tensor): initial hidden state of the LSTM """ if self.embed: inputs = self.vectors(inputs) if not isinstance(lengths, torch.Tensor): lengths = torch.Tensor(lengths).long() if inputs.is_cuda: with torch.cuda.device_of(inputs): lengths = lengths.cuda(torch.cuda.current_device()) lens, indices = torch.sort(lengths, 0, True) outputs = [inputs] if self.residual_embeddings else [] len_list = lens.tolist() packed_inputs = pack(inputs[indices], len_list, batch_first=True) if self.layer0: outputs0, hidden_t0 = self.rnn0(packed_inputs, hidden) unpacked_outputs0 = unpack(outputs0, batch_first=True)[0] _, _indices = torch.sort(indices, 0) unpacked_outputs0 = unpacked_outputs0[_indices] outputs.append(unpacked_outputs0) packed_inputs = outputs0 if self.layer1: outputs1, hidden_t1 = self.rnn1(packed_inputs, hidden) unpacked_outputs1 = unpack(outputs1, batch_first=True)[0] _, _indices = torch.sort(indices, 0) unpacked_outputs1 = unpacked_outputs1[_indices] outputs.append(unpacked_outputs1) outputs = torch.cat(outputs, 2) return outputs if self.trainable else outputs.detach()
Arguments: inputs (Tensor): If MTLSTM handles embedding, a Long Tensor of size (batch_size, timesteps). Otherwise, a Float Tensor of size (batch_size, timesteps, features). lengths (Long Tensor): lenghts of each sequence for handling padding hidden (Float Tensor): initial hidden state of the LSTM
forward
python
salesforce/cove
cove/encoder.py
https://github.com/salesforce/cove/blob/master/cove/encoder.py
BSD-3-Clause
def forward(self, input, context): """ input: batch x dim context: batch x sourceL x dim """ if not self.dot: targetT = self.linear_in(input).unsqueeze(2) # batch x dim x 1 else: targetT = input.unsqueeze(2) # Get attention attn = torch.bmm(context, targetT).squeeze(2) # batch x sourceL if self.mask is not None: attn.data.masked_fill_(self.mask, -float('inf')) attn = self.sm(attn) attn3 = attn.view(attn.size(0), 1, attn.size(1)) # batch x 1 x sourceL weightedContext = torch.bmm(attn3, context).squeeze(1) # batch x dim contextCombined = torch.cat((weightedContext, input), 1) contextOutput = self.tanh(self.linear_out(contextCombined)) return contextOutput, attn
input: batch x dim context: batch x sourceL x dim
forward
python
salesforce/cove
OpenNMT-py/onmt/modules/GlobalAttention.py
https://github.com/salesforce/cove/blob/master/OpenNMT-py/onmt/modules/GlobalAttention.py
BSD-3-Clause
def encode(s): """Encode a folder name using IMAP modified UTF-7 encoding. Despite the function's name, the output is still a unicode string. """ if not isinstance(s, text_type): return s r = [] _in = [] def extend_result_if_chars_buffered(): if _in: r.extend(['&', modified_utf7(''.join(_in)), '-']) del _in[:] for c in s: if ord(c) in PRINTABLE: extend_result_if_chars_buffered() r.append(c) elif c == '&': extend_result_if_chars_buffered() r.append('&-') else: _in.append(c) extend_result_if_chars_buffered() return ''.join(r)
Encode a folder name using IMAP modified UTF-7 encoding. Despite the function's name, the output is still a unicode string.
encode
python
charlierguo/gmail
gmail/utf.py
https://github.com/charlierguo/gmail/blob/master/gmail/utf.py
MIT
def decode(s): """Decode a folder name from IMAP modified UTF-7 encoding to unicode. Despite the function's name, the input may still be a unicode string. If the input is bytes, it's first decoded to unicode. """ if isinstance(s, binary_type): s = s.decode('latin-1') if not isinstance(s, text_type): return s r = [] _in = [] for c in s: if c == '&' and not _in: _in.append('&') elif c == '-' and _in: if len(_in) == 1: r.append('&') else: r.append(modified_deutf7(''.join(_in[1:]))) _in = [] elif _in: _in.append(c) else: r.append(c) if _in: r.append(modified_deutf7(''.join(_in[1:]))) return ''.join(r)
Decode a folder name from IMAP modified UTF-7 encoding to unicode. Despite the function's name, the input may still be a unicode string. If the input is bytes, it's first decoded to unicode.
decode
python
charlierguo/gmail
gmail/utf.py
https://github.com/charlierguo/gmail/blob/master/gmail/utf.py
MIT
def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ engine = create_engine( database_connection_url, poolclass=pool.NullPool) connection = engine.connect() context.configure( connection=connection, target_metadata=target_metadata ) try: with context.begin_transaction(): context.run_migrations() finally: connection.close()
Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context.
run_migrations_online
python
rsmusllp/king-phisher
data/server/king_phisher/alembic/env.py
https://github.com/rsmusllp/king-phisher/blob/master/data/server/king_phisher/alembic/env.py
BSD-3-Clause
def _compare_paths(path1, path2): """ Check if *path1* is the same as *path2*, taking into account file system links. """ if os.path.islink(path1): path1 = os.readlink(path1) if os.path.islink(path2): path2 = os.readlink(path2) return os.path.abspath(path1) == os.path.abspath(path2)
Check if *path1* is the same as *path2*, taking into account file system links.
_compare_paths
python
rsmusllp/king-phisher
king_phisher/archive.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/archive.py
BSD-3-Clause
def patch_zipfile(input_file, patches, output_file=None): """ Patch content into the specified input Zip file. The *input_file* must be either an input path string to the file to patch or a :py:class:`zipfile.ZipFile` instance. Patch data is supplied in the *patch* argument which is a dictionary keyed by the paths to modify, values are then used in place of the specified path. If the value of a path is ``None``, then that file is removed from the archive. The *output_file* is either a string to the path of where to place the patched archive, a :py:class:`~zipfile.ZipFile` instance or ``None``. If ``None`` is specified then *input_file* is modified in place. .. note:: If a :py:class:`~zipfile.ZipFile` instance is specified as *input_file* then *output_file* can not be ``None``. :param input_file: The Zip file archive to modify. :type input_file: str, :py:class:`~zipfile.ZipFile` :param dict patches: The data to modify from the original archive. :param output_file: The destination of the modified archive :type output_file: None, str, :py:class:`~zipfile.ZipFile` """ ZipMeta = collections.namedtuple('ZipMeta', ('close', 'delete', 'obj', 'path')) copy_out_to_in = False if isinstance(input_file, str): zin_meta = ZipMeta(close=True, delete=False, obj=zipfile.ZipFile(input_file, 'r'), path=os.path.abspath(input_file)) elif isinstance(input_file, zipfile.ZipFile): zin_meta = ZipMeta(close=False, delete=False, obj=input_file, path=os.path.abs(input_file.filename)) else: raise TypeError('arg 1 (input_file) must either be a path or zipfile.ZipFile instance') if isinstance(output_file, str) and _compare_paths(output_file, zin_meta.path): output_file = None if output_file is None: tmp_fd, output_file = tempfile.mkstemp(suffix=os.path.splitext(zin_meta.path)[1]) os.close(tmp_fd) zout_meta = ZipMeta(close=True, delete=True, obj=zipfile.ZipFile(output_file, 'w'), path=os.path.abspath(output_file)) copy_out_to_in = True elif isinstance(output_file, str): zout_meta = ZipMeta(close=True, delete=False, obj=zipfile.ZipFile(output_file, 'w'), path=os.path.abspath(output_file)) elif isinstance(output_file, zipfile.ZipFile): zout_meta = ZipMeta(close=False, delete=False, obj=output_file, path=os.path.abspath(output_file.filename)) else: raise TypeError('arg 3 (output_file) must either be None, a path or zipfile.ZipFile instance') patches = copy.copy(patches) zout_meta.obj.comment = zin_meta.obj.comment for item in zin_meta.obj.infolist(): data = zin_meta.obj.read(item.filename) if item.filename in patches: data = patches.pop(item.filename) if data is None: continue zout_meta.obj.writestr(item, data) for filename, data in patches.items(): zout_meta.obj.writestr(filename, data) if zin_meta.close: zin_meta.obj.close() if zout_meta.close: zout_meta.obj.close() if copy_out_to_in: shutil.copyfile(zout_meta.path, zin_meta.path) # zin_meta.delete will never be True if zout_meta.delete: os.unlink(zout_meta.path)
Patch content into the specified input Zip file. The *input_file* must be either an input path string to the file to patch or a :py:class:`zipfile.ZipFile` instance. Patch data is supplied in the *patch* argument which is a dictionary keyed by the paths to modify, values are then used in place of the specified path. If the value of a path is ``None``, then that file is removed from the archive. The *output_file* is either a string to the path of where to place the patched archive, a :py:class:`~zipfile.ZipFile` instance or ``None``. If ``None`` is specified then *input_file* is modified in place. .. note:: If a :py:class:`~zipfile.ZipFile` instance is specified as *input_file* then *output_file* can not be ``None``. :param input_file: The Zip file archive to modify. :type input_file: str, :py:class:`~zipfile.ZipFile` :param dict patches: The data to modify from the original archive. :param output_file: The destination of the modified archive :type output_file: None, str, :py:class:`~zipfile.ZipFile`
patch_zipfile
python
rsmusllp/king-phisher
king_phisher/archive.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/archive.py
BSD-3-Clause
def __init__(self, file_name, mode, encoding='utf-8'): """ :param str file_name: The path to the file to open as an archive. :param str mode: The mode to open the file such as 'r' or 'w'. :param str encoding: The encoding to use for strings. """ self._mode = mode + ':bz2' self.encoding = encoding self.file_name = file_name epoch = datetime.datetime.utcfromtimestamp(0) self.mtime = (datetime.datetime.utcnow() - epoch).total_seconds() self._tar_h = tarfile.open(file_name, self._mode) if 'r' in mode and self.has_file(self.metadata_file_name): self.metadata = serializers.JSON.loads(self.get_data(self.metadata_file_name).decode(self.encoding)) else: self.metadata = {} if 'w' in mode: self.metadata['timestamp'] = datetime.datetime.utcnow().isoformat() self.metadata['version'] = version.version
:param str file_name: The path to the file to open as an archive. :param str mode: The mode to open the file such as 'r' or 'w'. :param str encoding: The encoding to use for strings.
__init__
python
rsmusllp/king-phisher
king_phisher/archive.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/archive.py
BSD-3-Clause
def add_data(self, name, data): """ Add arbitrary data directly to the archive under the specified name. This allows data to be directly inserted into the archive without first writing it to a file or file like object. :param str name: The name of the destination file in the archive. :param data: The data to place into the archive. :type data: bytes, str """ if its.py_v2 and isinstance(data, unicode): data = data.encode(self.encoding) elif its.py_v3 and isinstance(data, str): data = data.encode(self.encoding) pseudo_file = io.BytesIO() pseudo_file.write(data) tarinfo = tarfile.TarInfo(name=name) tarinfo.mtime = self.mtime tarinfo.size = pseudo_file.tell() pseudo_file.seek(os.SEEK_SET) self._tar_h.addfile(tarinfo=tarinfo, fileobj=pseudo_file)
Add arbitrary data directly to the archive under the specified name. This allows data to be directly inserted into the archive without first writing it to a file or file like object. :param str name: The name of the destination file in the archive. :param data: The data to place into the archive. :type data: bytes, str
add_data
python
rsmusllp/king-phisher
king_phisher/archive.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/archive.py
BSD-3-Clause
def close(self): """Close the handle to the archive.""" if 'w' in self.mode: self.add_data(self.metadata_file_name, serializers.JSON.dumps(self.metadata, pretty=True)) self._tar_h.close()
Close the handle to the archive.
close
python
rsmusllp/king-phisher
king_phisher/archive.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/archive.py
BSD-3-Clause
def files(self): """ This property is a generator which yields tuples of two objects each where the first is the file name and the second is the file object. The metadata file is skipped. :return: A generator which yields all the contained file name and file objects. :rtype: tuple """ for name in self._tar_h.getnames(): if name == self.metadata_file_name: continue yield name, self.get_file(name)
This property is a generator which yields tuples of two objects each where the first is the file name and the second is the file object. The metadata file is skipped. :return: A generator which yields all the contained file name and file objects. :rtype: tuple
files
python
rsmusllp/king-phisher
king_phisher/archive.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/archive.py
BSD-3-Clause
def file_names(self): """ This property is a generator which yields the names of all of the contained files. The metadata file is skipped. :return: A generator which yields all the contained file names. :rtype: str """ for name in self._tar_h.getnames(): if name == self.metadata_file_name: continue yield name
This property is a generator which yields the names of all of the contained files. The metadata file is skipped. :return: A generator which yields all the contained file names. :rtype: str
file_names
python
rsmusllp/king-phisher
king_phisher/archive.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/archive.py
BSD-3-Clause
def from_dict(cls, value): """ Load the collection item file from the specified dict object. :param dict value: The dictionary to load the data from. :return: """ # make sure both keys are present or neither are present return cls(value.get('path-destination', value['path-source']), value['path-source'], signature=value.get('signature'), signed_by=value.get('signed-by'))
Load the collection item file from the specified dict object. :param dict value: The dictionary to load the data from. :return:
from_dict
python
rsmusllp/king-phisher
king_phisher/catalog.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/catalog.py
BSD-3-Clause
def to_dict(self): """ Dump the instance to a dictionary suitable for being reloaded with :py:meth:`.from_dict`. :return: The instance represented as a dictionary. :rtype: dict """ data = { 'path-destination': self.path_destination, 'path-source': self.path_source } if self.signature and self.signed_by: data['signature'] = self.signature data['signed-by'] = self.signed_by return data
Dump the instance to a dictionary suitable for being reloaded with :py:meth:`.from_dict`. :return: The instance represented as a dictionary. :rtype: dict
to_dict
python
rsmusllp/king-phisher
king_phisher/catalog.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/catalog.py
BSD-3-Clause
def __init__(self, repo, type, items): """ :param repo: The repository this collection is associated with. :type repo: :py:class:`.Repository` :param str type: The collection type of these items. :param dict items: The items that are members of this collection, keyed by their name. """ self.__repo_ref = weakref.ref(repo) self.type = type self._storage = items
:param repo: The repository this collection is associated with. :type repo: :py:class:`.Repository` :param str type: The collection type of these items. :param dict items: The items that are members of this collection, keyed by their name.
__init__
python
rsmusllp/king-phisher
king_phisher/catalog.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/catalog.py
BSD-3-Clause
def __init__(self, data, keys=None): """ :param dict data: The formatted repository data. :param keys: The keys to use for verifying remote data. :type keys: :py:class:`~king_phisher.security_keys.SecurityKeys` """ self.security_keys = keys or security_keys.SecurityKeys() """The :py:class:`~king_phisher.security_keys.SecurityKeys` used for verifying remote data.""" self._req_sess = requests.Session() self._req_sess.mount('file://', requests_file.FileAdapter()) self.description = data.get('description') self.homepage = data.get('homepage') """The URL of the homepage for this repository if it was specified.""" self.id = data['id'] """The unique identifier of this repository.""" self.title = data['title'] """The title string of this repository.""" self.url_base = data['url-base'] """The base URL string of files included in this repository.""" self.collections = utilities.FreezableDict() """The dictionary of the different collection types included in this repository.""" if 'collections-include' in data: # include-files is reversed so the dictionary can get .update()'ed and the first seen will be the value kept for include in reversed(data['collections-include']): include_data = self._fetch_json(include) utilities.validate_json_schema(include_data, 'king-phisher.catalog.collections') include_data = include_data['collections'] for collection_type in include.get('types', COLLECTION_TYPES): collection = include_data.get(collection_type) if collection is None: continue self._add_collection_data(collection_type, collection) if 'collections' in data: for collection_type in COLLECTION_TYPES: collection = data['collections'].get(collection_type) if collection is None: continue self._add_collection_data(collection_type, collection) item_count = sum(len(collection) for collection in self.collections.values()) self.logger.debug("initialized catalog repository with {0} collection types and {1} total items".format(len(self.collections), item_count)) for collection_type, collection in self.collections.items(): collection.freeze() self.collections[collection_type] = Collection(self, collection_type, collection) self.collections.freeze()
:param dict data: The formatted repository data. :param keys: The keys to use for verifying remote data. :type keys: :py:class:`~king_phisher.security_keys.SecurityKeys`
__init__
python
rsmusllp/king-phisher
king_phisher/catalog.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/catalog.py
BSD-3-Clause
def to_dict(self): """ Dump the instance to a dictionary suitable for being reloaded with :py:meth:`.__init__`. :return: The instance represented as a dictionary. :rtype: dict """ data = { 'id': self.id, 'title': self.title, 'url-base': self.url_base } if self.collections: data['collections'] = {key: value.to_dict()['items'] for key, value in self.collections.items()} if self.description: data['description'] = self.description if self.homepage: data['homepage'] = self.homepage return data
Dump the instance to a dictionary suitable for being reloaded with :py:meth:`.__init__`. :return: The instance represented as a dictionary. :rtype: dict
to_dict
python
rsmusllp/king-phisher
king_phisher/catalog.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/catalog.py
BSD-3-Clause
def get_file(self, item_file, encoding=None): """ Download and return the file data from the repository. If no encoding is specified, the data is return as bytes, otherwise it is decoded to a string using the specified encoding. The file's contents are verified using the signature that must be specified by the *item_file* information. :param item_file: The information for the file to download. :type item_file: :py:class:`.CollectionItemFile` :param str encoding: An optional encoding of the remote data. :return: The files contents. :rtype: bytes, str """ if not isinstance(item_file, CollectionItemFile): raise TypeError('the file object must be a CollectionItemFile instance') return self._fetch(item_file, encoding=encoding)
Download and return the file data from the repository. If no encoding is specified, the data is return as bytes, otherwise it is decoded to a string using the specified encoding. The file's contents are verified using the signature that must be specified by the *item_file* information. :param item_file: The information for the file to download. :type item_file: :py:class:`.CollectionItemFile` :param str encoding: An optional encoding of the remote data. :return: The files contents. :rtype: bytes, str
get_file
python
rsmusllp/king-phisher
king_phisher/catalog.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/catalog.py
BSD-3-Clause
def get_item_files(self, collection_type, name, destination): """ Download all of the file references from the named item. :param str collection_type: The type of collection the specified item is in. :param str name: The name of the item to retrieve. :param str destination: The path of where to save the downloaded files to. """ item = self.get_item(collection_type, name) destination = os.path.abspath(destination) self.logger.debug("fetching catalog item: {0}/{1} to {2}".format(collection_type, name, destination)) if not os.path.isdir(destination): os.makedirs(destination, exist_ok=True) for item_file in item['files']: data = self._fetch(item_file) file_destination = os.path.abspath(os.path.join(destination, item_file.path_destination)) if not file_destination.startswith(destination + os.path.sep): raise RuntimeError('file destination is outside of the specified path') dir_name = os.path.dirname(file_destination) os.makedirs(dir_name, exist_ok=True) with open(file_destination, 'wb') as file_h: file_h.write(data)
Download all of the file references from the named item. :param str collection_type: The type of collection the specified item is in. :param str name: The name of the item to retrieve. :param str destination: The path of where to save the downloaded files to.
get_item_files
python
rsmusllp/king-phisher
king_phisher/catalog.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/catalog.py
BSD-3-Clause
def __init__(self, data, keys=None): """ :param dict data: The formatted catalog data. :param keys: The keys to use for verifying remote data. :type keys: :py:class:`~king_phisher.security_keys.SecurityKeys` """ self.security_keys = keys or security_keys.SecurityKeys() """The :py:class:`~king_phisher.security_keys.SecurityKeys` used for verifying remote data.""" self.created = dateutil.parser.parse(data['created']) """The timestamp of when the remote data was generated.""" self.created_by = data['created-by'] self.id = data['id'] """The unique identifier of this catalog.""" self.maintainers = tuple(maintainer['id'] for maintainer in data['maintainers']) """ A tuple containing the maintainers of the catalog and repositories. These are also the key identities that should be present for verifying the remote data. """ self.repositories = dict((repo['id'], Repository(repo, keys=self.security_keys)) for repo in data['repositories']) """A dict of the :py:class:`.Repository` objects included in this catalog keyed by their id.""" self.logger.info("initialized catalog with {0:,} repositories".format(len(self.repositories)))
:param dict data: The formatted catalog data. :param keys: The keys to use for verifying remote data. :type keys: :py:class:`~king_phisher.security_keys.SecurityKeys`
__init__
python
rsmusllp/king-phisher
king_phisher/catalog.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/catalog.py
BSD-3-Clause
def from_url(cls, url, keys=None, encoding='utf-8'): """ Initialize a new :py:class:`.Catalog` object from a resource at the specified URL. The resulting data is validated against a schema file with :py:func:`~king_phisher.utilities.validate_json_schema` before being passed to :py:meth:`~.__init__`. :param str url: The URL to the catalog data to load. :param keys: The keys to use for verifying remote data. :type keys: :py:class:`~king_phisher.security_keys.SecurityKeys` :param str encoding: The encoding of the catalog data. :return: The new catalog instance. :rtype: :py:class:`.Catalog` """ keys = keys or security_keys.SecurityKeys() req_sess = requests.Session() req_sess.mount('file://', requests_file.FileAdapter()) cls.logger.debug('fetching catalog from: ' + url) resp = req_sess.get(url) data = resp.content.decode(encoding) data = serializers.JSON.loads(data) utilities.validate_json_schema(data, 'king-phisher.catalog') keys.verify_dict(data, signature_encoding='base64') return cls(data, keys=keys)
Initialize a new :py:class:`.Catalog` object from a resource at the specified URL. The resulting data is validated against a schema file with :py:func:`~king_phisher.utilities.validate_json_schema` before being passed to :py:meth:`~.__init__`. :param str url: The URL to the catalog data to load. :param keys: The keys to use for verifying remote data. :type keys: :py:class:`~king_phisher.security_keys.SecurityKeys` :param str encoding: The encoding of the catalog data. :return: The new catalog instance. :rtype: :py:class:`.Catalog`
from_url
python
rsmusllp/king-phisher
king_phisher/catalog.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/catalog.py
BSD-3-Clause
def sign_item_files(local_path, signing_key, repo_path=None): """ This utility function is used to create a :py:class:`.CollectionItemFile` iterator from the specified source to be included in either a catalog file or one of it's included files. .. warning:: This function contains a black list of file extensions which will be skipped. This is to avoid signing files originating from the development process such as ``.pyc`` and ``.ui~``. :param str local_path: The real location of where the files exist on disk. :param signing_key: The key with which to sign the files for verification. :param str repo_path: The path of the repository as it exists on disk. """ local_path = os.path.abspath(local_path) if repo_path is None: repo_path = local_path else: repo_path = os.path.abspath(repo_path) if not local_path.startswith(repo_path + os.path.sep): raise ValueError('local_path must be a sub-directory of repo_path') walker = smoke_zephyr.utilities.FileWalker(local_path, absolute_path=True, skip_dirs=True) for local_file_path in walker: # first skip black listed files that shouldn't be included _, file_extension = os.path.splitext(local_file_path) if file_extension in ('.pyc', '.ui~'): continue with open(local_file_path, 'rb') as file_h: signature = signing_key.sign(file_h.read()) # source and destination are flipped here because the processing of the # data is done in reverse, meaning our source file as it exists on disk # will be the destination when the client fetches it source_file_path = os.path.relpath(local_file_path, repo_path) destination_file_path = os.path.relpath(local_file_path, os.path.dirname(local_path)) signature = binascii.b2a_base64(signature).decode('utf-8').rstrip() item_file = CollectionItemFile( path_destination=destination_file_path, path_source=source_file_path, signature=signature, signed_by=signing_key.id ) yield item_file
This utility function is used to create a :py:class:`.CollectionItemFile` iterator from the specified source to be included in either a catalog file or one of it's included files. .. warning:: This function contains a black list of file extensions which will be skipped. This is to avoid signing files originating from the development process such as ``.pyc`` and ``.ui~``. :param str local_path: The real location of where the files exist on disk. :param signing_key: The key with which to sign the files for verification. :param str repo_path: The path of the repository as it exists on disk.
sign_item_files
python
rsmusllp/king-phisher
king_phisher/catalog.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/catalog.py
BSD-3-Clause
def convert_hex_to_tuple(hex_color, raw=False): """ Converts an RGB hex triplet such as #ff0000 into an RGB tuple. If *raw* is True then each value is on a scale from 0 to 255 instead of 0.0 to 1.0. :param str hex_color: The hex code for the desired color. :param bool raw: Whether the values are raw or percentages. :return: The color as a red, green, blue tuple. :rtype: tuple """ if hex_color.startswith('#'): hex_color = hex_color[1:] if len(hex_color) != 6: raise ValueError('hex color code is in an invalid format') rgb = (int(x, 16) for x in (hex_color[i:i + 2] for i in range(0, 6, 2))) if not raw: rgb = (float(x) / 255.0 for x in rgb) return tuple(rgb)
Converts an RGB hex triplet such as #ff0000 into an RGB tuple. If *raw* is True then each value is on a scale from 0 to 255 instead of 0.0 to 1.0. :param str hex_color: The hex code for the desired color. :param bool raw: Whether the values are raw or percentages. :return: The color as a red, green, blue tuple. :rtype: tuple
convert_hex_to_tuple
python
rsmusllp/king-phisher
king_phisher/color.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/color.py
BSD-3-Clause
def convert_tuple_to_hex(rgb, raw=False): """ Converts an RGB color tuple info a hex string such as #ff0000. If *raw* is True then each value is treated as if it were on a scale from 0 to 255 instead of 0.0 to 1.0. :param tuple rgb: The RGB tuple to convert into a string. :param bool raw: Whether the values are raw or percentages. :return: The RGB color as a string. :rtype: str """ if raw: rgb = (int(x) for x in rgb) else: rgb = (int(round(float(x) * 255.0)) for x in rgb) return "#{0:02x}{1:02x}{2:02x}".format(*rgb)
Converts an RGB color tuple info a hex string such as #ff0000. If *raw* is True then each value is treated as if it were on a scale from 0 to 255 instead of 0.0 to 1.0. :param tuple rgb: The RGB tuple to convert into a string. :param bool raw: Whether the values are raw or percentages. :return: The RGB color as a string. :rtype: str
convert_tuple_to_hex
python
rsmusllp/king-phisher
king_phisher/color.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/color.py
BSD-3-Clause
def get_scale(color_low, color_high, count, ascending=True): """ Create a scale of colors gradually moving from the low color to the high color. :param tuple color_low: The darker color to start the scale with. :param tuple color_high: The lighter color to end the scale with. :param count: The total number of resulting colors. :param bool ascending: Whether the colors should be ascending from lighter to darker or the reverse. :return: An array of colors starting with the low and gradually transitioning to the high. :rtype: tuple """ if sum(color_low) > sum(color_high): # the colors are reversed so fix it and continue color_low, color_high = (color_high, color_low) ascending = not ascending for _ in range(1): if count < 1: scale = [] elif count == 1: scale = [color_low if ascending else color_high] elif count == 2: scale = [color_low, color_high] else: scale = [color_low] for modifier in range(1, count - 1): modifier = float(modifier) / float(count - 1) scale.append(tuple(min(color_high[i], color_low[i]) + (abs(color_high[i] - color_low[i]) * modifier) for i in range(0, 3))) scale.append(color_high) if not ascending: scale.reverse() return tuple(scale)
Create a scale of colors gradually moving from the low color to the high color. :param tuple color_low: The darker color to start the scale with. :param tuple color_high: The lighter color to end the scale with. :param count: The total number of resulting colors. :param bool ascending: Whether the colors should be ascending from lighter to darker or the reverse. :return: An array of colors starting with the low and gradually transitioning to the high. :rtype: tuple
get_scale
python
rsmusllp/king-phisher
king_phisher/color.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/color.py
BSD-3-Clause
def print_error(message): """ Print an error message to the console. :param str message: The message to print """ prefix = '[-] ' if print_colors: prefix = termcolor.colored(prefix, 'red', attrs=['bold']) print(prefix + message)
Print an error message to the console. :param str message: The message to print
print_error
python
rsmusllp/king-phisher
king_phisher/color.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/color.py
BSD-3-Clause
def print_good(message): """ Print a good message to the console. :param str message: The message to print """ prefix = '[+] ' if print_colors: prefix = termcolor.colored(prefix, 'green', attrs=['bold']) print(prefix + message)
Print a good message to the console. :param str message: The message to print
print_good
python
rsmusllp/king-phisher
king_phisher/color.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/color.py
BSD-3-Clause
def print_status(message): """ Print a status message to the console. :param str message: The message to print """ prefix = '[*] ' if print_colors: prefix = termcolor.colored(prefix, 'blue', attrs=['bold']) print(prefix + message)
Print a status message to the console. :param str message: The message to print
print_status
python
rsmusllp/king-phisher
king_phisher/color.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/color.py
BSD-3-Clause
def names(cls): """Iterate over the names in a group of constants.""" for name in dir(cls): if name.upper() != name: continue yield name
Iterate over the names in a group of constants.
names
python
rsmusllp/king-phisher
king_phisher/constants.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/constants.py
BSD-3-Clause
def items(cls): """Iterate over the names and values in a group of constants.""" for name in dir(cls): if name.upper() != name: continue yield (name, getattr(cls, name))
Iterate over the names and values in a group of constants.
items
python
rsmusllp/king-phisher
king_phisher/constants.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/constants.py
BSD-3-Clause
def values(cls): """Iterate over the values in a group of constants.""" for name in dir(cls): if name.upper() != name: continue yield getattr(cls, name)
Iterate over the values in a group of constants.
values
python
rsmusllp/king-phisher
king_phisher/constants.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/constants.py
BSD-3-Clause
def __init__(self, response_sent=False): """ :param bool response_sent: Whether or not a response has already been sent to the client. """ super(KingPhisherAbortRequestError, self).__init__() self.response_sent = response_sent
:param bool response_sent: Whether or not a response has already been sent to the client.
__init__
python
rsmusllp/king-phisher
king_phisher/errors.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/errors.py
BSD-3-Clause
def data_path_append(path): """ Add a directory to the data search path. The directory will be used by the :py:func:`.data_file` and :py:func:`.data_directory` functions. :param str path: The path to add for searching. """ path_var = os.environ[ENV_VAR].split(os.pathsep) if path in path_var: return path_var.append(path) os.environ[ENV_VAR] = os.pathsep.join(path_var)
Add a directory to the data search path. The directory will be used by the :py:func:`.data_file` and :py:func:`.data_directory` functions. :param str path: The path to add for searching.
data_path_append
python
rsmusllp/king-phisher
king_phisher/find.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/find.py
BSD-3-Clause
def init_data_path(directory=None): """ Add a directory to the data search path for either client or server data files. :param str directory: The directory to add, either 'client' or 'server'. """ found = False possible_data_paths = [] if its.frozen: possible_data_paths.append(os.path.dirname(sys.executable)) else: data_path = os.path.dirname(__file__) if directory is not None: possible_data_paths.append(os.path.abspath(os.path.join(data_path, '..', 'data', directory))) possible_data_paths.append(os.path.join(os.getcwd(), 'data', directory)) possible_data_paths.append(os.path.abspath(os.path.join(data_path, '..', 'data'))) possible_data_paths.append(os.path.join(os.getcwd(), 'data')) for data_path in possible_data_paths: if not os.path.isdir(data_path): continue found = True data_path_append(data_path) if not found: raise RuntimeError('failed to initialize the specified data directory')
Add a directory to the data search path for either client or server data files. :param str directory: The directory to add, either 'client' or 'server'.
init_data_path
python
rsmusllp/king-phisher
king_phisher/find.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/find.py
BSD-3-Clause
def data_file(name, access_mode=os.R_OK): """ Locate a data file by searching the directories specified in :py:data:`.ENV_VAR`. If *access_mode* is specified, it needs to be a value suitable for use with :py:func:`os.access`. :param str name: The name of the file to locate. :param int access_mode: The access that is required for the file. :return: The path to the located file. :rtype: str """ search_path = os.environ[ENV_VAR] for directory in search_path.split(os.pathsep): test_path = os.path.join(directory, DATA_DIRECTORY_NAME, name) if not os.path.isfile(test_path): continue if not os.access(test_path, access_mode): continue return test_path return None
Locate a data file by searching the directories specified in :py:data:`.ENV_VAR`. If *access_mode* is specified, it needs to be a value suitable for use with :py:func:`os.access`. :param str name: The name of the file to locate. :param int access_mode: The access that is required for the file. :return: The path to the located file. :rtype: str
data_file
python
rsmusllp/king-phisher
king_phisher/find.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/find.py
BSD-3-Clause
def data_directory(name, access_mode=os.R_OK): """ Locate a subdirectory in the data search path. :param str name: The directory name to locate. :param int access_mode: The access that is required for the directory. :return: The path to the located directory. :rtype: str """ search_path = os.environ[ENV_VAR] for directory in search_path.split(os.pathsep): test_path = os.path.join(directory, DATA_DIRECTORY_NAME, name) if not os.path.isdir(test_path): continue if not os.access(test_path, access_mode): continue return test_path return None
Locate a subdirectory in the data search path. :param str name: The directory name to locate. :param int access_mode: The access that is required for the directory. :return: The path to the located directory. :rtype: str
data_directory
python
rsmusllp/king-phisher
king_phisher/find.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/find.py
BSD-3-Clause
def init_database(database_file): """ Create and initialize the GeoLite2 database engine. This must be done before classes and functions in this module attempt to look up results. If the specified database file does not exist, a new copy will be downloaded. :param str database_file: The GeoLite2 database file to use. :return: The initialized GeoLite2 database object. :rtype: :py:class:`geoip2.database.Reader` """ # pylint: disable=global-statement global _geoip_db if not os.path.isfile(database_file): db_path = find.data_file('GeoLite2-City.mmdb') if db_path is None: raise errors.KingPhisherResourceError('the default geoip database file is unavailable') logger.info('initializing the default geoip database') shutil.copyfile(db_path, database_file) try: _geoip_db = geoip2.database.Reader(database_file) except maxminddb.errors.InvalidDatabaseError: logger.warning('the geoip database file is invalid, downloading a new one') download_geolite2_city_db(database_file) _geoip_db = geoip2.database.Reader(database_file) metadata = _geoip_db.metadata() if not metadata.database_type == 'GeoLite2-City': raise ValueError('the connected database is not a GeoLite2-City database') build_date = datetime.datetime.fromtimestamp(metadata.build_epoch) if build_date < datetime.datetime.utcnow() - datetime.timedelta(days=90): logger.warning('the geoip database is older than 90 days') return _geoip_db
Create and initialize the GeoLite2 database engine. This must be done before classes and functions in this module attempt to look up results. If the specified database file does not exist, a new copy will be downloaded. :param str database_file: The GeoLite2 database file to use. :return: The initialized GeoLite2 database object. :rtype: :py:class:`geoip2.database.Reader`
init_database
python
rsmusllp/king-phisher
king_phisher/geoip.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/geoip.py
BSD-3-Clause
def lookup(ip, lang='en'): """ Lookup the geo location information for the specified IP from the configured GeoLite2 City database. :param str ip: The IP address to look up the information for. :param str lang: The language to prefer for regional names. :return: The geo location information as a dict. The keys are the values of :py:data:`.DB_RESULT_FIELDS`. :rtype: dict """ if not _geoip_db: raise RuntimeError('the geoip database has not been initialized yet') lang = (lang or 'en') if isinstance(ip, str): ip = ipaddress.ip_address(ip) if isinstance(ip, ipaddress.IPv6Address): raise TypeError('ipv6 addresses are not supported at this time') if ip.is_loopback or ip.is_private: raise RuntimeError('the specified IP address is not a public IP address') with _geoip_db_lock: city = _geoip_db.city(str(ip)) result = {} result['city'] = city.city.names.get(lang) result['continent'] = city.continent.names.get(lang) result['coordinates'] = Coordinates(latitude=city.location.latitude, longitude=city.location.longitude) result['country'] = city.country.names.get(lang) result['postal_code'] = city.postal.code result['time_zone'] = city.location.time_zone return result
Lookup the geo location information for the specified IP from the configured GeoLite2 City database. :param str ip: The IP address to look up the information for. :param str lang: The language to prefer for regional names. :return: The geo location information as a dict. The keys are the values of :py:data:`.DB_RESULT_FIELDS`. :rtype: dict
lookup
python
rsmusllp/king-phisher
king_phisher/geoip.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/geoip.py
BSD-3-Clause
def __init__(self, ip, lang='en', result=None): """ :param str ip: The IP address to look up geographic location data for. :param str lang: The language to prefer for regional names. :param dict result: A raw query result from a previous call to :py:func:`.lookup`. """ if isinstance(ip, str): ip = ipaddress.ip_address(ip) if not result: result = lookup(ip, lang=lang) self.ip_address = ip """The :py:class:`~ipaddress.IPv4Address` which this geographic location data describes.""" for field in DB_RESULT_FIELDS: if field not in result: raise RuntimeError('the retrieved information is missing required data field: ' + field) if field in ('coordinates',): continue setattr(self, field, result[field]) self.coordinates = Coordinates(latitude=result['coordinates'][0], longitude=result['coordinates'][1])
:param str ip: The IP address to look up geographic location data for. :param str lang: The language to prefer for regional names. :param dict result: A raw query result from a previous call to :py:func:`.lookup`.
__init__
python
rsmusllp/king-phisher
king_phisher/geoip.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/geoip.py
BSD-3-Clause
def get_timedelta_for_offset(offset): """ Take a POSIX environment variable style offset from UTC and convert it into a :py:class:`~datetime.timedelta` instance suitable for use with the :py:mod:`icalendar`. :param str offset: The offset from UTC such as "-5:00" :return: The parsed offset. :rtype: :py:class:`datetime.timedelta` """ sign = '+' if offset[0] in ('+', '-'): sign = offset[0] offset = offset[1:] if ':' in offset: hours, minutes = offset.split(':') else: hours, minutes = offset, 0 hours = int(hours) minutes = int(minutes) seconds = ((hours * 60 * 60) + (minutes * 60)) if sign == '-': delta = datetime.timedelta(0, seconds) else: delta = datetime.timedelta(-1, SECONDS_IN_ONE_DAY - seconds) return delta
Take a POSIX environment variable style offset from UTC and convert it into a :py:class:`~datetime.timedelta` instance suitable for use with the :py:mod:`icalendar`. :param str offset: The offset from UTC such as "-5:00" :return: The parsed offset. :rtype: :py:class:`datetime.timedelta`
get_timedelta_for_offset
python
rsmusllp/king-phisher
king_phisher/ics.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/ics.py
BSD-3-Clause
def get_tz_posix_env_var(tz_name): """ Get the timezone information in the POSIX TZ environment variable format from the IANA timezone data files included in the :py:mod:`pytz` package. :param str tz_name: The name of the timezone to get the environment variable for such as "America/New_York". :return: The TZ environment variable string, if it is specified in the timezone data file. :rtype: str """ buffer_size = 2048 if not os.path.isdir(zoneinfo_path): raise ValueError('zoneinfo_path must be a valid directory') file_path = os.path.join(zoneinfo_path, *tz_name.split('/')) with open(file_path, 'rb') as file_h: magic = file_h.read(4) if magic != b'TZif': raise ValueError('the timezone file header is incorrect') version = file_h.read(1) if version != b'2': return '' file_h.seek(max(os.path.getsize(file_path) - buffer_size, 0), os.SEEK_SET) data = file_h.read(buffer_size) end_pos = -2 if its.py_v3: newline = 0x0a else: newline = '\n' while data[end_pos] != newline: end_pos -= 1 end_pos += 1 env_var = data[end_pos:-1] if its.py_v3: env_var = env_var.decode('utf-8') return env_var
Get the timezone information in the POSIX TZ environment variable format from the IANA timezone data files included in the :py:mod:`pytz` package. :param str tz_name: The name of the timezone to get the environment variable for such as "America/New_York". :return: The TZ environment variable string, if it is specified in the timezone data file. :rtype: str
get_tz_posix_env_var
python
rsmusllp/king-phisher
king_phisher/ics.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/ics.py
BSD-3-Clause
def parse_tz_posix_env_var(posix_env_var): """ Get the details regarding a timezone by parsing the POSIX style TZ environment variable. :param str posix_env_var: The POSIX style TZ environment variable. :return: The parsed TZ environment variable. :rtype: :py:class:`.TimezoneOffsetDetails` """ match = POSIX_VAR_OFFSET.match(posix_env_var) if match is None: return match = match.groupdict() offset = get_timedelta_for_offset(match['offset']) if match['offset_dst'] is None: offset_dst = None elif len(match['offset_dst']): offset_dst = get_timedelta_for_offset(match['offset_dst']) else: # default to an hour difference if it's not specified offset_dst = offset - datetime.timedelta(0, SECONDS_IN_ONE_HOUR) dst_start = None dst_end = None match = POSIX_VAR.match(posix_env_var) if match: match = match.groupdict() dst_start = match['start'] dst_end = match['end'] match = POSIX_VAR_DST_RRULE.match(dst_start) details = match.groupdict() byday = details['week'] + DAY_ABBREVIATIONS[int(details['day'])] dst_start = icalendar.vRecur({'BYMONTH': details['month'], 'FREQ': 'YEARLY', 'INTERVAL': 1, 'BYDAY': byday}) match = POSIX_VAR_DST_RRULE.match(dst_end) details = match.groupdict() byday = details['week'] + DAY_ABBREVIATIONS[int(details['day'])] dst_end = icalendar.vRecur({'BYMONTH': details['month'], 'FREQ': 'YEARLY', 'INTERVAL': 1, 'BYDAY': byday}) else: # remove the dst offset if not rrule is present on when it's active offset_dst = None details = TimezoneOffsetDetails(offset, offset_dst, dst_start, dst_end) return details
Get the details regarding a timezone by parsing the POSIX style TZ environment variable. :param str posix_env_var: The POSIX style TZ environment variable. :return: The parsed TZ environment variable. :rtype: :py:class:`.TimezoneOffsetDetails`
parse_tz_posix_env_var
python
rsmusllp/king-phisher
king_phisher/ics.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/ics.py
BSD-3-Clause
def __init__(self, tz_name=None): """ :param str tz_name: The timezone to represent, if not specified it defaults to the local timezone. """ super(Timezone, self).__init__() if tz_name is None: tz_name = tzlocal.get_localzone().zone self.add('tzid', tz_name) tz_details = parse_tz_posix_env_var(get_tz_posix_env_var(tz_name)) timezone_standard = icalendar.TimezoneStandard() timezone_standard.add('dtstart', datetime.datetime(1601, 1, 1, 2, 0, tzinfo=dateutil.tz.tzutc())) timezone_standard.add('tzoffsetfrom', tz_details.offset + datetime.timedelta(0, SECONDS_IN_ONE_HOUR)) timezone_standard.add('tzoffsetto', tz_details.offset) if tz_details.offset_dst: timezone_standard.add('rrule', tz_details.dst_end) timezone_daylight = icalendar.TimezoneDaylight() timezone_daylight.add('dtstart', datetime.datetime(1601, 1, 1, 2, 0, tzinfo=dateutil.tz.tzutc())) timezone_daylight.add('tzoffsetfrom', tz_details.offset) timezone_daylight.add('tzoffsetto', tz_details.offset + datetime.timedelta(0, SECONDS_IN_ONE_HOUR)) timezone_daylight.add('rrule', tz_details.dst_start) self.add_component(timezone_daylight) self.add_component(timezone_standard)
:param str tz_name: The timezone to represent, if not specified it defaults to the local timezone.
__init__
python
rsmusllp/king-phisher
king_phisher/ics.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/ics.py
BSD-3-Clause
def __init__(self, organizer_email, start, summary, organizer_cn=None, description=None, duration='1h', location=None): """ :param str organizer_email: The email of the event organizer. :param start: The start time for the event. :type start: :py:class:`datetime.datetime` :param str summary: A short summary of the event. :param str organizer_cn: The name of the event organizer. :param str description: A more complete description of the event than what is provided by the *summary* parameter. :param duration: The events scheduled duration. :type duration: int, str, :py:class:`~datetime.timedelta`, :py:class:`.DurationAllDay` :param str location: The location for the event. """ utilities.assert_arg_type(start, datetime.datetime, 2) super(Calendar, self).__init__() if start.tzinfo is None: start = start.replace(tzinfo=dateutil.tz.tzlocal()) start = start.astimezone(dateutil.tz.tzutc()) for case in utilities.switch(duration, comp=isinstance): if case(str): duration = smoke_zephyr.utilities.parse_timespan(duration) duration = datetime.timedelta(seconds=duration) break if case(int): duration = datetime.timedelta(seconds=duration) break if case(datetime.timedelta): break if case(DurationAllDay): break else: raise TypeError('unknown duration type') self.add('method', 'REQUEST') self.add('prodid', 'Microsoft Exchange Server 2010') self.add('version', '2.0') self._event = icalendar.Event() event = self._event self.add_component(event) self.add_component(Timezone()) organizer = icalendar.vCalAddress('MAILTO:' + organizer_email) organizer.params['cn'] = icalendar.vText(organizer_cn or organizer_email) event['organizer'] = organizer event.add('description', description or summary) event.add('uid', str(uuid.uuid4())) event.add('summary', summary) if isinstance(duration, DurationAllDay): event.add('dtstart', start.date()) event.add('dtend', (start + datetime.timedelta(days=duration.days)).date()) else: event.add('dtstart', start) event.add('dtend', start + duration) event.add('class', 'PUBLIC') event.add('priority', 5) event.add('dtstamp', datetime.datetime.now(dateutil.tz.tzutc())) event.add('transp', 'OPAQUE') event.add('status', 'CONFIRMED') event.add('sequence', 0) if location: event.add('location', icalendar.vText(location)) alarm = icalendar.Alarm() alarm.add('description', 'REMINDER') alarm.add('trigger;related=start', '-PT1H') alarm.add('action', 'DISPLAY') event.add_component(alarm)
:param str organizer_email: The email of the event organizer. :param start: The start time for the event. :type start: :py:class:`datetime.datetime` :param str summary: A short summary of the event. :param str organizer_cn: The name of the event organizer. :param str description: A more complete description of the event than what is provided by the *summary* parameter. :param duration: The events scheduled duration. :type duration: int, str, :py:class:`~datetime.timedelta`, :py:class:`.DurationAllDay` :param str location: The location for the event.
__init__
python
rsmusllp/king-phisher
king_phisher/ics.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/ics.py
BSD-3-Clause
def add_attendee(self, email, cn=None, rsvp=True): """ Add an attendee to the event. If the event is being sent via an email, the recipient should be added as an attendee. :param str email: The attendee's email address. :param str cn: The attendee's common name. :param bool rsvp: Whether or not to request an RSVP response from the attendee. """ attendee = icalendar.vCalAddress('MAILTO:' + email) attendee.params['ROLE'] = icalendar.vText('REQ-PARTICIPANT') attendee.params['PARTSTAT'] = icalendar.vText('NEEDS-ACTION') attendee.params['RSVP'] = icalendar.vText(str(bool(rsvp)).upper()) attendee.params['CN'] = icalendar.vText(cn or email) self._event.add('attendee', attendee)
Add an attendee to the event. If the event is being sent via an email, the recipient should be added as an attendee. :param str email: The attendee's email address. :param str cn: The attendee's common name. :param bool rsvp: Whether or not to request an RSVP response from the attendee.
add_attendee
python
rsmusllp/king-phisher
king_phisher/ics.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/ics.py
BSD-3-Clause
def is_loopback(address): """ Check if an address is a loopback address or a common name for the loopback interface. :param str address: The address to check. :return: Whether or not the address is a loopback address. :rtype: bool """ if address == 'localhost': return True elif is_valid(address) and ip_address(address).is_loopback: return True return False
Check if an address is a loopback address or a common name for the loopback interface. :param str address: The address to check. :return: Whether or not the address is a loopback address. :rtype: bool
is_loopback
python
rsmusllp/king-phisher
king_phisher/ipaddress.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/ipaddress.py
BSD-3-Clause
def is_valid(address): """ Check that the string specified appears to be either a valid IPv4 or IPv6 address. :param str address: The IP address to validate. :return: Whether the IP address appears to be valid or not. :rtype: bool """ try: ipaddress.ip_address(address) except ValueError: return False return True
Check that the string specified appears to be either a valid IPv4 or IPv6 address. :param str address: The IP address to validate. :return: Whether the IP address appears to be valid or not. :rtype: bool
is_valid
python
rsmusllp/king-phisher
king_phisher/ipaddress.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/ipaddress.py
BSD-3-Clause
def __init__(self, name, description, default=None): """ :param str name: The name of this option. :param str description: The description of this option. :param default: The default value of this option. """ self.name = name self.description = description self.default = default
:param str name: The name of this option. :param str description: The description of this option. :param default: The default value of this option.
__init__
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def __init__(self, name, description, choices, default=None): """ :param str name: The name of this option. :param str description: The description of this option. :param tuple choices: The supported values for this option. :param default: The default value of this option. """ self.choices = choices super(OptionEnum, self).__init__(name, description, default=default)
:param str name: The name of this option. :param str description: The description of this option. :param tuple choices: The supported values for this option. :param default: The default value of this option.
__init__
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def __init__(self, items): """ :param dict items: A dictionary or two-dimensional array mapping requirement names to their respective values. """ # call dict here to allow items to be a two dimensional array suitable for passing to dict items = dict(items) packages = items.get('packages') if isinstance(packages, (list, set, tuple)): missing_packages = self._check_for_missing_packages(packages) packages_dict = {} for package_version in packages: match = self._package_regex.match(package_version) package_name = match.group('name') if match else package_version packages_dict[package_version] = package_name not in missing_packages items['packages'] = packages_dict self._storage = items
:param dict items: A dictionary or two-dimensional array mapping requirement names to their respective values.
__init__
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def is_compatible(self): """Whether or not all requirements are met.""" for req_type, req_details, req_met in self.compatibility_iter(): if not req_met: return False return True
Whether or not all requirements are met.
is_compatible
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def compatibility_iter(self): """ Iterate over each of the requirements, evaluate them and yield a tuple regarding them. """ StrictVersion = distutils.version.StrictVersion if self._storage.get('minimum-python-version'): # platform.python_version() cannot be used with StrictVersion because it returns letters in the version number. available = StrictVersion(self._storage['minimum-python-version']) <= StrictVersion('.'.join(map(str, sys.version_info[:3]))) yield ('Minimum Python Version', self._storage['minimum-python-version'], available) if self._storage.get('minimum-version'): available = StrictVersion(self._storage['minimum-version']) <= StrictVersion(version.distutils_version) yield ('Minimum King Phisher Version', self._storage['minimum-version'], available) if self._storage.get('packages'): for name, available in self._storage['packages'].items(): yield ('Required Package', name, available) if self._storage.get('platforms'): platforms = tuple(p.title() for p in self._storage['platforms']) system = platform.system() yield ('Supported Platforms', ', '.join(platforms), system.title() in platforms)
Iterate over each of the requirements, evaluate them and yield a tuple regarding them.
compatibility_iter
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def __init__(self, path, args=None, library_path=constants.AUTOMATIC): """ :param tuple path: A tuple of directories from which to load plugins. :param tuple args: Arguments which should be passed to plugins when their class is initialized. :param str library_path: A path to use for plugins library dependencies. This value will be added to :py:attr:`sys.path` if it is not already included. """ self._lock = threading.RLock() self.plugin_init_args = (args or ()) self.plugin_base = pluginbase.PluginBase(package='king_phisher.plugins.loaded') self.plugin_source = self.plugin_base.make_plugin_source(searchpath=path) self.loaded_plugins = {} """A dictionary of the loaded plugins and their respective modules.""" self.enabled_plugins = {} """A dictionary of the enabled plugins and their respective instances.""" self.logger = logging.getLogger('KingPhisher.Plugins.Manager') if library_path is not None: library_path = _resolve_lib_path(library_path) if library_path: if library_path not in sys.path: sys.path.append(library_path) library_path = os.path.abspath(library_path) self.logger.debug('using plugin-specific library path: ' + library_path) else: self.logger.debug('no plugin-specific library path has been specified') self.library_path = library_path """ The path to a directory which is included for additional libraries. This path must be writable by the current user. The default value is platform and Python-version (where X.Y is the major and minor versions of Python) dependant: :Linux: ``~/.local/lib/king-phisher/pythonX.Y/site-packages`` :Windows: ``%LOCALAPPDATA%\\king-phisher\\lib\\pythonX.Y\\site-packages`` """
:param tuple path: A tuple of directories from which to load plugins. :param tuple args: Arguments which should be passed to plugins when their class is initialized. :param str library_path: A path to use for plugins library dependencies. This value will be added to :py:attr:`sys.path` if it is not already included.
__init__
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def get_plugin_path(self, name): """ Get the path at which the plugin data resides. This is either the path to the single plugin file or a folder in the case that the plugin is a module. In either case, the path is an absolute path. :param str name: The name of the plugin to get the path for. :return: The path of the plugin data. :rtype: str """ module = self.load_module(name) path = getattr(module, '__file__', None) if path is None: return if path.endswith(('.pyc', '.pyo')): path = path[:-1] if path.endswith(os.path.sep + '__init__.py'): path = path[:-11] return path
Get the path at which the plugin data resides. This is either the path to the single plugin file or a folder in the case that the plugin is a module. In either case, the path is an absolute path. :param str name: The name of the plugin to get the path for. :return: The path of the plugin data. :rtype: str
get_plugin_path
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def enable(self, name): """ Enable a plugin by it's name. This will create a new instance of the plugin modules "Plugin" class, passing it the arguments defined in :py:attr:`.plugin_init_args`. A reference to the plugin instance is kept in :py:attr:`.enabled_plugins`. After the instance is created, the plugins :py:meth:`~.PluginBase.initialize` method is called. :param str name: The name of the plugin to enable. :return: The newly created instance. :rtype: :py:class:`.PluginBase` """ self._lock.acquire() klass = self.loaded_plugins[name] if not klass.is_compatible: self._lock.release() raise errors.KingPhisherPluginError(name, 'the plugin is incompatible') inst = klass(*self.plugin_init_args) try: initialized = inst.initialize() except Exception: self.logger.error("failed to enable plugin '{0}', initialize threw an exception".format(name), exc_info=True) try: inst._cleanup() except Exception: self.logger.error("failed to clean up resources for plugin '{0}'".format(name), exc_info=True) self._lock.release() raise if not initialized: self.logger.warning("failed to enable plugin '{0}', initialize check failed".format(name)) self._lock.release() return self.enabled_plugins[name] = inst self._lock.release() self.logger.info("plugin '{0}' has been enabled".format(name)) return inst
Enable a plugin by it's name. This will create a new instance of the plugin modules "Plugin" class, passing it the arguments defined in :py:attr:`.plugin_init_args`. A reference to the plugin instance is kept in :py:attr:`.enabled_plugins`. After the instance is created, the plugins :py:meth:`~.PluginBase.initialize` method is called. :param str name: The name of the plugin to enable. :return: The newly created instance. :rtype: :py:class:`.PluginBase`
enable
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def disable(self, name): """ Disable a plugin by it's name. This call the plugins :py:meth:`.PluginBase.finalize` method to allow it to perform any clean up operations. :param str name: The name of the plugin to disable. """ self._lock.acquire() inst = self.enabled_plugins[name] inst.finalize() inst._cleanup() del self.enabled_plugins[name] self._lock.release() self.logger.info("plugin '{0}' has been disabled".format(name))
Disable a plugin by it's name. This call the plugins :py:meth:`.PluginBase.finalize` method to allow it to perform any clean up operations. :param str name: The name of the plugin to disable.
disable
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def load(self, name, reload_module=False): """ Load a plugin into memory, this is effectively the Python equivalent of importing it. A reference to the plugin class is kept in :py:attr:`.loaded_plugins`. If the plugin is already loaded, no changes are made. :param str name: The name of the plugin to load. :param bool reload_module: Reload the module to allow changes to take affect. :return: The plugin class. """ self._lock.acquire() if not reload_module and name in self.loaded_plugins: self._lock.release() return module = self.load_module(name, reload_module=reload_module) klass = getattr(module, 'Plugin', None) if klass is None: self._lock.release() self.logger.warning("failed to load plugin '{0}', Plugin class not found".format(name)) raise errors.KingPhisherPluginError(name, 'the Plugin class is missing') if not issubclass(klass, self._plugin_klass): self._lock.release() self.logger.warning("failed to load plugin '{0}', Plugin class is invalid".format(name)) raise errors.KingPhisherPluginError(name, 'the Plugin class is invalid') self.loaded_plugins[name] = klass self.logger.debug("plugin '{0}' has been {1}loaded".format(name, 're' if reload_module else '')) self._lock.release() return klass
Load a plugin into memory, this is effectively the Python equivalent of importing it. A reference to the plugin class is kept in :py:attr:`.loaded_plugins`. If the plugin is already loaded, no changes are made. :param str name: The name of the plugin to load. :param bool reload_module: Reload the module to allow changes to take affect. :return: The plugin class.
load
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def load_all(self, on_error=None): """ Load all available plugins. Exceptions while loading specific plugins are ignored. If *on_error* is specified, it will be called from within the exception handler when a plugin fails to load correctly. It will be called with two parameters, the name of the plugin and the exception instance. :param on_error: A call back function to call when an error occurs while loading a plugin. :type on_error: function """ self._lock.acquire() plugins = self.plugin_source.list_plugins() self.logger.info("loading {0:,} plugins".format(len(plugins))) for name in plugins: try: self.load(name) except Exception as error: if on_error: on_error(name, error) self._lock.release()
Load all available plugins. Exceptions while loading specific plugins are ignored. If *on_error* is specified, it will be called from within the exception handler when a plugin fails to load correctly. It will be called with two parameters, the name of the plugin and the exception instance. :param on_error: A call back function to call when an error occurs while loading a plugin. :type on_error: function
load_all
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def load_module(self, name, reload_module=False): """ Load the module which contains a plugin into memory and return the entire module object. :param str name: The name of the plugin module to load. :param bool reload_module: Reload the module to allow changes to take affect. :return: The plugin module. """ try: module = self.plugin_source.load_plugin(name) except Exception as error: self._lock.release() raise error if reload_module: recursive_reload(module) return module
Load the module which contains a plugin into memory and return the entire module object. :param str name: The name of the plugin module to load. :param bool reload_module: Reload the module to allow changes to take affect. :return: The plugin module.
load_module
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def install_packages(self, packages): """ This function will take a list of Python packages and attempt to install them through pip to the :py:attr:`.library_path`. .. versionadded:: 1.14.0 :param list packages: list of python packages to install using pip. :return: The process results from the command execution. :rtype: :py:class:`~.ProcessResults` """ pip_options = [] if self.library_path is None: raise errors.KingPhisherResourceError('missing plugin-specific library path') pip_options.extend(['--target', self.library_path]) if its.frozen: args = [os.path.join(os.path.dirname(sys.executable), 'python.exe')] else: args = [sys.executable] args += ['-m', 'pip', 'install'] + pip_options + packages if len(packages) > 1: info_string = "installing packages: {}" else: info_string = "installing package: {}" self.logger.info(info_string.format(', '.join(packages))) return startup.run_process(args)
This function will take a list of Python packages and attempt to install them through pip to the :py:attr:`.library_path`. .. versionadded:: 1.14.0 :param list packages: list of python packages to install using pip. :return: The process results from the command execution. :rtype: :py:class:`~.ProcessResults`
install_packages
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def uninstall(self, name): """ Uninstall a plugin by first unloading it and then delete it's data on disk. The plugin data on disk is found with the :py:meth:`.get_plugin_path` method. :param str name: The name of the plugin to uninstall. :return: Whether or not the plugin was successfully uninstalled. :rtype: bool """ plugin_path = self.get_plugin_path(name) if os.path.isfile(plugin_path) or os.path.islink(plugin_path): os.remove(plugin_path) elif os.path.isdir(plugin_path): shutil.rmtree(plugin_path) else: self.logger.warning('failed to identify the data path for plugin: ' + name) return False self.unload(name) return True
Uninstall a plugin by first unloading it and then delete it's data on disk. The plugin data on disk is found with the :py:meth:`.get_plugin_path` method. :param str name: The name of the plugin to uninstall. :return: Whether or not the plugin was successfully uninstalled. :rtype: bool
uninstall
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def unload(self, name): """ Unload a plugin from memory. If the specified plugin is currently enabled, it will first be disabled before being unloaded. If the plugin is not already loaded, no changes are made. :param str name: The name of the plugin to unload. """ self._lock.acquire() if not name in self.loaded_plugins: self._lock.release() return if name in self.enabled_plugins: self.disable(name) del self.loaded_plugins[name] self.logger.debug("plugin '{0}' has been unloaded".format(name)) self._lock.release()
Unload a plugin from memory. If the specified plugin is currently enabled, it will first be disabled before being unloaded. If the plugin is not already loaded, no changes are made. :param str name: The name of the plugin to unload.
unload
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def unload_all(self): """ Unload all available plugins. Exceptions while unloading specific plugins are ignored. """ self._lock.acquire() self.logger.info("unloading {0:,} plugins".format(len(self.loaded_plugins))) for name in tuple(self.loaded_plugins.keys()): try: self.unload(name) except Exception: pass self._lock.release()
Unload all available plugins. Exceptions while unloading specific plugins are ignored.
unload_all
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def openssl_decrypt_data(ciphertext, password, digest='sha256', encoding='utf-8'): """ Decrypt *ciphertext* in the same way as OpenSSL. For the meaning of *digest* see the :py:func:`.openssl_derive_key_and_iv` function documentation. .. note:: This function can be used to decrypt ciphertext created with the ``openssl`` command line utility. .. code-block:: none openssl enc -e -aes-256-cbc -in file -out file.enc -md sha256 :param bytes ciphertext: The encrypted data to decrypt. :param str password: The password to use when deriving the decryption key. :param str digest: The name of hashing function to use to generate the key. :param str encoding: The name of the encoding to use for the password. :return: The decrypted data. :rtype: bytes """ salt = b'' if ciphertext[:8] == b'Salted__': salt = ciphertext[8:16] ciphertext = ciphertext[16:] my_key, my_iv = openssl_derive_key_and_iv(password, salt, 32, 16, digest=digest, encoding=encoding) cipher = ciphers.Cipher( ciphers.algorithms.AES(my_key), ciphers.modes.CBC(my_iv), backend=backends.default_backend() ) decryptor = cipher.decryptor() plaintext = decryptor.update(ciphertext) + decryptor.finalize() unpadder = padding.PKCS7(cipher.algorithm.block_size).unpadder() return unpadder.update(plaintext) + unpadder.finalize()
Decrypt *ciphertext* in the same way as OpenSSL. For the meaning of *digest* see the :py:func:`.openssl_derive_key_and_iv` function documentation. .. note:: This function can be used to decrypt ciphertext created with the ``openssl`` command line utility. .. code-block:: none openssl enc -e -aes-256-cbc -in file -out file.enc -md sha256 :param bytes ciphertext: The encrypted data to decrypt. :param str password: The password to use when deriving the decryption key. :param str digest: The name of hashing function to use to generate the key. :param str encoding: The name of the encoding to use for the password. :return: The decrypted data. :rtype: bytes
openssl_decrypt_data
python
rsmusllp/king-phisher
king_phisher/security_keys.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/security_keys.py
BSD-3-Clause
def openssl_derive_key_and_iv(password, salt, key_length, iv_length, digest='sha256', encoding='utf-8'): """ Derive an encryption key and initialization vector (IV) in the same way as OpenSSL. .. note:: Different versions of OpenSSL use a different default value for the *digest* function used to derive keys and initialization vectors. A specific one can be used by passing the ``-md`` option to the ``openssl`` command which corresponds to the *digest* parameter of this function. :param str password: The password to use when deriving the key and IV. :param bytes salt: A value to use as a salt for the operation. :param int key_length: The length in bytes of the key to return. :param int iv_length: The length in bytes of the IV to return. :param str digest: The name of hashing function to use to generate the key. :param str encoding: The name of the encoding to use for the password. :return: The key and IV as a tuple. :rtype: tuple """ password = password.encode(encoding) digest_function = getattr(hashlib, digest) chunk = b'' data = b'' while len(data) < key_length + iv_length: chunk = digest_function(chunk + password + salt).digest() data += chunk return data[:key_length], data[key_length:key_length + iv_length]
Derive an encryption key and initialization vector (IV) in the same way as OpenSSL. .. note:: Different versions of OpenSSL use a different default value for the *digest* function used to derive keys and initialization vectors. A specific one can be used by passing the ``-md`` option to the ``openssl`` command which corresponds to the *digest* parameter of this function. :param str password: The password to use when deriving the key and IV. :param bytes salt: A value to use as a salt for the operation. :param int key_length: The length in bytes of the key to return. :param int iv_length: The length in bytes of the IV to return. :param str digest: The name of hashing function to use to generate the key. :param str encoding: The name of the encoding to use for the password. :return: The key and IV as a tuple. :rtype: tuple
openssl_derive_key_and_iv
python
rsmusllp/king-phisher
king_phisher/security_keys.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/security_keys.py
BSD-3-Clause
def from_file(cls, file_path, password=None, encoding='utf-8'): """ Load the signing key from the specified file. If *password* is specified, the file is assumed to have been encrypted using OpenSSL with ``aes-256-cbc`` as the cipher and ``sha256`` as the message digest. This uses :py:func:`.openssl_decrypt_data` internally for decrypting the data. :param str file_path: The path to the file to load. :param str password: An optional password to use for decrypting the file. :param str encoding: The encoding of the data. :return: A tuple of the key's ID, and the new :py:class:`.SigningKey` instance. :rtype: tuple """ with open(file_path, 'rb') as file_h: file_data = file_h.read() if password: file_data = openssl_decrypt_data(file_data, password, encoding=encoding) file_data = file_data.decode(encoding) file_data = serializers.JSON.loads(file_data) utilities.validate_json_schema(file_data, 'king-phisher.security.key') return cls.from_dict(file_data['signing-key'], encoding=file_data.pop('encoding', 'base64'), id=file_data['id'])
Load the signing key from the specified file. If *password* is specified, the file is assumed to have been encrypted using OpenSSL with ``aes-256-cbc`` as the cipher and ``sha256`` as the message digest. This uses :py:func:`.openssl_decrypt_data` internally for decrypting the data. :param str file_path: The path to the file to load. :param str password: An optional password to use for decrypting the file. :param str encoding: The encoding of the data. :return: A tuple of the key's ID, and the new :py:class:`.SigningKey` instance. :rtype: tuple
from_file
python
rsmusllp/king-phisher
king_phisher/security_keys.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/security_keys.py
BSD-3-Clause
def sign_dict(self, data, signature_encoding='base64'): """ Sign a dictionary object. The dictionary will have a 'signature' key added is required by the :py:meth:`.VerifyingKey.verify_dict` method. To serialize the dictionary to data suitable for the operation the :py:func:`json.dumps` function is used and the resulting data is then UTF-8 encoded. :param dict data: The dictionary of data to sign. :param str signature_encoding: The encoding name of the signature data. :return: The dictionary object is returned with the 'signature' key added. """ utilities.assert_arg_type(data, dict, arg_pos=1) data = copy.copy(data) data.pop('signature', None) # remove a pre-existing signature json_data = json.dumps(data, sort_keys=True).encode('utf-8') data['signature'] = _encoding_data(self.sign(json_data), encoding=signature_encoding) return data
Sign a dictionary object. The dictionary will have a 'signature' key added is required by the :py:meth:`.VerifyingKey.verify_dict` method. To serialize the dictionary to data suitable for the operation the :py:func:`json.dumps` function is used and the resulting data is then UTF-8 encoded. :param dict data: The dictionary of data to sign. :param str signature_encoding: The encoding name of the signature data. :return: The dictionary object is returned with the 'signature' key added.
sign_dict
python
rsmusllp/king-phisher
king_phisher/security_keys.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/security_keys.py
BSD-3-Clause
def verify_dict(self, data, signature_encoding='base64'): """ Verify a signed dictionary object. The dictionary must have a 'signature' key as added by the :py:meth:`.SigningKey.sign_dict` method. To serialize the dictionary to data suitable for the operation the :py:func:`json.dumps` function is used and the resulting data is then UTF-8 encoded. :param dict data: The dictionary of data to verify. :param str signature_encoding: The encoding name of the signature data. """ utilities.assert_arg_type(data, dict, arg_pos=1) data = copy.copy(data) signature = _decode_data(data.pop('signature'), encoding=signature_encoding) data = json.dumps(data, sort_keys=True).encode('utf-8') return self.verify(signature, data)
Verify a signed dictionary object. The dictionary must have a 'signature' key as added by the :py:meth:`.SigningKey.sign_dict` method. To serialize the dictionary to data suitable for the operation the :py:func:`json.dumps` function is used and the resulting data is then UTF-8 encoded. :param dict data: The dictionary of data to verify. :param str signature_encoding: The encoding name of the signature data.
verify_dict
python
rsmusllp/king-phisher
king_phisher/security_keys.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/security_keys.py
BSD-3-Clause
def verify(self, key_id, data, signature): """ Verify the data with the specified signature as signed by the specified key. This function will raise an exception if the verification fails for any reason, including if the key can not be found. :param str key_id: The key's identifier. :param bytes data: The data to verify against the signature. :param bytes signature: The signature of the data to verify. """ verifying_key = self._get_verifying_key(key_id) return verifying_key.verify(signature, data)
Verify the data with the specified signature as signed by the specified key. This function will raise an exception if the verification fails for any reason, including if the key can not be found. :param str key_id: The key's identifier. :param bytes data: The data to verify against the signature. :param bytes signature: The signature of the data to verify.
verify
python
rsmusllp/king-phisher
king_phisher/security_keys.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/security_keys.py
BSD-3-Clause
def verify_dict(self, data, signature_encoding='base64'): """ Verify the signed dictionary, using the key specified within the 'signed-by' key. This function will raise an exception if the verification fails for any reason, including if the key can not be found. :param str key_id: The key's identifier. :param bytes data: The data to verify against the signature. :param bytes signature: The signature of the data to verify. """ key_id = data['signed-by'] verifying_key = self._get_verifying_key(key_id) return verifying_key.verify_dict(data, signature_encoding=signature_encoding)
Verify the signed dictionary, using the key specified within the 'signed-by' key. This function will raise an exception if the verification fails for any reason, including if the key can not be found. :param str key_id: The key's identifier. :param bytes data: The data to verify against the signature. :param bytes signature: The signature of the data to verify.
verify_dict
python
rsmusllp/king-phisher
king_phisher/security_keys.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/security_keys.py
BSD-3-Clause
def dumps(cls, data, pretty=True): """ Convert a Python object to a JSON encoded string. :param data: The object to encode. :param bool pretty: Set options to make the resulting JSON data more readable. :return: The encoded data. :rtype: str """ kwargs = {'default': cls._json_default} if pretty: kwargs['sort_keys'] = True kwargs['indent'] = 2 kwargs['separators'] = (',', ': ') return json.dumps(data, **kwargs)
Convert a Python object to a JSON encoded string. :param data: The object to encode. :param bool pretty: Set options to make the resulting JSON data more readable. :return: The encoded data. :rtype: str
dumps
python
rsmusllp/king-phisher
king_phisher/serializers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/serializers.py
BSD-3-Clause
def loads(cls, data, strict=True): """ Load JSON encoded data. :param str data: The encoded data to load. :param bool strict: Do not try remove trailing commas from the JSON data. :return: The Python object represented by the encoded data. """ if not strict: data = CLEAN_JSON_REGEX.sub(r'\1', data) return json.loads(data, object_hook=cls._json_object_hook)
Load JSON encoded data. :param str data: The encoded data to load. :param bool strict: Do not try remove trailing commas from the JSON data. :return: The Python object represented by the encoded data.
loads
python
rsmusllp/king-phisher
king_phisher/serializers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/serializers.py
BSD-3-Clause
def from_elementtree_element(element, require_type=True): """ Load a value from an :py:class:`xml.etree.ElementTree.SubElement` instance. If *require_type* is True, then the element must specify an acceptable value via the "type" attribute. If *require_type* is False and no type attribute is specified, the value is returned as a string. :param element: The element to load a value from. :type element: :py:class:`xml.etree.ElementTree.Element` :param bool require_type: Whether or not to require type information. :return: The deserialized value from the element. """ if require_type and not 'type' in element.attrib: raise TypeError('type is not specified in the element attributes') type_ = element.attrib.get('type', 'string') value = element.text for case in switch(type_): if case('boolean'): value = value.lower() if not value in ('true', 'false'): raise ValueError('unknown boolean value: ' + value) value = value == 'true' break if case('date'): value = dateutil.parser.parse(value).date() break if case('datetime'): value = dateutil.parser.parse(value) break if case('float'): value = float(value) break if case('integer'): value = int(value) break if case('null'): value = None break if case('string'): value = value or '' break if case('time'): value = dateutil.parser.parse(value).time() else: raise TypeError('can not serialize value to an xml subelement') return value
Load a value from an :py:class:`xml.etree.ElementTree.SubElement` instance. If *require_type* is True, then the element must specify an acceptable value via the "type" attribute. If *require_type* is False and no type attribute is specified, the value is returned as a string. :param element: The element to load a value from. :type element: :py:class:`xml.etree.ElementTree.Element` :param bool require_type: Whether or not to require type information. :return: The deserialized value from the element.
from_elementtree_element
python
rsmusllp/king-phisher
king_phisher/serializers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/serializers.py
BSD-3-Clause
def to_elementtree_subelement(parent, tag, value, attrib=None): """ Serialize *value* to an :py:class:`xml.etree.ElementTree.SubElement` with appropriate information describing it's type. If *value* is not of a supported type, a :py:exc:`TypeError` will be raised. :param parent: The parent element to associate this subelement with. :type parent: :py:class:`xml.etree.ElementTree.Element` :param str tag: The name of the XML tag. :param value: The value to serialize to an XML element. :param dict attrib: Optional attributes to include in the element. :return: The newly created XML element, representing *value*. :rtype: :py:class:`xml.etree.ElementTree.Element` """ attrib = attrib or {} for case in switch(type(value)): if case(type(None)): value = '' type_ = 'null' break if case(bool): value = str(value).lower() type_ = 'boolean' break if case(datetime.date): value = value.isoformat() type_ = 'date' break if case(datetime.datetime): value = value.isoformat() type_ = 'datetime' break if case(float): value = str(value) type_ = 'float' break if case(int): value = str(value) type_ = 'integer' break if case(str) or (its.py_v2 and case(unicode)): type_ = 'string' break if case(datetime.time): value = value.isoformat() type_ = 'time' break else: raise TypeError('can not serialize value to an xml subelement') attrib['type'] = type_ sub_element = ET.SubElement(parent, tag, attrib=attrib) sub_element.text = value return sub_element
Serialize *value* to an :py:class:`xml.etree.ElementTree.SubElement` with appropriate information describing it's type. If *value* is not of a supported type, a :py:exc:`TypeError` will be raised. :param parent: The parent element to associate this subelement with. :type parent: :py:class:`xml.etree.ElementTree.Element` :param str tag: The name of the XML tag. :param value: The value to serialize to an XML element. :param dict attrib: Optional attributes to include in the element. :return: The newly created XML element, representing *value*. :rtype: :py:class:`xml.etree.ElementTree.Element`
to_elementtree_subelement
python
rsmusllp/king-phisher
king_phisher/serializers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/serializers.py
BSD-3-Clause
def get_smtp_servers(domain): """ Get the SMTP servers for the specified domain by querying their MX records. :param str domain: The domain to look up the MX records for. :return: The smtp servers for the specified domain. :rtype: list """ mx_records = dns.resolver.query(domain, 'MX') return [str(r.exchange).rstrip('.') for r in mx_records]
Get the SMTP servers for the specified domain by querying their MX records. :param str domain: The domain to look up the MX records for. :return: The smtp servers for the specified domain. :rtype: list
get_smtp_servers
python
rsmusllp/king-phisher
king_phisher/sms.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/sms.py
BSD-3-Clause
def lookup_carrier_gateway(carrier): """ Lookup the SMS gateway for the specified carrier. Normalization on the carrier name does take place and if an invalid or unknown value is specified, None will be returned. :param str carrier: The name of the carrier to lookup. :return: The SMS gateway for the specified carrier. :rtype: str """ carrier = normalize_name(carrier) carrier_address = [c for c in CARRIERS.keys() if normalize_name(c) == carrier] if len(carrier_address) != 1: return None return CARRIERS[carrier_address[0]]
Lookup the SMS gateway for the specified carrier. Normalization on the carrier name does take place and if an invalid or unknown value is specified, None will be returned. :param str carrier: The name of the carrier to lookup. :return: The SMS gateway for the specified carrier. :rtype: str
lookup_carrier_gateway
python
rsmusllp/king-phisher
king_phisher/sms.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/sms.py
BSD-3-Clause
def send_sms(message_text, phone_number, carrier, from_address=None): """ Send an SMS message by emailing the carriers SMS gateway. This method requires no money however some networks are blocked by the carriers due to being flagged for spam which can cause issues. :param str message_text: The message to send. :param str phone_number: The phone number to send the SMS to. :param str carrier: The cellular carrier that the phone number belongs to. :param str from_address: The optional address to display in the 'from' field of the SMS. :return: This returns the status of the sent message. :rtype: bool """ from_address = (from_address or DEFAULT_FROM_ADDRESS) phone_number = phone_number.replace('-', '').replace(' ', '') # remove the country code for these 10-digit based match = re.match('1?(?P<phone_number>[0-9]{10})', phone_number) if match is None: raise ValueError('the phone number appears invalid') phone_number = match.group('phone_number') if len(message_text) > 160: raise ValueError('message length exceeds 160 characters') message = MIMEText(message_text) carrier_address = lookup_carrier_gateway(carrier) if not carrier_address: raise ValueError('unknown carrier specified') to_address = "{0}@{1}".format(phone_number, carrier_address) message['To'] = to_address message['From'] = from_address sms_gateways = get_smtp_servers(carrier_address) random.shuffle(sms_gateways) message_sent = False for sms_gateway in sms_gateways: try: smtp_connection = smtplib.SMTP(sms_gateway) smtp_connection.sendmail(from_address, [to_address], message.as_string()) smtp_connection.quit() except (smtplib.SMTPConnectError, smtplib.SMTPDataError, smtplib.SMTPHeloError): continue message_sent = True break return message_sent
Send an SMS message by emailing the carriers SMS gateway. This method requires no money however some networks are blocked by the carriers due to being flagged for spam which can cause issues. :param str message_text: The message to send. :param str phone_number: The phone number to send the SMS to. :param str carrier: The cellular carrier that the phone number belongs to. :param str from_address: The optional address to display in the 'from' field of the SMS. :return: This returns the status of the sent message. :rtype: bool
send_sms
python
rsmusllp/king-phisher
king_phisher/sms.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/sms.py
BSD-3-Clause
def __init__(self, localaddr, remoteaddr=None): """ :param tuple localaddr: The local address to bind to. :param tuple remoteaddr: The remote address to use as an upstream SMTP relayer. """ self.logger = logging.getLogger('KingPhisher.SMTPD') super(BaseSMTPServer, self).__init__(localaddr, remoteaddr) self.logger.info("smtp server listening on {0}:{1}".format(localaddr[0], localaddr[1]))
:param tuple localaddr: The local address to bind to. :param tuple remoteaddr: The remote address to use as an upstream SMTP relayer.
__init__
python
rsmusllp/king-phisher
king_phisher/smtp_server.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/smtp_server.py
BSD-3-Clause
def __init__(self, mechanism, qualifier, rvalue=None): """ :param str mechanism: The SPF mechanism that this directive uses. :param str qualifier: The qualifier value of the directive in it's single character format. :param str rvalue: The optional rvalue for directives which use them. """ if qualifier not in QUALIFIERS: raise ValueError('invalid qualifier: ' + qualifier) self.mechanism = mechanism self.qualifier = qualifier self.rvalue = rvalue
:param str mechanism: The SPF mechanism that this directive uses. :param str qualifier: The qualifier value of the directive in it's single character format. :param str rvalue: The optional rvalue for directives which use them.
__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 from_string(cls, directive): """ Parse an SPF directive from a string and return it's class representation. :param str directive: The SPF directive to parse. """ if ':' in directive: (mechanism, rvalue) = directive.split(':', 1) else: (mechanism, rvalue) = (directive, None) mechanism = mechanism.lower() qualifier = '+' if mechanism[0] in QUALIFIERS: qualifier = mechanism[0] mechanism = mechanism[1:] return cls(mechanism, qualifier, rvalue)
Parse an SPF directive from a string and return it's class representation. :param str directive: The SPF directive to parse.
from_string
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, directives, domain=None): """ :param list directives: A list of :py:class:`.SPFDirective` instances. :param str domain: The domain with which this record is associated with. """ self.directives = directives self.domain = domain
:param list directives: A list of :py:class:`.SPFDirective` instances. :param str domain: The domain with which this record is associated with.
__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 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