code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
"Open an editor visiting the current file at the current line" if arg == '': filename, lineno = self._get_current_position() else: filename, lineno, _ = self._get_position_of_arg(arg) if filename is None: return # this case handles code...
def do_edit(self, arg)
Open an editor visiting the current file at the current line
5.452367
4.676002
1.166032
if hasattr(local, '_pdbpp_completing'): # Handle set_trace being called during completion, e.g. with # fancycompleter's attr_matches. return if frame is None: frame = sys._getframe().f_back self._via_set_trace_frame = frame return ...
def set_trace(self, frame=None)
Remember starting frame. This is used with pytest, which does not use pdb.set_trace().
8.655931
7.901907
1.095423
if module_name is None: return False return super(Pdb, self).is_skipped_module(module_name)
def is_skipped_module(self, module_name)
Backport for https://bugs.python.org/issue36130. Fixed in Python 3.8+.
3.954011
3.564096
1.109401
print("***", msg, file=self.stdout) if not self.config.show_traceback_on_error: return etype, evalue, tb = sys.exc_info() if tb and tb.tb_frame.f_code.co_name == "default": tb = tb.tb_next if tb and tb.tb_frame.f_code.co_filename == "<stdin>...
def error(self, msg)
Override/enhance default error method to display tracebacks.
3.680306
3.542878
1.03879
removed_bdb_context = evalue while removed_bdb_context.__context__: ctx = removed_bdb_context.__context__ if ( isinstance(ctx, AttributeError) and ctx.__traceback__.tb_frame.f_code.co_name == "onecmd" ): removed...
def _remove_bdb_context(evalue)
Remove exception context from Pdb from the exception. E.g. "AttributeError: 'Pdb' object has no attribute 'do_foo'", when trying to look up commands (bpo-36494).
3.436675
3.04494
1.128651
new_kwargs = {} params = signature(func).parameters for param_name in params.keys(): if param_name in kwargs: new_kwargs[param_name] = kwargs[param_name] return func(**new_kwargs)
def apply_kwargs(func, **kwargs)
Call *func* with kwargs, but only those kwargs that it accepts.
2.105148
2.024081
1.040051
func_args = signature(func).parameters @wraps(func) def wrapper(*args, **kwargs): config = get_config() for i, argname in enumerate(func_args): if len(args) > i or argname in kwargs: continue elif argname in config: kwargs[argname...
def args_from_config(func)
Decorator that injects parameters from the configuration.
2.687128
2.643996
1.016313
process = psutil.Process(os.getpid()) mem = process.memory_info()[0] / float(2 ** 20) mem_vms = process.memory_info()[1] / float(2 ** 20) return mem, mem_vms
def memory_usage_psutil()
Return the current process memory usage in MB.
1.893845
1.89152
1.001229
def version_cmd(argv=sys.argv[1:]): # pragma: no cover docopt(version_cmd.__doc__, argv=argv) print(__version__)
\ Print the version number of Palladium. Usage: pld-version [options] Options: -h --help Show this screen.
null
null
null
def upgrade_cmd(argv=sys.argv[1:]): # pragma: no cover arguments = docopt(upgrade_cmd.__doc__, argv=argv) initialize_config(__mode__='fit') upgrade(from_version=arguments['--from'], to_version=arguments['--to'])
\ Upgrade the database to the latest version. Usage: pld-ugprade [options] Options: --from=<v> Upgrade from a specific version, overriding the version stored in the database. --to=<v> Upgrade to a specific version instead of the ...
null
null
null
def export_cmd(argv=sys.argv[1:]): # pragma: no cover arguments = docopt(export_cmd.__doc__, argv=argv) model_version = export( model_version=arguments['--version'], activate=not arguments['--no-activate'], ) logger.info("Exported model. New version number: {}".format(model_ver...
\ Export a model from one model persister to another. The model persister to export to is supposed to be available in the configuration file under the 'model_persister_export' key. Usage: pld-export [options] Options: --version=<v> Export a specific version rather than the active ...
null
null
null
if isinstance(func, str): func = resolve_dotted_name(func) partial_func = partial(func, **kwargs) update_wrapper(partial_func, func) return partial_func
def Partial(func, **kwargs)
Allows the use of partially applied functions in the configuration.
2.67688
3.12867
0.855597
json_encoded = ujson.encode(obj, ensure_ascii=False, double_precision=-1) resp = make_response(json_encoded) resp.mimetype = 'application/json' resp.content_type = 'application/json; charset=utf-8' resp.status_code = status_code return resp
def make_ujson_response(obj, status_code=200)
Encodes the given *obj* to json and wraps it in a response. :return: A Flask response.
2.408581
2.65263
0.907997
model_persister = config.get('model_persister') @app.route(route, methods=['GET', 'POST'], endpoint=route) @PluggableDecorator(decorator_list_name) def predict_func(): return predict(model_persister, predict_service) return predict_func
def create_predict_function( route, predict_service, decorator_list_name, config)
Creates a predict function and registers it to the Flask app using the route decorator. :param str route: Path of the entry point. :param palladium.interfaces.PredictService predict_service: The predict service to be registered to this entry point. :param str decorator_list_name: Th...
4.118012
5.632986
0.731053
def devserver_cmd(argv=sys.argv[1:]): # pragma: no cover arguments = docopt(devserver_cmd.__doc__, argv=argv) initialize_config() app.run( host=arguments['--host'], port=int(arguments['--port']), debug=int(arguments['--debug']), )
\ Serve the web API for development. Usage: pld-devserver [options] Options: -h --help Show this screen. --host=<host> The host to use [default: 0.0.0.0]. --port=<port> The port to use [default: 5000]. --debug=<debug> Whether or not to use debug mode [default: 0]...
null
null
null
def stream_cmd(argv=sys.argv[1:]): # pragma: no cover docopt(stream_cmd.__doc__, argv=argv) initialize_config() stream = PredictStream() stream.listen(sys.stdin, sys.stdout, sys.stderr)
\ Start the streaming server, which listens to stdin, processes line by line, and returns predictions. The input should consist of a list of json objects, where each object will result in a prediction. Each line is processed in a batch. Example input (must be on a single line): [{"sepal length": 1.0, "sepal width...
null
null
null
values = [] for key, type_name in self.mapping: value_type = self.types[type_name] values.append(value_type(data[key])) if self.unwrap_sample: assert len(values) == 1 return np.array(values[0]) else: return np.array(val...
def sample_from_data(self, model, data)
Convert incoming sample *data* into a numpy array. :param model: The :class:`~Model` instance to use for making predictions. :param data: A dict-like with the sample's data, typically retrieved from ``request.args`` or similar.
3.661857
4.061448
0.901614
params = {} for key, type_name in self.params: value_type = self.types[type_name] if key in data: params[key] = value_type(data[key]) elif hasattr(model, key): params[key] = getattr(model, key) return params
def params_from_data(self, model, data)
Retrieve additional parameters (keyword arguments) for ``model.predict`` from request *data*. :param model: The :class:`~Model` instance to use for making predictions. :param data: A dict-like with the parameter data, typically retrieved from ``request.args`` or si...
2.582335
3.105382
0.831568
result = y_pred.tolist() if single: result = result[0] response = { 'metadata': get_metadata(), 'result': result, } return make_ujson_response(response, status_code=200)
def response_from_prediction(self, y_pred, single=True)
Turns a model's prediction in *y_pred* into a JSON response.
4.11813
4.007551
1.027593
for line in io_in: if line.strip().lower() == 'exit': break try: y_pred = self.process_line(line) except Exception as e: io_out.write('[]\n') io_err.write( "Error while processing in...
def listen(self, io_in, io_out, io_err)
Listens to provided io stream and writes predictions to output. In case of errors, the error stream will be used.
2.922304
2.849416
1.02558
def list_cmd(argv=sys.argv[1:]): # pragma: no cover docopt(list_cmd.__doc__, argv=argv) initialize_config(__mode__='fit') list()
\ List information about available models. Uses the 'model_persister' from the configuration to display a list of models and their metadata. Usage: pld-list [options] Options: -h --help Show this screen.
null
null
null
save_if_better_than = float(save_if_better_than) initialize_config(__mode__='fit') fit( persist=not no_save, activate=not no_activate, evaluate=evaluate, persist_if_better_than=save_if_better_than, )
def fit_cmd(argv=sys.argv[1:]): # pragma: no cover arguments = docopt(fit_cmd.__doc__, argv=argv) no_save = arguments['--no-save'] no_activate = arguments['--no-activate'] save_if_better_than = arguments['--save-if-better-than'] evaluate = arguments['--evaluate'] or bool(save_if_better_than) ...
\ Fit a model and save to database. Will use 'dataset_loader_train', 'model', and 'model_perister' from the configuration file, to load a dataset to train a model with, and persist it. Usage: pld-fit [options] Options: -n --no-save Don't persist the fitted model to disk. --no-activate ...
3.787422
6.139996
0.616844
activate(model_version=int(arguments['<version>'])) elif arguments['delete']: delete(model_version=int(arguments['<version>']))
def admin_cmd(argv=sys.argv[1:]): # pragma: no cover arguments = docopt(admin_cmd.__doc__, argv=argv) initialize_config(__mode__='fit') if arguments['activate']
\ Activate or delete models. Models are usually made active right after fitting (see command pld-fit). The 'activate' command allows you to explicitly set the currently active model. Use 'pld-list' to get an overview of all available models along with their version identifiers. Deleting a model will simply remove i...
5.489707
8.493933
0.646309
def grid_search_cmd(argv=sys.argv[1:]): # pragma: no cover arguments = docopt(grid_search_cmd.__doc__, argv=argv) initialize_config(__mode__='fit') grid_search( save_results=arguments['--save-results'], persist_best=arguments['--persist-best'], )
\ Grid search parameters for the model. Uses 'dataset_loader_train', 'model', and 'grid_search' from the configuration to load a training dataset, and run a grid search on the model using the grid of hyperparameters. Usage: pld-grid-search [options] Options: --save-results=<fname> Save results to CSV file --...
null
null
null
if message is None and cause is None: return None elif message is None: return '%s, caused by %r' % (e.__class__, cause) elif cause is None: return message else: return '%s, caused by %r' % (message, cause)
def error_message(e, message=None, cause=None)
Formats exception message + cause :param e: :param message: :param cause: :return: formatted message, includes cause if any is set
2.560715
2.750822
0.930891
if key is None: return None if isinstance(key, (int, long)): return '%016x' % key elif isinstance(key, list): return [format_pgp_key(x) for x in key] else: key = key.strip() key = strip_hex_prefix(key) return format_pgp_key(int(key, 16))
def format_pgp_key(key)
Formats PGP key in 16hex digits :param key: :return:
2.896442
2.726187
1.062452
if js is None: return default if key not in js: return default if js[key] is None and not take_none: return default return js[key]
def defvalkey(js, key, default=None, take_none=True)
Returns js[key] if set, otherwise default. Note js[key] can be None. :param js: :param key: :param default: :param take_none: :return:
2.198892
2.257065
0.974226
return [x for x in arr if not isinstance(x, list) or len(x) > 0]
def drop_empty(arr)
Drop empty array element :param arr: :return:
3.453365
4.626482
0.746434
if not isinstance(elem, list): elem = [elem] if acc is None: acc = [] for x in elem: acc.append(x) return acc
def add_res(acc, elem)
Adds results to the accumulator :param acc: :param elem: :return:
2.60528
2.745631
0.948882
try: iterator, sentinel, stack = iter(iterable), object(), [] except TypeError: yield iterable return while True: value = next(iterator, sentinel) if value is sentinel: if not stack: break iterator = stack.pop() el...
def flatten(iterable)
Non-recursive flatten. :param iterable: :return:
2.423644
2.521531
0.96118
try: if subject is None: return None if oid is None: return None for sub in subject: if oid is not None and sub.oid == oid: return sub.value except: pass return None
def try_get_dn_part(subject, oid=None)
Tries to extracts the OID from the X500 name. :param subject: :param oid: :return:
3.270657
3.363101
0.972512
try: from cryptography.x509.oid import NameOID from cryptography.x509 import ObjectIdentifier oid_names = { getattr(NameOID, 'COMMON_NAME', ObjectIdentifier("2.5.4.3")): "CN", getattr(NameOID, 'COUNTRY_NAME', ObjectIdentifier("2.5.4.6")): "C", getattr...
def try_get_dn_string(subject, shorten=False)
Returns DN as a string :param subject: :param shorten: :return:
1.650636
1.664196
0.991852
if haystack is None: return None if sys.version_info[0] < 3: return haystack.startswith(prefix) return to_bytes(haystack).startswith(to_bytes(prefix))
def startswith(haystack, prefix)
py3 comp startswith :param haystack: :param prefix: :return:
2.65481
2.910564
0.912129
if isinstance(x, bytes): return x.decode('utf-8') if isinstance(x, basestring): return x
def to_string(x)
Utf8 conversion :param x: :return:
2.696794
2.903207
0.928902
if isinstance(x, bytes): return x if isinstance(x, basestring): return x.encode('utf-8')
def to_bytes(x)
Byte conv :param x: :return:
2.622066
2.963113
0.884903
if sys.version_info[0] < 3: return needle in haystack else: return to_bytes(needle) in to_bytes(haystack)
def contains(haystack, needle)
py3 contains :param haystack: :param needle: :return:
2.746517
3.058363
0.898035
x = x.replace(b' ', b'') x = x.replace(b'\t', b'') return x
def strip_spaces(x)
Strips spaces :param x: :return:
2.693062
3.202986
0.840797
if x is None: return None x = to_string(x) pem = x.replace('-----BEGIN CERTIFICATE-----', '') pem = pem.replace('-----END CERTIFICATE-----', '') pem = re.sub(r'-----BEGIN .+?-----', '', pem) pem = re.sub(r'-----END .+?-----', '', pem) pem = pem.replace(' ', '') pem = pem.re...
def strip_pem(x)
Strips PEM to bare base64 encoded form :param x: :return:
1.885412
1.978189
0.9531
message = error_message(self, cause=cause) exc_type, exc_value, exc_traceback = sys.exc_info() traceback_formatted = traceback.format_exc() traceback_val = traceback.extract_tb(exc_traceback) md5 = hashlib.md5(traceback_formatted.encode('utf-8')).hexdigest() if...
def log(self, cause=None, do_message=True, custom_msg=None)
Loads exception data from the current exception frame - should be called inside the except block :return:
2.652991
2.634327
1.007085
if modulus <= 2: return False d = DlogFprint.discrete_log(modulus, self.generator, self.generator_order, self.generator_order_decomposition, self.m) return d is not None
def fprint(self, modulus)
Returns True if fingerprint is present / detected. :param modulus: :return:
12.000818
12.030377
0.997543
mprime = max(self.primes) if max_prime > mprime: raise ValueError('Current primorial implementation does not support values above %s' % mprime) primorial = 1 phi_primorial = 1 for prime in self.primes: primorial *= prime phi_primorial...
def primorial(self, max_prime=167)
Returns primorial (and its totient) with max prime inclusive - product of all primes below the value :param max_prime: :param dummy: :return: primorial, phi(primorial)
3.549729
3.05322
1.162618
if a < 2: return False if a == 2 or a == 3: return True # manually test 2 and 3 if a % 2 == 0 or a % 3 == 0: return False # exclude multiples of 2 and 3 max_divisor = int(math.ceil(a ** 0.5)) d, i = 5, 2 while d <= max_divis...
def prime3(a)
Simple trial division prime detection :param a: :return:
2.650404
2.664832
0.994586
num = [] # add 2, 3 to list or prime factors and remove all even numbers(like sieve of ertosthenes) while n % 2 == 0: num.append(2) n = n // 2 while n % 3 == 0: num.append(3) n = n // 3 max_divisor = int(math.ceil(n ** 0...
def prime_factors(n, limit=None)
Simple trial division factorization :param n: :param limit: :return:
3.882971
3.93292
0.9873
ret = {} for k, g in itertools.groupby(factors): ret[k] = len(list(g)) return ret
def factor_list_to_map(factors)
Factor list to map factor -> power :param factors: :return:
4.297412
4.22167
1.017941
if element == 1: return 1 # by definition if pow(element, phi_m, modulus) != 1: return None # not an element of the group order = phi_m for factor, power in list(phi_m_decomposition.items()): for p in range(1, power + 1): n...
def element_order(element, modulus, phi_m, phi_m_decomposition)
Returns order of the element in Zmod(modulus) :param element: :param modulus: :param phi_m: phi(modulus) :param phi_m_decomposition: factorization of phi(modulus) :return:
3.119456
3.182058
0.980326
sum = 0 prod = reduce(lambda a, b: a * b, n) for n_i, a_i in zip(n, a): p = prod // n_i sum += a_i * DlogFprint.mul_inv(p, n_i) * p return sum % prod
def chinese_remainder(n, a)
Solves CRT for moduli and remainders :param n: :param a: :return:
3.632262
4.194612
0.865935
b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a // b a, b = b, a % b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1
def mul_inv(a, b)
Modular inversion a mod b :param a: :param b: :return:
1.394054
1.922888
0.724979
factors = DlogFprint.prime_factors(x, limit=max_prime) return DlogFprint.factor_list_to_map(factors)
def small_factors(x, max_prime)
Factorizing x up to max_prime limit. :param x: :param max_prime: :return:
11.066021
13.289765
0.832672
if pow(element, generator_order, modulus) != 1: # logger.debug('Powmod not one') return None moduli = [] remainders = [] for prime, power in list(generator_order_decomposition.items()): prime_to_power = prime ** power order_div_pr...
def discrete_log(element, generator, generator_order, generator_order_decomposition, modulus)
Simple discrete logarithm :param element: :param generator: :param generator_order: :param generator_order_decomposition: :param modulus: :return:
3.563113
3.611207
0.986682
if not self.is_acceptable_modulus(modulus): return False self.tested += 1 for i in range(0, len(self.primes)): if (1 << (modulus % self.primes[i])) & self.prints[i] == 0: return False self.found += 1 return True
def has_fingerprint_moduli(self, modulus)
Returns true if the fingerprint was detected in the key :param modulus: :return:
4.35453
4.769973
0.912905
if not self.is_acceptable_modulus(modulus): return False self.tested += 1 positive = self.dlog_fprinter.fprint(modulus) if positive: self.found += 1 return positive
def has_fingerprint_dlog(self, modulus)
Exact fingerprint using mathematical structure of the primes :param modulus: :return:
7.470218
8.32262
0.89758
if old: self.has_fingerprint = self.has_fingerprint_moduli else: self.has_fingerprint = self.has_fingerprint_dlog
def switch_fingerprint_method(self, old=False)
Switches main fingerprinting method. :param old: if True old fingerprinting method will be used. :return:
5.431566
6.688779
0.812041
META_AMZ_FACT = 92. / 152. # conversion from university cluster to AWS AMZ_C4_PRICE = 0.1 # price of 2 AWS CPUs per hour length = int(ceil(log(modulus, 2))) length_ceiling = int(ceil(length / 32)) * 32 if length_ceiling in self.length_to_time_years: effor...
def mark_and_add_effort(self, modulus, json_info)
Inserts factorization effort for vulnerable modulus into json_info :param modulus: :param json_info: :return:
5.720195
5.70783
1.002166
if not isinstance(extensions, list): extensions = [extensions] for ext in extensions: if fname.endswith('.%s' % ext): return True return False
def file_matches_extensions(self, fname, extensions)
True if file matches one of extensions :param fname: :param extensions: :return:
2.141769
2.629151
0.814624
ret = [] files = self.args.files if files is None: return ret for fname in files: if fname == '-': if self.args.base64stdin: for line in sys.stdin: data = base64.b64decode(line) ...
def process_inputs(self)
Processes input data :return:
2.606654
2.642118
0.986578
import tarfile # lazy import, only when needed ret = [] with tarfile.open(fname) as tr: members = tr.getmembers() for member in members: if not member.isfile(): continue fh = tr.extractfile(member) ...
def process_tar(self, fname)
Tar(gz) archive processing :param fname: :return:
3.052018
3.084404
0.9895
ret = [] sub_rec = [f for f in os.listdir(dirname)] for fname in sub_rec: full_path = os.path.join(dirname, fname) if os.path.isfile(full_path): with open(full_path, 'rb') as fh: sub = self.process_file(fh.read(), fname) ...
def process_dir(self, dirname)
Directory processing :param dirname: :return:
2.289372
2.319465
0.987026
try: return self.process_file_autodetect(data, name) except Exception as e: logger.debug('Exception processing file %s : %s' % (name, e)) self.trace_logger.log(e) # autodetection fallback - all formats ret = [] logger.debug('processi...
def process_file(self, data, name)
Processes a single file :param data: :param name: :return:
1.918522
1.929541
0.994289
try: ret = [] data = to_string(data) parts = re.split(r'-----BEGIN', data) if len(parts) == 0: return None if len(parts[0]) == 0: parts.pop(0) crt_arr = ['-----BEGIN' + x for x in parts] ...
def process_pem(self, data, name)
PEM processing - splitting further by the type of the records :param data: :param name: :return:
2.903052
2.88458
1.006404
from cryptography.x509.base import load_der_x509_certificate try: x509 = load_der_x509_certificate(pem_to_der(data), self.get_backend()) self.num_pem_certs += 1 return self.process_x509(x509, name=name, idx=idx, data=data, pem=True, source='pem-cert') ...
def process_pem_cert(self, data, name, idx)
Processes PEM encoded certificate :param data: :param name: :param idx: :return:
3.185977
3.363846
0.947123
from cryptography.x509.base import load_der_x509_csr try: csr = load_der_x509_csr(pem_to_der(data), self.get_backend()) self.num_pem_csr += 1 return self.process_csr(csr, name=name, idx=idx, data=data, pem=True, source='pem-csr') except Exception as ...
def process_pem_csr(self, data, name, idx)
Processes PEM encoded certificate request PKCS#10 :param data: :param name: :param idx: :return:
3.410383
3.55783
0.958557
from cryptography.hazmat.primitives.serialization import load_der_public_key from cryptography.hazmat.primitives.serialization import load_der_private_key try: if startswith(data, '-----BEGIN RSA PUBLIC KEY') or startswith(data, '-----BEGIN PUBLIC KEY'): rsa ...
def process_pem_rsakey(self, data, name, idx)
Processes PEM encoded RSA key :param data: :param name: :param idx: :return:
2.886789
2.897339
0.996359
from cryptography.x509.base import load_der_x509_certificate try: x509 = load_der_x509_certificate(data, self.get_backend()) self.num_der_certs += 1 return self.process_x509(x509, name=name, pem=False, source='der-cert') except Exception as e: ...
def process_der(self, data, name)
DER processing :param data: :param name: :return:
3.598983
3.605779
0.998115
if x509 is None: return from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey from cryptography.x509.oid import NameOID pub = x509.public_key() if not isinstance(pub, RSAPublicKey): ...
def process_x509(self, x509, name, idx=None, data=None, pem=True, source='', aux=None)
Processing parsed X509 certificate :param x509: :param name: :param idx: :param data: :param pem: :param source: :param aux: :return:
2.769547
2.806369
0.986879
if csr is None: return from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey pub = csr.public_key() if not isinstance(pub, RSAPublicKey): return self.num_rsa += 1 pubnum = csr.public_key().public_numbers() js =...
def process_csr(self, csr, name, idx=None, data=None, pem=True, source='', aux=None)
Processing parsed X509 csr :param csr: :type csr: cryptography.x509.CertificateSigningRequest :param name: :param idx: :param data: :param pem: :param source: :param aux: :return:
4.356616
4.39723
0.990764
ret = [] try: data = to_string(data) parts = re.split(r'-{5,}BEGIN', data) if len(parts) == 0: return if len(parts[0]) == 0: parts.pop(0) crt_arr = ['-----BEGIN' + x for x in parts] for idx...
def process_pgp(self, data, name)
PGP key processing :param data: :param name: :return:
3.074501
3.074322
1.000058
try: from pgpdump.data import AsciiData from pgpdump.packet import SignaturePacket, PublicKeyPacket, PublicSubkeyPacket, UserIDPacket except Exception as e: logger.warning('Could not import pgpdump, try running: pip install pgpdump') return [Test...
def process_pgp_raw(self, data, name, file_idx=None)
Processes single PGP key :param data: file data :param name: file name :param file_idx: index in the file :return:
2.984311
2.978834
1.001839
if data is None or len(data) == 0: return ret = [] try: lines = [x.strip() for x in data.split(b'\n')] for idx, line in enumerate(lines): ret.append(self.process_ssh_line(line, name, idx)) except Exception as e: l...
def process_ssh(self, data, name)
Processes SSH keys :param data: :param name: :return:
3.204482
3.247736
0.986682
data = data.strip() if not contains(data, 'ssh-rsa'): return # strip ssh params / adjustments try: data = data[to_bytes(data).find(b'ssh-rsa'):] except Exception as e: pass from cryptography.hazmat.primitives.serialization im...
def process_ssh_line(self, data, name, idx)
Processes single SSH key :param data: :param name: :param idx: :return:
3.521834
3.566774
0.9874
data = data.strip() if len(data) == 0: return ret = [] try: js = json.loads(data) self.num_json += 1 ret.append(self.process_json_rec(js, name, idx, [])) except Exception as e: logger.debug('Exception in proce...
def process_json_line(self, data, name, idx)
Processes single json line :param data: :param name: :param idx: :return:
3.694673
3.933001
0.939403
ret = [] if isinstance(data, list): for kidx, rec in enumerate(data): sub = self.process_json_rec(rec, name, idx, list(sub_idx + [kidx])) ret.append(sub) return ret if isinstance(data, dict): for key in data: ...
def process_json_rec(self, data, name, idx, sub_idx)
Processes json rec - json object :param data: :param name: :param idx: :param sub_idx: :return:
2.082757
2.103627
0.990079
if isinstance(data, (int, long)): js = collections.OrderedDict() js['type'] = 'js-mod-num' js['fname'] = name js['idx'] = idx js['sub_idx'] = sub_idx js['n'] = '0x%x' % data if self.has_fingerprint(data): ...
def process_js_mod(self, data, name, idx, sub_idx)
Processes one moduli from JSON :param data: :param name: :param idx: :param sub_idx: :return:
5.741068
5.731244
1.001714
from cryptography.x509.base import load_der_x509_certificate ret = [] for crt_hex in data: try: bindata = base64.b64decode(crt_hex) x509 = load_der_x509_certificate(bindata, self.get_backend()) self.num_ldiff_cert += 1 ...
def process_js_certs(self, data, name, idx, sub_idx)
Process one certificate from JSON :param data: :param name: :param idx: :param sub_idx: :return:
4.100473
4.203756
0.975431
try: from apk_parse.apk import APK except Exception as e: logger.warning('Could not import apk_parse, try running: pip install apk_parse_ph4') return [TestResult(fname=name, type='apk-pem-cert', error='cannot-import')] ret = [] try: ...
def process_apk(self, data, name)
Processes Android application :param data: :param name: :return:
5.378414
5.422778
0.991819
ret = [] try: lines = [x.strip() for x in data.split(bytes(b'\n'))] for idx, line in enumerate(lines): sub = self.process_mod_line(line, name, idx) ret.append(sub) except Exception as e: logger.debug('Error in line mod...
def process_mod(self, data, name)
Processing one modulus per line :param data: :param name: :return:
4.282004
4.264239
1.004166
if data is None or len(data) == 0: return ret = [] try: if self.args.key_fmt_base64 or self.re_match(r'^[a-zA-Z0-9+/=\s\t]+$', data): ret.append(self.process_mod_line_num(strip_spaces(data), name, idx, 'base64', aux)) if self.args.ke...
def process_mod_line(self, data, name, idx, aux=None)
Processes one line mod :param data: :param name: :param idx: :param aux: :return:
2.593579
2.600073
0.997502
try: num = 0 if num_type == 'base64': num = int(base64.b16encode(base64.b64decode(data)), 16) elif num_type == 'hex': num = int(strip_hex_prefix(data), 16) elif num_type == 'dec': num = int(data) ...
def process_mod_line_num(self, data, name, idx, num_type='hex', aux=None)
Processes particular number :param data: :param name: :param idx: :param num_type: :param aux: :return:
3.54649
3.608147
0.982912
from cryptography.x509.base import load_der_x509_certificate reg = re.compile(r'binary::\s*([0-9a-zA-Z+/=\s\t\r\n]{20,})$', re.MULTILINE | re.DOTALL) matches = re.findall(reg, str(data)) ret = [] num_certs_found = 0 for idx, match in enumerate(matches): ...
def process_ldiff(self, data, name)
Processes LDAP output field;binary::blob :param data: :param name: :return:
3.942224
3.79066
1.039984
if self.jks_file_passwords is None and self.args.jks_pass_file is not None: self.jks_file_passwords = [] if not os.path.exists(self.args.jks_pass_file): logger.warning('JKS password file %s does not exist' % self.args.jks_pass_file) with open(self.arg...
def process_jks(self, data, name)
Processes Java Key Store file :param data: :param name: :return:
2.575371
2.588309
0.995002
try: import jks except: logger.warning('Could not import jks, try running: pip install pyjks') raise ImportException('Cannot import pyjks') pwdlist = sorted(list(set(self.jks_file_passwords + self.jks_passwords))) for cur in pwdlist: ...
def try_open_jks(self, data, name)
Tries to guess JKS password :param name: :param data: :return:
5.117067
5.053855
1.012508
from cryptography.hazmat.backends.openssl.backend import backend from cryptography.hazmat.backends.openssl.x509 import _Certificate # DER conversion is_pem = startswith(data, '-----') if self.re_match(r'^[a-zA-Z0-9-\s+=/]+$', data): is_pem = True tr...
def process_pkcs7(self, data, name)
Process PKCS7 signature with certificate in it. :param data: :param name: :return:
2.610295
2.627524
0.993443
try: return re.match(pattern, haystack.decode('utf8'), **kwargs) except Exception as e: logger.debug('re.match exception: %s' % e) self.trace_logger.log(e)
def re_match(self, pattern, haystack, **kwargs)
re.match py3 compat :param pattern: :param haystack: :return:
3.979221
4.126762
0.964248
from cryptography.hazmat.backends import default_backend return default_backend() if backend is None else backend
def get_backend(self, backend=None)
Default crypto backend :param backend: :return:
4.136185
3.218864
1.284983
if self.args.flatten: ret = drop_none(flatten(ret)) logger.info('Dump: \n' + json.dumps(ret, cls=AutoJSONEncoder, indent=2 if self.args.indent else None))
def dump(self, ret)
Dumps the return value :param ret: :return:
6.303556
6.805527
0.926241
self.do_print = True if self.args.old: self.switch_fingerprint_method(True) ret = self.process_inputs() if self.args.dump: self.dump(ret) logger.info('### SUMMARY ####################') logger.info('Records tested: %s' % self.tested) ...
def work(self)
Entry point after argument processing. :return:
3.653396
3.674263
0.994321
parser = argparse.ArgumentParser(description='ROCA Fingerprinter') parser.add_argument('--tmp', dest='tmp_dir', default='.', help='Temporary dir for subprocessing (e.g. APK parsing scratch)') parser.add_argument('--debug', dest='debug', default=False, actio...
def init_parser(self)
Init command line parser :return:
1.940211
1.943622
0.998245
parser = self.init_parser() self.args = parser.parse_args() if self.args.debug: coloredlogs.install(level=logging.DEBUG, fmt=LOG_FORMAT) self.work()
def main(self)
Main entry point :return:
3.332582
3.637197
0.91625
ret = [] try: lines = [x.strip() for x in data.split('\n')] for idx, line in enumerate(lines): if line == '': continue sub = self.process_host(line, name, idx) if sub is not None: re...
def process_tls(self, data, name)
Remote TLS processing - one address:port per line :param data: :param name: :return:
3.93514
3.877671
1.01482
try: parts = host_spec.split(':', 1) host = parts[0].strip() port = parts[1] if len(parts) > 1 else 443 pem_cert = self.get_server_certificate(host, port) if pem_cert: sub = self.roca.process_pem_cert(pem_cert, name, line_idx) ...
def process_host(self, host_spec, name, line_idx=0)
One host spec processing :param host_spec: :param name: :param line_idx: :return:
3.693575
3.758442
0.982741
logger.info("Fetching server certificate from %s:%s" % (host,port)) try: return get_server_certificate((host, int(port))) except Exception as e: logger.error('Error getting server certificate from %s:%s: %s' % (host, port, e)) ...
def get_server_certificate(self, host, port)
Gets the remote x.509 certificate :param host: :param port: :return:
2.699162
2.989621
0.902844
ret = [] files = self.args.files if files is None: return ret for fname in files: # arguments are host specs if self.args.hosts: sub = self.process_host(fname, fname, 0) if sub is not None: ...
def process_inputs(self)
Processes input data :return:
4.676259
4.814335
0.97132
self.roca.do_print = True ret = self.process_inputs() if self.args.dump: self.roca.dump(ret) if self.roca.found > 0: logger.info('Fingerprinted keys found: %s' % self.roca.found) logger.info('WARNING: Potential vulnerability') else: ...
def work(self)
Entry point after argument processing. :return:
7.022145
7.427793
0.945388
parser = argparse.ArgumentParser(description='ROCA TLS Fingerprinter') parser.add_argument('--debug', dest='debug', default=False, action='store_const', const=True, help='Debugging logging') parser.add_argument('--dump', dest='dump', default=False, action='...
def init_parser(self)
Init command line parser :return:
2.585812
2.612359
0.989838
parser = self.init_parser() if len(sys.argv) < 2: parser.print_usage() sys.exit(0) self.args = parser.parse_args() self.roca.args.flatten = self.args.flatten self.roca.args.indent = self.args.indent if self.args.debug: colore...
def main(self)
Main entry point :return:
3.143628
3.252532
0.966517
N = (dims * dims - dims) / 2 m = np.ceil(np.sqrt(2 * N)) c = m - np.round(np.sqrt(2 * (N - indices))) - 1 r = np.mod(indices + (c + 1) * (c + 2) / 2 - 1, m) + 1 return np.array([r, c], dtype=np.int64)
def _map_tril_1d_on_2d(indices, dims)
Map 1d indices on lower triangular matrix in 2d.
4.133413
3.785555
1.091891
a = np.ascontiguousarray(a) unique_a = np.unique(a.view([('', a.dtype)] * a.shape[1])) return unique_a.view(a.dtype).reshape((unique_a.shape[0], a.shape[1]))
def _unique_rows_numpy(a)
return unique rows
1.605753
1.679975
0.95582
if not isinstance(random_state, np.random.RandomState): random_state = np.random.RandomState(random_state) n_max = max_pairs(shape) if n_max <= 0: raise ValueError('n_max must be larger than 0') # make random pairs indices = random_state.randint(0, n_max, n) if len(shap...
def random_pairs_with_replacement(n, shape, random_state=None)
make random record pairs
3.194703
3.128005
1.021323
n_max = max_pairs(shape) sample = np.array([]) # Run as long as the number of pairs is less than the requested number # of pairs n. while len(sample) < n: # The number of pairs to sample (sample twice as much record pairs # because the duplicates are dropped). n_samp...
def random_pairs_without_replacement_large_frames( n, shape, random_state=None)
Make a sample of random pairs with replacement
5.31521
5.400809
0.984151
if s.shape[0] == 0: return s # Lower s if lower is True if lowercase is True: s = s.str.lower() # Accent stripping based on https://github.com/scikit-learn/ # scikit-learn/blob/412996f/sklearn/feature_extraction/text.py # BSD license if not strip_accents: pass...
def clean(s, lowercase=True, replace_by_none=r'[^ \-\_A-Za-z0-9]+', replace_by_whitespace=r'[\-\_]', strip_accents=None, remove_brackets=True, encoding='utf-8', decode_error='strict')
Clean string variables. Clean strings in the Series by removing unwanted tokens, whitespace and brackets. Parameters ---------- s : pandas.Series A Series to clean. lower : bool, optional Convert strings in the Series to lowercase. Default True. replace_by_none : str, optio...
2.267474
2.206587
1.027593
# https://github.com/pydata/pandas/issues/3729 value_count = s.fillna('NAN') return value_count.groupby(by=value_count).transform('count')
def value_occurence(s)
Count the number of times each value occurs. This function returns the counts for each row, in contrast with `pandas.value_counts <http://pandas.pydata.org/pandas- docs/stable/generated/pandas.Series.value_counts.html>`_. Returns ------- pandas.Series A Series with value counts.
7.31188
7.133834
1.024958