desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Given a bow vector of an input text, predict most probable label. Returns only the most likely label. :param X: bow of input text :return: tuple of first, the most probable label and second, its probability'
def predict(self, X):
import numpy as np pred_result = self.predict_prob(X) sorted_indices = np.fliplr(np.argsort(pred_result, axis=1)) return (sorted_indices, pred_result[:, sorted_indices])
'Persist this model into the passed directory. Returns the metadata necessary to load the model again.'
def persist(self, model_dir):
import cloudpickle classifier_file = os.path.join(model_dir, u'intent_classifier.pkl') with io.open(classifier_file, u'wb') as f: cloudpickle.dump(self, f) return {u'intent_classifier_sklearn': u'intent_classifier.pkl'}
'Main Rasa route to check if the server is online'
@app.route(u'/', methods=[u'GET']) @check_cors def hello(self, request):
return (u'hello from Rasa NLU: ' + __version__)
'Returns the Rasa server\'s version'
@app.route(u'/version', methods=[u'GET']) @requires_auth @check_cors def version(self, request):
request.setHeader(u'Content-Type', u'application/json') return json.dumps({u'version': __version__})
'Returns the in-memory configuration of the Rasa server'
@app.route(u'/config', methods=[u'GET']) @requires_auth @check_cors def rasaconfig(self, request):
request.setHeader(u'Content-Type', u'application/json') return json.dumps(self.config.as_dict())
'Take a sentence and return entities in json format'
def extract_entities(self, message):
if (self.ent_tagger is not None): text_data = self._from_text_to_crf(message) features = self._sentence_to_features(text_data) ents = self.ent_tagger.predict_single(features) return self._from_crf_to_json(message, ents) else: return []
'Persist this model into the passed directory. Returns the metadata necessary to load the model again.'
def persist(self, model_dir):
from sklearn.externals import joblib if self.ent_tagger: model_file_name = os.path.join(model_dir, u'crf_model.pkl') joblib.dump(self.ent_tagger, model_file_name) return {u'entity_extractor_crf': {u'model_file': u'crf_model.pkl', u'crf_features': self.crf_features, u'BILOU_flag': self.BI...
'Convert a word into discrete features in self.crf_features, including word before and word after.'
def _sentence_to_features(self, sentence):
sentence_features = [] for word_idx in range(len(sentence)): prefixes = [u'-1', u'0', u'+1'] word_features = {} for i in range(3): if ((word_idx == (len(sentence) - 1)) and (i == 2)): word_features[u'EOS'] = True elif ((word_idx == 0) and (i == 0))...
'Takes the json examples and switches them to a format which crfsuite likes.'
def _from_json_to_crf(self, message, entity_offsets):
from spacy.gold import GoldParse doc = message.get(u'spacy_doc') gold = GoldParse(doc, entities=entity_offsets) ents = [l[5] for l in gold.orig_annot] if (u'-' in ents): logger.warn(((u"Misaligned entity annotation in sentence '{}'. ".format(doc.text) + u'Make sure th...
'Takes a sentence and switches it to crfsuite format.'
def _from_text_to_crf(self, message, entities=None):
crf_format = [] for (i, token) in enumerate(message.get(u'spacy_doc')): pattern = self.__pattern_of_token(message, i) entity = (entities[i] if entities else u'N/A') crf_format.append((token.text, token.tag_, entity, pattern)) return crf_format
'Train the crf tagger based on the training data.'
def _train_model(self, df_train):
import sklearn_crfsuite X_train = [self._sentence_to_features(sent) for sent in df_train] y_train = [self._sentence_to_labels(sent) for sent in df_train] self.ent_tagger = sklearn_crfsuite.CRF(algorithm=u'lbfgs', c1=1.0, c2=0.001, max_iterations=50, all_possible_transitions=True) self.ent_tagger.fit...
'Checks which known patterns match the message. Given a sentence, returns a vector of {1,0} values indicating which regexes did match. Furthermore, if the message is tokenized, the function will mark the matching regex on the tokens that are part of the match.'
def features_for_patterns(self, message):
import numpy as np found = [] for (i, exp) in enumerate(self.known_patterns): match = re.search(exp[u'pattern'], message.text) if (match is not None): for t in message.get(u'tokens', []): if ((t.offset < match.end()) and (t.end > match.start())): ...
'Persist this model into the passed directory. Returns the metadata necessary to load the model again.'
def persist(self, model_dir):
if self.known_patterns: regex_file = os.path.join(model_dir, u'regex_featurizer.json') with io.open(regex_file, u'w') as f: f.write(str(json.dumps(self.known_patterns, indent=4))) return {u'regex_featurizer': u'regex_featurizer.json'} else: return {u'regex_featurizer'...
'Persist this model into the passed directory. Returns the metadata necessary to load the model again.'
def persist(self, model_dir):
import cloudpickle classifier_file = os.path.join(model_dir, u'ngram_featurizer.pkl') with io.open(classifier_file, u'wb') as f: cloudpickle.dump(self, f) return {u'ngram_featurizer': u'ngram_featurizer.pkl'}
'Returns an ordered list of the best character ngrams for an intent classification problem'
def _get_best_ngrams(self, examples, labels):
oov_strings = self._remove_in_vocab_words(examples) ngrams = self._generate_all_ngrams(oov_strings) return self._sort_applicable_ngrams(ngrams, examples, labels)
'Automatically removes words with digits in them, that may be a hyperlink or that _are_ in vocabulary for the nlp'
def _remove_in_vocab_words(self, examples):
new_sents = [] for example in examples: new_sents.append(self._remove_in_vocab_words_from_sentence(example)) return new_sents
'Automatically removes words with digits in them, hyperlink and in-vocab-words.'
def _remove_in_vocab_words_from_sentence(self, example):
cleaned_tokens = [] for token in example.get(u'spacy_doc'): if ((not token.has_vector) and (not token.like_url) and (not token.like_num) and (not token.like_email) and (not token.is_punct)): cleaned_tokens.append(token) non_words = u' '.join([t.text for t in cleaned_tokens]) non_w...
'Given an intent classification problem and a list of ngrams, creates ordered list of most useful ngrams.'
def _sort_applicable_ngrams(self, list_of_ngrams, examples, labels):
if list_of_ngrams: from sklearn import linear_model, preprocessing import numpy as np usable_labels = [] for label in np.unique(labels): lab_sents = np.array(examples)[(np.array(labels) == label)] if (len(lab_sents) < self.min_intent_examples_for_ngram_classif...
'Given a set of sentences, returns a feature vector for each sentence. The first $k$ elements are from the `intent_features`, the rest are {1,0} elements denoting whether an ngram is in sentence.'
def _ngrams_in_sentences(self, examples, ngrams):
all_vectors = [] for example in examples: presence_vector = self._ngrams_in_sentence(example, ngrams) all_vectors.append(presence_vector) return all_vectors
'Given a set of sentences, returns a vector of {1,0} values indicating ngram presence'
def _ngrams_in_sentence(self, example, ngrams):
import numpy as np cleaned_sentence = self._remove_in_vocab_words_from_sentence(example) presence_vector = np.zeros(len(ngrams)) idx_array = [idx for idx in range(len(ngrams)) if (ngrams[idx] in cleaned_sentence)] presence_vector[idx_array] = 1 return presence_vector
'Takes a list of strings and generates all character ngrams. Generated ngrams are at least 3 characters (and at most 17), occur at least 5 times and occur independently of longer superset ngrams at least once.'
def _generate_all_ngrams(self, list_of_strings):
features = {} counters = {(self.n_gram_min_length - 1): Counter()} for n in range(self.n_gram_min_length, self.n_gram_max_length): candidates = [] features[n] = [] counters[n] = Counter() for text in list_of_strings: text = text.replace(punctuation, u' ') ...
'choose the best number of ngrams to include in bow. Given an intent classification problem and a set of ordered ngrams (ordered in terms of importance by pick_applicable_ngrams) we choose the best number of ngrams to include in our bow vecs by cross validation.'
def _cross_validation(self, examples, labels, max_ngrams):
from sklearn import preprocessing from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_val_score import numpy as np if examples: collected_features = [e.get(u'text_features') for e in examples if (e.get(u'text_features') is not None)] else: ...
'Terminates workers pool processes'
def __del__(self):
self.pool.shutdown()
'Public wrapper over the internal __del__ function'
def shutdown(self):
self.__del__()
'Creates a logger that will persist incomming queries and their results.'
@staticmethod def _create_query_logger(response_log_dir):
if response_log_dir: timestamp = datetime.datetime.now().strftime(u'%Y%m%d-%H%M%S') log_file_name = u'rasa_nlu_log-{}-{}.log'.format(timestamp, os.getpid()) response_logfile = os.path.join(response_log_dir, log_file_name) utils.create_dir_for_file(response_logfile) query_logg...
'Adds a new training process to the list of running processes.'
def _add_training_to_queue(self):
self._trainings_queued += 1
'Decreases the ongoing trainings count by one'
def _remove_training_from_queue(self):
self._trainings_queued -= 1
'Sets which NLU webservice to emulate among those supported by Rasa'
def __create_emulator(self):
mode = self.config[u'emulate'] if (mode is None): from rasa_nlu.emulators import NoEmulator return NoEmulator() elif (mode.lower() == u'wit'): from rasa_nlu.emulators.wit import WitEmulator return WitEmulator() elif (mode.lower() == u'luis'): from rasa_nlu.emulato...
'Loads the metadata from a models directory.'
@staticmethod def load(model_dir):
try: with io.open(os.path.join(model_dir, u'metadata.json'), encoding=u'utf-8') as f: data = json.loads(f.read()) return Metadata(data, model_dir) except Exception as e: raise InvalidModelError(u'Failed to load model metadata. {}'.format(e))
'Language of the underlying model'
@property def language(self):
return self.get(u'language')
'Names of the processing pipeline elements.'
@property def pipeline(self):
return self.get(u'pipeline', [])
'Persists the metadata of a model to a given directory.'
def persist(self, model_dir):
metadata = self.metadata.copy() metadata.update({u'trained_at': datetime.datetime.now().strftime(u'%Y%m%d-%H%M%S'), u'rasa_nlu_version': rasa_nlu.__version__}) with io.open(os.path.join(model_dir, u'metadata.json'), u'w') as f: f.write(str(json.dumps(metadata, indent=4)))
'Trains the underlying pipeline by using the provided training data.'
def train(self, data):
self.training_data = copy.deepcopy(data) context = {} for component in self.pipeline: updates = component.provide_context() if updates: context.update(updates) if (not self.skip_validation): components.validate_arguments(self.pipeline, context) for (i, component) ...
'Persist all components of the pipeline to the passed path. Returns the directory of the persisted model.'
def persist(self, path, persistor=None, model_name=None):
timestamp = datetime.datetime.now().strftime(u'%Y%m%d-%H%M%S') metadata = {u'language': self.config[u'language'], u'pipeline': [component.name for component in self.pipeline]} if (model_name is None): dir_name = os.path.join(path, (u'model_' + timestamp)) else: dir_name = os.path.join(pa...
'Load a stored model and its components defined by the provided metadata.'
@staticmethod def load(model_metadata, config, component_builder=None, skip_valdation=False):
context = {} if (component_builder is None): component_builder = components.ComponentBuilder() pipeline = [] if (not skip_valdation): components.validate_requirements(model_metadata.pipeline) for component_name in model_metadata.pipeline: component = component_builder.load_co...
'Parse the input text, classify it and return an object containing its intent and entities.'
def parse(self, text, time=None):
if (not text): output = self.default_output_attributes() output[u'text'] = u'' return output message = Message(text, self.default_output_attributes(), time=time) for component in self.pipeline: component.process(message, **self.context) output = self.default_output_attrib...
'Makes sure the training data is cleaned, e.q. removes trailing whitespaces from intent annotations.'
def sanitice_examples(self, examples):
for e in examples: if (e.get(u'intent') is not None): e.set(u'intent', e.get(u'intent').strip()) return examples
'Returns the number of proper entity training examples (containing at least one annotated entity).'
@lazyproperty def num_entity_examples(self):
return len([e for e in self.training_examples if (len(e.get(u'entities', [])) > 0)])
'Returns the number of intent examples.'
@lazyproperty def num_intent_examples(self):
return len(self.intent_examples)
'Represent this set of training examples as json adding the passed meta information.'
def as_json(self, **kwargs):
syns_as_tuples = sorted([i for i in self.entity_synonyms.items() if (i[0] != i[1])], key=(lambda x: x[1])) self.entity_synonyms = [] for (i, s) in enumerate(syns_as_tuples): if ((i == 0) or (s[1] != syns_as_tuples[(i - 1)][1])): self.entity_synonyms.append({u'value': s[1], u'synonyms': [...
'Represent this set of training examples as markdown adding the passed meta information.'
def as_markdown(self, **kwargs):
return JsonToMd(self.training_examples, self.entity_synonyms).to_markdown()
'Persists this training data to disk and returns necessary information to load it again.'
def persist(self, dir_name):
data_file = os.path.join(dir_name, u'training_data.json') with io.open(data_file, u'w') as f: f.write(self.as_json(indent=2)) return {u'training_data': u'training_data.json'}
'Sorts the entity examples by the annotated entity.'
def sorted_entity_examples(self):
return sorted([entity for ex in self.entity_examples for entity in ex.get(u'entities')], key=(lambda e: e[u'entity']))
'Sorts the intent examples by the name of the intent.'
def sorted_intent_examples(self):
return sorted(self.intent_examples, key=(lambda e: e.get(u'intent')))
'Ensures that the loaded training data is valid, e.g. has a minimum of certain training examples.'
def validate(self):
logger.debug(u'Validating training data...') examples = self.sorted_intent_examples() different_intents = [] for (intent, group) in groupby(examples, (lambda e: e.get(u'intent'))): size = len(list(group)) different_intents.append(intent) if (size < self.MIN_EXAMPLES_PER_INT...
'Transform data to target format.'
def normalise_response_json(self, data):
return data
'Transform data to wit.ai format.'
def normalise_response_json(self, data):
entities = {} for entity in data[u'entities']: entities[entity[u'entity']] = {u'confidence': None, u'type': u'value', u'value': entity[u'value'], u'start': entity[u'start'], u'end': entity[u'end']} return [{u'_text': data[u'text'], u'confidence': data[u'intent'][u'confidence'], u'intent': data[u'int...
'Transform data to API.ai format.'
def normalise_response_json(self, data):
entities = {entity_type: [] for entity_type in set([x[u'entity'] for x in data[u'entities']])} for entity in data[u'entities']: entities[entity[u'entity']].append(entity[u'value']) return {u'id': str(uuid.uuid1()), u'timestamp': datetime.now().isoformat(), u'result': {u'source': u'agent', u'resolved...
'Transform data to luis.ai format.'
def normalise_response_json(self, data):
top_intent = self._top_intent(data) ranking = self._ranking(data) return {u'query': data[u'text'], u'topScoringIntent': top_intent, u'intents': ranking, u'entities': ([{u'entity': e[u'value'], u'type': e[u'entity'], u'startIndex': None, u'endIndex': None, u'score': None} for e in data[u'entities']] if (u'en...
'Checks if the spacy language model is properly loaded. Raises an exception if the model is invalid.'
@staticmethod def ensure_proper_language_model(nlp):
if (nlp is None): raise Exception(u"Failed to load spacy language model. Loading the model returned 'None'.") if (nlp.path is None): raise Exception((u"Failed to load spacy language model for lang '{}'. ".format(nlp.lang) + u'Make sure ...
'switch between \'intent\' and \'synonyms\' mode'
def set_current_state(self, state, value):
if (state == u'intent'): self.current_intent = value elif (state == u'synonym'): self.current_intent = None self.entity_synonyms.append({u'value': value, u'synonyms': []}) else: raise ValueError(u"State must be either 'intent' or 'synonym'")
'informs whether whether we are currently loading intents or synonyms'
def get_current_state(self):
if (self.current_intent is not None): return u'intent' else: return u'synonym'
'parse the content of the actual .md file'
def load(self):
with io.open(self.file_name, u'rU', encoding=u'utf-8-sig') as f: for row in f: intent_match = re.search(intent_regex, row) if (intent_match is not None): self.set_current_state(u'intent', intent_match.group(1)) continue synonym_match = re.s...
'status(status, *args, **kwargs) Logs a status update for the running job. If the progress logger is animated the status line will be updated in place. Status updates are throttled at one update per 100ms.'
def status(self, status, *args, **kwargs):
now = time.time() if ((now - self.last_status) > self.rate): self.last_status = now self._log(status, args, kwargs, 'status')
'success(status = \'Done\', *args, **kwargs) Logs that the running job succeeded. No further status updates are allowed. If the Logger is animated, the animation is stopped.'
def success(self, status='Done', *args, **kwargs):
self._log(status, args, kwargs, 'success') self._stopped = True
'failure(message) Logs that the running job failed. No further status updates are allowed. If the Logger is animated, the animation is stopped.'
def failure(self, status='Failed', *args, **kwargs):
self._log(status, args, kwargs, 'failure') self._stopped = True
'progress(message, status = \'\', *args, level = logging.INFO, **kwargs) -> Progress Creates a new progress logger which creates log records with log level `level`. Progress status can be updated using :meth:`Progress.status` and stopped using :meth:`Progress.success` or :meth:`Progress.failure`. If `term.term_mode` is...
def progress(self, message, status='', *args, **kwargs):
level = self._getlevel(kwargs.pop('level', logging.INFO)) return Progress(self, message, status, level, args, kwargs)
'Alias for :meth:`progress`.'
def waitfor(self, *args, **kwargs):
return self.progress(*args, **kwargs)
'indented(message, *args, level = logging.INFO, **kwargs) Log a message but don\'t put a line prefix on it. Arguments: level(int): Alternate log level at which to set the indented message. Defaults to :const:`logging.INFO`.'
def indented(self, message, *args, **kwargs):
level = self._getlevel(kwargs.pop('level', logging.INFO)) self._log(level, message, args, kwargs, 'indented')
'success(message, *args, **kwargs) Logs a success message.'
def success(self, message, *args, **kwargs):
self._log(logging.INFO, message, args, kwargs, 'success')
'failure(message, *args, **kwargs) Logs a failure message.'
def failure(self, message, *args, **kwargs):
self._log(logging.INFO, message, args, kwargs, 'failure')
'info_once(message, *args, **kwargs) Logs an info message. The same message is never printed again.'
def info_once(self, message, *args, **kwargs):
m = (message % args) if (m not in self._one_time_infos): if self.isEnabledFor(logging.INFO): self._one_time_infos.add(m) self._log(logging.INFO, message, args, kwargs, 'info_once')
'warning_once(message, *args, **kwargs) Logs a warning message. The same message is never printed again.'
def warning_once(self, message, *args, **kwargs):
m = (message % args) if (m not in self._one_time_warnings): if self.isEnabledFor(logging.INFO): self._one_time_warnings.add(m) self._log(logging.WARNING, message, args, kwargs, 'warning_once')
'Alias for :meth:`warning_once`.'
def warn_once(self, *args, **kwargs):
return self.warning_once(*args, **kwargs)
'debug(message, *args, **kwargs) Logs a debug message.'
def debug(self, message, *args, **kwargs):
self._log(logging.DEBUG, message, args, kwargs, 'debug')
'info(message, *args, **kwargs) Logs an info message.'
def info(self, message, *args, **kwargs):
self._log(logging.INFO, message, args, kwargs, 'info')
'warning(message, *args, **kwargs) Logs a warning message.'
def warning(self, message, *args, **kwargs):
self._log(logging.WARNING, message, args, kwargs, 'warning')
'Alias for :meth:`warning`.'
def warn(self, *args, **kwargs):
return self.warning(*args, **kwargs)
'error(message, *args, **kwargs) To be called outside an exception handler. Logs an error message, then raises a ``PwnlibException``.'
def error(self, message, *args, **kwargs):
self._log(logging.ERROR, message, args, kwargs, 'error') raise PwnlibException((message % args))
'exception(message, *args, **kwargs) To be called from an exception handler. Logs a error message, then re-raises the current exception.'
def exception(self, message, *args, **kwargs):
kwargs['exc_info'] = 1 self._log(logging.ERROR, message, args, kwargs, 'exception') raise
'critical(message, *args, **kwargs) Logs a critical message.'
def critical(self, message, *args, **kwargs):
self._log(logging.CRITICAL, message, args, kwargs, 'critical')
'log(level, message, *args, **kwargs) Logs a message with log level `level`. The ``pwnlib`` formatter will use the default :mod:`logging` formater to format this message.'
def log(self, level, message, *args, **kwargs):
self._log(level, message, args, kwargs, None)
'isEnabledFor(level) -> bool See if the underlying logger is enabled for the specified level.'
def isEnabledFor(self, level):
effectiveLevel = self._logger.getEffectiveLevel() if (effectiveLevel == 1): effectiveLevel = context.log_level return (effectiveLevel <= level)
'setLevel(level) Set the logging level for the underlying logger.'
def setLevel(self, level):
with context.local(log_level=level): self._logger.setLevel(context.log_level)
'addHandler(handler) Add the specified handler to the underlying logger.'
def addHandler(self, handler):
self._logger.addHandler(handler)
'removeHandler(handler) Remove the specified handler from the underlying logger.'
def removeHandler(self, handler):
self._logger.removeHandler(handler)
'Emit a log record or create/update an animated progress logger depending on whether :data:`term.term_mode` is enabled.'
def emit(self, record):
level = logging.getLogger(record.name).getEffectiveLevel() if (level == 1): level = context.log_level if (level > record.levelno): return progress = getattr(record, 'pwnlib_progress', None) if ((progress is None) or (not term.term_mode)): super(Handler, self).emit(record) ...
'bar'
def __init__(self, msg, reason=None, exit_code=None):
Exception.__init__(self, msg) self.reason = reason self.exit_code = exit_code
'Timeout for obj operations. By default, uses ``context.timeout``.'
@property def timeout(self):
timeout = self._timeout stop = self._stop if (not stop): return timeout return max((stop - time.time()), 0)
'Callback for subclasses to hook a timeout change.'
def timeout_change(self):
pass
'Scoped timeout setter. Sets the timeout within the scope, and restores it when leaving the scope. When accessing :attr:`timeout` within the scope, it will be calculated against the time when the scope was entered, in a countdown fashion. If :const:`None` is specified for ``timeout``, then the current timeout is used ...
def countdown(self, timeout=default):
if (timeout is self.maximum): return _DummyContext if ((timeout is self.default) and (self.timeout is self.maximum)): return _DummyContext if (timeout is self.default): timeout = self._timeout return _countdown_handler(self, timeout)
'Scoped timeout setter. Sets the timeout within the scope, and restores it when leaving the scope.'
def local(self, timeout):
if ((timeout is self.default) or (timeout == self.timeout)): return _DummyContext return _local_handler(self, timeout)
'Instantiates an object which can resolve symbols in a running binary given a :class:`pwnlib.memleak.MemLeak` leaker and a pointer inside the binary. Arguments: leak(MemLeak): Instance of pwnlib.memleak.MemLeak for leaking memory pointer(int): A pointer into a loaded ELF file elf(str,ELF): Path to the ELF file on dis...
def __init__(self, leak, pointer=None, elf=None, libcdb=True):
self.libcdb = libcdb self._elfclass = None self._elftype = None self._link_map = None self._waitfor = None self._bases = {} self._dynamic = None if (not (pointer or (elf and elf.address))): log.error('Must specify either a pointer into a module and/or a...
'Given a :class:`pwnlib.memleak.MemLeak` object and a pointer into a library, find its base address.'
@staticmethod def find_base(leak, ptr):
return DynELF(leak, ptr).libbase
'32 or 64'
@property def elfclass(self):
if (not self._elfclass): elfclass = self.leak.field(self.libbase, elf.Elf_eident.EI_CLASS) self._elfclass = {constants.ELFCLASS32: 32, constants.ELFCLASS64: 64}[elfclass] return self._elfclass
'e_type from the elf header. In practice the value will almost always be \'EXEC\' or \'DYN\'. If the value is architecture-specific (between ET_LOPROC and ET_HIPROC) or invalid, KeyError is raised.'
@property def elftype(self):
if (not self._elftype): Ehdr = {32: elf.Elf32_Ehdr, 64: elf.Elf64_Ehdr}[self.elfclass] elftype = self.leak.field(self.libbase, Ehdr.e_type) self._elftype = {constants.ET_NONE: 'NONE', constants.ET_REL: 'REL', constants.ET_EXEC: 'EXEC', constants.ET_DYN: 'DYN', constants.ET_CORE: 'CORE'}[elft...
'Pointer to the runtime link_map object'
@property def link_map(self):
if (not self._link_map): self._link_map = self._find_linkmap() return self._link_map
'Returns: Pointer to the ``.DYNAMIC`` area.'
@property def dynamic(self):
if (not self._dynamic): self._dynamic = self._find_dynamic_phdr() return self._dynamic
'Uses an ELF file to assist in finding the link_map.'
def _find_linkmap_assisted(self, path):
if isinstance(path, ELF): path = path.path with context.local(log_level='error'): elf = ELF(path) elf.address = self.libbase w = self.waitfor(('Loading from %r' % elf.path)) real_leak = self.leak @MemLeak def fake_leak(address): try: return elf.read(...
'Returns the address of the first Program Header with the type PT_DYNAMIC.'
def _find_dynamic_phdr(self):
leak = self.leak base = self.libbase Ehdr = {32: elf.Elf32_Ehdr, 64: elf.Elf64_Ehdr}[self.elfclass] Phdr = {32: elf.Elf32_Phdr, 64: elf.Elf64_Phdr}[self.elfclass] self.status('PT_DYNAMIC') phead = (base + leak.field(base, Ehdr.e_phoff)) self.status(('PT_DYNAMIC header = %#x' % phead...
'Find an entry in the DYNAMIC array. Arguments: tag(int): Single tag to find Returns: Pointer to the data described by the specified entry.'
def _find_dt(self, tag):
leak = self.leak base = self.libbase dynamic = self.dynamic name = next((k for (k, v) in ENUM_D_TAG.items() if (v == tag))) Dyn = {32: elf.Elf32_Dyn, 64: elf.Elf64_Dyn}[self.elfclass] while (not leak.field_compare(dynamic, Dyn.d_tag, constants.DT_NULL)): if leak.field_compare(dynamic, Dy...
'The linkmap is a chained structure created by the loader at runtime which contains information on the names and load addresses osf all libraries. For non-RELRO binaries, a pointer to this is stored in the .got.plt area. For RELRO binaries, a pointer is additionally stored in the DT_DEBUG area.'
def _find_linkmap(self, pltgot=None, debug=None):
w = self.waitfor('Finding linkmap') Got = {32: elf.Elf_i386_GOT, 64: elf.Elf_x86_64_GOT}[self.elfclass] r_debug = {32: elf.Elf32_r_debug, 64: elf.Elf64_r_debug}[self.elfclass] result = None if (not pltgot): w.status('Finding linkmap: DT_PLTGOT') pltgot = self._find_dt(consta...
'libc(self) -> ELF Leak the Build ID of the remote libc.so, download the file, and load an ``ELF`` object with the correct base address. Returns: An ELF object, or None.'
@property def libc(self):
libc = 'libc.so' with self.waitfor('Downloading libc'): dynlib = self._dynamic_load_dynelf(libc) self.status('Trying lookup based on Build ID') build_id = dynlib._lookup_build_id(libc) if (not build_id): return None self.status(('Trying lo...
'lookup(symb = None, lib = None) -> int Find the address of ``symbol``, which is found in ``lib``. Arguments: symb(str): Named routine to look up lib(str): Substring to match for the library name. If omitted, the current library is searched. If set to ``\'libc\'``, ``\'libc.so\'`` is assumed. Returns: Address of the na...
def lookup(self, symb=None, lib=None):
result = None if (lib == 'libc'): lib = 'libc.so' if (symb and lib): pretty = ('%r in %r' % (symb, lib)) else: pretty = repr((symb or lib)) if (not pretty): self.failure('Must specify a library or symbol') self.waitfor(('Resolving %s' % pre...
'Resolve base addresses of all loaded libraries. Return a dictionary mapping library path to its base address.'
def bases(self):
if (not self._bases): leak = self.leak LinkMap = {32: elf.Elf32_Link_Map, 64: elf.Elf64_Link_Map}[self.elfclass] cur = self.link_map while leak.field(cur, LinkMap.l_prev): cur = leak.field(cur, LinkMap.l_prev) while cur: p_name = leak.field(cur, LinkMa...
'_dynamic_load_dynelf(libname) -> DynELF Looks up information about a loaded library via the link map. Arguments: libname(str): Name of the library to resolve, or a substring (e.g. \'libc.so\') Returns: A DynELF instance for the loaded library, or None.'
def _dynamic_load_dynelf(self, libname):
cur = self.link_map leak = self.leak LinkMap = {32: elf.Elf32_Link_Map, 64: elf.Elf64_Link_Map}[self.elfclass] while leak.field(cur, LinkMap.l_prev): cur = leak.field(cur, LinkMap.l_prev) while cur: self.status(('link_map entry %#x' % cur)) p_name = leak.field(cur, Link...
'Performs the actual symbol lookup within one ELF file.'
def _lookup(self, symb):
leak = self.leak Dyn = {32: elf.Elf32_Dyn, 64: elf.Elf64_Dyn}[self.elfclass] name = (lambda tag: next((k for (k, v) in ENUM_D_TAG.items() if (v == tag)))) self.status('.gnu.hash/.hash, .strtab and .symtab offsets') hshtab = self._find_dt(constants.DT_GNU_HASH) strtab = self._find_dt(...
'Internal Documentation: See the ELF manual for more information. Search for the phrase "A hash table of Elf32_Word objects supports symbol table access", or see: https://docs.oracle.com/cd/E19504-01/802-6319/6ia12qkfo/index.html#chapter6-48031 struct Elf_Hash { uint32_t nbucket; uint32_t nchain; uint32_t bucket[nbuck...
def _resolve_symbol_sysv(self, libbase, symb, hshtab, strtab, symtab):
self.status('.hash parms') leak = self.leak Sym = {32: elf.Elf32_Sym, 64: elf.Elf64_Sym}[self.elfclass] nbucket = leak.field(hshtab, elf.Elf_HashTable.nbucket) bucketaddr = (hshtab + sizeof(elf.Elf_HashTable)) chain = (bucketaddr + (nbucket * 4)) self.status('hashmap') hsh = (sysv_has...
'Internal Documentation: The GNU hash structure is a bit more complex than the normal hash structure. Again, Oracle has good documentation. https://blogs.oracle.com/ali/entry/gnu_hash_elf_sections You can force an ELF to use this type of symbol table by compiling with \'gcc -Wl,--hash-style=gnu\''
def _resolve_symbol_gnu(self, libbase, symb, hshtab, strtab, symtab):
self.status('.gnu.hash parms') leak = self.leak Sym = {32: elf.Elf32_Sym, 64: elf.Elf64_Sym}[self.elfclass] nbuckets = leak.field(hshtab, elf.GNU_HASH.nbuckets) symndx = leak.field(hshtab, elf.GNU_HASH.symndx) maskwords = leak.field(hshtab, elf.GNU_HASH.maskwords) elfword = (self.elfclass...
'For shared libraries (or PIE executables), many ELF fields may contain offsets rather than actual pointers. If the ELF type is \'DYN\', the argument may be an offset. It will not necessarily be an offset, because the run-time linker may have fixed it up to be a real pointer already. In this case an educated guess is m...
def _make_absolute_ptr(self, ptr_or_offset):
if_ptr = ptr_or_offset if_offset = (ptr_or_offset + self.libbase) if (self.elftype != 'DYN'): return if_ptr if (0 < ptr_or_offset < self.libbase): return if_offset else: return if_ptr