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 generated with py.code.Source() # filename is something like '<0-codegen foo.py:18>' match = re.match(r'.*<\d+-codegen (.*):(\d+)>', filename) if match: filename = match.group(1) lineno = int(match.group(2)) try: self._open_editor(self._get_editor_cmd(filename, lineno)) except Exception as exc: self.error(exc)
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 super(Pdb, self).set_trace(frame)
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>": tb = tb.tb_next if tb: # only display with actual traceback. self._remove_bdb_context(evalue) tb_limit = self.config.show_traceback_on_error_limit fmt_exc = traceback.format_exception( etype, evalue, tb, limit=tb_limit ) # Remove last line (exception string again). if len(fmt_exc) > 1 and fmt_exc[-1][0] != " ": fmt_exc.pop() print("".join(fmt_exc).rstrip(), file=self.stdout)
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_bdb_context.__context__ = None break removed_bdb_context = removed_bdb_context.__context__
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] = config[argname] try: getcallargs(func, *args, **kwargs) except TypeError as exc: msg = "{}\n{}".format(exc.args[0], PALLADIUM_CONFIG_ERROR) exc.args = (msg,) raise exc return func(*args, **kwargs) wrapper.__wrapped__ = func return wrapper
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 latest version. -h --help Show this screen.
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_version))
\ 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 one. --no-activate Don't activate the exported model with the 'model_persister_export'. -h --help Show this screen.
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: The decorator list to be used for this predict service. It is OK if there is no such entry in the active Palladium config. :return: A predict service function that will be used to process predict requests.
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": 1.1, "petal length": 0.7, "petal width": 5}, {"sepal length": 1.0, "sepal width": 8.0, "petal length": 1.4, "petal width": 5}] Example output: ["Iris-virginica","Iris-setosa"] An input line with the word 'exit' will quit the streaming server. Usage: pld-stream [options] Options: -h --help Show this screen.
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(values, dtype=object)
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 similar.
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 input row: {}" "{}: {}\n".format(line, type(e), e)) io_err.flush() else: io_out.write(ujson.dumps(y_pred.tolist())) io_out.write('\n') io_out.flush()
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) if save_if_better_than is not None
\ 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 Don't activate the fitted model. --save-if-better-than=<k> Persist only if test score better than given value. -e --evaluate Evaluate fitted model on train and test set and print out results. -h --help Show this screen.
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 it from the database. Usage: pld-admin activate <version> [options] pld-admin delete <version> [options] Options: -h --help Show this screen.
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 --persist-best Persist the best model from grid search -h --help Show this screen.
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() elif isinstance(value, str): yield value else: try: new_iterator = iter(value) except TypeError: yield value else: stack.append(iterator) iterator = new_iterator
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(NameOID, 'LOCALITY_NAME', ObjectIdentifier("2.5.4.7")): "L", getattr(NameOID, 'STATE_OR_PROVINCE_NAME', ObjectIdentifier("2.5.4.8")): "ST", getattr(NameOID, 'STREET_ADDRESS', ObjectIdentifier("2.5.4.9")): "St", getattr(NameOID, 'ORGANIZATION_NAME', ObjectIdentifier("2.5.4.10")): "O", getattr(NameOID, 'ORGANIZATIONAL_UNIT_NAME', ObjectIdentifier("2.5.4.11")): "OU", getattr(NameOID, 'SERIAL_NUMBER', ObjectIdentifier("2.5.4.5")): "SN", getattr(NameOID, 'USER_ID', ObjectIdentifier("0.9.2342.19200300.100.1.1")): "userID", getattr(NameOID, 'DOMAIN_COMPONENT', ObjectIdentifier("0.9.2342.19200300.100.1.25")): "domainComponent", getattr(NameOID, 'EMAIL_ADDRESS', ObjectIdentifier("1.2.840.113549.1.9.1")): "emailAddress", getattr(NameOID, 'POSTAL_CODE', ObjectIdentifier("2.5.4.17")): "ZIP", } ret = [] try: for attribute in subject: oid = attribute.oid dot = oid.dotted_string oid_name = oid_names[oid] if shorten and oid in oid_names else oid._name val = attribute.value ret.append('%s: %s' % (oid_name, val)) except: pass return ', '.join(ret) except Exception as e: logger.warning('Unexpected error: %s' % e) return 'N/A'
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.replace('\t', '') pem = pem.replace('\r', '') pem = pem.replace('\n', '') return pem.strip()
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 md5 in self._db: # self.logger.debug('Exception trace logged: %s' % md5) return if custom_msg is not None and cause is not None: self.logger.debug('%s : %s' % (custom_msg, cause)) elif custom_msg is not None: self.logger.debug(custom_msg) elif cause is not None: self.logger.debug('%s' % cause) self.logger.debug(traceback_formatted) self._db.add(md5)
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 *= prime - 1 return primorial, 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_divisor: if a % d == 0: return False d += i i = 6 - i # this modifies 2 into 4 and vice versa return True
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.5)) if limit is None else limit d, i = 5, 2 while d <= max_divisor: while n % d == 0: num.append(d) n = n // d d += i i = 6 - i # this modifies 2 into 4 and vice versa # if no is > 2 i.e no is a prime number that is only divisible by itself add it if n > 2: num.append(n) return num
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): next_order = order // factor if pow(element, next_order, modulus) == 1: order = next_order else: break return order
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_prime_power = generator_order // prime_to_power # g.div(generator_order, prime_to_power) g_dash = pow(generator, order_div_prime_power, modulus) h_dash = pow(element, order_div_prime_power, modulus) found = False for i in range(0, prime_to_power): if pow(g_dash, i, modulus) == h_dash: remainders.append(i) moduli.append(prime_to_power) found = True break if not found: # logger.debug('Not found :(') return None ccrt = DlogFprint.chinese_remainder(moduli, remainders) return ccrt
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: effort_time = self.length_to_time_years[length_ceiling] else: effort_time = -1 if effort_time > 0: effort_time *= META_AMZ_FACT # scaling to more powerful AWS CPU effort_price = effort_time * 365.25 * 24 * 0.5 * AMZ_C4_PRICE else: effort_price = -1 json_info['marked'] = True json_info['time_years'] = effort_time json_info['price_aws_c4'] = effort_price return json_info
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) ret.append(self.process_file(data, fname)) continue else: fh = sys.stdin elif fname.endswith('.tar') or fname.endswith('.tar.gz'): sub = self.process_tar(fname) ret.append(sub) continue elif not os.path.isfile(fname): sub = self.process_dir(fname) ret.append(sub) continue else: fh = open(fname, 'rb') with fh: data = fh.read() sub = self.process_file(data, fname) ret.append(sub) return ret
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) sub = self.process_file(fh.read(), member.name) ret.append(sub) return ret
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) ret.append(sub) elif os.path.isdir(full_path): sub = self.process_dir(full_path) ret.append(sub) return ret
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('processing %s as PEM' % name) ret.append(self.process_pem(data, name)) logger.debug('processing %s as DER' % name) ret.append(self.process_der(data, name)) logger.debug('processing %s as PGP' % name) ret.append(self.process_pgp(data, name)) logger.debug('processing %s as SSH' % name) ret.append(self.process_ssh(data, name)) logger.debug('processing %s as JSON' % name) ret.append(self.process_json(data, name)) logger.debug('processing %s as APK' % name) ret.append(self.process_apk(data, name)) logger.debug('processing %s as MOD' % name) ret.append(self.process_mod(data, name)) logger.debug('processing %s as LDIFF' % name) ret.append(self.process_ldiff(data, name)) logger.debug('processing %s as JKS' % name) ret.append(self.process_jks(data, name)) logger.debug('processing %s as PKCS7' % name) ret.append(self.process_pkcs7(data, name)) return ret
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] for idx, pem_rec in enumerate(crt_arr): pem_rec = pem_rec.strip() if len(pem_rec) == 0: continue if startswith(pem_rec, '-----BEGIN CERTIFICATE REQUEST'): return self.process_pem_csr(pem_rec, name, idx) elif startswith(pem_rec, '-----BEGIN CERTIF'): return self.process_pem_cert(pem_rec, name, idx) elif startswith(pem_rec, '-----BEGIN '): # fallback return self.process_pem_rsakey(pem_rec, name, idx) return ret except Exception as e: logger.debug('Exception processing PEM file %s : %s' % (name, e)) self.trace_logger.log(e) return None
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') except Exception as e: logger.debug('PEM processing failed: %s' % e) self.trace_logger.log(e)
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 e: logger.debug('PEM processing failed: %s' % e) self.trace_logger.log(e)
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 = load_der_public_key(pem_to_der(data), self.get_backend()) public_numbers = rsa.public_numbers() elif startswith(data, '-----BEGIN RSA PRIVATE KEY') or startswith(data, '-----BEGIN PRIVATE KEY'): rsa = load_der_private_key(pem_to_der(data), None, self.get_backend()) public_numbers = rsa.private_numbers().public_numbers else: return None self.num_rsa_keys += 1 self.num_rsa += 1 js = collections.OrderedDict() js['type'] = 'pem-rsa-key' js['fname'] = name js['idx'] = idx js['pem'] = data js['e'] = '0x%x' % public_numbers.e js['n'] = '0x%x' % public_numbers.n if self.has_fingerprint(public_numbers.n): logger.warning('Fingerprint found in PEM RSA key %s ' % name) self.mark_and_add_effort(public_numbers.n, js) if self.do_print: print(json.dumps(js)) return TestResult(js) except Exception as e: logger.debug('Pubkey loading error: %s : %s [%s] : %s' % (name, idx, data[:20], e)) self.trace_logger.log(e)
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: logger.debug('DER processing failed: %s : %s' % (name, e)) self.trace_logger.log(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): return self.num_rsa += 1 pubnum = x509.public_key().public_numbers() js = collections.OrderedDict() js['type'] = source js['fname'] = name js['idx'] = idx js['fprint'] = binascii.hexlify(x509.fingerprint(hashes.SHA256())) js['subject'] = utf8ize(try_get_dn_string(x509.subject, shorten=True)) js['issuer'] = utf8ize(try_get_dn_string(x509.issuer, shorten=True)) js['issuer_org'] = utf8ize(try_get_dn_part(x509.issuer, NameOID.ORGANIZATION_NAME)) js['created_at'] = self.strtime(x509.not_valid_before) js['created_at_utc'] = unix_time(x509.not_valid_before) js['not_valid_after_utc'] = unix_time(x509.not_valid_after) js['pem'] = data if pem else None js['aux'] = aux js['e'] = '0x%x' % pubnum.e js['n'] = '0x%x' % pubnum.n if self.has_fingerprint(pubnum.n): logger.warning('Fingerprint found in the Certificate %s idx %s ' % (name, idx)) self.mark_and_add_effort(pubnum.n, js) if self.do_print: print(json.dumps(js)) return TestResult(js)
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 = collections.OrderedDict() js['type'] = source js['fname'] = name js['idx'] = idx js['subject'] = utf8ize(try_get_dn_string(csr.subject, shorten=True)) js['pem'] = data if pem else None js['aux'] = aux js['e'] = '0x%x' % pubnum.e js['n'] = '0x%x' % pubnum.n if self.has_fingerprint(pubnum.n): logger.warning('Fingerprint found in the CSR %s idx %s ' % (name, idx)) self.mark_and_add_effort(pubnum.n, js) if self.do_print: print(json.dumps(js)) return TestResult(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, pem_rec in enumerate(crt_arr): try: pem_rec = pem_rec.strip() if len(pem_rec) == 0: continue ret.append(self.process_pgp_raw(pem_rec.encode(), name, idx)) except Exception as e: logger.error('Exception in processing PGP rec file %s: %s' % (name, e)) self.trace_logger.log(e) except Exception as e: logger.error('Exception in processing PGP file %s: %s' % (name, e)) self.trace_logger.log(e) return ret
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 [TestResult(fname=name, type='pgp', error='cannot-import')] ret = [] js_base = collections.OrderedDict() pgp_key_data = AsciiData(data) packets = list(pgp_key_data.packets()) self.num_pgp_masters += 1 master_fprint = None master_key_id = None identities = [] pubkeys = [] sign_key_ids = [] sig_cnt = 0 for idx, packet in enumerate(packets): if isinstance(packet, PublicKeyPacket): master_fprint = packet.fingerprint master_key_id = format_pgp_key(packet.key_id) pubkeys.append(packet) elif isinstance(packet, PublicSubkeyPacket): pubkeys.append(packet) elif isinstance(packet, UserIDPacket): identities.append(packet) elif isinstance(packet, SignaturePacket): sign_key_ids.append(packet.key_id) sig_cnt += 1 # Names / identities ids_arr = [] identity = None for packet in identities: idjs = collections.OrderedDict() idjs['name'] = packet.user_name idjs['email'] = packet.user_email ids_arr.append(idjs) if identity is None: identity = '%s <%s>' % (packet.user_name, packet.user_email) js_base['type'] = 'pgp' js_base['fname'] = name js_base['fname_idx'] = file_idx js_base['master_key_id'] = master_key_id js_base['master_fprint'] = master_fprint js_base['identities'] = ids_arr js_base['signatures_count'] = sig_cnt js_base['packets_count'] = len(packets) js_base['keys_count'] = len(pubkeys) js_base['signature_keys'] = list(set(sign_key_ids)) # Public keys processing for packet in pubkeys: try: self.num_pgp_total += 1 if packet.modulus is None: continue self.num_rsa += 1 js = collections.OrderedDict(js_base) js['created_at'] = self.strtime(packet.creation_time) js['created_at_utc'] = unix_time(packet.creation_time) js['is_master'] = master_fprint == packet.fingerprint js['kid'] = format_pgp_key(packet.key_id) js['bitsize'] = packet.modulus_bitlen js['master_kid'] = master_key_id js['e'] = '0x%x' % packet.exponent js['n'] = '0x%x' % packet.modulus if self.has_fingerprint(packet.modulus): self.mark_and_add_effort(packet.modulus, js) logger.warning('Fingerprint found in PGP key %s key ID 0x%s' % (name, js['kid'])) if self.do_print: print(json.dumps(js)) ret.append(TestResult(js)) except Exception as e: logger.error('Excetion in processing the key: %s' % e) self.trace_logger.log(e) return ret
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: logger.debug('Exception in processing SSH public key %s : %s' % (name, e)) self.trace_logger.log(e) return ret
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 import load_ssh_public_key from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey try: key_obj = load_ssh_public_key(data, self.get_backend()) self.num_ssh += 1 if not isinstance(key_obj, RSAPublicKey): return self.num_rsa += 1 numbers = key_obj.public_numbers() js = collections.OrderedDict() js['type'] = 'ssh-rsa' js['fname'] = name js['idx'] = idx js['e'] = '0x%x' % numbers.e js['n'] = '0x%x' % numbers.n js['ssh'] = data if self.has_fingerprint(numbers.n): logger.warning('Fingerprint found in the SSH key %s idx %s ' % (name, idx)) self.mark_and_add_effort(numbers.n, js) if self.do_print: print(json.dumps(js)) return TestResult(js) except Exception as e: logger.debug('Exception in processing SSH public key %s idx %s : %s' % (name, idx, e)) self.trace_logger.log(e)
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 processing JSON %s idx %s : %s' % (name, idx, e)) self.trace_logger.log(e) return ret
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: rec = data[key] sub = self.process_json_rec(rec, name, idx, list(sub_idx + [rec])) ret.append(sub) if 'n' in data: ret.append(self.process_js_mod(data['n'], name, idx, sub_idx)) if 'mod' in data: ret.append(self.process_js_mod(data['mod'], name, idx, sub_idx)) if 'cert' in data: ret.append(self.process_js_certs([data['cert']], name, idx, sub_idx)) if 'certs' in data: ret.append(self.process_js_certs(data['certs'], name, idx, sub_idx)) return ret
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): logger.warning('Fingerprint found in json int modulus %s idx %s %s' % (name, idx, sub_idx)) self.mark_and_add_effort(data, js) if self.do_print: print(json.dumps(js)) return TestResult(js) self.process_mod_line(data, name, idx, aux={'stype': 'json', 'sub_idx': sub_idx})
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 sub = self.process_x509(x509, name=name, pem=False, source='ldiff-cert') ret.append(sub) except Exception as e: logger.debug('Error in line JSON cert file processing %s, idx %s, subidx %s : %s' % (name, idx, sub_idx, e)) self.trace_logger.log(e) return ret
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: from cryptography.x509.base import load_der_x509_certificate apkf = APK(data, process_now=False, process_file_types=False, raw=True, temp_dir=self.args.tmp_dir) apkf.process() self.num_apk += 1 pem = apkf.cert_pem aux = {'subtype': 'apk'} x509 = load_der_x509_certificate(pem_to_der(pem), self.get_backend()) sub = self.process_x509(x509, name=name, idx=0, data=data, pem=True, source='apk-pem-cert', aux=aux) ret.append(sub) except Exception as e: logger.debug('Exception in processing APK %s : %s' % (name, e)) self.trace_logger.log(e) return ret
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 file processing %s : %s' % (name, e)) self.trace_logger.log(e) return ret
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.key_fmt_hex or self.re_match(r'^(0x)?[a-fA-F0-9\s\t]+$', data): ret.append(self.process_mod_line_num(strip_spaces(data), name, idx, 'hex', aux)) if self.args.key_fmt_dec or self.re_match(r'^[0-9\s\t]+$', data): ret.append(self.process_mod_line_num(strip_spaces(data), name, idx, 'dec', aux)) except Exception as e: logger.debug('Error in line mod processing %s idx %s : %s' % (name, idx, e)) self.trace_logger.log(e) return ret
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) else: raise ValueError('Unknown number format: %s' % num_type) js = collections.OrderedDict() js['type'] = 'mod-%s' % num_type js['fname'] = name js['idx'] = idx js['aux'] = aux js['n'] = '0x%x' % num if self.has_fingerprint(num): logger.warning('Fingerprint found in modulus %s idx %s ' % (name, idx)) self.mark_and_add_effort(num, js) if self.do_print: print(json.dumps(js)) return TestResult(js) except Exception as e: logger.debug('Exception in testing modulus %s idx %s : %s data: %s' % (name, idx, e, data[:30])) self.trace_logger.log(e)
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): match = re.sub('[\r\t\n\s]', '', match) try: bindata = base64.b64decode(match) x509 = load_der_x509_certificate(bindata, self.get_backend()) self.num_ldiff_cert += 1 sub = self.process_x509(x509, name=name, pem=False, source='ldiff-cert') ret.append(sub) except Exception as e: logger.debug('Error in line ldiff file processing %s, idx %s, matchlen %s : %s' % (name, idx, len(match), e)) self.trace_logger.log(e) return ret
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.args.jks_pass_file) as fh: self.jks_file_passwords = sorted(list(set([x.strip() for x in fh]))) if self.jks_file_passwords is None: self.jks_file_passwords = [] try: ks = self.try_open_jks(data, name) if ks is None: logger.warning('Could not open JKS file: %s, password not valid, ' 'try specify passwords in --jks-pass-file' % name) return # certs from cryptography.x509.base import load_der_x509_certificate ret = [] for alias, cert in list(ks.certs.items()): try: x509 = load_der_x509_certificate(cert.cert, self.get_backend()) self.num_jks_cert += 1 sub = self.process_x509(x509, name=name, pem=False, source='jks-cert', aux='cert-%s' % alias) ret.append(sub) except Exception as e: logger.debug('Error in JKS cert processing %s, alias %s : %s' % (name, alias, e)) self.trace_logger.log(e) # priv key chains for alias, pk in list(ks.private_keys.items()): for idx, cert in enumerate(pk.cert_chain): try: x509 = load_der_x509_certificate(cert[1], self.get_backend()) self.num_jks_cert += 1 sub = self.process_x509(x509, name=name, pem=False, source='jks-cert-chain', aux='cert-chain-%s-%s' % (alias, idx)) ret.append(sub) except Exception as e: logger.debug('Error in JKS priv key cert-chain processing %s, alias %s %s : %s' % (name, alias, idx, e)) self.trace_logger.log(e) return ret except ImportException: return [TestResult(fname=name, type='jks-cert', error='cannot-import')] except Exception as e: logger.warning('Exception in JKS processing: %s' % e) return None
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: try: return jks.KeyStore.loads(data, cur) except Exception as e: pass return None
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 try: der = data if is_pem: data = data.decode('utf8') data = re.sub(r'\s*-----\s*BEGIN\s+PKCS7\s*-----', '', data) data = re.sub(r'\s*-----\s*END\s+PKCS7\s*-----', '', data) der = base64.b64decode(data) bio = backend._bytes_to_bio(der) pkcs7 = backend._lib.d2i_PKCS7_bio(bio.bio, backend._ffi.NULL) backend.openssl_assert(pkcs7 != backend._ffi.NULL) signers = backend._lib.PKCS7_get0_signers(pkcs7, backend._ffi.NULL, 0) backend.openssl_assert(signers != backend._ffi.NULL) backend.openssl_assert(backend._lib.sk_X509_num(signers) > 0) x509_ptr = backend._lib.sk_X509_value(signers, 0) backend.openssl_assert(x509_ptr != backend._ffi.NULL) x509_ptr = backend._ffi.gc(x509_ptr, backend._lib.X509_free) x509 = _Certificate(backend, x509_ptr) self.num_pkcs7_cert += 1 return [self.process_x509(x509, name=name, pem=False, source='pkcs7-cert', aux='')] except Exception as e: logger.debug('Error in PKCS7 processing %s: %s' % (name, e)) self.trace_logger.log(e)
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) logger.info('.. PEM certs: . . . %s' % self.num_pem_certs) logger.info('.. DER certs: . . . %s' % self.num_der_certs) logger.info('.. RSA key files: . %s' % self.num_rsa_keys) logger.info('.. PGP master keys: %s' % self.num_pgp_masters) logger.info('.. PGP total keys: %s' % self.num_pgp_total) logger.info('.. SSH keys: . . . %s' % self.num_ssh) logger.info('.. APK keys: . . . %s' % self.num_apk) logger.info('.. JSON keys: . . . %s' % self.num_json) logger.info('.. LDIFF certs: . . %s' % self.num_ldiff_cert) logger.info('.. JKS certs: . . . %s' % self.num_jks_cert) logger.info('.. PKCS7: . . . . . %s' % self.num_pkcs7_cert) logger.debug('. Total RSA keys . %s (# of keys RSA extracted & analyzed)' % self.num_rsa) if self.found > 0: logger.info('Fingerprinted keys found: %s' % self.found) logger.info('WARNING: Potential vulnerability') else: logger.info('No fingerprinted keys found (OK)') logger.info('################################')
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, action='store_const', const=True, help='Debugging logging') parser.add_argument('--dump', dest='dump', default=False, action='store_const', const=True, help='Dump all processed info') parser.add_argument('--flatten', dest='flatten', default=False, action='store_const', const=True, help='Flatten the dump') parser.add_argument('--indent', dest='indent', default=False, action='store_const', const=True, help='Indent the dump') parser.add_argument('--old', dest='old', default=False, action='store_const', const=True, help='Old fingerprinting algorithm - moduli detector') parser.add_argument('--base64-stdin', dest='base64stdin', default=False, action='store_const', const=True, help='Decode STDIN as base64') parser.add_argument('--file-pem', dest='file_pem', default=False, action='store_const', const=True, help='Force read as PEM encoded file') parser.add_argument('--file-der', dest='file_der', default=False, action='store_const', const=True, help='Force read as DER encoded file') parser.add_argument('--file-pgp', dest='file_pgp', default=False, action='store_const', const=True, help='Force read as PGP ASC encoded file') parser.add_argument('--file-ssh', dest='file_ssh', default=False, action='store_const', const=True, help='Force read as SSH public key file') parser.add_argument('--file-mod', dest='file_mod', default=False, action='store_const', const=True, help='Force read as One modulus per line') parser.add_argument('--file-json', dest='file_json', default=False, action='store_const', const=True, help='Force read as JSON file') parser.add_argument('--file-ldiff', dest='file_ldiff', default=False, action='store_const', const=True, help='Force read as LDIFF file') parser.add_argument('--file-pkcs7', dest='file_pkcs7', default=False, action='store_const', const=True, help='Force read as PKCS7 file') parser.add_argument('--key-fmt-base64', dest='key_fmt_base64', default=False, action='store_const', const=True, help='Modulus per line, base64 encoded') parser.add_argument('--key-fmt-hex', dest='key_fmt_hex', default=False, action='store_const', const=True, help='Modulus per line, hex encoded') parser.add_argument('--key-fmt-dec', dest='key_fmt_dec', default=False, action='store_const', const=True, help='Modulus per line, dec encoded') parser.add_argument('--jks-pass-file', dest='jks_pass_file', default=None, help='Password file for JKS, one per line') parser.add_argument('files', nargs=argparse.ZERO_OR_MORE, default=[], help='files to process') return parser
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: ret.append(sub) except Exception as e: logger.error('Error in file processing %s : %s' % (name, e)) self.roca.trace_logger.log(e) return ret
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) return sub except Exception as e: logger.error('Error in file processing %s (%s) : %s' % (host_spec, name, e)) self.roca.trace_logger.log(e)
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)) return False
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: ret.append(sub) continue # arguments are file names fh = open(fname, 'r') with fh: data = fh.read() sub = self.process_tls(data, fname) ret.append(sub) return ret
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: logger.info('No fingerprinted keys found (OK)')
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='store_const', const=True, help='Dump all processed info') parser.add_argument('--flatten', dest='flatten', default=False, action='store_const', const=True, help='Flatten the dump') parser.add_argument('--indent', dest='indent', default=False, action='store_const', const=True, help='Indent the dump') parser.add_argument('--hosts', dest='hosts', default=False, action='store_const', const=True, help='Arguments are host names not file names') parser.add_argument('files', nargs=argparse.ZERO_OR_MORE, default=[], help='files to process') return parser
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: coloredlogs.install(level=logging.DEBUG) self.roca.args.debug = True self.work()
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(shape) == 1: return _map_tril_1d_on_2d(indices, shape[0]) else: return np.unravel_index(indices, shape)
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_sample_size = (n - len(sample)) * 2 sample = random_state.randint(n_max, size=n_sample_size) # concatenate pairs and deduplicate pairs_non_unique = np.append(sample, sample) sample = _unique_rows_numpy(pairs_non_unique) # return 2d indices if len(shape) == 1: return _map_tril_1d_on_2d(sample[0:n], shape[0]) else: return np.unravel_index(sample[0:n], shape)
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 elif callable(strip_accents): strip_accents_fn = strip_accents elif strip_accents == 'ascii': strip_accents_fn = strip_accents_ascii elif strip_accents == 'unicode': strip_accents_fn = strip_accents_unicode else: raise ValueError( "Invalid value for 'strip_accents': {}".format(strip_accents) ) # Remove accents etc if strip_accents: def strip_accents_fn_wrapper(x): if sys.version_info[0] >= 3: if isinstance(x, str): return strip_accents_fn(x) else: return x else: if isinstance(x, unicode): # noqa return strip_accents_fn(x) else: return x # encoding s = s.apply( lambda x: x.decode(encoding, decode_error) if type(x) == bytes else x) s = s.map(lambda x: strip_accents_fn_wrapper(x)) # Remove all content between brackets if remove_brackets is True: s = s.str.replace(r'(\[.*?\]|\(.*?\)|\{.*?\})', '') # Remove the special characters if replace_by_none: s = s.str.replace(replace_by_none, '') if replace_by_whitespace: s = s.str.replace(replace_by_whitespace, ' ') # Remove multiple whitespaces s = s.str.replace(r'\s\s+', ' ') # Strip s s = s.str.lstrip().str.rstrip() return s
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, optional The matches of this regular expression are replaced by ''. replace_by_whitespace : str, optional The matches of this regular expression are replaced by a whitespace. remove_brackets : bool, optional Remove all content between brackets and the bracket themselves. Default True. strip_accents : {'ascii', 'unicode', None}, optional Remove accents during the preprocessing step. 'ascii' is a fast method that only works on characters that have an direct ASCII mapping. 'unicode' is a slightly slower method that works on any characters. None (default) does nothing. encoding : str, optional If bytes are given, this encoding is used to decode. Default is 'utf-8'. decode_error : {'strict', 'ignore', 'replace'}, optional Instruction on what to do if a byte Series is given that contains characters not of the given `encoding`. By default, it is 'strict', meaning that a UnicodeDecodeError will be raised. Other values are 'ignore' and 'replace'. Example ------- >>> import pandas >>> from recordlinkage.preprocessing import clean >>> >>> names = ['Mary-ann', 'Bob :)', 'Angel', 'Bob (alias Billy)', None] >>> s = pandas.Series(names) >>> print(clean(s)) 0 mary ann 1 bob 2 angel 3 bob 4 NaN dtype: object Returns ------- pandas.Series: A cleaned Series of strings.
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