INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
We expect this. If tls_version is not set, this means we did not process
any complete ClientHello, so we're most probably reading/building a
signature_algorithms extension, hence we cannot be in phantom_mode.
However, if the tls_version has been set, we test for TLS 1.2. | def phantom_mode(pkt):
"""
We expect this. If tls_version is not set, this means we did not process
any complete ClientHello, so we're most probably reading/building a
signature_algorithms extension, hence we cannot be in phantom_mode.
However, if the tls_version has been set, we test for TLS 1.2.
... |
Decorator for version-dependent fields.
If get_or_add is True (means get), we return s, self.phantom_value.
If it is False (means add), we return s. | def phantom_decorate(f, get_or_add):
"""
Decorator for version-dependent fields.
If get_or_add is True (means get), we return s, self.phantom_value.
If it is False (means add), we return s.
"""
def wrapper(*args):
self, pkt, s = args[:3]
if phantom_mode(pkt):
if get_o... |
With SSLv2 you will never be able to add a sig_len. | def addfield(self, pkt, s, val):
"""With SSLv2 you will never be able to add a sig_len."""
v = pkt.tls_session.tls_version
if v and v < 0x0300:
return s
return super(SigLenField, self).addfield(pkt, s, val) |
Sign 'm' with the PrivKey 'key' and update our own 'sig_val'.
Note that, even when 'sig_alg' is not None, we use the signature scheme
of the PrivKey (neither do we care to compare the both of them). | def _update_sig(self, m, key):
"""
Sign 'm' with the PrivKey 'key' and update our own 'sig_val'.
Note that, even when 'sig_alg' is not None, we use the signature scheme
of the PrivKey (neither do we care to compare the both of them).
"""
if self.sig_alg is None:
... |
Verify that our own 'sig_val' carries the signature of 'm' by the
key associated to the Cert 'cert'. | def _verify_sig(self, m, cert):
"""
Verify that our own 'sig_val' carries the signature of 'm' by the
key associated to the Cert 'cert'.
"""
if self.sig_val:
if self.sig_alg:
h, sig = _tls_hash_sig[self.sig_alg].split('+')
if sig.endswi... |
We do not want TLSServerKeyExchange.build() to overload and recompute
things every time it is called. This method can be called specifically
to have things filled in a smart fashion.
Note that we do not expect default_params.g to be more than 0xff. | def fill_missing(self):
"""
We do not want TLSServerKeyExchange.build() to overload and recompute
things every time it is called. This method can be called specifically
to have things filled in a smart fashion.
Note that we do not expect default_params.g to be more than 0xff.
... |
XXX Check that the pubkey received is in the group. | def register_pubkey(self):
"""
XXX Check that the pubkey received is in the group.
"""
p = pkcs_os2ip(self.dh_p)
g = pkcs_os2ip(self.dh_g)
pn = dh.DHParameterNumbers(p, g)
y = pkcs_os2ip(self.dh_Ys)
public_numbers = dh.DHPublicNumbers(y, pn)
s = ... |
We do not want TLSServerKeyExchange.build() to overload and recompute
things every time it is called. This method can be called specifically
to have things filled in a smart fashion.
XXX We should account for the point_format (before 'point' filling). | def fill_missing(self):
"""
We do not want TLSServerKeyExchange.build() to overload and recompute
things every time it is called. This method can be called specifically
to have things filled in a smart fashion.
XXX We should account for the point_format (before 'point' filling).... |
XXX Support compressed point format.
XXX Check that the pubkey received is on the curve. | def register_pubkey(self):
"""
XXX Support compressed point format.
XXX Check that the pubkey received is on the curve.
"""
# point_format = 0
# if self.point[0] in [b'\x02', b'\x03']:
# point_format = 1
curve_name = _tls_named_curves[self.named_curve]... |
First we update the client DHParams. Then, we try to update the server
DHParams generated during Server*DHParams building, with the shared
secret. Finally, we derive the session keys and update the context. | def post_dissection(self, m):
"""
First we update the client DHParams. Then, we try to update the server
DHParams generated during Server*DHParams building, with the shared
secret. Finally, we derive the session keys and update the context.
"""
s = self.tls_session
... |
We encrypt the premaster secret (the 48 bytes) with either the server
certificate or the temporary RSA key provided in a server key exchange
message. After that step, we add the 2 bytes to provide the length, as
described in implementation notes at the end of section 7.4.7.1. | def post_build(self, pkt, pay):
"""
We encrypt the premaster secret (the 48 bytes) with either the server
certificate or the temporary RSA key provided in a server key exchange
message. After that step, we add the 2 bytes to provide the length, as
described in implementation note... |
Converts a Python 2 function as
lambda (x,y): x + y
In the Python 3 format:
lambda x,y : x + y | def lambda_tuple_converter(func):
"""
Converts a Python 2 function as
lambda (x,y): x + y
In the Python 3 format:
lambda x,y : x + y
"""
if func is not None and func.__code__.co_argcount == 1:
return lambda *args: func(args[0] if len(args) == 1 else args)
else:
return... |
Turn base64 into bytes | def base64_bytes(x):
"""Turn base64 into bytes"""
if six.PY2:
return base64.decodestring(x)
return base64.decodebytes(bytes_encode(x)) |
Turn bytes into base64 | def bytes_base64(x):
"""Turn bytes into base64"""
if six.PY2:
return base64.encodestring(x).replace('\n', '')
return base64.encodebytes(bytes_encode(x)).replace(b'\n', b'') |
Try to parse one of the TLS subprotocols (ccs, alert, handshake or
application_data). This is used inside a loop managed by .getfield(). | def m2i(self, pkt, m):
"""
Try to parse one of the TLS subprotocols (ccs, alert, handshake or
application_data). This is used inside a loop managed by .getfield().
"""
cls = Raw
if pkt.type == 22:
if len(m) >= 1:
msgtype = orb(m[0])
... |
If the decryption of the content did not fail with a CipherError,
we begin a loop on the clear content in order to get as much messages
as possible, of the type advertised in the record header. This is
notably important for several TLS handshake implementations, which
may for instance pa... | def getfield(self, pkt, s):
"""
If the decryption of the content did not fail with a CipherError,
we begin a loop on the clear content in order to get as much messages
as possible, of the type advertised in the record header. This is
notably important for several TLS handshake im... |
Update the context with information from the built packet.
If no type was given at the record layer, we try to infer it. | def i2m(self, pkt, p):
"""
Update the context with information from the built packet.
If no type was given at the record layer, we try to infer it.
"""
cur = b""
if isinstance(p, _GenericTLSSessionInheritance):
if pkt.type is None:
if isinstanc... |
Reconstruct the header because the TLS type may have been updated.
Then, append the content. | def addfield(self, pkt, s, val):
"""
Reconstruct the header because the TLS type may have been updated.
Then, append the content.
"""
res = b""
for p in val:
res += self.i2m(pkt, p)
if (isinstance(pkt, _GenericTLSSessionInheritance) and
_tl... |
If the TLS class was called on raw SSLv2 data, we want to return an
SSLv2 record instance. We acknowledge the risk of SSLv2 packets with a
msglen of 0x1403, 0x1503, 0x1603 or 0x1703 which will never be casted
as SSLv2 records but TLS ones instead, but hey, we can't be held
responsible fo... | def dispatch_hook(cls, _pkt=None, *args, **kargs):
"""
If the TLS class was called on raw SSLv2 data, we want to return an
SSLv2 record instance. We acknowledge the risk of SSLv2 packets with a
msglen of 0x1403, 0x1503, 0x1603 or 0x1703 which will never be casted
as SSLv2 records... |
Provided with the record header, the TLSCompressed.fragment and the
HMAC, return True if the HMAC is correct. If we could not compute the
HMAC because the key was missing, there is no sense in verifying
anything, thus we also return True.
Meant to be used with a block cipher or a stream... | def _tls_hmac_verify(self, hdr, msg, mac):
"""
Provided with the record header, the TLSCompressed.fragment and the
HMAC, return True if the HMAC is correct. If we could not compute the
HMAC because the key was missing, there is no sense in verifying
anything, thus we also return ... |
Provided with the TLSCompressed.fragment,
return the TLSPlaintext.fragment. | def _tls_decompress(self, s):
"""
Provided with the TLSCompressed.fragment,
return the TLSPlaintext.fragment.
"""
alg = self.tls_session.rcs.compression
return alg.decompress(s) |
Decrypt, verify and decompress the message,
i.e. apply the previous methods according to the reading cipher type.
If the decryption was successful, 'len' will be the length of the
TLSPlaintext.fragment. Else, it should be the length of the
_TLSEncryptedContent. | def pre_dissect(self, s):
"""
Decrypt, verify and decompress the message,
i.e. apply the previous methods according to the reading cipher type.
If the decryption was successful, 'len' will be the length of the
TLSPlaintext.fragment. Else, it should be the length of the
_T... |
Commit the pending r/w state if it has been triggered (e.g. by an
underlying TLSChangeCipherSpec or a SSLv2ClientMasterKey). We update
nothing if the prcs was not set, as this probably means that we're
working out-of-context (and we need to keep the default rcs). | def post_dissect(self, s):
"""
Commit the pending r/w state if it has been triggered (e.g. by an
underlying TLSChangeCipherSpec or a SSLv2ClientMasterKey). We update
nothing if the prcs was not set, as this probably means that we're
working out-of-context (and we need to keep the... |
Provided with the TLSPlaintext.fragment,
return the TLSCompressed.fragment. | def _tls_compress(self, s):
"""
Provided with the TLSPlaintext.fragment,
return the TLSCompressed.fragment.
"""
alg = self.tls_session.wcs.compression
return alg.compress(s) |
Return the TLSCiphertext.fragment for AEAD ciphers, i.e. the whole
GenericAEADCipher. Also, the additional data is computed right here. | def _tls_auth_encrypt(self, s):
"""
Return the TLSCiphertext.fragment for AEAD ciphers, i.e. the whole
GenericAEADCipher. Also, the additional data is computed right here.
"""
write_seq_num = struct.pack("!Q", self.tls_session.wcs.seq_num)
self.tls_session.wcs.seq_num += ... |
Provided with the record header (concatenation of the TLSCompressed
type, version and length fields) and the TLSCompressed.fragment,
return the concatenation of the TLSCompressed.fragment and the HMAC.
Meant to be used with a block cipher or a stream cipher.
It would fail with an AEAD c... | def _tls_hmac_add(self, hdr, msg):
"""
Provided with the record header (concatenation of the TLSCompressed
type, version and length fields) and the TLSCompressed.fragment,
return the concatenation of the TLSCompressed.fragment and the HMAC.
Meant to be used with a block cipher o... |
Provided with the concatenation of the TLSCompressed.fragment and the
HMAC, append the right padding and return it as a whole.
This is the TLS-style padding: while SSL allowed for random padding,
TLS (misguidedly) specifies the repetition of the same byte all over,
and this byte must be ... | def _tls_pad(self, s):
"""
Provided with the concatenation of the TLSCompressed.fragment and the
HMAC, append the right padding and return it as a whole.
This is the TLS-style padding: while SSL allowed for random padding,
TLS (misguidedly) specifies the repetition of the same by... |
Apply the previous methods according to the writing cipher type. | def post_build(self, pkt, pay):
"""
Apply the previous methods according to the writing cipher type.
"""
# Compute the length of TLSPlaintext fragment
hdr, frag = pkt[:5], pkt[5:]
tmp_len = len(frag)
hdr = hdr[:3] + struct.pack("!H", tmp_len)
# Compressio... |
This function is called during sendrecv() routine to select
the available sockets.
params:
- sockets: an array of sockets that need to be selected
returns:
- an array of sockets that were selected
- the function to be called next to get the packets (i.g. recv) | def select(sockets, remain=conf.recv_poll_rate):
"""This function is called during sendrecv() routine to select
the available sockets.
params:
- sockets: an array of sockets that need to be selected
returns:
- an array of sockets that were selected
- the funct... |
Open the TUN or TAP device. | def open(self):
"""Open the TUN or TAP device."""
if not self.closed:
return
self.outs = self.ins = open(
"/dev/net/tun" if LINUX else ("/dev/%s" % self.iface), "r+b",
buffering=0
)
if LINUX:
from fcntl import ioctl
# TU... |
Calculate the length of the attribute value field | def util_mic_len(pkt):
''' Calculate the length of the attribute value field '''
if (pkt.nwk_seclevel == 0): # no encryption, no mic
return 0
elif (pkt.nwk_seclevel == 1): # MIC-32
return 4
elif (pkt.nwk_seclevel == 2): # MIC-64
return 8
elif (pkt.nwk_seclevel == 3): # MI... |
Builds a list of EIR messages to wrap this frame. | def build_eir(self):
"""Builds a list of EIR messages to wrap this frame."""
return LowEnergyBeaconHelper.base_eir + [
EIR_Hdr() / EIR_CompleteList16BitServiceUUIDs(svc_uuids=[
EDDYSTONE_UUID]),
EIR_Hdr() / EIR_ServiceData16BitUUID() / self
] |
Ex:
add(dst="2001:db8:cafe:f000::/56")
add(dst="2001:db8:cafe:f000::/56", gw="2001:db8:cafe::1")
add(dst="2001:db8:cafe:f000::/64", gw="2001:db8:cafe::1", dev="eth0") | def add(self, *args, **kargs):
"""Ex:
add(dst="2001:db8:cafe:f000::/56")
add(dst="2001:db8:cafe:f000::/56", gw="2001:db8:cafe::1")
add(dst="2001:db8:cafe:f000::/64", gw="2001:db8:cafe::1", dev="eth0")
"""
self.invalidate_cache()
self.routes.append(self.make_route(... |
removes all route entries that uses 'iff' interface. | def ifdel(self, iff):
""" removes all route entries that uses 'iff' interface. """
new_routes = []
for rt in self.routes:
if rt[3] != iff:
new_routes.append(rt)
self.invalidate_cache()
self.routes = new_routes |
Creates an Eddystone_Frame with a Eddystone_URL for a given URL. | def from_url(url):
"""Creates an Eddystone_Frame with a Eddystone_URL for a given URL."""
url = url.encode('ascii')
scheme = None
for k, v in EDDYSTONE_URL_SCHEMES.items():
if url.startswith(v):
scheme = k
url = url[len(v):]
bre... |
Add an interface 'iff' with provided address into routing table.
Ex: ifadd('eth0', '2001:bd8:cafe:1::1/64') will add following entry into # noqa: E501
Scapy6 internal routing table:
Destination Next Hop iface Def src @ Metric
2001:bd8:cafe:1::/64 :: ... | def ifadd(self, iff, addr):
"""
Add an interface 'iff' with provided address into routing table.
Ex: ifadd('eth0', '2001:bd8:cafe:1::1/64') will add following entry into # noqa: E501
Scapy6 internal routing table:
Destination Next Hop iface Def src @ ... |
Provide best route to IPv6 destination address, based on Scapy
internal routing table content.
When a set of address is passed (e.g. 2001:db8:cafe:*::1-5) an address
of the set is used. Be aware of that behavior when using wildcards in
upper parts of addresses !
If 'dst' parame... | def route(self, dst=None, dev=None, verbose=conf.verb):
"""
Provide best route to IPv6 destination address, based on Scapy
internal routing table content.
When a set of address is passed (e.g. 2001:db8:cafe:*::1-5) an address
of the set is used. Be aware of that behavior when us... |
Compress p (a TLSPlaintext instance) using compression algorithm instance
alg and return a TLSCompressed instance. | def _tls_compress(alg, p):
"""
Compress p (a TLSPlaintext instance) using compression algorithm instance
alg and return a TLSCompressed instance.
"""
c = TLSCompressed()
c.type = p.type
c.version = p.version
c.data = alg.compress(p.data)
c.len = len(c.data)
return c |
Decompress c (a TLSCompressed instance) using compression algorithm
instance alg and return a TLSPlaintext instance. | def _tls_decompress(alg, c):
"""
Decompress c (a TLSCompressed instance) using compression algorithm
instance alg and return a TLSPlaintext instance.
"""
p = TLSPlaintext()
p.type = c.type
p.version = c.version
p.data = alg.decompress(c.data)
p.len = len(p.data)
return p |
Compute the MAC using provided MAC alg instance over TLSCiphertext c using
current write sequence number write_seq_num. Computed MAC is then appended
to c.data and c.len is updated to reflect that change. It is the
caller responsibility to increment the sequence number after the operation.
The function ... | def _tls_mac_add(alg, c, write_seq_num):
"""
Compute the MAC using provided MAC alg instance over TLSCiphertext c using
current write sequence number write_seq_num. Computed MAC is then appended
to c.data and c.len is updated to reflect that change. It is the
caller responsibility to increment the s... |
Verify if the MAC in provided message (message resulting from decryption
and padding removal) is valid. Current read sequence number is used in
the verification process.
If the MAC is valid:
- The function returns True
- The packet p is updated in the following way: trailing MAC value is
r... | def _tls_mac_verify(alg, p, read_seq_num):
"""
Verify if the MAC in provided message (message resulting from decryption
and padding removal) is valid. Current read sequence number is used in
the verification process.
If the MAC is valid:
- The function returns True
- The packet p is updat... |
Provided with cipher block size parameter and current TLSCompressed packet
p (after MAC addition), the function adds required, deterministic padding
to p.data before encryption step, as it is defined for TLS (i.e. not
SSL and its allowed random padding). The function has no return value. | def _tls_add_pad(p, block_size):
"""
Provided with cipher block size parameter and current TLSCompressed packet
p (after MAC addition), the function adds required, deterministic padding
to p.data before encryption step, as it is defined for TLS (i.e. not
SSL and its allowed random padding). The func... |
Provided with a just decrypted TLSCiphertext (now a TLSPlaintext instance)
p, the function removes the trailing padding found in p.data. It also
performs some sanity checks on the padding (length, content, ...). False
is returned if one of the check fails. Otherwise, True is returned,
indicating that p.... | def _tls_del_pad(p):
"""
Provided with a just decrypted TLSCiphertext (now a TLSPlaintext instance)
p, the function removes the trailing padding found in p.data. It also
performs some sanity checks on the padding (length, content, ...). False
is returned if one of the check fails. Otherwise, True is... |
Provided with an already MACed TLSCompressed packet, and a stream or block
cipher alg, the function converts it into a TLSCiphertext (i.e. encrypts it
and updates length). The function returns a newly created TLSCiphertext
instance. | def _tls_encrypt(alg, p):
"""
Provided with an already MACed TLSCompressed packet, and a stream or block
cipher alg, the function converts it into a TLSCiphertext (i.e. encrypts it
and updates length). The function returns a newly created TLSCiphertext
instance.
"""
c = TLSCiphertext()
c... |
Provided with a TLSCiphertext instance c, and a stream or block cipher alg,
the function decrypts c.data and returns a newly created TLSPlaintext. | def _tls_decrypt(alg, c):
"""
Provided with a TLSCiphertext instance c, and a stream or block cipher alg,
the function decrypts c.data and returns a newly created TLSPlaintext.
"""
p = TLSPlaintext()
p.type = c.type
p.version = c.version
p.data = alg.decrypt(c.data)
p.len = len(p.dat... |
Provided with a TLSCompressed instance p, the function applies AEAD
cipher alg to p.data and builds a new TLSCiphertext instance. Unlike
for block and stream ciphers, for which the authentication step is done
separately, AEAD alg does it simultaneously: this is the reason why
write_seq_num is passed to ... | def _tls_aead_auth_encrypt(alg, p, write_seq_num):
"""
Provided with a TLSCompressed instance p, the function applies AEAD
cipher alg to p.data and builds a new TLSCiphertext instance. Unlike
for block and stream ciphers, for which the authentication step is done
separately, AEAD alg does it simulta... |
Provided with a TLSCiphertext instance c, the function applies AEAD
cipher alg auth_decrypt function to c.data (and additional data)
in order to authenticate the data and decrypt c.data. When those
steps succeed, the result is a newly created TLSCompressed instance.
On error, None is returned. Note that... | def _tls_aead_auth_decrypt(alg, c, read_seq_num):
"""
Provided with a TLSCiphertext instance c, the function applies AEAD
cipher alg auth_decrypt function to c.data (and additional data)
in order to authenticate the data and decrypt c.data. When those
steps succeed, the result is a newly created TLS... |
Function used to call a program using the extcap format,
then parse the results | def _extcap_call(prog, args, keyword, values):
"""Function used to call a program using the extcap format,
then parse the results"""
p = subprocess.Popen(
[prog] + args,
stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
data, err = p.communicate()
if p.returncode != 0:
rai... |
Builds a list of _HCSINullField with numbered "Reserved" names.
Takes the same arguments as the ``range`` built-in.
:returns: list[HCSINullField] | def _hcsi_null_range(*args, **kwargs):
"""Builds a list of _HCSINullField with numbered "Reserved" names.
Takes the same arguments as the ``range`` built-in.
:returns: list[HCSINullField]
"""
return [
HCSINullField('Reserved{:02d}'.format(x))
for x in range(*args, **kwargs)
] |
Convert internal value to machine value | def i2m(self, pkt, x):
"""Convert internal value to machine value"""
if x is None:
# Try to return zero if undefined
x = self.h2i(pkt, 0)
return x |
Returns the main global unicast address associated with provided
interface, in human readable form. If no global address is found,
None is returned. | def get_if_addr6(iff):
"""
Returns the main global unicast address associated with provided
interface, in human readable form. If no global address is found,
None is returned.
"""
return next((x[0] for x in in6_getifaddr()
if x[2] == iff and x[1] == IPV6_ADDR_GLOBAL), None) |
Returns the main global unicast address associated with provided
interface, in network format. If no global address is found, None
is returned. | def get_if_raw_addr6(iff):
"""
Returns the main global unicast address associated with provided
interface, in network format. If no global address is found, None
is returned.
"""
ip6 = get_if_addr6(iff)
if ip6 is not None:
return inet_pton(socket.AF_INET6, ip6)
return None |
Get representation name of a pnio frame ID
:param x: a key of the PNIO_FRAME_IDS dictionary
:returns: str | def i2s_frameid(x):
""" Get representation name of a pnio frame ID
:param x: a key of the PNIO_FRAME_IDS dictionary
:returns: str
"""
try:
return PNIO_FRAME_IDS[x]
except KeyError:
pass
if 0x0100 <= x < 0x1000:
return "RT_CLASS_3 (%4x)" % x
if 0x8000 <= x < 0xC00... |
Get pnio frame ID from a representation name
Performs a reverse look-up in PNIO_FRAME_IDS dictionary
:param x: a value of PNIO_FRAME_IDS dict
:returns: integer | def s2i_frameid(x):
""" Get pnio frame ID from a representation name
Performs a reverse look-up in PNIO_FRAME_IDS dictionary
:param x: a value of PNIO_FRAME_IDS dict
:returns: integer
"""
try:
return {
"RT_CLASS_3": 0x0100,
"RT_CLASS_1": 0x8000,
"RT_... |
Attribution of correct type depending on version and pdu_type | def dispatch_hook(cls, _pkt=None, *args, **kargs):
'''
Attribution of correct type depending on version and pdu_type
'''
if _pkt and len(_pkt) >= 2:
version = orb(_pkt[0])
pdu_type = orb(_pkt[1])
if version == 0:
return PDU_CLASS_VERS... |
Parse bulk cymru data | def parse(self, data):
"""Parse bulk cymru data"""
ASNlist = []
for line in data.splitlines()[1:]:
line = plain_str(line)
if "|" not in line:
continue
asn, ip, desc = [elt.strip() for elt in line.split('|')]
if asn == "NA":
... |
Encode and replace the mrcode value to its IGMPv3 encoded time value if needed, # noqa: E501
as specified in rfc3376#section-4.1.1.
If value < 128, return the value specified. If >= 128, encode as a floating # noqa: E501
point value. Value can be 0 - 31744. | def encode_maxrespcode(self):
"""Encode and replace the mrcode value to its IGMPv3 encoded time value if needed, # noqa: E501
as specified in rfc3376#section-4.1.1.
If value < 128, return the value specified. If >= 128, encode as a floating # noqa: E501
point value. Value can be 0 - 3... |
This can be used as a class decorator; if we want to support Python
2.5, we have to replace
@_register_lltd_specific_class(x[, y[, ...]])
class LLTDAttributeSpecific(LLTDAttribute):
[...]
by
class LLTDAttributeSpecific(LLTDAttribute):
[...]
LLTDAttributeSpecific = _register_lltd_specific_class(x[, y[, ...]])(
... | def _register_lltd_specific_class(*attr_types):
"""This can be used as a class decorator; if we want to support Python
2.5, we have to replace
@_register_lltd_specific_class(x[, y[, ...]])
class LLTDAttributeSpecific(LLTDAttribute):
[...]
by
class LLTDAttributeSpecific(LLTDAttribute):
[...]
LLTDAttributeSpec... |
Update the builder using the provided `plist`. `plist` can
be either a Packet() or a PacketList(). | def parse(self, plist):
"""Update the builder using the provided `plist`. `plist` can
be either a Packet() or a PacketList().
"""
if not isinstance(plist, PacketList):
plist = PacketList(plist)
for pkt in plist[LLTD]:
if LLTDQueryLargeTlv in pkt:
... |
Returns a dictionary object, keys are strings "source >
destincation [content type]", and values are the content
fetched, also as a string. | def get_data(self):
"""Returns a dictionary object, keys are strings "source >
destincation [content type]", and values are the content
fetched, also as a string.
"""
return {key: "".join(chr(byte) for byte in data)
for key, data in six.iteritems(self.data)} |
Convert an IPv6 address from text representation into binary form,
used when socket.inet_pton is not available. | def _inet6_pton(addr):
"""Convert an IPv6 address from text representation into binary form,
used when socket.inet_pton is not available.
"""
joker_pos = None
result = b""
addr = plain_str(addr)
if addr == '::':
return b'\x00' * 16
if addr.startswith('::'):
addr = addr[1:]
... |
Convert an IP address from text representation into binary form. | def inet_pton(af, addr):
"""Convert an IP address from text representation into binary form."""
# Will replace Net/Net6 objects
addr = plain_str(addr)
# Use inet_pton if available
try:
return socket.inet_pton(af, addr)
except AttributeError:
try:
return _INET_PTON[af]... |
Convert an IPv6 address from binary form into text representation,
used when socket.inet_pton is not available. | def _inet6_ntop(addr):
"""Convert an IPv6 address from binary form into text representation,
used when socket.inet_pton is not available.
"""
# IPv6 addresses have 128bits (16 bytes)
if len(addr) != 16:
raise ValueError("invalid length of packed IP address string")
# Decode to hex represen... |
Convert an IP address from binary form into text representation. | def inet_ntop(af, addr):
"""Convert an IP address from binary form into text representation."""
# Use inet_ntop if available
addr = bytes_encode(addr)
try:
return socket.inet_ntop(af, addr)
except AttributeError:
try:
return _INET_NTOP[af](addr)
except KeyError:
... |
Receives a packet, then returns a tuple containing (cls, pkt_data, time) | def recv_raw(self, x=MTU):
"""Receives a packet, then returns a tuple containing (cls, pkt_data, time)""" # noqa: E501
ll = self.ins.datalink()
if ll in conf.l2types:
cls = conf.l2types[ll]
else:
cls = conf.default_l2
warning("Unable to guess datalink... |
Receives and dissect a packet in non-blocking mode.
Note: on Windows, this won't do anything. | def nonblock_recv(self):
"""Receives and dissect a packet in non-blocking mode.
Note: on Windows, this won't do anything."""
self.ins.setnonblock(1)
p = self.recv(MTU)
self.ins.setnonblock(0)
return p |
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 route found") |
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 ... | def route(self, dst=None, verbose=conf.verb):
"""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... |
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 of 1ms: will return instantly
with open(os.devnull, 'wb') as DEVNULL:
return subprocess.Popen("ping -4 -w 1 -n 1... |
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.
"""
super(TLSClientHello, self).tls_session_update(msg_str)
self.tls_session.advertised_tls_version = self... |
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... | def tls_session_update(self, msg_str):
"""
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 ... |
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):
"""
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.
... |
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... | def build(self, *args, **kargs):
"""
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 ac... |
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 have been updated.
XXX Add a 'fixed_dh' OR condition to the 'anonymous' test.
"""
s = self.tls_session
if s.prcs and s.prcs.key_exchange.no_ske:
... |
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_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.
"""
... |
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 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.
'''
with Modules() as m:
... |
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, sys.stderr, etc).
Returns None.
'''
with Modules() as m:
fd.write(m.help()) |
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 extracted files, if applicable).
Also re/initializes self.status.
All modules should access the target file list through this method.
'''
fp = None
# Ensure files ar... |
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):
'''
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.
... |
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 None.
'''
exception_header_width = 100
e = Error(**kwargs)
e.module = self.__class__.__name__
self... |
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.RESULT_FORMAT)
self.config.display.add_custom_header(self.VERBOSE_FORMAT, self.VERBOSE)
... |
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.
'''
self.status = self.parent.status
self.modules = self.parent.executed_modules
# A special exception for th... |
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.
@attribute - The desired module attribute.
Returns a list of modules that contain the specified attribute, in the order they should be executed.
'''
import binwalk.modules
modul... |
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 += "Craig Heffner, ReFirmLabs\n"
help_string += "https://github.com/... |
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 objects.
'''
run_modules = []
orig_arguments = self.arguments
if args or kwargs:
self._set_a... |
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.status.clear()
# ... |
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:]):
'''
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.
... |
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 for kwarg processing.
@obj - An instance of the module (e.g., self)
@kwargs - The kwargs passed to the module
Returns None.
'''
if hasattr(obj, "KWARGS"):
... |
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... | def status_server(self, port):
'''
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,
... |
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':
return strlen+i
return bufflen |
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 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.
'''
restr = ""
#... |
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 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.
'''
filtere... |
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, offset, expression):
'''
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 th... |
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):
'''
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.