text stringlengths 81 112k |
|---|
delt(host|net, gw|dev)
def delt(self, *args, **kargs):
"""delt(host|net, gw|dev)"""
self.invalidate_cache()
route = self.make_route(*args, **kargs)
try:
i = self.routes.index(route)
del(self.routes[i])
except ValueError:
warning("no matching r... |
Returns the IPv4 routes to a host.
parameters:
- dst: the IPv4 of the destination host
returns: (iface, output_ip, gateway_ip)
- iface: the interface used to connect to the host
- output_ip: the outgoing IP that will be used
- gateway_ip: the gateway IP that will be ... |
Temporarily open the ICMP firewall. Tricks Windows into allowing
ICMP packets for a short period of time (~ 1 minute)
def open_icmp_firewall(host):
"""Temporarily open the ICMP firewall. Tricks Windows into allowing
ICMP packets for a short period of time (~ 1 minute)"""
# We call ping with a timeout o... |
Either for parsing or building, we store the client_random
along with the raw string representing this handshake message.
def tls_session_update(self, msg_str):
"""
Either for parsing or building, we store the client_random
along with the raw string representing this handshake message.
... |
Either for parsing or building, we store the server_random
along with the raw string representing this handshake message.
We also store the session_id, the cipher suite (if recognized),
the compression method, and finally we instantiate the pending write
and read connection states. Usual... |
Either for parsing or building, we store the server_random along with
the raw string representing this handshake message. We also store the
cipher suite (if recognized), and finally we instantiate the write and
read connection states.
def tls_session_update(self, msg_str):
"""
E... |
We overload build() method in order to provide a valid default value
for params based on TLS session if not provided. This cannot be done by
overriding i2m() because the method is called on a copy of the packet.
The 'params' field is built according to key_exchange.server_kx_msg_cls
whi... |
While previously dissecting Server*DHParams, the session
server_kx_pubkey should have been updated.
XXX Add a 'fixed_dh' OR condition to the 'anonymous' test.
def post_dissection(self, pkt):
"""
While previously dissecting Server*DHParams, the session
server_kx_pubkey should ha... |
The client_kx_msg may be either None, EncryptedPreMasterSecret
(for RSA encryption key exchange), ClientDiffieHellmanPublic,
or ClientECDiffieHellmanPublic. When either one of them gets
dissected, the session context is updated accordingly.
def m2i(self, pkt, m):
"""
The client_... |
nmap fingerprinting
nmap_fp(target, [oport=80,] [cport=81,]) -> list of best guesses with accuracy
def nmap_fp(target, oport=80, cport=81):
"""nmap fingerprinting
nmap_fp(target, [oport=80,] [cport=81,]) -> list of best guesses with accuracy
"""
sigs = nmap_sig(target, oport, cport)
return nmap_search(sigs... |
Convenience wrapper around binwalk.core.module.Modules.kwargs.
@obj - The class object (an instance of a sub-class of binwalk.core.module.Module).
@kwargs - The kwargs provided to the object's __init__ method.
Returns None.
def process_kwargs(obj, kwargs):
'''
Convenience wrapper around binwal... |
Convenience wrapper around binwalk.core.module.Modules.help.
@fd - An object with a write method (e.g., sys.stdout, sys.stderr, etc).
Returns None.
def show_help(fd=sys.stdout):
'''
Convenience wrapper around binwalk.core.module.Modules.help.
@fd - An object with a write method (e.g., sys.stdout... |
Gets the next file to be scanned (including pending extracted files, if applicable).
Also re/initializes self.status.
All modules should access the target file list through this method.
def next_file(self, close_previous=True):
'''
Gets the next file to be scanned (including pending ext... |
Clears results and errors lists.
def clear(self, results=True, errors=True):
'''
Clears results and errors lists.
'''
if results:
self.results = []
if errors:
self.errors = [] |
Validates a result, stores it in self.results and prints it.
Accepts the same kwargs as the binwalk.core.module.Result class.
@r - An existing instance of binwalk.core.module.Result.
Returns an instance of binwalk.core.module.Result.
def result(self, r=None, **kwargs):
'''
Val... |
Stores the specified error in self.errors.
Accepts the same kwargs as the binwalk.core.module.Error class.
Returns None.
def error(self, **kwargs):
'''
Stores the specified error in self.errors.
Accepts the same kwargs as the binwalk.core.module.Error class.
Returns ... |
Displays the scan header, as defined by self.HEADER and self.HEADER_FORMAT.
Returns None.
def header(self):
'''
Displays the scan header, as defined by self.HEADER and self.HEADER_FORMAT.
Returns None.
'''
self.config.display.format_strings(self.HEADER_FORMAT, self.RES... |
Responsible for calling self.init, initializing self.config.display, and calling self.run.
Returns the value returned from self.run.
def main(self):
'''
Responsible for calling self.init, initializing self.config.display, and calling self.run.
Returns the value returned from self.run.... |
Finds all modules with the specified attribute.
@attribute - The desired module attribute.
Returns a list of modules that contain the specified attribute, in the order they should be executed.
def list(self, attribute="run"):
'''
Finds all modules with the specified attribute.
... |
Generates formatted help output.
Returns the help string.
def help(self):
'''
Generates formatted help output.
Returns the help string.
'''
modules = {}
help_string = "\n"
help_string += "Binwalk v%s\n" % binwalk.__version__
help_string += "Crai... |
Executes all appropriate modules according to the options specified in args/kwargs.
Returns a list of executed module objects.
def execute(self, *args, **kwargs):
'''
Executes all appropriate modules according to the options specified in args/kwargs.
Returns a list of executed module ... |
Runs a specific module.
def run(self, module, dependency=False, kwargs={}):
'''
Runs a specific module.
'''
try:
obj = self.load(module, kwargs)
if isinstance(obj, binwalk.core.module.Module) and obj.enabled:
obj.main()
self.statu... |
Processes argv for any options specific to the specified module.
@module - The module to process argv for.
@argv - A list of command line arguments (excluding argv[0]).
Returns a dictionary of kwargs for the specified module.
def argv(self, module, argv=sys.argv[1:]):
'''
Pr... |
Processes a module's kwargs. All modules should use this for kwarg processing.
@obj - An instance of the module (e.g., self)
@kwargs - The kwargs passed to the module
Returns None.
def kwargs(self, obj, kwargs):
'''
Processes a module's kwargs. All modules should use this f... |
Starts the progress bar TCP service on the specified port.
This service will only be started once per instance, regardless of the
number of times this method is invoked.
Failure to start the status service is considered non-critical; that is,
a warning will be displayed to the user, but... |
Returns a 2 byte integer.
def _make_short(self, data, endianness):
"""Returns a 2 byte integer."""
data = binwalk.core.compat.str2bytes(data)
return struct.unpack('%sH' % endianness, data)[0] |
Returns the number of bytes designated for the filename.
def _get_fname_len(self, bufflen=128):
"""Returns the number of bytes designated for the filename."""
buff = self.meta.peek(bufflen)
strlen = buff.find('\0')
for i, b in enumerate(buff[strlen:]):
if b != '\0':
... |
Reads a chunk of meta data from file and returns a PFSNode.
def _get_node(self):
"""Reads a chunk of meta data from file and returns a PFSNode."""
data = self.meta.read(self.node_size)
return PFSNode(data, self.endianness) |
Returns file meta-data entries one by one.
def entries(self):
"""Returns file meta-data entries one by one."""
self.meta.seek(self.file_list_start)
for i in range(0, self.num_files):
yield self._get_node() |
Extracts the actual string from the available bytes.
def _decode_fname(self):
"""Extracts the actual string from the available bytes."""
self.fname = self.fname[:self.fname.find('\0')]
self.fname = self.fname.replace('\\', '/') |
Generates a regular expression from the magic bytes of a signature.
The regex is used by Magic._analyze.
@line - The first SignatureLine object of the signature.
Returns a compile regular expression.
def _generate_regex(self, line):
'''
Generates a regular expression from the ... |
Tests if a string should be filtered out or not.
@text - The string to check against filter rules.
Returns True if the string should be filtered out, i.e., not displayed.
Returns False if the string should be displayed.
def _filtered(self, text):
'''
Tests if a string should b... |
Parses and evaluates complex expressions, e.g., "(4.l+12)", "(6*32)", etc.
@offset - The offset inside self.data that the current signature starts at.
@expressions - The expression to evaluate.
Returns an integer value that is the result of the evaluated expression.
def _do_math(self, of... |
Analyzes self.data for the specified signature data at the specified offset .
@signature - The signature to apply to the data.
@offset - The offset in self.data to apply the signature to.
Returns a dictionary of tags parsed from the data.
def _analyze(self, signature, offset):
'''
... |
Scan a data block for matching signatures.
@data - A string of data to scan.
@dlen - If specified, signatures at offsets larger than dlen will be ignored.
Returns a list of SignatureResult objects.
def scan(self, data, dlen=None):
'''
Scan a data block for matching signatures.... |
Load signatures from a file.
@fname - Path to signature file.
Returns None.
def load(self, fname):
'''
Load signatures from a file.
@fname - Path to signature file.
Returns None.
'''
# Magic files must be ASCII, else encoding issues can arise.
... |
Parse signature file lines.
@lines - A list of lines from a signature file.
Returns None.
def parse(self, lines):
'''
Parse signature file lines.
@lines - A list of lines from a signature file.
Returns None.
'''
signature = None
for line in l... |
Sets the appropriate verbosity.
Must be called after self._test_target_files so that self.target_files is properly set.
def _set_verbosity(self):
'''
Sets the appropriate verbosity.
Must be called after self._test_target_files so that self.target_files is properly set.
'''
... |
Checks to see if a file should be scanned based on file name include/exclude filters.
Most useful for matryoshka scans where only certian files are desired.
@fp - An instances of binwalk.common.BlockFile
Returns True if the file should be scanned, False if not.
def file_name_filter(self, fp):... |
Opens the specified file with all pertinent configuration settings.
def open_file(self, fname, length=None, offset=None, swap=None, block=None, peek=None):
'''
Opens the specified file with all pertinent configuration settings.
'''
if length is None:
length = self.length
... |
Checks if the target files can be opened.
Any files that cannot be opened are removed from the self.target_files list.
def _open_target_files(self):
'''
Checks if the target files can be opened.
Any files that cannot be opened are removed from the self.target_files list.
'''
... |
Called automatically by self.result.
def validate(self, r):
'''
Called automatically by self.result.
'''
if self.show_invalid:
r.valid = True
elif r.valid:
if not r.description:
r.valid = False
if r.size and (r.size + r.offset... |
Obtain a list of all user and system plugin modules.
Returns a dictionary of:
{
'user' : {
'modules' : [list, of, module, names],
'descriptions' : {'module_name' : 'module pydoc string'},
... |
Performs a Shannon entropy analysis on a given block of data.
def shannon(self, data):
'''
Performs a Shannon entropy analysis on a given block of data.
'''
entropy = 0
if data:
length = len(data)
seen = dict(((chr(x), 0) for x in range(0, 256)))
... |
Performs an entropy analysis based on zlib compression ratio.
This is faster than the shannon entropy analysis, but not as accurate.
def gzip(self, data, truncate=True):
'''
Performs an entropy analysis based on zlib compression ratio.
This is faster than the shannon entropy analysis, b... |
Convert a null-terminated string field to a python string.
def nts(self, s):
"""
Convert a null-terminated string field to a python string.
"""
# Use the string up to the first null char.
p = s.find("\0")
if p == -1:
return s
return s[:p] |
Convert a number field to a python number.
def nti(self, s):
"""
Convert a number field to a python number.
"""
# There are two possible encodings for a number field, see
# itn() below.
if s[0] != chr(0x80):
try:
n = int(self.nts(s) or "0", 8)... |
Displays debug messages to stderr only if the Python interpreter was invoked with the -O flag.
def debug(msg):
'''
Displays debug messages to stderr only if the Python interpreter was invoked with the -O flag.
'''
if DEBUG:
sys.stderr.write("DEBUG: " + msg + "\n")
sys.stderr.flush() |
Generate an MD5 hash of the specified file.
@file_name - The file to hash.
Returns an MD5 hex digest string.
def file_md5(file_name):
'''
Generate an MD5 hash of the specified file.
@file_name - The file to hash.
Returns an MD5 hex digest string.
'''
md5 = hashlib.md5()
with op... |
Obtains the size of a given file.
@filename - Path to the file.
Returns the size of the file.
def file_size(filename):
'''
Obtains the size of a given file.
@filename - Path to the file.
Returns the size of the file.
'''
# Using open/lseek works on both regular files and block devic... |
Returns a string comprised of all data in between double quotes.
@quoted_string - String to get quoted data from.
Returns a string of quoted data on success.
Returns a blank string if no quoted data is present.
def get_quoted_strings(quoted_string):
'''
Returns a string comprised of all data in b... |
Creates a unique file name based on the specified base name.
@base_name - The base name to use for the unique file name.
@extension - The file extension to use for the unique file name.
Returns a unique file string.
def unique_file_name(base_name, extension=''):
'''
Creates a unique file name bas... |
A strings generator, similar to the Unix strings utility.
@filename - The file to search for strings in.
@minimum - The minimum string length to search for.
Yeilds printable ASCII strings from filename.
def strings(filename, minimum=4):
'''
A strings generator, similar to the Unix strings utilit... |
For cross compatibility between Python 2 and Python 3 strings.
def bytes2str(bs):
'''
For cross compatibility between Python 2 and Python 3 strings.
'''
if isinstance(bs, type(b'')) and PY_MAJOR_VERSION > 2:
return bs.decode('latin1')
else:
return bs |
Adds a set of rules to the extraction rule list.
@txtrule - Rule string, or list of rule strings, in the format <regular expression>:<file extension>[:<command to run>]
@regex - If rule string is not specified, this is the regular expression string to use.
@extension - If rule string is n... |
Remove all rules that match a specified description.
@description - The description to match against.
Returns the number of rules removed.
def remove_rules(self, description):
'''
Remove all rules that match a specified description.
@description - The description to match aga... |
Edit all rules that match a specified description.
@description - The description to match against.
@key - The key to change for each matching rule.
@value - The new key value for each matching rule.
Returns the number of rules modified.
def edit_rules(self, description,... |
Returns a list of extraction rules that match a given description.
@description - The description to match against.
Returns a list of extraction rules that match the given description.
If no description is provided, a list of all rules are returned.
def get_rules(self, description=None):
... |
Loads extraction rules from the specified file.
@fname - Path to the extraction rule file.
Returns None.
def load_from_file(self, fname):
'''
Loads extraction rules from the specified file.
@fname - Path to the extraction rule file.
Returns None.
'''
... |
Loads default extraction rules from the user and system extract.conf files.
Returns None.
def load_defaults(self):
'''
Loads default extraction rules from the user and system extract.conf files.
Returns None.
'''
# Load the user extract file first to ensure its rules t... |
Set the output directory for extracted files.
@path - The path to the file that data will be extracted from.
Returns None.
def build_output_directory(self, path):
'''
Set the output directory for extracted files.
@path - The path to the file that data will be extracted from.
... |
Extract an embedded file from the target file, if it matches an extract rule.
Called automatically by Binwalk.scan().
@offset - Offset inside the target file to begin the extraction.
@description - Description of the embedded file to extract, as returned by libmagic.
@file_name -... |
Gets the offset of the first entry that matches the description.
@index - Index into the entries list to begin searching.
@entries - Dictionary of result entries.
@description - Case insensitive description.
Returns the offset, if a matching description is found.
Retu... |
Check to see if the provided description string matches an extract rule.
Called internally by self.extract().
@description - Description string to check.
Returns the associated rule dictionary if a match is found.
Returns None if no match is found.
def match(self, description):
... |
Parses an extraction rule.
@rule - Rule string.
Returns an array of ['<case insensitive matching string>', '<file extension>', '<command to run>', '<comma separated return codes>', <recurse into extracted directories: True|False>].
def _parse_rule(self, rule):
'''
Parses an extraction... |
Extracts a file embedded inside the target file.
@file_name - Path to the target file.
@offset - Offset inside the target file where the embedded file begins.
@size - Number of bytes to extract.
@extension - The file exension to assign to the extracte... |
Execute a command against the specified file.
@cmd - Command to execute.
@fname - File to run command against.
@codes - List of return codes indicating cmd success.
Returns True on success, False on failure, or None if the external extraction utility could not be found.
def execute(... |
Convenience wrapper for self.log which is passed a list of format arguments.
def _fix_unicode_list(self, columns):
'''
Convenience wrapper for self.log which is passed a list of format arguments.
'''
if type(columns) in [list, tuple]:
for i in range(0, len(columns)):
... |
Intelligently appends data to self.string_parts.
For use by self._format.
def _append_to_data_parts(self, data, start, end):
'''
Intelligently appends data to self.string_parts.
For use by self._format.
'''
try:
while data[start] == ' ':
start... |
Formats a line of text to fit in the terminal window.
For Tim.
def _format_line(self, line):
'''
Formats a line of text to fit in the terminal window.
For Tim.
'''
delim = '\n'
offset = 0
self.string_parts = []
# Split the line into an array of c... |
Configures output formatting, and fitting output to the current terminal width.
Returns None.
def _configure_formatting(self):
'''
Configures output formatting, and fitting output to the current terminal width.
Returns None.
'''
self.format_strings(self.DEFAULT_FORMAT,... |
Find all user/system magic signature files.
@system_only - If True, only the system magic file directory will be searched.
@user_only - If True, only the user magic file directory will be searched.
Returns a list of user/system magic signature files.
def _magic_signature_files(self, system_... |
Finds the specified magic file name in the system / user magic file directories.
@fname - The name of the magic file.
@system_only - If True, only the system magic file directory will be searched.
@user_only - If True, only the user magic file directory will be searched.
If sys... |
Get the user's home directory.
def _get_user_dir(self):
'''
Get the user's home directory.
'''
try:
# This should work in both Windows and Unix environments
for envname in ['USERPROFILE', 'HOME']:
user_dir = os.getenv(envname)
if u... |
Builds an absolute path and creates the directory and file if they don't already exist.
@dirname - Directory path.
@filename - File name.
Returns a full path of 'dirname/filename'.
def _file_path(self, dirname, filename):
'''
Builds an absolute path and creates the directory ... |
Gets the full path to the 'subdir/basename' file in the user binwalk directory.
@subdir - Subdirectory inside the user binwalk directory.
@basename - File name inside the subdirectory.
Returns the full path to the 'subdir/basename' file.
def _user_path(self, subdir, basename=''):
''... |
Gets the full path to the 'subdir/basename' file in the system binwalk directory.
@subdir - Subdirectory inside the system binwalk directory.
@basename - File name inside the subdirectory.
Returns the full path to the 'subdir/basename' file.
def _system_path(self, subdir, basename=''):
... |
This does the extraction (e.g., it decrypts the image and writes it to a new file on disk).
def _decrypt_and_extract(self, fname):
'''
This does the extraction (e.g., it decrypts the image and writes it to a new file on disk).
'''
with open(fname, "r") as fp_in:
encrypted_da... |
This does the actual decryption.
def _hilink_decrypt(self, encrypted_firmware):
'''
This does the actual decryption.
'''
cipher = DES.new(self.DES_KEY, DES.MODE_ECB)
p1 = encrypted_firmware[0:3]
p2 = encrypted_firmware[3:]
p2 += b"\x00" * (8 - (len(p2) % 8))
... |
Validate signature results.
def scan(self, result):
'''
Validate signature results.
'''
if self.enabled is True:
if result.valid is True:
if result.description.lower().startswith(self.SIGNATURE_DESCRIPTION) is True:
# Read in the first 64 ... |
Locks the main thread while the subscription in running
def run():
print("Environment", os.environ)
try:
os.environ["SELENIUM"]
except KeyError:
print("Please set the environment variable SELENIUM to Selenium URL")
sys.exit(1)
driver = WhatsAPIDriver(client='remote', command_ex... |
Function to save the firefox profile to the permanant one
def save_firefox_profile(self, remove_old=False):
"""Function to save the firefox profile to the permanant one"""
self.logger.info("Saving profile from %s to %s" % (self._profile.path, self._profile_path))
if remove_old:
if ... |
Waits for the QR to go away
def wait_for_login(self, timeout=90):
"""Waits for the QR to go away"""
WebDriverWait(self.driver, timeout).until(
EC.visibility_of_element_located((By.CSS_SELECTOR, self._SELECTORS['mainPage']))
) |
Get pairing QR code from client
def get_qr(self, filename=None):
"""Get pairing QR code from client"""
if "Click to reload QR code" in self.driver.page_source:
self.reload_qr()
qr = self.driver.find_element_by_css_selector(self._SELECTORS['qrCode'])
if filename is None:
... |
Fetches list of all contacts
This will return chats with people from the address book only
Use get_all_chats for all chats
:return: List of contacts
:rtype: list[Contact]
def get_contacts(self):
"""
Fetches list of all contacts
This will return chats with people... |
Fetches list of added contacts
:return: List of contacts
:rtype: list[Contact]
def get_my_contacts(self):
"""
Fetches list of added contacts
:return: List of contacts
:rtype: list[Contact]
"""
my_contacts = self.wapi_functions.getMyContacts()
re... |
Fetches all chats
:return: List of chats
:rtype: list[Chat]
def get_all_chats(self):
"""
Fetches all chats
:return: List of chats
:rtype: list[Chat]
"""
chats = self.wapi_functions.getAllChats()
if chats:
return [factory_chat(chat, s... |
Fetches unread messages
:param include_me: Include user's messages
:type include_me: bool or None
:param include_notifications: Include events happening on chat
:type include_notifications: bool or None
:param use_unread_count: If set uses chat's 'unreadCount' attribute to fetch ... |
I fetch unread messages from an asked chat.
:param id: chat id
:type id: str
:param include_me: if user's messages are to be included
:type include_me: bool
:param include_notifications: if events happening on chat are to be included
:type include_notifications: bool
... |
Fetches messages in chat
:param include_me: Include user's messages
:type include_me: bool or None
:param include_notifications: Include events happening on chat
:type include_notifications: bool or None
:return: List of messages in chat
:rtype: list[Message]
def get_al... |
Fetches message ids in chat
:param include_me: Include user's messages
:type include_me: bool or None
:param include_notifications: Include events happening on chat
:type include_notifications: bool or None
:return: List of message ids in chat
:rtype: list[str]
def get_... |
Fetch a message
:param message_id: Message ID
:type message_id: str
:return: Message or False
:rtype: Message
def get_message_by_id(self, message_id):
"""
Fetch a message
:param message_id: Message ID
:type message_id: str
:return: Message or Fa... |
Fetches a contact given its ID
:param contact_id: Contact ID
:type contact_id: str
:return: Contact or Error
:rtype: Contact
def get_contact_from_id(self, contact_id):
"""
Fetches a contact given its ID
:param contact_id: Contact ID
:type contact_id: st... |
Fetches a chat given its ID
:param chat_id: Chat ID
:type chat_id: str
:return: Chat or Error
:rtype: Chat
def get_chat_from_id(self, chat_id):
"""
Fetches a chat given its ID
:param chat_id: Chat ID
:type chat_id: str
:return: Chat or Error
... |
Gets chat by phone number
Number format should be as it appears in Whatsapp ID
For example, for the number:
+972-51-234-5678
This function would receive:
972512345678
:param number: Phone number
:return: Chat
:rtype: Chat
def get_chat_from_phone_number(s... |
Returns status of the driver
:return: Status
:rtype: WhatsAPIDriverStatus
def get_status(self):
"""
Returns status of the driver
:return: Status
:rtype: WhatsAPIDriverStatus
"""
if self.driver is None:
return WhatsAPIDriverStatus.NotConnecte... |
Returns groups common between a user and the contact with given id.
:return: Contact or Error
:rtype: Contact
def contact_get_common_groups(self, contact_id):
"""
Returns groups common between a user and the contact with given id.
:return: Contact or Error
:rtype: Cont... |
:param path: file path
:return: returns the converted string and formatted for the send media function send_media
def convert_to_base64(self, path):
"""
:param path: file path
:return: returns the converted string and formatted for the send media function send_media
"""
... |
converts the file to base64 and sends it using the sendImage function of wapi.js
:param path: file path
:param chatid: chatId to be sent
:param caption:
:return:
def send_media(self, path, chatid, caption):
"""
converts the file to base64 and sends it using the sendI... |
Get full profile pic from an id
The ID must be on your contact book to
successfully get their profile picture.
:param id: ID
:type id: str
def get_profile_pic_from_id(self, id):
"""
Get full profile pic from an id
The ID must be on your contact book to
s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.