code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
''' add a done/queued/progress callback to the appropriate list '''
for subscriber in subscribers:
callback_name = 'on_' + callback_type
if hasattr(subscriber, callback_name):
_function = functools.partial(getattr(subscriber, callback_name), **kwargs)
... | def _add_subscribers_for_type(self, callback_type, subscribers, callbacks, **kwargs) | add a done/queued/progress callback to the appropriate list | 4.632262 | 2.89417 | 1.600549 |
with self._callbacks_lock:
_function = functools.partial(function, **kwargs)
self._done_callbacks.append(_function) | def add_done_callback(self, function, **kwargs) | Add a done callback to be invoked when transfer is complete | 3.53228 | 3.781235 | 0.93416 |
if subscribers:
with self._callbacks_lock:
self._add_subscribers_for_type(
'done', subscribers, self._done_callbacks, **kwargs)
self._add_subscribers_for_type(
'queued', subscribers, self._queued_callbacks, **kwargs)
... | def add_subscribers(self, subscribers, **kwargs) | Add a callbacks to be invoked during transfer | 2.781489 | 2.569504 | 1.0825 |
''' run the init/quued calback when the trasnfer is initiated on apsera '''
for callback in self._queued_callbacks:
try:
callback()
except Exception as ex:
logger.error("Exception: %s" % str(ex)) | def _run_queued_callbacks(self) | run the init/quued calback when the trasnfer is initiated on apsera | 13.182681 | 2.917228 | 4.518907 |
''' pass the number of bytes process to progress callbacks '''
if bytes_transferred:
for callback in self._progress_callbacks:
try:
callback(bytes_transferred=bytes_transferred)
except Exception as ex:
logger.error("Exce... | def _run_progress_callbacks(self, bytes_transferred) | pass the number of bytes process to progress callbacks | 4.094975 | 3.083428 | 1.328059 |
''' Run the callbacks and remove the callbacks from the internal
List so they do not get run again if done is notified more than once.
'''
with self._callbacks_lock:
for callback in self._done_callbacks:
try:
callback()
... | def _run_done_callbacks(self) | Run the callbacks and remove the callbacks from the internal
List so they do not get run again if done is notified more than once. | 7.467957 | 4.608545 | 1.620459 |
if not self.locations:
raise ValueError('BioCAnnotation must have at least one location')
start = min(l.offset for l in self.locations)
end = max(l.end for l in self.locations)
return BioCLocation(start, end - start) | def total_span(self) -> BioCLocation | The total span of this annotation. Discontinued locations will be merged. | 3.047097 | 2.621988 | 1.162132 |
return next((node for node in self.nodes if node.role == role), default) | def get_node(self, role: str, default=None) -> BioCNode | Get the first node with role
Args:
role: role
default: node returned instead of raising StopIteration
Returns:
the first node with role | 4.214369 | 6.346642 | 0.664031 |
for sentence in self.sentences:
if sentence.offset == offset:
return sentence
return None | def get_sentence(self, offset: int) -> BioCSentence or None | Gets sentence with specified offset
Args:
offset: sentence offset
Return:
the sentence with specified offset | 3.981674 | 3.907317 | 1.01903 |
for passage in self.passages:
if passage.offset == offset:
return passage
return None | def get_passage(self, offset: int) -> BioCPassage or None | Gets passage
Args:
offset: passage offset
Return:
the passage with specified offset | 3.620794 | 3.427775 | 1.05631 |
if len(passages) <= 0:
raise ValueError("There has to be at least one passage.")
c = BioCDocument()
for passage in passages:
if passage is None:
raise ValueError('Passage is None')
c.add_passage(passage)
return c | def of(cls, *passages: BioCPassage) | Returns a collection passages | 3.313658 | 3.008477 | 1.10144 |
if len(documents) <= 0:
raise ValueError("There has to be at least one document.")
c = BioCCollection()
for document in documents:
if document is None:
raise ValueError('Document is None')
c.add_document(document)
return c | def of(cls, *documents: BioCDocument) | Returns a collection documents | 3.487185 | 3.044393 | 1.145445 |
md5s = []
for filename in file_list:
if filename != '.DS_Store':
with open(filename, 'rb') as pe_file:
base_name = os.path.basename(filename)
md5 = workbench.store_sample(pe_file.read(), base_name, 'exe')
workbench.add_node(md5, md5[:6], l... | def add_it(workbench, file_list, labels) | Add the given file_list to workbench as samples, also add them as nodes.
Args:
workbench: Instance of Workbench Client.
file_list: list of files.
labels: labels for the nodes.
Returns:
A list of md5s. | 3.542987 | 3.182145 | 1.113396 |
sim_info_list = []
for feature_info in feature_list:
md5_source = feature_info['md5']
features_source = feature_info['features']
for feature_info in feature_list:
md5_target = feature_info['md5']
features_target = feature_info['features']
if md5_... | def jaccard_sims(feature_list) | Compute Jaccard similarities between all the observations in the feature list.
Args:
feature_list: a list of dictionaries, each having structure as
{ 'md5' : String, 'features': list of Strings }
Returns:
list of dictionaries with structure as
{'source': md5 Stri... | 2.101297 | 1.766491 | 1.189532 |
set1 = set(features1)
set2 = set(features2)
try:
return len(set1.intersection(set2))/float(max(len(set1), len(set2)))
except ZeroDivisionError:
return 0 | def jaccard_sim(features1, features2) | Compute similarity between two sets using Jaccard similarity.
Args:
features1: list of PE Symbols.
features2: list of PE Symbols.
Returns:
Returns an int. | 2.086039 | 2.317379 | 0.900172 |
def pad_char(text: str, width: int, char: str = '\n') -> str:
dis = width - len(text)
if dis < 0:
raise ValueError
if dis > 0:
text += char * dis
return text | Pads a text until length width. | null | null | null | |
def get_text(obj) -> Tuple[int, str]:
from bioc.bioc import BioCDocument, BioCPassage, BioCSentence
if isinstance(obj, BioCSentence):
return obj.offset, obj.text
if isinstance(obj, BioCPassage):
if obj.text:
return obj.offset, obj.text
text = ''
fo... | Return text with its offset in the document
Args:
obj: BioCDocument, BioCPassage, or BioCSentence
Returns:
offset, text | null | null | null | |
def pretty_print(source, dest):
parser = etree.XMLParser(remove_blank_text=True)
if not isinstance(source, str):
source = str(source)
tree = etree.parse(source, parser)
docinfo = tree.docinfo
with open(dest, 'wb') as fp:
fp.write(etree.tostring(tree, pretty_print=True,
... | Pretty print the XML file | null | null | null | |
def shorten_text(text: str):
if len(text) <= 40:
text = text
else:
text = text[:17] + ' ... ' + text[-17:]
return repr(text) | Return a short repr of text if it is longer than 40 | null | null | null | |
''' This worker computes meta data for any file type. '''
raw_bytes = input_data['sample']['raw_bytes']
self.meta['md5'] = hashlib.md5(raw_bytes).hexdigest()
self.meta['tags'] = input_data['tags']['tags']
self.meta['type_tag'] = input_data['sample']['type_tag']
with magic... | def execute(self, input_data) | This worker computes meta data for any file type. | 2.345635 | 2.075876 | 1.12995 |
''' Execute the Strings worker '''
raw_bytes = input_data['sample']['raw_bytes']
strings = self.find_strings.findall(raw_bytes)
return {'string_list': strings} | def execute(self, input_data) | Execute the Strings worker | 12.334381 | 8.63794 | 1.427931 |
''' Execute the PEIndicators worker '''
raw_bytes = input_data['sample']['raw_bytes']
# Analyze the output of pefile for any anomalous conditions.
# Have the PE File module process the file
try:
self.pefile_handle = pefile.PE(data=raw_bytes, fast_load=False)
... | def execute(self, input_data) | Execute the PEIndicators worker | 7.035119 | 6.380435 | 1.102608 |
''' Checking for a checksum that doesn't match the generated checksum '''
if self.pefile_handle.OPTIONAL_HEADER:
if self.pefile_handle.OPTIONAL_HEADER.CheckSum != self.pefile_handle.generate_checksum():
return {'description': 'Reported Checksum does not match actual checksum'... | def check_checksum_mismatch(self) | Checking for a checksum that doesn't match the generated checksum | 6.452864 | 5.246216 | 1.230003 |
''' Checking for an non-standard section name '''
std_sections = ['.text', '.bss', '.rdata', '.data', '.rsrc', '.edata', '.idata',
'.pdata', '.debug', '.reloc', '.stab', '.stabstr', '.tls',
'.crt', '.gnu_deb', '.eh_fram', '.exptbl', '.rodata']
for ... | def check_nonstandard_section_name(self) | Checking for an non-standard section name | 6.347769 | 5.988794 | 1.059941 |
''' Checking if the reported image size matches the actual image size '''
last_virtual_address = 0
last_virtual_size = 0
section_alignment = self.pefile_handle.OPTIONAL_HEADER.SectionAlignment
total_image_size = self.pefile_handle.OPTIONAL_HEADER.SizeOfImage
for section... | def check_image_size_incorrect(self) | Checking if the reported image size matches the actual image size | 3.409457 | 3.183621 | 1.070937 |
''' Checking if any of the sections are unaligned '''
file_alignment = self.pefile_handle.OPTIONAL_HEADER.FileAlignment
unaligned_sections = []
for section in self.pefile_handle.sections:
if section.PointerToRawData % file_alignment:
unaligned_sections.append(... | def check_section_unaligned(self) | Checking if any of the sections are unaligned | 5.026293 | 4.773078 | 1.053051 |
''' Checking if any of the sections go past the total size of the image '''
total_image_size = self.pefile_handle.OPTIONAL_HEADER.SizeOfImage
for section in self.pefile_handle.sections:
if section.PointerToRawData + section.SizeOfRawData > total_image_size:
return {'... | def check_section_oversized(self) | Checking if any of the sections go past the total size of the image | 7.132101 | 5.406407 | 1.319194 |
''' Just encapsulating a search that takes place fairly often '''
pattern = '|'.join(re.escape(match) for match in matches)
exp = re.compile(pattern)
if any(exp.search(warning) for warning in self.pefile_handle.get_warnings()):
return True
return False | def _search_within_pe_warnings(self, matches) | Just encapsulating a search that takes place fairly often | 7.800014 | 4.397124 | 1.77389 |
''' Just encapsulating a search that takes place fairly often '''
# Sanity check
if not hasattr(self.pefile_handle, 'DIRECTORY_ENTRY_IMPORT'):
return []
# Find symbols that match
pattern = '|'.join(re.escape(match) for match in matches)
exp = re.compile(patt... | def _search_for_import_symbols(self, matches) | Just encapsulating a search that takes place fairly often | 3.751387 | 2.895561 | 1.295565 |
''' Just encapsulating a search that takes place fairly often '''
pattern = '|'.join(re.escape(match) for match in matches)
exp = re.compile(pattern)
symbol_list = []
try:
for symbol in self.pefile_handle.DIRECTORY_ENTRY_EXPORT.symbols:
if symbol.name:... | def _search_for_export_symbols(self, matches) | Just encapsulating a search that takes place fairly often | 3.813921 | 2.73175 | 1.396146 |
def annotations(obj: BioCCollection or BioCDocument or BioCPassage or BioCSentence,
docid: str = None, level: int = PASSAGE) -> Generator[BioCAnnotation, None, None]:
if isinstance(obj, BioCCollection):
for document in filter(lambda d: docid is None or docid == d.id, obj.documents):... | Get all annotations in document id.
Args:
obj: BioCCollection, BioCDocument, BioCPassage, or BioCSentence
docid: document id. If None, all documents
level: one of DOCUMENT, PASSAGE, SENTENCE
Yields:
one annotation | null | null | null | |
def sentences(obj: BioCCollection or BioCDocument or BioCPassage) \
-> Generator[BioCSentence, None, None]:
if isinstance(obj, BioCCollection):
for document in obj.documents:
yield from sentences(document)
elif isinstance(obj, BioCDocument):
for passage in obj.pas... | Get all sentences in document id.
Args:
obj: BioCCollection, BioCDocument, or BioCPassage
Yields:
one sentence | null | null | null | |
''' This worker classifies PEFiles as Evil or AOK (TOY not a real classifier at this point)'''
# In general you'd do something different with these two outputs
# for this toy example will just smash them in a big string
pefile_output = input_data['pe_features']
indicators = inp... | def execute(self, input_data) | This worker classifies PEFiles as Evil or AOK (TOY not a real classifier at this point) | 20.116535 | 8.870117 | 2.2679 |
def dump(collection: BioCCollection, fp, pretty_print: bool = True):
fp.write(dumps(collection, pretty_print)) | Serialize ``collection`` as a BioC formatted stream to ``fp``.
Args:
collection: the BioC collection
fp: a ``.write()``-supporting file-like object
pretty_print: enables formatted XML | null | null | null | |
def dumps(collection: BioCCollection, pretty_print: bool = True) -> str:
doc = etree.ElementTree(BioCXMLEncoder().encode(collection))
s = etree.tostring(doc, pretty_print=pretty_print, encoding=collection.encoding,
standalone=collection.standalone)
return s.decode(collection... | Serialize ``collection`` to a BioC formatted ``str``.
Args:
collection: the BioC collection
pretty_print: enables formatted XML
Returns:
a BioC formatted ``str`` | null | null | null | |
def encode_location(location: BioCLocation):
return etree.Element('location',
{'offset': str(location.offset), 'length': str(location.length)}) | Encode a single location. | null | null | null | |
def encode_relation(relation: BioCRelation):
tree = etree.Element('relation', {'id': relation.id})
encode_infons(tree, relation.infons)
for node in relation.nodes:
tree.append(encode_node(node))
return tree | Encode a single relation. | null | null | null | |
def encode_annotation(annotation):
tree = etree.Element('annotation', {'id': annotation.id})
encode_infons(tree, annotation.infons)
for location in annotation.locations:
tree.append(encode_location(location))
etree.SubElement(tree, 'text').text = annotation.text
return tree | Encode a single annotation. | null | null | null | |
def encode_sentence(sentence):
tree = etree.Element('sentence')
encode_infons(tree, sentence.infons)
etree.SubElement(tree, 'offset').text = str(sentence.offset)
if sentence.text:
etree.SubElement(tree, 'text').text = sentence.text
for ann in sentence.annotations:
tree.a... | Encode a single sentence. | null | null | null | |
def encode_passage(passage):
tree = etree.Element('passage')
encode_infons(tree, passage.infons)
etree.SubElement(tree, 'offset').text = str(passage.offset)
if passage.text:
etree.SubElement(tree, 'text').text = passage.text
for sen in passage.sentences:
tree.append(enco... | Encode a single passage. | null | null | null | |
def encode_document(document):
tree = etree.Element('document')
etree.SubElement(tree, 'id').text = document.id
encode_infons(tree, document.infons)
for passage in document.passages:
tree.append(encode_passage(passage))
for ann in document.annotations:
tree.append(encode... | Encode a single document. | null | null | null | |
def encode_collection(collection):
tree = etree.Element('collection')
etree.SubElement(tree, 'source').text = collection.source
etree.SubElement(tree, 'date').text = collection.date
etree.SubElement(tree, 'key').text = collection.key
encode_infons(tree, collection.infons)
for doc in ... | Encode a single collection. | null | null | null | |
def default(self, obj):
if isinstance(obj, BioCDocument):
return encode_document(obj)
if isinstance(obj, BioCCollection):
return encode_collection(obj)
raise TypeError(f'Object of type {obj.__class__.__name__} is not BioC XML serializable') | Implement this method in a subclass such that it returns a tree for ``o``. | null | null | null | |
def write_collection_info(self, collection: BioCCollection):
elem = etree.Element('source')
elem.text = collection.source
self.__writer.send(elem)
elem = etree.Element('date')
elem.text = collection.date
self.__writer.send(elem)
elem = etree.E... | Writes the collection information: encoding, version, DTD, source, date, key, infons, etc. | null | null | null | |
def write_document(self, document: BioCDocument):
tree = self.encoder.encode(document)
self.__writer.send(tree) | Encode and write a single document. | null | null | null | |
# Grab server args
args = client_helper.grab_server_args()
# Start up workbench connection
workbench = zerorpc.Client(timeout=300, heartbeat=60)
workbench.connect('tcp://'+args['server']+':'+args['port'])
all_set = workbench.generate_sample_set()
results = workbench.set_work_requ... | def run() | This client generates customer reports on all the samples in workbench. | 6.732356 | 5.481183 | 1.228267 |
''' check if a file/folder exists and has a given IO access '''
if ((is_file and not os.path.isfile(ioobj)) or
(not is_file and not os.path.isdir(ioobj)) or
not os.access(ioobj, access)):
_objtype = "File" if is_file else "Directory"
raise IOError("Error accessing %s:... | def check_io_access(ioobj, access, is_file=False) | check if a file/folder exists and has a given IO access | 3.115382 | 2.764599 | 1.126884 |
BioCValidator(onerror).validate(collection) | def validate(collection, onerror: Callable[[str, List], None] = None) | Validate BioC data structure. | 92.208313 | 13.955548 | 6.607287 |
annotations = []
annotations.extend(document.annotations)
annotations.extend(document.relations)
for passage in document.passages:
annotations.extend(passage.annotations)
annotations.extend(passage.relations)
for sentence in passage.sentences:... | def validate_doc(self, document: BioCDocument) | Validate a single document. | 2.173445 | 2.119389 | 1.025505 |
for document in collection.documents:
self.validate_doc(document) | def validate(self, collection: BioCCollection) | Validate a single collection. | 7.644627 | 4.39913 | 1.737759 |
# Grab server args
args = client_helper.grab_server_args()
# Start up workbench connection
workbench = zerorpc.Client(timeout=300, heartbeat=60)
workbench.connect('tcp://'+args['server']+':'+args['port'])
# Test out PEFile -> strings -> indexer -> search
data_path = os.path.join(... | def run() | This client pushes PE Files -> ELS Indexer. | 4.258836 | 4.091041 | 1.041015 |
''' Execute method '''
# Spin up the rekall adapter
adapter = RekallAdapter()
adapter.set_plugin_name(self.plugin_name)
# Create a temporary directory and run this plugin from there
with self.goto_temp_directory():
# Run the procdump plugin
... | def execute(self, input_data) | Execute method | 5.559671 | 5.576521 | 0.996978 |
''' Convert string to UTF8 '''
if (isinstance(string, unicode)):
return string.encode('utf-8')
try:
u = unicode(string, 'utf-8')
except TypeError:
return str(string)
utf8 = u.encode('utf-8')
return utf8 | def convert_to_utf8(string) | Convert string to UTF8 | 2.920852 | 3.077534 | 0.949088 |
''' Process the input bytes with pefile '''
raw_bytes = input_data['sample']['raw_bytes']
# Have the PE File module process the file
pefile_handle, error_str = self.open_using_pefile('unknown', raw_bytes)
if not pefile_handle:
return {'error': error_str, 'dense_feat... | def execute(self, input_data) | Process the input bytes with pefile | 5.792684 | 4.906771 | 1.180549 |
''' Open the PE File using the Python pefile module. '''
try:
pef = pefile.PE(data=input_bytes, fast_load=False)
except (AttributeError, pefile.PEFormatError), error:
print 'warning: pe_fail (with exception from pefile module) on file: %s' % input_name
error_s... | def open_using_pefile(input_name, input_bytes) | Open the PE File using the Python pefile module. | 4.247116 | 4.118293 | 1.031281 |
# Make sure we're at the beginning
logfile.seek(0)
# First parse the header of the bro log
field_names, _ = self._parse_bro_header(logfile)
# Note: SO stupid to write a csv reader, but csv.DictReader on Bro
# files was doing something weird with generato... | def read_log(self, logfile) | The read_log method returns a memory efficient generator for rows in a Bro log.
Usage:
rows = my_bro_reader.read_log(logfile)
for row in rows:
do something with row
Args:
logfile: The Bro Log file. | 13.326758 | 12.018035 | 1.108897 |
# Skip until you find the #fields line
_line = next(logfile)
while (not _line.startswith('#fields')):
_line = next(logfile)
# Read in the field names
_field_names = _line.strip().split(self.delimiter)[1:]
# Read in the types
_line = next(lo... | def _parse_bro_header(self, logfile) | This method tries to parse the Bro log header section.
Note: My googling is failing me on the documentation on the format,
so just making a lot of assumptions and skipping some shit.
Assumption 1: The delimeter is a tab.
Assumption 2: Types are either time, string, int or float
... | 2.861574 | 2.570794 | 1.113109 |
for key, value in data_dict.iteritems():
data_dict[key] = self._cast_value(value)
# Fixme: resp_body_data can be very large so removing it for now
if 'resp_body_data' in data_dict:
del data_dict['resp_body_data']
return data_dict | def _cast_dict(self, data_dict) | Internal method that makes sure any dictionary elements
are properly cast into the correct types, instead of
just treating everything like a string from the csv file.
Args:
data_dict: dictionary containing bro log data.
Returns:
Cleaned Data dict. | 3.698893 | 4.09048 | 0.904269 |
# Try to convert to a datetime (if requested)
if (self.convert_datetimes):
try:
date_time = datetime.datetime.fromtimestamp(float(value))
if datetime.datetime(1970, 1, 1) > date_time:
raise ValueError
else:
... | def _cast_value(self, value) | Internal method that makes sure every value in dictionary
is properly cast into the correct types, instead of
just treating everything like a string from the csv file.
Args:
value : The value to be casted
Returns:
A casted Value. | 4.094697 | 4.419474 | 0.926512 |
# Grab server args
args = client_helper.grab_server_args()
# Start up workbench connection
workbench = zerorpc.Client(timeout=300, heartbeat=60)
workbench.connect('tcp://'+args['server']+':'+args['port'])
# Test out zip data
data_path = os.path.join(os.path.dirname(os.path.realpa... | def run() | This client shows workbench extacting files from a zip file. | 3.910974 | 3.660925 | 1.068302 |
''' Execute the VTQuery worker '''
md5 = input_data['meta']['md5']
response = requests.get('http://www.virustotal.com/vtapi/v2/file/report',
params={'apikey':self.apikey,'resource':md5, 'allinfo':1})
# Make sure we got a json blob back
try:
... | def execute(self, input_data) | Execute the VTQuery worker | 4.851505 | 4.523365 | 1.072543 |
''' Grab the peid_userdb.txt file from local disk '''
# Try to find the yara rules directory relative to the worker
my_dir = os.path.dirname(os.path.realpath(__file__))
db_path = os.path.join(my_dir, 'peid_userdb.txt')
if not os.path.exists(db_path):
raise RuntimeError('peid could not find ... | def get_peid_db() | Grab the peid_userdb.txt file from local disk | 4.986478 | 4.33621 | 1.149962 |
''' Execute the PEIDWorker '''
raw_bytes = input_data['sample']['raw_bytes']
# Have the PE File module process the file
try:
pefile_handle = pefile.PE(data=raw_bytes, fast_load=False)
except (AttributeError, pefile.PEFormatError), error:
return {'error': ... | def execute(self, input_data) | Execute the PEIDWorker | 6.238546 | 5.579967 | 1.118026 |
''' Get features from PEid signature database'''
peid_match = self.peid_sigs.match(pefile_handle)
return peid_match if peid_match else [] | def peid_features(self, pefile_handle) | Get features from PEid signature database | 6.980908 | 5.143736 | 1.357167 |
global WORKBENCH
# Grab grab_server_argsrver args
args = client_helper.grab_server_args()
# Start up workbench connection
WORKBENCH = zerorpc.Client(timeout=300, heartbeat=60)
WORKBENCH.connect('tcp://'+args['server']+':'+args['port'])
data_path = os.path.join(
os.path.d... | def run() | This client pulls PCAP files for building report.
Returns:
A list with `view_pcap` , `meta` and `filename` objects. | 4.681935 | 4.258584 | 1.099411 |
'''Renders template with `view` of the md5.'''
if not WORKBENCH:
return flask.redirect('/')
md5_view = WORKBENCH.work_request('view', md5)
return flask.render_template('templates/md5_view.html', md5_view=md5_view['view'], md5=md5) | def show_files(md5) | Renders template with `view` of the md5. | 6.92104 | 4.692396 | 1.474948 |
'''Renders template with `stream_sample` of the md5.'''
if not WORKBENCH:
return flask.redirect('/')
md5_view = WORKBENCH.stream_sample(md5)
return flask.render_template('templates/md5_view.html', md5_view=list(md5_view), md5=md5) | def show_md5_view(md5) | Renders template with `stream_sample` of the md5. | 6.875285 | 4.142755 | 1.659593 |
if 'sample' in input_data:
print 'Warning: PEFeaturesDF is supposed to be called on a sample_set'
self.samples.append(input_data['sample']['md5'])
else:
self.samples = input_data['sample_set']['md5_list']
# Make a sample set
sample_set = self... | def execute(self, input_data) | This worker puts the output of pe_features into a dictionary of dataframes | 2.709609 | 2.537891 | 1.067662 |
node = self.graph_db.get_or_create_indexed_node('Node', 'node_id', node_id, {'node_id': node_id, 'name': name})
try:
node.add_labels(*labels)
except NotImplementedError:
pass | def add_node(self, node_id, name, labels) | Add the node with name and labels.
Args:
node_id: Id for the node.
name: Name for the node.
labels: Label for the node.
Raises:
NotImplementedError: When adding labels is not supported. | 3.545702 | 4.201579 | 0.843898 |
# Add the relationship
n1_ref = self.graph_db.get_indexed_node('Node', 'node_id', source_node_id)
n2_ref = self.graph_db.get_indexed_node('Node', 'node_id', target_node_id)
# Sanity check
if not n1_ref or not n2_ref:
print 'Cannot add relationship between u... | def add_rel(self, source_node_id, target_node_id, rel) | Add a relationship between nodes.
Args:
source_node_id: Node Id for the source node.
target_node_id: Node Id for the target node.
rel: Name of the relationship 'contains' | 2.833453 | 2.89261 | 0.979549 |
print 'NeoDB Stub getting called...'
print '%s %s %s %s' % (self, node_id, name, labels) | def add_node(self, node_id, name, labels) | NeoDB Stub. | 14.153864 | 6.903438 | 2.050263 |
print 'NeoDB Stub getting called...'
print '%s %s %s %s' % (self, source_node_id, target_node_id, rel) | def add_rel(self, source_node_id, target_node_id, rel) | NeoDB Stub. | 9.089197 | 5.057509 | 1.797169 |
''' Tail a file using pygtail. Note: this could probably be improved '''
with make_temp_file() as offset_file:
while True:
for line in pygtail.Pygtail(filename, offset_file=offset_file):
yield line
time.sleep(1.0) | def tail_file(filename) | Tail a file using pygtail. Note: this could probably be improved | 5.969886 | 4.174589 | 1.430054 |
''' Execute the ViewPE worker '''
# Just a small check to make sure we haven't been called on the wrong file type
if (input_data['meta']['type_tag'] != 'exe'):
return {'error': self.__class__.__name__+': called on '+input_data['meta']['type_tag']}
view = {}
view['in... | def execute(self, input_data) | Execute the ViewPE worker | 6.564625 | 5.9455 | 1.104133 |
''' Safely access dictionary keys when plugin may have failed '''
for key in key_list:
data = data.get(key, {})
return data if data else 'plugin_failed' | def safe_get(data, key_list) | Safely access dictionary keys when plugin may have failed | 11.910406 | 4.390768 | 2.712602 |
''' Begin capturing PCAPs and sending them to workbench '''
# Create a temporary directory
self.temp_dir = tempfile.mkdtemp()
os.chdir(self.temp_dir)
# Spin up the directory watcher
DirWatcher(self.temp_dir, self.file_created)
# Spin up tcpdump
self.sub... | def execute(self) | Begin capturing PCAPs and sending them to workbench | 7.356771 | 4.881326 | 1.507125 |
''' File created callback '''
# Send the on-deck pcap to workbench
if self.on_deck:
self.store_file(self.on_deck)
os.remove(self.on_deck)
# Now put the newly created file on-deck
self.on_deck = filepath | def file_created(self, filepath) | File created callback | 8.130074 | 8.71708 | 0.93266 |
''' Store a file into workbench '''
# Spin up workbench
self.workbench = zerorpc.Client(timeout=300, heartbeat=60)
self.workbench.connect("tcp://127.0.0.1:4242")
# Open the file and send it to workbench
storage_name = "streaming_pcap" + str(self.pcap_index)
... | def store_file(self, filename) | Store a file into workbench | 3.930629 | 3.846796 | 1.021793 |
def encode_document(obj):
warnings.warn("deprecated. Please use bioc.biocxml.encoder.encode_document", DeprecationWarning)
return bioc.biocxml.encoder.encode_document(obj) | Encode a single document. | null | null | null | |
def encode_passage(obj):
warnings.warn("deprecated. Please use bioc.biocxml.encoder.encode_passage", DeprecationWarning)
return bioc.biocxml.encoder.encode_passage(obj) | Encode a single passage. | null | null | null | |
def encode_sentence(obj):
warnings.warn("deprecated. Please use bioc.biocxml.encoder.encode_sentence", DeprecationWarning)
return bioc.biocxml.encoder.encode_sentence(obj) | Encode a single sentence. | null | null | null | |
def encode_annotation(obj):
warnings.warn("deprecated. Please use bioc.biocxml.encoder.encode_annotation",
DeprecationWarning)
return bioc.biocxml.encoder.encode_annotation(obj) | Encode a single annotation. | null | null | null | |
def encode_relation(obj):
warnings.warn("deprecated. Please use bioc.biocxml.encoder.encode_relation", DeprecationWarning)
return bioc.biocxml.encoder.encode_relation(obj) | Encode a single relation. | null | null | null | |
Name = eprocess_data['_EPROCESS']['Cybox']['Name']
PID = eprocess_data['_EPROCESS']['Cybox']['PID']
PPID = eprocess_data['_EPROCESS']['Cybox']['Parent_PID']
return {'Name': Name, 'PID': PID, 'PPID': PPID} | def parse_eprocess(self, eprocess_data) | Parse the EProcess object we get from some rekall output | 3.625929 | 3.248096 | 1.116324 |
''' Execute the Unzip worker '''
raw_bytes = input_data['sample']['raw_bytes']
zipfile_output = zipfile.ZipFile(StringIO(raw_bytes))
payload_md5s = []
for name in zipfile_output.namelist():
filename = os.path.basename(name)
payload_md5s.append(self.workben... | def execute(self, input_data) | Execute the Unzip worker | 4.700469 | 4.233109 | 1.110406 |
''' Execute method '''
# Spin up the rekall adapter
adapter = RekallAdapter()
adapter.set_plugin_name(self.plugin_name)
rekall_output = adapter.execute(input_data)
# Process the output data
for line in rekall_output:
if line['type'] == 'm': # Meta
... | def execute(self, input_data) | Execute method | 4.183362 | 4.22069 | 0.991156 |
help = '%sWelcome to Workbench CLI Help:%s' % (color.Yellow, color.Normal)
help += '\n\t%s> help cli_basic %s for getting started help' % (color.Green, color.LightBlue)
help += '\n\t%s> help workers %s for help on available workers' % (color.Green, color.LightBlue)
help += '\n\t... | def help_cli(self) | Help on Workbench CLI | 3.306791 | 3.140097 | 1.053086 |
help = '%sWorkbench: Getting started...' % (color.Yellow)
help += '\n%sLoad in a sample:' % (color.Green)
help += '\n\t%s> load_sample /path/to/file' % (color.LightBlue)
help += '\n\n%sNotice the prompt now shows the md5 of the sample...'% (color.Yellow)
help += '\n%sR... | def help_cli_basic(self) | Help for Workbench CLI Basics | 7.369701 | 7.154132 | 1.030132 |
help = '%sSearch: %s returns sample_sets, a sample_set is a set/list of md5s.' % (color.Yellow, color.Green)
help += '\n\n\t%sSearch for all samples in the database that are known bad pe files,' % (color.Green)
help += '\n\t%sthis command returns the sample_set containing the matching... | def help_cli_search(self) | Help for Workbench CLI Search | 5.850215 | 5.817164 | 1.005682 |
help = '%sMaking a DataFrame: %s how to make a dataframe from raw data (pcap, memory, pe files)' % (color.Yellow, color.Green)
help += '\n\t%sNote: for memory_image and pe_files see > help dataframe_memory or dataframe_pe' % (color.Green)
help += '\n\n%sPCAP Example:' % (color.Green)... | def help_dataframe(self) | Help for making a DataFrame with Workbench CLI | 4.761573 | 4.763445 | 0.999607 |
help = '%sMaking a DataFrame: %s how to make a dataframe from memory_forensics sample' % (color.Yellow, color.Green)
help += '\n\n%sMemory Images Example:' % (color.Green)
help += '\n\t%s> load_sample /path/to/pcap/exemplar4.vmem [\'bad\', \'aptz13\']' % (color.LightBlue)
help... | def help_dataframe_memory(self) | Help for making a DataFrame with Workbench CLI | 13.487879 | 12.888236 | 1.046526 |
help = '%sMaking a DataFrame: %s how to make a dataframe from pe files' % (color.Yellow, color.Green)
help += '\n\n%sPE Files Example (loading a directory):' % (color.Green)
help += '\n\t%s> load_sample /path/to/pe/bad [\'bad\', \'case_69\']' % (color.LightBlue)
help += '\n\n\... | def help_dataframe_pe(self) | Help for making a DataFrame with Workbench CLI | 4.198414 | 4.162264 | 1.008685 |
methods = {name:method for name, method in inspect.getmembers(self, predicate=inspect.isroutine) if not name.startswith('_')}
return methods | def _all_help_methods(self) | Returns a list of all the Workbench commands | 3.308856 | 3.391117 | 0.975742 |
''' ViewPcapDeep execute method '''
# Copy info from input
view = input_data['view_pcap']
# Grab a couple of handles
extracted_files = input_data['view_pcap']['extracted_files']
# Dump a couple of fields
del view['extracted_files']
# Grab addit... | def execute(self, input_data) | ViewPcapDeep execute method | 12.427628 | 9.053444 | 1.372696 |
''' Execute Method '''
# View on all the meta data files in the sample
fields = ['filename', 'md5', 'length', 'customer', 'import_time', 'type_tag']
view = {key:input_data['meta'][key] for key in fields}
return view | def execute(self, input_data) | Execute Method | 15.901524 | 15.618416 | 1.018127 |
input_data = input_data['info']
type_tag = input_data['type_tag']
if type_tag == 'help':
return {'help': input_data['help'], 'type_tag': input_data['type_tag']}
elif type_tag == 'worker':
out_keys = ['name', 'dependencies', 'docstring', 'type_tag']
... | def execute(self, input_data) | Info objects all have a type_tag of ('help','worker','command', or 'other') | 2.865093 | 2.152193 | 1.331243 |
def parse_collection(obj: dict) -> BioCCollection:
collection = BioCCollection()
collection.source = obj['source']
collection.date = obj['date']
collection.key = obj['key']
collection.infons = obj['infons']
for doc in obj['documents']:
collection.add_document(parse_doc(doc))... | Deserialize a dict obj to a BioCCollection object | null | null | null | |
def parse_annotation(obj: dict) -> BioCAnnotation:
ann = BioCAnnotation()
ann.id = obj['id']
ann.infons = obj['infons']
ann.text = obj['text']
for loc in obj['locations']:
ann.add_location(BioCLocation(loc['offset'], loc['length']))
return ann | Deserialize a dict obj to a BioCAnnotation object | null | null | null | |
def parse_relation(obj: dict) -> BioCRelation:
rel = BioCRelation()
rel.id = obj['id']
rel.infons = obj['infons']
for node in obj['nodes']:
rel.add_node(BioCNode(node['refid'], node['role']))
return rel | Deserialize a dict obj to a BioCRelation object | null | null | null | |
def parse_sentence(obj: dict) -> BioCSentence:
sentence = BioCSentence()
sentence.offset = obj['offset']
sentence.infons = obj['infons']
sentence.text = obj['text']
for annotation in obj['annotations']:
sentence.add_annotation(parse_annotation(annotation))
for relation in ob... | Deserialize a dict obj to a BioCSentence object | null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.